From 15c82b1728291d8f592001f5acda6554196aeb26 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 02:25:08 +0900 Subject: [PATCH 01/64] fix(search): use the selected Codex pool account network route (#9129) * fix(search): use the selected Codex pool account network route * docs: keep the search routing contract within the provider guide limit * docs(search): distinguish pool overrides from the main login route * docs(es): align the existing main-login paragraph with the search exception * fix(search): honor longer response deadlines over SOCKS5 * docs(search): put the relay timeout in the server settings reference --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- .../es/reference/configuration/providers.md | 4 +- .../docs/es/reference/configuration/server.md | 1 + .../docs/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/server.md | 1 + src/lib/socks5-fetch.ts | 12 +++- src/server/search.ts | 17 +++++- .../providers/codex-installation-identity.md | 5 ++ structure/transports/inventory.md | 2 + tests/lib/socks5-fetch.test.ts | 26 ++++++++- tests/server/server-search.test.ts | 56 +++++++++++++++++++ 10 files changed, 118 insertions(+), 8 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 1eb3daef7cc..b77f5f37067 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -921,7 +921,9 @@ Rotar entre cuentas de suscripción gasta la cuota de una segunda cuenta y puede ### Formas de registro administradas -`apiKeys[]` entradas contienen `id`, `name`, generado `key`, y cadenas ISO `createdAt`. Opcional `allowMeteredComboTargets: true` permite explícitamente los objetivos marcados `metered: true`; el consentimiento omitido o falso los niega. El token de entorno nunca califica. Las personas que llaman solo en bucle local pueden usar per-combo `allowMeteredTargets: true`; las personas que llaman con clave configurada y vinculada aún necesitan consentimiento de clave. Véase [Consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). `codexAccounts[]` entradas requieren `id`, `email`, y `isMain`, con opcional `plan`, `chatgptAccountId`, y la privacidad de seguridad `logLabel`. Estos registros normalmente se administran en el panel de control. Un objeto opcional `egress` da a una cuenta del grupo su propia ruta, con los mismos valores `proxy` y `noProxy` que la salida por proveedor: un `proxy` de la cuenta sustituye al del proveedor `openai` para las solicitudes, compactaciones, renovaciones de token, consultas de uso, calentamientos, descubrimiento de modelos y llamadas de créditos de reinicio de esa cuenta, y la consulta de uso y el calentamiento tras iniciar sesión; un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. Las llamadas en segundo plano del grupo ahora siguen `providers.openai.proxy`, y un `egress` por cuenta lo sustituye: una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` falta o no se puede leer, o una credencial guardada ya no figura en `codexAccounts` (por ejemplo, se eliminó mientras una llamada estaba en curso), la llamada se rechaza en lugar de enviarse sin la ruta configurada. El inicio de sesión principal no tiene entrada en el grupo y siempre usa la ruta del proveedor. +`apiKeys[]` entradas contienen `id`, `name`, generado `key`, y cadenas ISO `createdAt`. Opcional `allowMeteredComboTargets: true` permite explícitamente los objetivos marcados `metered: true`; el consentimiento omitido o falso los niega. El token de entorno nunca califica. Las personas que llaman solo en bucle local pueden usar per-combo `allowMeteredTargets: true`; las personas que llaman con clave configurada y vinculada aún necesitan consentimiento de clave. Véase [Consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). `codexAccounts[]` entradas requieren `id`, `email`, y `isMain`, con opcional `plan`, `chatgptAccountId`, y la privacidad de seguridad `logLabel`. Estos registros normalmente se administran en el panel de control. Un objeto opcional `egress` da a una cuenta del grupo su propia ruta, con los mismos valores `proxy` y `noProxy` que la salida por proveedor: un `proxy` de la cuenta sustituye al del proveedor `openai` para las solicitudes, compactaciones, renovaciones de token, consultas de uso, calentamientos, descubrimiento de modelos y llamadas de créditos de reinicio de esa cuenta, y la consulta de uso y el calentamiento tras iniciar sesión; un `proxy` omitido conserva el del proveedor, y las entradas `noProxy` de la cuenta se aplican antes que las del proveedor. Las llamadas en segundo plano del grupo ahora siguen `providers.openai.proxy`, y un `egress` por cuenta lo sustituye: una cuenta del grupo sin objeto `egress` también envía esas llamadas por la ruta del proveedor `openai`. Si `config.json` falta o no se puede leer, o una credencial guardada ya no figura en `codexAccounts` (por ejemplo, se eliminó mientras una llamada estaba en curso), la llamada se rechaza en lugar de enviarse sin la ruta configurada. La sesión principal no tiene una configuración de salida por cuenta. + +En la búsqueda web alojada, cada cuenta secundaria usa su propio proxy o, si no tiene uno, el del proveedor. Una coincidencia con `noProxy` de la cuenta o del proveedor selecciona una conexión directa. Las búsquedas con la sesión principal, incluso si la selecciona el grupo, y las que usan la sesión aportada por el cliente conservan la ruta de red del proceso. ### `tokenGuardian` (`OcxTokenGuardianConfig`) diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index 9d384c86340..bb5ca1dd732 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -24,6 +24,7 @@ La configuración del servidor controla la forma en que el proxy local escucha, | `oauthOpenBrowser?` | `boolean` | `true` | Permite abrir el navegador en la máquina que ejecuta el proxy al iniciar sesión. Omitir el campo o usar `true` conserva esa apertura; solo `false` la desactiva. Es útil si necesita otro perfil de navegador o si el panel está en otra máquina: el inicio de sesión comienza igualmente y se devuelve y muestra la URL. `POST /api/oauth/login` y `POST /api/codex-auth/login` admiten un booleano `openBrowser` por solicitud que tiene prioridad sobre este ajuste; el panel ofrece la misma opción junto al botón de inicio de sesión. Ambas rutas informan `browserLaunch`: `started`, `failed` (el panel indica que no se pudo abrir) o `skipped`. Los flujos con código de dispositivo nunca abren el navegador. | | `codexAuthMethod?` | `"auto" \| "device-only"` | `"auto"` | Cómo se autorizan los inicios de sesión de cuentas del grupo de ChatGPT/Codex (`POST /api/codex-auth/login`: las acciones de añadir y volver a autenticar del panel de control y `ocx account login openai`). Omitir el campo o usar `"auto"` conserva el comportamiento existente: un inicio de sesión en el navegador con devolución de llamada a localhost, salvo que quien llama pida el flujo de dispositivo. `"device-only"` hace que todos esos inicios de sesión usen el flujo con código de dispositivo aunque no se haya pedido, así que un concentrador sin pantalla nunca inicia un inicio de sesión con devolución de llamada a localhost; la respuesta incluye entonces `authMethod: "device-only"`, y el panel de control y la CLI indican que el proxy lo exige. La reautenticación mantiene sus comprobaciones de identidad de la misma cuenta. No afecta a los inicios de sesión de otros proveedores ni al de la cuenta principal nativa. Se lee al iniciar el proxy: reinicie el proxy para aplicar un cambio. Si el archivo contiene un valor no válido, el inicio del proxy y `ocx config validate` avisan de que se usará `"auto"`. | | `connectTimeoutMs?` | `number` | `200000` (público) / desactivado (local) | Plazo por intento desde el envío hasta el primer encabezado del proveedor, incluidos DNS, TCP, TLS y la espera de encabezados. Termina antes del cuerpo y es independiente de `stallTimeoutSec`. Sin configurar, un destino local (loopback, privado o nombre `.local`/`.lan`) no tiene plazo y uno público usa 200 s. Un valor positivo se aplica a ambos; `0` o un valor no positivo desactiva el plazo en todos. Así un modelo local puede dedicar minutos al prefill sin interrumpir un turno sano. | +| `search.timeoutMs?` | `number` | `200000` | Plazo total en milisegundos para la búsqueda alojada de `/v1/alpha/search`. Un plazo mayor permite esperar más de 200 segundos sin recibir datos, incluso a través de SOCKS5. | | `offlineResendWaitSec?` | `number` | desactivado | Espera opcional después de que el nombre del proveedor no se resuelva (DNS `ENOTFOUND` o `EAI_AGAIN`), por ejemplo cuando un portátil se despierta o cambia de Wi-Fi. OpenCodex comprueba una vez por segundo el DNS del nombre que resuelve la solicitud (el del proveedor, o el del proxy de salida cuando uno la transporta) durante hasta esta cantidad de segundos (máximo 300) y luego reenvía la solicitud una vez. Nada llegó al proveedor, así que el reenvío no puede repetir su trabajo, y cuenta dentro del presupuesto de envíos existente de la solicitud. Solo espera el primer envío de una solicitud `/v1/responses`: un combo pasa a su siguiente miembro, y una conexión rechazada o inaccesible, una dirección IP literal del proveedor o del proxy, un fallo en un reintento posterior, un segundo fallo de DNS, una espera agotada o una solicitud cancelada devuelven el error original de inmediato. Cada comprobación de DNS también está limitada por la espera y por la cancelación del cliente. Vertex AI y Antigravity (Google Cloud Code Assist), Kiro, Cursor, Zed, Command Code y MiMo Free gestionan su propio transporte y mantienen su propio comportamiento de reintento; Google AI Studio directo usa la espera. Sin configurar o `0` mantiene el 502 inmediato actual. | | `shutdownTimeoutMs?` | `number` | `5000` | Plazo para finalizar los turnos de forma ordenada antes de abortar los que sigan activos. | | `websockets?` | `boolean` | `false` | Anuncie y admita la ruta Responses WebSocket orientada al cliente. False mantiene a los clientes en HTTP / SSE; no desactiva una optimización WS canónica elegible de ChatGPT. Las solicitudes de entrada completa pueden reutilizar una conexión ascendente dentro de la misma credencial, cuenta, subproceso y turno seleccionados; la política de enlace cambiada o la identidad faltante mantienen las solicitudes en conexiones separadas. Esto no recorta la entrada HTTP ni crea ID de respuesta anterior. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 06a24ab7cff..a60ad83580b 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1426,7 +1426,7 @@ provider in question. `apiKeys[]` entries contain `id`, `name`, generated `key`, and ISO `createdAt` strings. Optional `allowMeteredComboTargets: true` explicitly permits targets marked `metered: true`; omitted or false consent denies them. The environment token never qualifies. Local loopback-only callers can instead use per-combo `allowMeteredTargets: true`; configured-key and linked callers still need key consent. See [Metered fallback consent](/guides/combos/#metered-fallback-consent). `codexAccounts[]` entries require `id`, `email`, and `isMain`, with optional `plan`, `chatgptAccountId`, and privacy-safe `logLabel`. These records are normally dashboard-managed. -An optional `egress` object gives one pool account its own route, with the same `proxy` and `noProxy` values as a provider's [per-provider egress](#per-provider-egress): an account `proxy` replaces the `openai` provider's for that account's requests, compactions, token refreshes, usage checks, warmups, model discovery and reset-credit calls, and the usage check and warmup after signing in; an omitted `proxy` keeps the provider's, and the account's `noProxy` entries apply ahead of the provider's. Pool background calls now follow `providers.openai.proxy`, and a per-account `egress` overrides it: a pool account without an `egress` object sends those calls by the `openai` provider's route too. If `config.json` is missing or cannot be read, or a stored account credential is no longer listed in `codexAccounts` (for example, removed while a call was in flight), the call is refused instead of sent without the configured route. The main login has no pool entry and always uses the provider's route. +An optional `egress` object gives one pool account its own route, with the same `proxy` and `noProxy` values as a provider's [per-provider egress](#per-provider-egress): an account `proxy` replaces the `openai` provider's for that account's requests, hosted web searches, compactions, token refreshes, usage checks, warmups, model discovery and reset-credit calls, and the usage check and warmup after signing in; an omitted `proxy` keeps the provider's, and matching a `noProxy` entry selects a direct connection (account entries are checked before the provider’s). Pool background calls now follow `providers.openai.proxy`, and a per-account `egress` overrides it: a pool account without an `egress` object sends those calls by the `openai` provider's route too. If `config.json` is missing or cannot be read, or a stored account credential is no longer listed in `codexAccounts` (for example, removed while a call was in flight), the call is refused instead of sent without the configured route. The main login has no per-account egress override. For hosted web search it keeps the process-wide route, even when chosen in pool mode, as does a caller-provided login. ### `tokenGuardian` (`OcxTokenGuardianConfig`) diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index 6e5fdb033ae..430fb67e5cb 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -30,6 +30,7 @@ passthrough, including native WebSocket output, retain their existing stop behav | `oauthOpenBrowser?` | `boolean` | `true` | Whether a login may open a browser on the machine running the proxy. Absent and `true` both open, so an existing install is unchanged; only an explicit `false` declines. Decline when you need the authorization link in a different browser profile, or when the dashboard is not on the proxy's machine — the login still starts and the URL is still returned and displayed. `POST /api/oauth/login` and `POST /api/codex-auth/login` accept a per-request `openBrowser` boolean that overrides this, and the dashboard exposes the same choice beside the login button. Both routes report the outcome as `browserLaunch`: `started`, `failed` (nothing could be opened; the dashboard says so), or `skipped`. Device-code flows never open a browser either way. | | `codexAuthMethod?` | `"auto" \| "device-only"` | `"auto"` | How ChatGPT/Codex pool account logins (`POST /api/codex-auth/login`: the dashboard's add and Re-authenticate actions and `ocx account login openai`) authorize. Absent and `"auto"` keep the existing behavior: a browser login with a localhost callback unless the caller asks for the device flow. `"device-only"` makes every such login use the device-code flow even when the caller did not ask for it, so a headless hub never starts a localhost callback login; the response then carries `authMethod: "device-only"`, and the dashboard and CLI say that the proxy requires it. Reauthentication keeps its same-account identity checks. Other providers' logins and the native main-account login are not affected. Restart the proxy to apply a change. If the file contains an invalid value, startup and `ocx config validate` warn that the proxy will use `"auto"`. | | `connectTimeoutMs?` | `number` | `200000` (public) / disabled (local) | Per-attempt deadline from dispatch until the upstream returns its first response header (DNS/TCP/TLS and the header wait); it ends before body generation and is unrelated to `stallTimeoutSec`, which governs the body stream. Unset, a **local** upstream (loopback, private, or a `.local`/`.lan` name) defaults to disabled and a public upstream to 200 s; a positive value applies to both; `0` (or any non-positive value) disables the header deadline everywhere. Disabled is what lets a local model spend minutes in prompt prefill on a large prompt without the first-header clock cutting a healthy turn. | +| `search.timeoutMs?` | `number` | `200000` | Whole-request deadline in milliseconds for hosted `/v1/alpha/search`. A longer budget also allows the upstream to stay silent beyond 200 seconds, including over SOCKS5. | | `offlineResendWaitSec?` | `number` | off | Opt-in wait after the provider's name fails to resolve (DNS `ENOTFOUND` or `EAI_AGAIN`), for example while a laptop wakes or changes Wi-Fi. OpenCodex checks DNS once a second for the name the request resolves (the provider's, or the outbound proxy's when one carries the request) for up to this many seconds (maximum 300) and then resends the request once. Nothing reached the provider, so the resend cannot repeat its work, and it counts against the request's existing send budget. Only the first send of a `/v1/responses` request waits: a combo moves on to its next member instead, and a refused or unreachable connection, an IP-literal provider or proxy address, a failure on a later retry, a second DNS failure, an exhausted wait or a cancelled request returns the original error at once. Each DNS check is itself bounded by the wait and by client cancellation. Vertex AI and Antigravity (Google Cloud Code Assist), Kiro, Cursor, Zed, Command Code and MiMo Free own their transport and keep their own retry behavior; direct Google AI Studio uses the wait. Unset or `0` keeps today's immediate 502. | | `shutdownTimeoutMs?` | `number` | `5000` | Graceful drain deadline before active turns are aborted. | | `websockets?` | `boolean` | `false` | Advertise and admit the client-facing Responses WebSocket path. False keeps clients on HTTP/SSE; it does not disable an eligible canonical ChatGPT upstream WS optimization. Complete-input requests may reuse an upstream connection within the same selected credential, account, thread and turn; changed handshake policy or missing identity keeps requests on separate connections. This does not trim HTTP input or create previous-response IDs. | diff --git a/src/lib/socks5-fetch.ts b/src/lib/socks5-fetch.ts index 6fb3e7172b0..03ce04d0539 100644 --- a/src/lib/socks5-fetch.ts +++ b/src/lib/socks5-fetch.ts @@ -664,10 +664,10 @@ async function uploadRequestBody( export async function socks5Fetch( input: RequestInfo | URL, - init: RequestInit | undefined, + init: BunFetchRequestInit | undefined, proxy: string, ): Promise { - const protocol = (init as (RequestInit & { protocol?: string }) | undefined)?.protocol; + const protocol = init?.protocol; if (protocol === "http2" || protocol === "h2") { throw new Socks5FetchError("SOCKS5 transport cannot honor an explicit HTTP/2 pin"); } @@ -692,7 +692,13 @@ export async function socks5Fetch( request.signal.addEventListener("abort", onAbort, { once: true }); try { if (target.protocol === "https:") socket = await secureSocket(tunnel, target, request.signal); - socket.setTimeout(SOCKS5_RESPONSE_TIMEOUT_MS, onResponseTimeout); + // A positive Bun fetch timeout is the request's socket idle budget. Keep the tunnel's + // existing bound for callers that didn't request a positive timeout. + const idleMs = init?.timeout; + const responseTimeoutMs = typeof idleMs === "number" && Number.isFinite(idleMs) && idleMs > 0 + ? Math.min(2_147_483_647, Math.ceil(idleMs)) + : SOCKS5_RESPONSE_TIMEOUT_MS; + socket.setTimeout(responseTimeoutMs, onResponseTimeout); // Observe socket errors and early responses while uploading, not only after it. reader = new SocketReader(socket); const headers = requestHeaders(request, target); diff --git a/src/server/search.ts b/src/server/search.ts index 5b28c568e3f..0d33ffe4d1d 100644 --- a/src/server/search.ts +++ b/src/server/search.ts @@ -1,4 +1,5 @@ import { CodexInstallationIdUnavailableError } from "../codex/installation-id"; +import { CodexAccountRouteUnavailableError, codexAccountFetch } from "../codex/account-egress-runtime"; import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers"; /** * /v1/alpha/search relay. @@ -34,6 +35,8 @@ import { import { formatCodexProviderForLog } from "../codex/routing"; import { signalWithTimeout } from "../lib/abort"; import { readBoundedResponseBytes } from "../lib/bounded-body"; +import { InvalidProviderEgressError } from "../lib/provider-egress"; +import { ExplicitProxyExemptedError } from "../lib/proxy-env"; import { sidecarEnter } from "../lib/sidecar-tracker"; import type { OcxConfig } from "../types"; import { @@ -207,13 +210,17 @@ export async function handleSearch( let upstreamResponse: Response | undefined; try { upstream.beforeDispatch?.(); - upstreamResponse = await fetch(url, { + const send = codexAccountFetch(codexLogAccountId(upstream.authContext), { config }); + upstreamResponse = await send(url, { method: "POST", headers, body: JSON.stringify(isolateCodexPoolClientMetadata( relayBody, upstream.authContext.kind === "pool" ? upstream.authContext.chatgptAccountId : undefined, )), signal: linkedSignal.signal, + // Hosted search may send no headers until it finishes. Keep a longer configured deadline + // from being cut short by the transport's idle timer. The linked signal owns total time. + ...(timeoutMs > SEARCH_UPSTREAM_TIMEOUT_MS ? { timeout: timeoutMs } : {}), // Credential-bearing: do not follow a cross-origin 3xx. Bun strips `Authorization` // across origins but forwards nonstandard headers such as `chatgpt-account-id`, // `session_id`, and `x-codex-turn-metadata` to the redirect target. @@ -237,6 +244,10 @@ export async function handleSearch( if (contentType) relayHeaders["content-type"] = contentType; return new Response(observed.bytes, { status: upstreamResponse.status, headers: relayHeaders }); } catch (err) { + if (err instanceof CodexAccountRouteUnavailableError || err instanceof InvalidProviderEgressError || err instanceof ExplicitProxyExemptedError) { + upstream.releaseProbeLease?.(); + return formatErrorResponse(503, "server_busy", "The configured search network route is unavailable"); + } if (err instanceof CodexInstallationIdUnavailableError) { upstream.releaseProbeLease?.(); return formatErrorResponse(503, "server_busy", err.message); @@ -254,7 +265,9 @@ export async function handleSearch( return formatErrorResponse( 502, "upstream_error", - `search relay failed: ${err instanceof Error ? err.message : String(err)}`, + upstream.authContext.kind === "pool" + ? "The search relay could not reach the upstream for the selected account" + : `search relay failed: ${err instanceof Error ? err.message : String(err)}`, ); } finally { sidecarExit(); diff --git a/structure/providers/codex-installation-identity.md b/structure/providers/codex-installation-identity.md index 6d79332b279..69c3096b4b6 100644 --- a/structure/providers/codex-installation-identity.md +++ b/structure/providers/codex-installation-identity.md @@ -82,6 +82,11 @@ retain the selected context and project cloned client metadata immediately befor JSON send, including live's converted multipart session. Live inspects JSON content independently of Content-Type; non-JSON SDP retains its original bytes. Their selected headers authoritatively replace or remove mixed-case provider identity defaults; main and main-pool preserve caller values. +For hosted search, the selected pool account's network route takes precedence over the provider +route. A caller's own bearer retains the process route. A local routing refusal releases the +probe lease without recording an upstream connection failure. +Hosted search passes a configured deadline over 200 seconds to the transport as an idle budget. +The search signal still enforces the total deadline and caller cancellation. Vision, audio and sidecar credential selection share materialization. Dictation in `src/server/audio-dictation.ts` has a 600,000 ms recording budget and opts into a separate 60,000 ms finalization window after a validated `session.close`. diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 2a0954cd645..4b4e06754ca 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -393,6 +393,8 @@ HTTPS tunnels in `src/lib/socks5-fetch.ts` give the TLS handshake its own absolu 30-second deadline after SOCKS CONNECT. Successful TLS clears that deadline before the response timer takes over; timeout, caller cancellation, error and premature close release the owned socket and listeners. Certificate verification stays enabled. +After the handshake, a positive fetch `timeout` sets the tunnel's response idle timer in +milliseconds. Otherwise the existing 200-second response idle limit applies. `tests/lib/socks5-tls-lifecycle.test.ts` exercises stalled and interrupted handshakes. `src/config/proxy-env.ts` activates configured SOCKS5 through `src/lib/proxy-env.ts`; diff --git a/tests/lib/socks5-fetch.test.ts b/tests/lib/socks5-fetch.test.ts index 5f26106ea36..254b48b6009 100644 --- a/tests/lib/socks5-fetch.test.ts +++ b/tests/lib/socks5-fetch.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { randomBytes } from "node:crypto"; import { createServer as createHttpServer } from "node:http"; import net, { createConnection, createServer as createTcpServer, Socket, type Server as TcpServer } from "node:net"; @@ -143,6 +143,30 @@ function socksProxy(options: { } describe("socks5Fetch", () => { + test("sets the response idle deadline on the established tunnel", async () => { + const target = createHttpServer((_req, res) => res.end("ok")); + const proxy = socksProxy(); + const [targetPort, proxyPort] = await Promise.all([listen(target), listen(proxy)]); + const timer = spyOn(Socket.prototype, "setTimeout"); + try { + for (const [init, expectedMs] of [ + [undefined, 200_000], [{ timeout: 0 }, 200_000], [{ timeout: 450_000 }, 450_000], + ] as const) { + timer.mockClear(); + const response = await socks5Fetch( + `http://provider.invalid:${targetPort}/search`, init, `socks5://127.0.0.1:${proxyPort}`, + ); + expect(await response.text()).toBe("ok"); + const delays = timer.mock.calls.map(([delay]) => delay); + expect(delays).toContain(30_000); + expect(delays.filter(ms => ms >= 200_000)).toEqual([expectedMs]); + } + } finally { + timer.mockRestore(); + await Promise.all([close(proxy), close(target)]); + } + }); + test("performs a real domain CONNECT and streams the HTTP response", async () => { const target = createHttpServer((_request, response) => { response.writeHead(200, { "content-type": "text/plain" }); diff --git a/tests/server/server-search.test.ts b/tests/server/server-search.test.ts index 388306d5cc9..5d83a0fed63 100644 --- a/tests/server/server-search.test.ts +++ b/tests/server/server-search.test.ts @@ -323,6 +323,62 @@ test("an account-qualified search model uses that exact account and sends the ba } }); +test("search uses the selected account or provider network route and refuses an unavailable route locally", async () => { + const config = exactSearchConfig(); + const providerProxy = "http://provider.invalid:8080/"; + const accountProxy = "http://account.invalid:8080/"; + config.providers.openai!.proxy = providerProxy; + config.codexAccounts!.find(account => account.id === "pool-a")!.egress = { proxy: accountProxy }; + saveConfig(config); + saveExactSearchCredentials(); + + const calls: Array<{ + proxy: unknown; redirect?: RequestRedirect; account: string | null; timeout?: BunFetchRequestInit["timeout"]; + }> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: BunFetchRequestInit) => { + if (new URL(input instanceof Request ? input.url : input.toString()).pathname !== "/backend-api/codex/alpha/search") { + return Response.json({}); + } + calls.push({ + proxy: init?.proxy, redirect: init?.redirect, account: new Headers(init?.headers).get("chatgpt-account-id"), + timeout: init?.timeout, + }); + return Response.json({ output: "ok" }); + }) as typeof fetch; + const envKeys = ["NO_PROXY", "no_proxy"] as const; + const saved = envKeys.map(key => process.env[key]); + const search = (model: string, headers?: Record) => + handleSearch(alphaSearchRequest({ model }, headers), config, { model: "", provider: "" }); + try { + for (const key of envKeys) delete process.env[key]; + const poolHealth = getCodexUpstreamHealth("pool-a"); + process.env.NO_PROXY = "chatgpt.com"; + const denied = await search("side/gpt-test"); + expect(denied.status).toBe(503); + expect((await denied.json()).error.message).toBe("The configured search network route is unavailable"); + expect(calls).toHaveLength(0); + expect(getCodexUpstreamHealth("pool-a")).toEqual(poolHealth); + delete process.env.NO_PROXY; + config.search = { timeoutMs: 450_000 }; + expect((await search("side/gpt-test")).status).toBe(200); + delete config.search; + config.providers.openai!.codexAccountMode = "pool"; + expect((await search("gpt-test")).status).toBe(200); + config.providers.openai!.codexAccountMode = "direct"; + expect((await search("gpt-test", { authorization: `Bearer ${DIRECT_CHATGPT_TOKEN}`, "chatgpt-account-id": "acct-123" })).status).toBe(200); + expect(calls).toEqual([ + { proxy: accountProxy, redirect: "manual", account: "acct-pool-a", timeout: 450_000 }, + { proxy: providerProxy, redirect: "manual", account: "acct-pool-b", timeout: undefined }, + { proxy: undefined, redirect: "manual", account: "acct-123", timeout: undefined }, + ]); + } finally { + for (const [index, key] of envKeys.entries()) { + if (saved[index] === undefined) delete process.env[key]; + else process.env[key] = saved[index]; + } + } +}); + test("an exact search 429 never switches to the active Pool account and reports only its public selector", async () => { const captured: CapturedRequest[] = []; const upstream = fakeSearchUpstream(captured, 429, { error: { message: "rate limited" } }); From 580dd0e0ad0c6bd24393bae53dc91495637db0da Mon Sep 17 00:00:00 2001 From: Yu Zhang <34849476+AaronZ345@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:35:04 +0800 Subject: [PATCH 02/64] fix(integrations): preserve numeric-looking YAML strings (#9158) Co-authored-by: zhangyu.34 --- src/integrations/serialize.ts | 1 + structure/clients/integrations.md | 2 +- tests/clients/integrations-serialize.test.ts | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/integrations/serialize.ts b/src/integrations/serialize.ts index 28853db8714..144abe5f70c 100644 --- a/src/integrations/serialize.ts +++ b/src/integrations/serialize.ts @@ -58,6 +58,7 @@ function yamlString(value: string): string { const plainSafe = value.length > 0 && value.trim() === value && /^[A-Za-z_./][A-Za-z0-9_./-]*$/u.test(value) + && !/^[.][0-9]/u.test(value) && !/^(?:null|true|false|yes|no|on|off|~|\.nan|[-+]?\.inf)$/iu.test(value); return plainSafe ? value : JSON.stringify(value); } diff --git a/structure/clients/integrations.md b/structure/clients/integrations.md index 5efd800de27..35413f0b8b9 100644 --- a/structure/clients/integrations.md +++ b/structure/clients/integrations.md @@ -194,7 +194,7 @@ provider block in `models.yml`; default presets and proxy routing in `config.yml TOML temporal scalars cannot survive the JSON-cloned merge representation with their types intact. The common parser refuses documents containing them before either status or mutation -proceeds, including nested arrays and inline tables. Quoted date strings remain supported. +proceeds, including nested arrays and inline tables. Quoted date strings remain supported. YAML serializers quote leading-dot numeric strings, including exponent forms, in keys and values to preserve their string types. ## Catalog visibility diff --git a/tests/clients/integrations-serialize.test.ts b/tests/clients/integrations-serialize.test.ts index 74d21e81399..11c3128fe80 100644 --- a/tests/clients/integrations-serialize.test.ts +++ b/tests/clients/integrations-serialize.test.ts @@ -66,6 +66,15 @@ describe("renderYaml", () => { expect(renderYaml({ a: {}, b: [] })).toBe("a: {}\nb: []\n"); }); + test.each([".5", ".0", ".5e2", ".5e-2"])("preserves numeric-looking string %s in keys and values", value => { + const doc = { [value]: value, nested: { value }, items: [value, { [value]: value }] }; + expect(Bun.YAML.parse(serializeDocument(doc, "yaml"))).toEqual(doc); + }); + + test("keeps leading-dot paths readable and actual fractions numeric", () => { + expect(renderYaml({ path: ".config", fraction: 0.5 })).toBe("path: .config\nfraction: 0.5\n"); + }); + test("renders the values YAML actually allows", () => { /* * These renderers used to see only our own builder output, so anything From ad4de2c10a750e1548a0273f0324f7d487741b57 Mon Sep 17 00:00:00 2001 From: Oliver Mee <102673257+oliver-mee@users.noreply.github.com> Date: Sat, 28 Nov 2026 01:35:12 +0800 Subject: [PATCH 03/64] docs(cli): point operators to the next inspection (#9155) --- docs-site/src/content/docs/reference/cli.md | 6 +++ skills/ocx/references/03_recipes.md | 9 ++++ skills/ocx/references/05_remote_hub.md | 4 ++ src/cli/help.ts | 53 +++++++++++++++++++++ tests/cli/cli-help-navigation.test.ts | 27 +++++++++++ 5 files changed, 99 insertions(+) diff --git a/docs-site/src/content/docs/reference/cli.md b/docs-site/src/content/docs/reference/cli.md index 58910cbf81e..c511407b637 100644 --- a/docs-site/src/content/docs/reference/cli.md +++ b/docs-site/src/content/docs/reference/cli.md @@ -263,6 +263,12 @@ ocx help models ocx help models preset show ``` +For account pools, configuration, remote connections, models, and providers, +the family help's **Inspect first** line gives a read-only starting point and +identifies whether it inspects local settings or the running service. A read-only +command can still check a connection. Live catalogue reads can fetch upstream and +reconcile discovery state; use the local view or recorded arrivals for passive inspection. + Read the corresponding chapter in the repository's `skills/ocx/references/01_management_surface.md` or one of the public command-family pages above. Full `ocx help --all` is an escape to the top-level reference. A broad machine inventory is optional: diff --git a/skills/ocx/references/03_recipes.md b/skills/ocx/references/03_recipes.md index f27498ed975..092f09605cd 100644 --- a/skills/ocx/references/03_recipes.md +++ b/skills/ocx/references/03_recipes.md @@ -477,6 +477,12 @@ ocx models new-arrivals --json The provider read may report `inherit`; omission of `--provider` selects global policy. Recent arrivals show recorded discovery state, not a fresh upstream probe. +For a missing model, start with `ocx models list --provider --json` +for the local view and `ocx models new-arrivals --json` for recorded discoveries. +If you need to compare the live selection and available catalogue, use +`ocx models selected --json`. This may fetch upstream and reconcile +discovery state; it is not a passive snapshot. An available model is not proof +that the intended client has synced it or that a completion will succeed. ## 12. Inspect and dry-run an existing routing profile @@ -705,6 +711,9 @@ ocx account pool anthropic --json The target's `supported` list decides which fields can be written. Preserve null, `enabledEffective`, and optional `inert`: null is not false, stored policy is not proof of an available account, and threshold zero is not the pool enable switch. +For the OpenAI roster and observed selection, read `ocx account list openai --json` +separately; the pool policy read does not report which account a bound conversation +will use. Do not add `--quota --refresh` merely to verify a policy setting. OpenAI has no pool `--enabled` or `--quota-window` writer. `reset-first` is for OpenAI and generic OAuth pools. `reset-near-weighted` is for Codex and Anthropic pools and weights new assignments toward the nearest qualifying weekly reset. `least-loaded` is Kiro-only. Anthropic pool windows are diff --git a/skills/ocx/references/05_remote_hub.md b/skills/ocx/references/05_remote_hub.md index 7cd8f0b1b02..1c2b722ed63 100644 --- a/skills/ocx/references/05_remote_hub.md +++ b/skills/ocx/references/05_remote_hub.md @@ -15,6 +15,10 @@ local admin token admits the CLI read, and the Hub verifies the enrolled relay c The relayed dashboard can sign out its own Hub GUI session. Use the Hub dashboard directly for other management writes and reads outside the allowlist. Local config and local Lab commands still refer to this machine's files. +`ocx config show --source` explains the local config load. Check `source`, +`error`, and `warnings` rather than treating exit 0 as validation success; +it is not a dump of effective live settings on the Home. Use the feature's own +read command on the intended management host for that question. Read connection status again after an authorized connect, rotation or disconnect. A saved connection, completed catalog transfer, client-file rewrite and healthy diff --git a/src/cli/help.ts b/src/cli/help.ts index fb976c764bf..30b71d34f6d 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -134,6 +134,55 @@ export function hasHelpFlag(values: string[]): boolean { return values.some(value => value === "--help" || value === "-h" || value === "help"); } +// Human-readable navigation only: keep the versioned capability payload and command grammar unchanged. +const OPERATOR_HELP_GUIDANCE: Readonly> = { + account: [ + "Inspect first: ocx account pool openai --json", + "This reads live pool policy, not account availability. Read the roster and selection with ocx account list openai --json.", + "Operating guide: recipe 17, Inspect pool policy before changing account scope.", + ], + "account strategy": [ + "Inspect first: ocx account pool openai --json", + "For Codex: quota prefers lower usage when choosing a replacement; fill-first keeps placing new work on the active account until its threshold, cooldown, or unavailability; round-robin spreads new work across eligible accounts.", + "Reset-first prefers the nearest future five-hour or weekly reset among eligible accounts with threshold headroom; reset-near-weighted gives accounts closer to reset more weight for new work.", + "These choices are for new or unbound Codex work. Existing bindings follow affinity and recovery policy. Strategy support varies by provider.", + ], + "account pool": [ + "Inspect first: ocx account pool openai --json", + "Omit policy flags to read the selected runtime without changing it. Check supported and effective values before choosing flags.", + "Compare placement strategies: ocx help account strategy", + ], + config: [ + "Inspect first: ocx config show --source", + "This explains how the local settings were loaded; it is not a complete view of the running proxy. For live settings, start with the relevant feature's status command.", + ], + "config get": [ + "Inspect first: ocx config show --source", + "Reads validated local settings, which may include defaults, not the running hub's feature status.", + "Setting meanings and defaults: https://opencodex.me/reference/configuration/", + ], + connect: [ + "Inspect first: ocx connect status --json", + "Check the saved/local link and the reported readiness separately. Being connected does not make every management command target the remote server.", + "Operating guide: Remote hub, Discover locally, manage the intended machine.", + ], + models: [ + "Inspect first: ocx models list --json", + "This is a local model view. For recorded discoveries use ocx models new-arrivals --json; live catalogue reads such as models selected may fetch upstream and reconcile discovery state.", + "Operating guide: recipe 11, Choose a model preset and inspect new arrivals.", + ], + "models new-policy": [ + "Inspect first: ocx models new-policy --json", + "Add --provider to inspect the provider policy before changing it. This read does not refresh discovery.", + "Without an allowlist, off disables new arrivals and on leaves them eligible. admit extends custom selections without widening preset-derived selections.", + ], + provider: [ + "Inspect first: ocx provider snapshot --json", + "This reads the running proxy's non-secret provider configuration, not provider reachability. Use ocx provider show for authored local settings.", + "Operating guide: recipe 6, Save locally or change the running provider configuration.", + ], +}; + function printCapabilityDetails(capability: Capability, write: (text: string) => void, shown: readonly string[] = []): void { if (capability.flags.length) { write("\nDeclared flags:"); @@ -165,6 +214,8 @@ export function printSubcommandUsage( if (result.kind === "entry") { write(`Usage: ${result.entry.usage}\n\n${result.entry.summary}`); if (result.entry.details?.length) write(`\n${result.entry.details.join("\n")}`); + const guidance = OPERATOR_HELP_GUIDANCE[result.canonicalName]; + if (guidance) write(`\n${guidance.join("\n")}`); if (result.capability) printCapabilityDetails(result.capability, write, result.entry.details); if (result.children.length) { write("\nDeclared commands (incomplete):"); @@ -180,6 +231,8 @@ export function printSubcommandUsage( const { capability } = result; const heading = capability.usage !== undefined ? `Usage: ${capability.usage}` : `Command: ocx ${result.path.join(" ")}`; write(`${heading}\n\n${capability.summary}`); + const guidance = OPERATOR_HELP_GUIDANCE[capability.command.join(" ")]; + if (guidance) write(`\n${guidance.join("\n")}`); printCapabilityDetails(capability, write); if (result.children.length) { write("\nDeclared commands (incomplete):"); diff --git a/tests/cli/cli-help-navigation.test.ts b/tests/cli/cli-help-navigation.test.ts index 2e78ed8e490..357207f86a2 100644 --- a/tests/cli/cli-help-navigation.test.ts +++ b/tests/cli/cli-help-navigation.test.ts @@ -42,6 +42,33 @@ function run(args: string[], columns = "80") { } describe("CLI help navigation", () => { + test.each([ + ["account", "ocx account pool openai --json", "not account availability"], + ["config", "ocx config show --source", "not a complete view of the running proxy"], + ["connect", "ocx connect status --json", "does not make every management command"], + ["models", "ocx models list --json", "may fetch upstream and reconcile discovery state"], + ["provider", "ocx provider snapshot --json", "not provider reachability"], + ])("family help for %s gives the next inspection and its scope", (family, next, scope) => { + const result = run(["help", family]); + expect(result.status).toBe(0); + expect(result.stderr).toBe(""); + expect(result.stdout).toContain(`Inspect first: ${next}`); + expect(result.stdout).toContain(scope); + }); + + test.each([ + [["account", "strategy"], "ocx account pool openai --json", "Existing bindings follow affinity and recovery policy"], + [["account", "pool"], "ocx account pool openai --json", "supported"], + [["config", "get"], "ocx config show --source", "validated local settings"], + [["models", "new-policy"], "ocx models new-policy --json", "off disables new arrivals"], + ])("leaf help for %j gives a read-only next step", (path, next, context) => { + const result = run(["help", ...path]); + expect(result.status).toBe(0); + expect(result.stderr).toBe(""); + expect(result.stdout).toContain(`Inspect first: ${next}`); + expect(result.stdout).toContain(context); + }); + test("compact root fits 28 lines and provides the three discovery escapes", () => { const output = capture(printUsage); expect(output.split("\n").length).toBeLessThanOrEqual(28); From fd8e6edb1b3f7aed78db050c9bd56a760ccdc7fa Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 02:37:58 +0900 Subject: [PATCH 04/64] chore(deps): update Hono to 4.13.23 and clear MCP transport advisories (#9177) * chore(deps): update Hono for CVE-2026-137484 * chore(deps): take Hono to 4.13.23 for the 2026-11-26 advisories 4.13.18 clears GHSA-39q9-qp46-w8xg, GHSA-74fm-fwc7-3fwp, GHSA-92p4-j3wq-jmqx and GHSA-h25j-2p75-qj33, but three advisories published on 2026-11-26 (GHSA-586x-c76g-h528, GHSA-656w-x92q-369m, GHSA-mhwf-w6q6-q58w) are patched only in 4.13.23. The lock integrity matches the registry's published 4.13.23 tarball. Co-authored-by: Nick Davis * chore(deps): clear the remaining MCP transport audit findings The same overrides block still pinned two packages with open advisories: - @hono/node-server 2.1.0 -> 2.1.11 (GHSA-rmxm-3fg6-px4f, GHSA-qv5m-9pm6-hqp3, GHSA-jpvv-r467-5p4w; fixed in 2.1.6). The MCP SDK range ^1.19.9 || ^2.0.5 and the new peer range ^4 || ^5.0.0-0 both accept the pinned versions. - fast-uri ^3.1.7 -> ^3.1.9 (GHSA-w74x-v6f9-j3xg, GHSA-xhq7-xmqj-769h, GHSA-wjr9-j795-jxcr, GHSA-333x-w4r6-6crp), reached via the SDK's ajv. bun audit reports no vulnerabilities after this change. --------- Co-authored-by: Nick Davis --- bun.lock | 12 ++++++------ package.json | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/bun.lock b/bun.lock index cdfea17848a..05a9435fdf0 100644 --- a/bun.lock +++ b/bun.lock @@ -24,17 +24,17 @@ "bun", ], "overrides": { - "@hono/node-server": "2.1.0", + "@hono/node-server": "2.1.11", "body-parser": "2.4.0", - "fast-uri": "^3.1.7", - "hono": "4.13.13", + "fast-uri": "^3.1.9", + "hono": "4.13.23", "ip-address": "^10.7.4", "qs": "^6.16.1", }, "packages": { "@bufbuild/protobuf": ["@bufbuild/protobuf@2.14.0", "", {}, "sha512-C3UGsiCwSprE2NKIIFA3hCDlpXTMCAXRZuEVp88L1GY36Y41+rYL5fryE+nOFhp4p4JPQvdV8PQ4DWgHgeTE+w=="], - "@hono/node-server": ["@hono/node-server@2.1.0", "", { "peerDependencies": { "hono": "^4" } }, "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg=="], + "@hono/node-server": ["@hono/node-server@2.1.11", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog=="], "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.1", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw=="], @@ -192,7 +192,7 @@ "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], - "fast-uri": ["fast-uri@3.1.8", "", {}, "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg=="], + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], @@ -212,7 +212,7 @@ "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], - "hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="], + "hono": ["hono@4.13.23", "", {}, "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg=="], "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], diff --git a/package.json b/package.json index d7a70991f55..77dfec1d1d6 100644 --- a/package.json +++ b/package.json @@ -102,10 +102,10 @@ "wreq-js": "2.3.1" }, "overrides": { - "@hono/node-server": "2.1.0", + "@hono/node-server": "2.1.11", "body-parser": "2.4.0", - "fast-uri": "^3.1.7", - "hono": "4.13.13", + "fast-uri": "^3.1.9", + "hono": "4.13.23", "ip-address": "^10.7.4", "qs": "^6.16.1" }, From a41e7ffcbc3db9a5ae039d8da10ff914e87cb07e Mon Sep 17 00:00:00 2001 From: Shu Chen Date: Fri, 27 Nov 2026 12:38:09 -0500 Subject: [PATCH 05/64] fix(responses): use body prompt_cache_key as session_id when no session header is sent (#9137) (#9145) --- .../content/docs/reference/proxy-formats.md | 7 ++ src/server/caller-session-identity.ts | 17 ++-- src/server/request-log-conversation.ts | 28 ++++++ src/server/responses/request-prepare.ts | 14 +-- structure/data-planes/inbound-compat.md | 2 +- tests/server/caller-session-identity.test.ts | 89 ++++++++++++++++++- tests/server/caller-session-ingress.test.ts | 37 ++++++++ 7 files changed, 178 insertions(+), 16 deletions(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 83968a30c8c..d31d2a60d79 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -354,6 +354,13 @@ Use distinct markers for distinct conversations. This preserves conversation con for downstream consumers, but does not guarantee an upstream cache hit or measured savings. WebSocket frames, compact, and count_tokens do not use this promotion. +A Responses client that sends neither a session header nor `x-session-id` can name its +conversation with the body `prompt_cache_key` instead. On `POST /v1/responses`, over HTTP and +WebSocket frames, opencodex then uses that key as `session_id` under the same character rules +and the same loopback and principal scoping as a promoted `x-session-id`, so ChatGPT-backed +models can reuse the warmed prompt prefix. Any session header or `x-session-id` the client +sends wins, and Chat Completions and Messages requests keep their own identity rules. + On canonical ChatGPT-backed Responses dispatch, a non-empty explicit `session_id` wins. Otherwise, the first non-empty alias among `session-id`, then `thread-id`, supplies `session_id` if its value is safe; an invalid winning alias suppresses weaker identity. diff --git a/src/server/caller-session-identity.ts b/src/server/caller-session-identity.ts index d1254e47085..6ccd4455f15 100644 --- a/src/server/caller-session-identity.ts +++ b/src/server/caller-session-identity.ts @@ -15,16 +15,19 @@ export function callerSessionId(headers: Headers): string | undefined { } /** Authenticated callers share continuity only within their trusted credential principal. */ +export function principalScopedSessionId(conversation: string, admission: DataPlaneAdmission): string | undefined { + if (admission.kind === "loopback") return conversation; + const principal = contextPrincipalIdOf(admission); + if (!principal) return undefined; + return new Bun.CryptoHasher("sha256") + .update(JSON.stringify(["opencodex-caller-session-v1", principal, conversation])).digest("hex"); +} + export function withCallerSessionIdentity(req: Request, admission: DataPlaneAdmission): Request { const conversation = callerSessionId(req.headers); if (!conversation) return req; - let sessionId = conversation; - if (admission.kind !== "loopback") { - const principal = contextPrincipalIdOf(admission); - if (!principal) return req; - sessionId = new Bun.CryptoHasher("sha256") - .update(JSON.stringify(["opencodex-caller-session-v1", principal, conversation])).digest("hex"); - } + const sessionId = principalScopedSessionId(conversation, admission); + if (!sessionId) return req; const headers = new Headers(req.headers); headers.set("session_id", sessionId); // Preserve the unread body stream and propagate the original request's abort signal. diff --git a/src/server/request-log-conversation.ts b/src/server/request-log-conversation.ts index 61745f2ac67..d26dd6b3ed2 100644 --- a/src/server/request-log-conversation.ts +++ b/src/server/request-log-conversation.ts @@ -5,6 +5,7 @@ import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto"; import type { OcxConfig } from "../types"; import { resolveContextPrincipal, type DataPlaneAdmission } from "./auth-cors"; +import { principalScopedSessionId, safeCallerSessionId } from "./caller-session-identity"; /** Reject absurdly long client strings before hashing (DoS / JSONL bloat). */ export const LOG_CONVERSATION_ID_INPUT_MAX = 4096; @@ -216,6 +217,33 @@ export function conversationIdFromResponsesRequest(input: { ); } +/** + * A Responses caller that names its conversation only through the body `prompt_cache_key` + * (Oh My Pi, for one) sends no session header, so its turns bound no affinity lane and reached + * the ChatGPT Codex backend without the `session_id` it keys prefix reuse on (#9137). The body is + * read after ingress, so the key is promoted onto the request's own headers there. Any session + * header the caller sent, `x-session-id` included, wins, and authenticated callers are scoped to + * their principal exactly as an `x-session-id` is. + */ +export function promotePromptCacheKeySession( + headers: Headers, + body: unknown, + admission: DataPlaneAdmission | undefined, +): string | undefined { + if (!admission || !body || typeof body !== "object" || Array.isArray(body)) return undefined; + if (["session_id", "session-id", "thread-id", "x-session-id"].some(name => headers.has(name))) return undefined; + const key = (body as { prompt_cache_key?: unknown }).prompt_cache_key; + const conversation = typeof key === "string" ? safeCallerSessionId(key) : undefined; + const sessionId = conversation ? principalScopedSessionId(conversation, admission) : undefined; + if (!sessionId) return undefined; + try { + headers.set("session_id", sessionId); + } catch { + return undefined; + } + return sessionId; +} + /** * Hermes Agent session affinity header for log correlation (#330). * Kept separate from runtime/session identities so it cannot affect lanes or routing. diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index abcafd661cd..ffcee22706a 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -51,13 +51,9 @@ import { toolLoopPinnedPick, } from "./combo-tool-loop-pin"; import { - sessionLaneIdFromRequest, - conversationIdFromResponsesRequest, - assignNativeLogConversationId, - fillHermesLogConversationFallback, - nativeLogConversationIdFromHeaders, - sessionIdHeaderFromRequest, - reasoningReplayConversationIdFromResponsesRequest, + sessionLaneIdFromRequest, conversationIdFromResponsesRequest, assignNativeLogConversationId, + fillHermesLogConversationFallback, nativeLogConversationIdFromHeaders, sessionIdHeaderFromRequest, + promotePromptCacheKeySession, reasoningReplayConversationIdFromResponsesRequest, } from "../request-log-conversation"; import { contextPrincipalIdOf, resolveContextPrincipal } from "../auth-cors"; import { responseTurnMembership } from "./turn-membership"; @@ -299,6 +295,10 @@ export async function prepareResponsesRequest( : options.promptCacheKeyIsSharedCohort === false ? "metadata-derived" : "caller", contextPrincipalIdOf(options.admission), ); + // After the diagnostic above: a body prompt_cache_key stands in for a missing session header (#9137). + if (inboundWire === "responses" && options.promptCacheKeyIsSharedCohort !== true) { + promotePromptCacheKeySession(req.headers, body, options.admission); + } if (!concreteSelection && !options.compactionRoutingOverride && inboundWire === "responses") { options.compactionRoutingOverride = applyCompactionRoutingOverride(body, req.headers, config, { endpoint: "responses", diff --git a/structure/data-planes/inbound-compat.md b/structure/data-planes/inbound-compat.md index 7503398f5a1..775f8006546 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -231,7 +231,7 @@ caller values are forwarded like an explicit `session_id`, without principal sco promoted `x-session-id`. Original ingress headers and affinity computation are unchanged, as are custom and API-key destinations. No identity or originator is invented for marker-free requests. -`src/server/caller-session-identity.ts` promotes validated `x-session-id` on HTTP Responses, Messages and Chat Completions before turn admission in `src/server/index/serve-options.ts`. Explicit `session_id`, `session-id`, or `thread-id` presence wins, including empty values; managed Grok promotion runs first on Responses. The trimmed marker must start with an ASCII letter/digit, contain only letters, digits, dots, underscores, colons or hyphens, and stay within 128 characters. Loopback admission keeps it; authenticated admission scopes it with the trusted credential principal into an opaque SHA-256 identifier and skips promotion without that principal. Bodies and abort signals are preserved, and the original Request owns Bun timeout lookup. This provides continuity, not authorization or guaranteed cache hits. Existing explicit/Grok identities, WebSocket frames, compact and count_tokens retain their behavior. +`src/server/caller-session-identity.ts` promotes validated `x-session-id` on HTTP Responses, Messages and Chat Completions before turn admission in `src/server/index/serve-options.ts`. Explicit `session_id`, `session-id`, or `thread-id` presence wins, including empty values; managed Grok promotion runs first on Responses. The trimmed marker must start with an ASCII letter/digit, contain only letters, digits, dots, underscores, colons or hyphens, and stay within 128 characters. Loopback admission keeps it; authenticated admission scopes it with the trusted credential principal into an opaque SHA-256 identifier and skips promotion without that principal. Bodies and abort signals are preserved, and the original Request owns Bun timeout lookup. This provides continuity, not authorization or guaranteed cache hits. Existing explicit/Grok identities, WebSocket frames, compact and count_tokens retain their behavior. `promotePromptCacheKeySession` in `src/server/request-log-conversation.ts` covers Responses callers that send only a body `prompt_cache_key` (#9137). `src/server/responses/request-prepare.ts` calls it once the body is read, after the inbound cache diagnostic, for genuine Responses inbound (`inboundWire === "responses"`, HTTP and WebSocket frames) that is not a shared Claude cohort. It sets `session_id` on the request's own headers only when no `session_id`, `session-id`, `thread-id` or `x-session-id` is present, with the same marker rules and loopback/principal scoping as `x-session-id`. Turn admission has already run, so the key does not change admission lanes. ## Chat conversation identity forwarding diff --git a/tests/server/caller-session-identity.test.ts b/tests/server/caller-session-identity.test.ts index ea628880dea..d46855c6ba8 100644 --- a/tests/server/caller-session-identity.test.ts +++ b/tests/server/caller-session-identity.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { callerSessionId, withCallerSessionIdentity } from "../../src/server/caller-session-identity"; import { resolveDataPlaneAdmissionSecret, type DataPlaneAdmission } from "../../src/server/auth-cors"; -import { sessionLaneIdFromRequest } from "../../src/server/request-log-conversation"; +import { promotePromptCacheKeySession, sessionLaneIdFromRequest } from "../../src/server/request-log-conversation"; import { captureConfigGeneration } from "../../src/lib/state-store-sweeper"; import { clearComboRecallForTests, recallComboForLane, rememberComboForLane } from "../../src/server/responses/combo-session-recall"; import { withGrokSessionIdentity } from "../../src/grok/session-identity"; @@ -162,6 +162,93 @@ describe("Non-Codex callers reach the ChatGPT Codex backend with session_id", () expect(logCtx.conversationId).toBeTruthy(); } finally { lease?.release(); } }); + + // #9137: Oh My Pi sends only a body prompt_cache_key, no session header. + async function sendCacheKeyTurn(headers: Record, inboundWire: "responses" | "chat" = "responses") { + const cfg = { openaiProviderTierVersion: 2, providers: { + openai: { adapter: "openai-responses", authMode: "forward", codexAccountMode: "direct", baseUrl: "https://chatgpt.com/backend-api/codex", models: ["gpt-5.6-luna"] }, + } } as OcxConfig; + let wire: Headers | undefined; + globalThis.fetch = Object.assign(async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init); + if (request.url !== "https://chatgpt.com/backend-api/codex/responses") { + throw new Error("Unexpected outbound request in caller-session fixture"); + } + wire = request.headers; + return Response.json({ id: "resp_cache_key", object: "response", status: "completed", output: [], + usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 } }); + }, { preconnect() { /* No fixture opens an upstream socket. */ } }); + const lease = tryAdmitTurn(); + expect(lease).not.toBeNull(); + try { + const req = new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}`, "user-agent": "omp/19.1.1", ...headers }, + body: JSON.stringify({ model: "openai/gpt-5.6-luna", stream: false, store: false, prompt_cache_key: SESSION, input: "ping" }), + }); + const logCtx = { model: "", provider: "" } as Parameters[2]; + const response = await handleResponses(req, cfg, logCtx, { turnAdmissionLease: lease!, admission: LOOPBACK, inboundWire }); + const text = await response.text(); + expect(response.status, text).toBe(200); + expect(wire).toBeDefined(); + return { wire: wire!, logCtx }; + } finally { lease?.release(); } + } + + test("a body prompt_cache_key stands in for the missing session header", async () => { + const { wire, logCtx } = await sendCacheKeyTurn({}); + expect(wire.get("session_id")).toBe(SESSION); + expect(logCtx.conversationId).toBeTruthy(); + }); + + for (const explicit of ["session_id", "session-id", "thread-id"]) test(`an explicit ${explicit} header wins over prompt_cache_key`, async () => { + const { wire } = await sendCacheKeyTurn({ [explicit]: "explicit-winner" }); + expect(wire.get("session_id")).toBe("explicit-winner"); + }); + + test("a Chat Completions replay keeps its own identity rules", async () => { + const { wire } = await sendCacheKeyTurn({}, "chat"); + expect(wire.get("session_id")).toBeNull(); + }); +}); + +describe("promotePromptCacheKeySession", () => { + const body = (key: unknown) => ({ model: "m", input: "ping", prompt_cache_key: key }); + + test("promotes a safe key on loopback and returns it", () => { + const headers = new Headers(); + expect(promotePromptCacheKeySession(headers, body(` ${SESSION} `), LOOPBACK)).toBe(SESSION); + expect(headers.get("session_id")).toBe(SESSION); + }); + + test("any caller session header, x-session-id included, wins", () => { + for (const name of ["session_id", "session-id", "thread-id", "x-session-id"]) { + const headers = new Headers({ [name]: "caller" }); + expect(promotePromptCacheKeySession(headers, body(SESSION), LOOPBACK)).toBeUndefined(); + expect(headers.get("session_id")).toBe(name === "session_id" ? "caller" : null); + } + }); + + test("ignores missing, empty, unsafe, overlong and non-string keys and non-object bodies", () => { + for (const candidate of [body(undefined), body(""), body(" "), body("a b"), body("x".repeat(129)), body("-leading"), + body(42), body(null), body({ id: SESSION }), body(["x"]), null, "text", [body(SESSION)]]) { + const headers = new Headers(); + expect(promotePromptCacheKeySession(headers, candidate, LOOPBACK)).toBeUndefined(); + expect(headers.has("session_id")).toBe(false); + } + const headers = new Headers(); + expect(promotePromptCacheKeySession(headers, body("x".repeat(128)), LOOPBACK)).toBe("x".repeat(128)); + }); + + test("authenticated callers are scoped to their principal, like x-session-id", () => { + const admission = admitted("cache-key-fixture-a"); + const headers = new Headers(); + const scoped = promotePromptCacheKeySession(headers, body(SESSION), admission); + expect(scoped).toMatch(/^[a-f0-9]{64}$/); + expect(scoped).toBe(promoted(admission).headers.get("session_id")!); + expect(promotePromptCacheKeySession(new Headers(), body(SESSION), admitted("cache-key-fixture-b"))).not.toBe(scoped); + expect(promotePromptCacheKeySession(new Headers(), body(SESSION), { kind: "environment", source: "bearer" })).toBeUndefined(); + expect(promotePromptCacheKeySession(new Headers(), body(SESSION), undefined)).toBeUndefined(); + }); }); test("the public routes hand their handlers the caller-promoted request", () => { diff --git a/tests/server/caller-session-ingress.test.ts b/tests/server/caller-session-ingress.test.ts index f7ac786b470..3efa187ea6d 100644 --- a/tests/server/caller-session-ingress.test.ts +++ b/tests/server/caller-session-ingress.test.ts @@ -97,4 +97,41 @@ describe("caller session identity through admitted HTTP ingress", () => { } }); } + + // #9137: a Responses caller that names its conversation only through prompt_cache_key. + for (const transport of ["responses", "ws"] as const) { + test(`${transport} promotes a body prompt_cache_key when no session header is sent`, async () => { + const fixture = await reserveIngressFixture(); + const blockedFetch = globalThis.fetch; + const wires: Headers[] = []; + globalThis.fetch = Object.assign(async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + if (req.url === "https://chatgpt.com/backend-api/codex/responses") wires.push(req.headers); + return blockedFetch(req); + }, { preconnect() { /* No fixture opens an upstream socket. */ } }); + try { + const cacheKey = { prompt_cache_key: "omp-cache-key-1" }; + const local = await fixture.request("local", transport, "openai/gpt-5.6-luna", { authorization: `Bearer ${ACCESS}` }, cacheKey); + expect(local.status, local.text).toBe(200); + expect(wires.at(-1)!.get("session_id")).toBe("omp-cache-key-1"); + + const headers = { "x-opencodex-api-key": PROXY_KEY, authorization: `Bearer ${ACCESS}` }; + const first = await fixture.request("public", transport, "openai/gpt-5.6-luna", headers, cacheKey); + expect(first.status, first.text).toBe(200); + const scoped = wires.at(-1)!.get("session_id"); + expect(scoped).toMatch(/^[a-f0-9]{64}$/); + const second = await fixture.request("public", transport, "openai/gpt-5.6-luna", headers, cacheKey); + expect(second.status, second.text).toBe(200); + expect(wires.at(-1)!.get("session_id")).toBe(scoped); + + const explicit = await fixture.request("local", transport, "openai/gpt-5.6-luna", + { authorization: `Bearer ${ACCESS}`, session_id: "explicit-winner" }, cacheKey); + expect(explicit.status, explicit.text).toBe(200); + expect(wires.at(-1)!.get("session_id")).toBe("explicit-winner"); + } finally { + globalThis.fetch = blockedFetch; + await fixture.close(); + } + }); + } }); From 26aa2b01ac461ae67f53becc1d13f7b0d0ca1446 Mon Sep 17 00:00:00 2001 From: Muhammet Alan Date: Fri, 27 Nov 2026 20:38:17 +0300 Subject: [PATCH 06/64] fix(anthropic): keep the sidecar web_search prefix during routed compaction (#9173) * fix(anthropic): keep the sidecar web_search prefix during routed compaction A routed Anthropic summary deleted the caller's hosted web_search before planning, so it lacked the synthetic web_search tool, the tool names in the system tool contract and the replayed search pairs that the ordinary turn before it carried. Anthropic caches tools, system and messages in that order, so every such compaction rewrote the whole cached prompt. A prefix-preserving summary now resolves the search helper and plans like the ordinary turn, declares the same tool through a shared catalog helper and restores replayed searches instead of stripping them. It never searches, and the probe lease is released. Refs #7307 Co-Authored-By: Claude Opus 5.5 * test(anthropic): cover the ChatGPT helper path for compaction web_search Exercise the default search helper on a routed summary: the summary must declare the same tool, carry the recorded result of a replayed search and release the probe lease without dispatching a search. Each of these lines can now be removed only with a failing test. Update the adapter reference and the failover structure note, which still said a sidecar search tool changes the prefix on compaction, and drop a runTurn guard that the anthropic-only stash already implies. Refs #7307 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../src/content/docs/reference/adapters.md | 6 +- src/server/responses/request-sidecar-auth.ts | 4 +- src/server/responses/response-effects.ts | 3 + src/server/responses/sidecar-execution.ts | 35 ++++- src/types/request.ts | 6 + structure/transports/responses-failover.md | 2 +- ...ponses-anthropic-compaction-prefix.test.ts | 124 ++++++++++++++++-- 7 files changed, 157 insertions(+), 23 deletions(-) diff --git a/docs-site/src/content/docs/reference/adapters.md b/docs-site/src/content/docs/reference/adapters.md index fe68ba10d8e..1d5c375bd6e 100644 --- a/docs-site/src/content/docs/reference/adapters.md +++ b/docs-site/src/content/docs/reference/adapters.md @@ -481,8 +481,10 @@ a JEV combo's `decisionProvider` (see [Combos](/guides/combos/)). - Routed Codex compaction keeps the client tool catalog, system prompt and tool-selection options to preserve their prompt-cache prefix. Summary requests disable search/media sidecars; upstream-hosted tools retain their declarations with `tool_choice: none`, as does a - mandatory tool choice, while the advertised catalog stays the same. A request that advertises a - sidecar web-search tool (for example Exa) still changes its tool prefix on compaction. + mandatory tool choice, while the advertised catalog stays the same. When the ordinary turn + would declare the sidecar `web_search` tool (for example Exa or the ChatGPT helper), the summary + declares the same tool and keeps the replayed searches with their recorded results, but never + searches. A summary that attempts a tool call fails without publishing a function call or replacing history. A successful summary returns exactly one compaction item. With image-context recovery off, requests continue to use the existing image normalization and single tighter-image retry after HTTP 413. diff --git a/src/server/responses/request-sidecar-auth.ts b/src/server/responses/request-sidecar-auth.ts index 985d5a26bd2..93de561d002 100644 --- a/src/server/responses/request-sidecar-auth.ts +++ b/src/server/responses/request-sidecar-auth.ts @@ -179,7 +179,9 @@ export async function prepareResponsesSidecarAuth( // LOCAL PATCH (runturn-websearch): runTurn adapters can run the web-search // sidecar through src/web-search/run-turn-loop.ts, so resolve the helper // credential for them too. The passthrough bridge stays fetch-only. - const needsOpenAiSearch = !routedCompaction + // A prefix-preserving summary resolves the helper like the ordinary turn, only to decide whether + // the synthetic web_search is declared; it never searches (#7307). + const needsOpenAiSearch = (!routedCompaction || preserveCompactionPrefix) && (transportState.adapter.runTurn ? shouldResolveOpenAiWebSearchSidecar(config, parsed, isPassthrough) : (shouldResolveOpenAiWebSearchSidecar(config, parsed, isPassthrough) diff --git a/src/server/responses/response-effects.ts b/src/server/responses/response-effects.ts index 1aa78ac03d8..51ec54770ad 100644 --- a/src/server/responses/response-effects.ts +++ b/src/server/responses/response-effects.ts @@ -90,6 +90,9 @@ export function createResponsesEffects( } }; if (routedCompaction) { + // The summary never searches. With a preserved prefix it still declares the synthetic tool an + // ordinary turn declares; the sidecar step decides that from the same plan (#7307). + if (preserveCompactionPrefix && parsed._webSearch) parsed._summaryWebSearch = parsed._webSearch; delete parsed._webSearch; if (!preserveCompactionPrefix) { delete parsed.context.tools; diff --git a/src/server/responses/sidecar-execution.ts b/src/server/responses/sidecar-execution.ts index ea88fa6476d..77e17415a44 100644 --- a/src/server/responses/sidecar-execution.ts +++ b/src/server/responses/sidecar-execution.ts @@ -66,10 +66,21 @@ import { rememberResponseState } from "../../responses/state"; import { trackStreamLifetime } from "../lifecycle"; import { isAntigravityRawValidationRefusal } from "./antigravity-validation-refusal"; import { createSidecarSendBudget } from "./sidecar-send-budget"; -import { stripReplayedSearchPairs } from "../../web-search/sidecar-search-replay"; +import { restoreSidecarSearchResults, stripReplayedSearchPairs } from "../../web-search/sidecar-search-replay"; import { providerConnectTimeoutMs, providerStallTimeoutSec } from "../../stall-timeout"; import { settleAnthropicPerMessageEffort, shareAnthropicPerMessageEffortTurn } from "../../adapters/anthropic/per-message-effort"; +type RoutedTool = NonNullable[number]; + +/** The catalog a web-search sidecar turn sends: caller tools, the synthetic tool, then the advisor. */ +function webSearchTurnTools(requested: readonly RoutedTool[], advisorTool?: RoutedTool): RoutedTool[] { + return [ + ...requested.filter(tool => !advisorTool || (!tool.advisor && tool.name !== ADVISOR_TOOL_NAME)), + buildWebSearchTool(), + ...(advisorTool ? [advisorTool] : []), + ]; +} + /** One responsibility of the Responses request pipeline; state owners are explicit. */ export async function executeResponsesSidecars( requestContext: Pick, @@ -297,9 +308,23 @@ export async function executeResponsesSidecars( routedTransport: transportState.adapter.runTurn ? "runTurn" : "http", }) : undefined; + // A prefix-preserving summary plans like the ordinary turn but never searches: it declares the + // same synthetic tool and keeps the same replayed searches, so Anthropic reads the ordinary + // request's cached prefix instead of rewriting it (#7307). + const summaryWsPlan = routedCompaction && parsed._summaryWebSearch + ? planWebSearch(config, { ...parsed, _webSearch: parsed._summaryWebSearch }, false, route.provider, route.modelId, + openAiSidecar, { admission: options.admission, codexAuthPolicy: options.codexAuthPolicy, + providerName: route.providerName, routedTransport: "http" }) + : undefined; + delete parsed._summaryWebSearch; + if (summaryWsPlan) { + parsed.context.tools = webSearchTurnTools(parsed.context.tools ?? []); + restoreSidecarSearchResults(parsed); + } + if (routedCompaction) releaseSearchProbeLease(); const imgPlan = !routedCompaction ? await planImageBridge(config, parsed, route.provider) : undefined; // Replayed search pairs call the synthetic web_search tool only the sidecar declares (#7269). - if (!wsPlan) stripReplayedSearchPairs(parsed); + if (!wsPlan && !summaryWsPlan) stripReplayedSearchPairs(parsed); const vidPlan = !routedCompaction ? await planVideoBridge(config, parsed, route.provider) : undefined; // Hosted loops rebuild per iteration from spread copies; they share one per-message effort turn (#6895). if (wsPlan || imgPlan || vidPlan) shareAnthropicPerMessageEffortTurn(parsed); @@ -823,11 +848,7 @@ export async function executeResponsesSidecars( && typeof advisorPlan.consult === "function" && typeof advisorPlan.formatUnavailable === "function" ? advisorPlan : undefined; - parsed.context.tools = [ - ...requestedTools.filter(tool => !webSearchAdvisor || (!tool.advisor && tool.name !== ADVISOR_TOOL_NAME)), - buildWebSearchTool(), - ...(webSearchAdvisor ? [webSearchAdvisor.tool] : []), - ]; + parsed.context.tools = webSearchTurnTools(requestedTools, webSearchAdvisor?.tool); if (webSearchAdvisor) { withholdShadowedAdvisorTool(); requestState.toolBridgeMaps = buildToolBridgeMaps(parsed); diff --git a/src/types/request.ts b/src/types/request.ts index 426bedeaa35..9ed2989f51b 100644 --- a/src/types/request.ts +++ b/src/types/request.ts @@ -86,6 +86,12 @@ export interface OcxParsedRequest { * would (prompt-cache prefix), then send tool_choice none so no client or hosted tool runs. */ _summaryProhibitsToolCalls?: boolean; + /** + * Routed Anthropic compaction summary: the caller's hosted web_search, kept aside from + * `_webSearch` so the summary declares the synthetic tool the ordinary request would declare + * without ever running the sidecar (#7307). + */ + _summaryWebSearch?: Record; /** * Completed server-tool exchanges from the Claude client's history, keyed by the block that * followed them (`call:` / `text:`). Same audience as `_anthropicServerTools`. diff --git a/structure/transports/responses-failover.md b/structure/transports/responses-failover.md index 2320798eb11..e6e66355469 100644 --- a/structure/transports/responses-failover.md +++ b/structure/transports/responses-failover.md @@ -282,7 +282,7 @@ Search/media sidecar execution stays disabled; Anthropic server-tool declaration with wire `tool_choice: none` when server tools exist, preventing upstream execution. [Anthropic prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#what-invalidates-the-cache) orders the prefix as tools, system, messages: changing tool definitions invalidates all three; -changing tool choice invalidates message cache only. Client-only summaries keep an optional choice unchanged; a mandatory choice (required, named, or required allowed tools) keeps the caller's choice for catalog derivation and sets `_summaryProhibitsToolCalls`; `src/adapters/anthropic.ts` builds tools and system from that choice, provider name transforms included, then sends `tool_choice: none`, so tools and system stay byte-identical. Search sidecar declarations are not injected for summaries, so a request whose ordinary turn advertised a sidecar search tool still changes its tool prefix. +changing tool choice invalidates message cache only. Client-only summaries keep an optional choice unchanged; a mandatory choice (required, named, or required allowed tools) keeps the caller's choice for catalog derivation and sets `_summaryProhibitsToolCalls`; `src/adapters/anthropic.ts` builds tools and system from that choice, provider name transforms included, then sends `tool_choice: none`, so tools and system stay byte-identical. A summary plans the search sidecar exactly as the ordinary turn would (`src/server/responses/sidecar-execution.ts`, helper resolved by `request-sidecar-auth.ts`): with a plan it declares the same synthetic `web_search` tool and restores replayed search pairs instead of stripping them, then releases the helper probe lease without searching. A proxy advisor's tool is not declared for summaries, so an advisor turn still changes its tool prefix. `src/responses/compaction-summary.ts` suppresses tool/search events and rejects tool attempts, empty summaries and abnormal completions before delivery; only successful prose reaches the single synthetic compaction item. Truncated completions retain the existing incomplete outcome. diff --git a/tests/responses/responses-anthropic-compaction-prefix.test.ts b/tests/responses/responses-anthropic-compaction-prefix.test.ts index cd2e49800a7..5bda608efc3 100644 --- a/tests/responses/responses-anthropic-compaction-prefix.test.ts +++ b/tests/responses/responses-anthropic-compaction-prefix.test.ts @@ -1,7 +1,11 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import * as openAiSidecar from "../../src/providers/openai-sidecar"; +import { clearBridgeSearchReplayCacheForTests } from "../../src/responses/bridge-search-replay-cache"; +import { reasoningReplayConversationIdFromResponsesRequest } from "../../src/server/request-log-conversation"; +import { rememberSidecarSearch } from "../../src/web-search/sidecar-search-replay"; import { createResponsesEffects } from "../../src/server/responses/response-effects"; import { prepareResponsesSidecarAuth } from "../../src/server/responses/request-sidecar-auth"; import type { HandleResponsesOptions } from "../../src/server/responses/core-options"; @@ -304,32 +308,128 @@ describe("Anthropic compaction through Responses delivery", () => { }); } - test("hosted search is prohibited upstream and the configured search sidecar never executes", async () => { + test("a summary keeps the ordinary turn's synthetic web_search declaration and replayed searches (#7307)", async () => { const cfg = config(); cfg.webSearchSidecar = { backend: "exa", exaApiKey: "synthetic-search-key" }; - let primarySends = 0; - let hostedExecutions = 0; + const seen: Array<{ tools: Array<{ name: string }>; system: unknown; tool_choice: unknown; messages: unknown[] }> = []; + globalThis.fetch = (async (input, init) => { + if (!String(input).startsWith("https://api.anthropic.com/")) throw new Error("Neither turn may search"); + const wire = JSON.parse(String(init?.body)); + seen.push(wire); + return upstream(wire.stream === true); + }) as typeof fetch; + const history = [ + { type: "message", role: "user", content: "earlier turn" }, + { type: "web_search_call", id: "ws_replayed", status: "completed", action: { type: "search", query: "synthetic query" } }, + { type: "message", role: "assistant", content: [{ type: "output_text", text: "searched" }] }, + { type: "message", role: "user", content: "next turn" }, + ]; + const ordinary = { ...body(true, false), tools: [...body(true).tools, { type: "web_search" }], input: history }; + await (await send(ordinary, cfg)).text(); + const text = await (await send({ ...ordinary, input: [...history, { type: "compaction_trigger" }] }, cfg)).text(); + expect(text).toContain('"type":"compaction"'); + expect(seen).toHaveLength(2); + const [before, after] = seen as [typeof seen[0], typeof seen[0]]; + expect(before.tools.map(tool => tool.name)).toContain("web_search"); + expect(after.tools).toEqual(before.tools); + expect(after.system).toEqual(before.system); + expect(after.tool_choice).toEqual(before.tool_choice); + // Breakpoints move with the new tail, and a breakpoint turns string content into its single text + // block; Anthropic reads both forms as the same prompt, as consecutive ordinary turns already do. + const content = (messages: unknown[]) => JSON.parse(JSON.stringify(messages, (key, value) => + key === "cache_control" ? undefined + : key === "content" && typeof value === "string" ? [{ type: "text", text: value }] : value)); + expect(content(after.messages).slice(0, before.messages.length)).toEqual(content(before.messages)); + }); + + test("with the default ChatGPT search helper the summary keeps the prefix, recorded searches and the probe lease (#7307)", async () => { + const cfg = config(); + cfg.providers.openai = { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", codexAccountMode: "direct" } as OcxConfig["providers"][string]; + const helper = { released: 0, outcomes: 0, dispatches: 0 }; + const resolver = spyOn(openAiSidecar, "resolveFirstUsableOpenAiSidecar").mockImplementation(async (candidates, headers) => ({ + ...candidates[0]!, authContext: { kind: "main", accountId: null }, headers, + releaseProbeLease: () => { helper.released++; }, + recordOutcome: () => { helper.outcomes++; }, + beforeDispatch: () => { helper.dispatches++; }, + }) as Awaited>); + const seen: Array<{ tools: Array<{ name: string }>; system: unknown; tool_choice: unknown; messages: unknown[] }> = []; + globalThis.fetch = (async (input, init) => { + if (!String(input).startsWith("https://api.anthropic.com/")) throw new Error("Neither turn may search"); + const wire = JSON.parse(String(init?.body)); + seen.push(wire); + return upstream(wire.stream === true); + }) as typeof fetch; + const principal = { clientPrincipalId: "principal-7307" }; + const clientThreadId = reasoningReplayConversationIdFromResponsesRequest({ threadIdHeader: "thread-7307" })!; + rememberSidecarSearch({ _reasoningReplayScope: { ...principal, clientThreadId } }, "ws_recorded", + { id: "toolu_recorded", arguments: { query: "synthetic query" } }, "Recorded result: synthetic answer"); + const history = [ + { type: "message", role: "user", content: "earlier turn" }, + { type: "web_search_call", id: "ws_recorded", status: "completed", action: { type: "search", query: "synthetic query" } }, + { type: "message", role: "assistant", content: [{ type: "output_text", text: "searched" }] }, + { type: "message", role: "user", content: "next turn" }, + ]; + const ordinary = { ...body(true, false), tools: [...body(true).tools, { type: "web_search" }], input: history }; + const post = (input: typeof ordinary) => handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json", "thread-id": "thread-7307" }, body: JSON.stringify(input), + }), cfg, { model: "", provider: "" }, { replayPrincipal: principal }); + try { + await (await post(ordinary)).text(); + const beforeSummary = { ...helper }; + const text = await (await post({ ...ordinary, input: [...history, { type: "compaction_trigger" }] })).text(); + expect(text).toContain('"type":"compaction"'); + expect(resolver).toHaveBeenCalledTimes(2); + expect(helper.released).toBeGreaterThan(beforeSummary.released); + expect(helper.outcomes).toBe(0); + expect(helper.dispatches).toBe(0); + } finally { + resolver.mockRestore(); + clearBridgeSearchReplayCacheForTests(); + } + expect(seen).toHaveLength(2); + const [before, after] = seen as [typeof seen[0], typeof seen[0]]; + expect(before.tools.map(tool => tool.name)).toContain("web_search"); + expect(after.tools).toEqual(before.tools); + expect(after.system).toEqual(before.system); + expect(after.tool_choice).toEqual(before.tool_choice); + expect(JSON.stringify(before.messages)).toContain("Recorded result: synthetic answer"); + const content = (messages: unknown[]) => JSON.parse(JSON.stringify(messages, (key, value) => + key === "cache_control" ? undefined + : key === "content" && typeof value === "string" ? [{ type: "text", text: value }] : value)); + expect(content(after.messages).slice(0, before.messages.length)).toEqual(content(before.messages)); + }); + + test("hosted search is prohibited upstream, the search sidecar never executes, and the summary keeps the ordinary catalog", async () => { + const cfg = config(); + cfg.webSearchSidecar = { backend: "exa", exaApiKey: "synthetic-search-key" }; + const wires: Array<{ tools: unknown[]; system: unknown; tool_choice?: unknown }> = []; let sidecarSends = 0; globalThis.fetch = (async (input, init) => { if (!String(input).startsWith("https://api.anthropic.com/")) { sidecarSends++; - throw new Error("Summary must not dispatch a search sidecar"); + throw new Error("Neither turn may dispatch a search sidecar"); } - primarySends++; const wire = JSON.parse(String(init?.body)); - expect(wire.tools).toContainEqual(expect.objectContaining({ type: "web_search_20250305", name: "web_search" })); - if (wire.tool_choice?.type !== "none") hostedExecutions++; - return upstream(false); + wires.push(wire); + return upstream(wire.stream === true); }) as typeof fetch; const request = { ...body(false), tools: [...body(false).tools, { type: "web_search", name: "web_search", description: "Search", parameters: {} }] }; - const response = await send(request, cfg, { inboundWire: "anthropic", + const options = () => ({ inboundWire: "anthropic" as const, anthropicServerTools: [{ type: "web_search_20250305", name: "web_search" }] }); + await (await send({ ...request, input: body(false, false).input }, cfg, options())).text(); + const response = await send(request, cfg, options()); const result = await response.json(); expect(result).toMatchObject({ status: "completed" }); expect(result.output).toHaveLength(1); expect(result.output[0].type).toBe("compaction"); - expect(primarySends).toBe(1); - expect(hostedExecutions).toBe(0); + expect(wires).toHaveLength(2); + const [ordinary, summary] = wires as [typeof wires[0], typeof wires[0]]; + // The sidecar's synthetic web_search wins the name over the hosted declaration on both turns. + expect(ordinary.tools).toContainEqual(expect.objectContaining({ name: "web_search", input_schema: expect.anything() })); + expect(summary.tools).toEqual(ordinary.tools); + expect(summary.system).toEqual(ordinary.system); + expect(summary.tool_choice).toEqual({ type: "none" }); expect(sidecarSends).toBe(0); }); From cc139c06bddcc460181f6371119d1c4ec5c32ed9 Mon Sep 17 00:00:00 2001 From: Andrew Chen Date: Sat, 28 Nov 2026 01:39:20 +0800 Subject: [PATCH 07/64] fix(windows): recognize Traditional Chinese Task Scheduler states (#9160) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On zh-TW Windows, schtasks prints 就緒, 已停用 and 執行中, none of which the CSV fast path knew, so every checked-stop state read started PowerShell for the Schedule.Service fallback. Add the four zh-TW words from System32\zh-TW\schtasks.exe.mui alongside the zh-CN, ja-JP and ko-KR ones. Queued (已排入佇列) stays active, like the other locales. --- src/service/windows-checked-stop-live.ts | 9 +++++---- structure/ops/windows-checked-stop.md | 2 +- .../windows/windows-checked-stop-live.test.ts | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index 7bd3cd7fe30..655961cbded 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -177,14 +177,15 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, /** * Status words of `schtasks /query /fo CSV /nh`. schtasks localizes the column from its .mui * resources, and the PowerShell fallback cannot start inside Part A's 1 s manager-state cap on a - * cold machine (#8863), so the words observed from shipped resources are read here: zh-CN, ja-JP - * and ko-KR from their System32 locale directories, ko-KR running/ready also from two machines. + * cold machine (#8863), so the words observed from shipped resources are read here: zh-CN, zh-TW, + * ja-JP and ko-KR from their System32 locale directories, ko-KR running/ready also from two machines, + * zh-TW running/ready/disabled also from one. * Any other word stays unknown here and falls back to the numeric TASK_STATE read through the * Schedule.Service COM object, which is locale-independent and imports no module. */ // A queued instance can launch after Part A. Only ready and disabled prove inactivity. -const TASK_CSV_ACTIVE = new Set(["running", "queued", "正在运行", "已排队", "실행 중", "대기", "実行中", "キューに登録済み"]); -const TASK_CSV_NOT_RUNNING = new Set(["ready", "disabled", "就绪", "已禁用", "준비", "사용 안 함", "準備完了", "無効"]); +const TASK_CSV_ACTIVE = new Set(["running", "queued", "正在运行", "已排队", "執行中", "已排入佇列", "실행 중", "대기", "実行中", "キューに登録済み"]); +const TASK_CSV_NOT_RUNNING = new Set(["ready", "disabled", "就绪", "已禁用", "就緒", "已停用", "준비", "사용 안 함", "準備完了", "無効"]); export function parseTaskCsvState(csv: string): "running" | "not-running" | "unknown" { for (const line of csv.split(/\r?\n/)) { diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 1e1a38ee209..bd01351cd6d 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -182,7 +182,7 @@ objects. The final manager-state probe treats both running and queued tasks as a [Instance stop protocol](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsch/b3572584-8727-441f-83e6-9b02101ea7f4) The task's running state is read from `schtasks /query /fo CSV`. The status words observed from shipped -zh-CN, ko-KR, and ja-JP resources are recognized there, because a cold `Get-ScheduledTask` takes +zh-CN, zh-TW, ko-KR, and ja-JP resources are recognized there, because a cold `Get-ScheduledTask` takes 1.6 s to 4.9 s (#8863) and cannot finish inside the 1 s cap. Any other localized word (French `Prêt`, for example) falls back to the numeric `TASK_STATE` read through the `Schedule.Service` COM object, which needs no module import (about 0.3 s including PowerShell startup on the reporting host): 2 and 4 (queued, running) are active, 1 and 3 (disabled, ready) are stopped, and a failed, timed-out or other value stays unknown. The instance stop maps an access-denied HRESULT to `denied`. A running WinSW service is only this home's manager when `sc qc` shows a `BINARY_PATH_NAME` naming this installation's WinSW executable, the same diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index 193807b923d..ae4f2df32aa 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -234,6 +234,24 @@ describe("capped command answers", () => { expect(await deps.taskState(1_000)).toBe(expected); }); + // System32\zh-TW\schtasks.exe.mui: Running, Ready, Queued, Disabled. A zh-TW + // `schtasks /query /fo CSV /nh` prints the first, second and fourth. + test.each([ + ["就緒", "not-running"], + ["已停用", "not-running"], + ["執行中", "running"], + ["已排入佇列", "running"], + ])("zh-TW task state %s is read from the CSV without starting PowerShell", async (status, expected) => { + const deps = windowsCheckedStopLiveDeps({ + run: async (program, args) => { + expect(program).toBe("schtasks"); + expect(args).toEqual(["/query", "/tn", "opencodex-proxy", "/fo", "CSV", "/nh"]); + return result(0, `"\\opencodex-proxy","N/A","${status}"\r\n`); + }, + }); + expect(await deps.taskState(1_000)).toBe(expected); + }); + test("the helper must finish successfully and receive proof approval before reporting success", async () => { const sid = "S-1-5-21-100-200-300-1001"; const xml = buildWindowsTaskXml(undefined, windowsLauncherVbsPath(), undefined, sid) From 8df9b0bc0b2aa424974c20f5c244455b033e5c56 Mon Sep 17 00:00:00 2001 From: Shu Chen Date: Fri, 27 Nov 2026 12:43:53 -0500 Subject: [PATCH 08/64] fix(history): order per-key, conversation and profile indexes by time (#9103) (#9111) --- src/routing/history/schema.ts | 13 ++++-- structure/dashboard-and-usage.md | 2 +- tests/usage/request-history-index.test.ts | 52 +++++++++++++++++++++++ 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/src/routing/history/schema.ts b/src/routing/history/schema.ts index 4d6f0073596..d47990ade84 100644 --- a/src/routing/history/schema.ts +++ b/src/routing/history/schema.ts @@ -8,7 +8,12 @@ // Version 2 rebuilds the derived projection so old raw requested-model selectors // are replaced by the bounded encoding already used by canonical JSONL reads. -export const HISTORY_SCHEMA_VERSION = 2; +// Version 3 orders the conversation, API-key and profile indexes by +// (timestamp DESC, request_id DESC), so a filtered page reads `limit + 1` rows +// in index order instead of sorting every matching row (#9103). The index names +// stay the same: on a version-2 file `CREATE INDEX IF NOT EXISTS` is then a +// no-op at open, and the version mismatch rebuilds it like any other upgrade. +export const HISTORY_SCHEMA_VERSION = 3; export const HISTORY_DB_FILENAME = "routing-history.sqlite"; export const HISTORY_META_KEYS = { @@ -64,9 +69,9 @@ CREATE INDEX IF NOT EXISTS idx_requests_provider ON requests(provider); CREATE INDEX IF NOT EXISTS idx_requests_model ON requests(model); CREATE INDEX IF NOT EXISTS idx_requests_requested_model ON requests(requested_model); CREATE INDEX IF NOT EXISTS idx_requests_status ON requests(status); -CREATE INDEX IF NOT EXISTS idx_requests_conversation ON requests(conversation_id); -CREATE INDEX IF NOT EXISTS idx_requests_api_key ON requests(api_key_id); -CREATE INDEX IF NOT EXISTS idx_requests_profile ON requests(profile_id); +CREATE INDEX IF NOT EXISTS idx_requests_conversation ON requests(conversation_id, timestamp DESC, request_id DESC); +CREATE INDEX IF NOT EXISTS idx_requests_api_key ON requests(api_key_id, timestamp DESC, request_id DESC); +CREATE INDEX IF NOT EXISTS idx_requests_profile ON requests(profile_id, timestamp DESC, request_id DESC); `; export function historyIndexPath(configDir: string): string { diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 3dcf72589b6..9b8b8b222d0 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -277,7 +277,7 @@ Provider debug formats one ring line per attempt from those counts. `GET /api/us fingerprint over closed vocabularies only, rebuilt through the same cooperative scanner and inheriting its bounds, so deleting a ledger row removes it from the grouping. `usageLedgerMaxBytes` is unset by default; when set, an append that crosses it publishes the newest whole rows byte for byte through the shared atomic writer, refuses the rename unless the source is the exact revision that was copied, and then discards the Logs ring, the retained aggregates and the request-history index so no surface serves rows the ledger no longer has. -That index (`src/routing/history/`) rebuilds a ledger of at least `REQUEST_HISTORY_WORKER_REBUILD_MIN_BYTES` (1 MiB) on a worker thread (#6990): `rebuild-worker.ts`, driven by `rebuild-job.ts`, ingests the ledger snapshot the refresh recorded into a private `.rebuild--` file through the same `ingest.ts` the inline path uses, switches it to WAL and closes it; the serving thread then closes the old index and renames the build over it. Async readers wait for the build; the routing-time sync entry never does and throws `RequestHistoryIndexBusyError`, which health scoring reads as unknown evidence. Health scoring (`src/routing/health.ts`) counts physical sends only: a request answered locally or refused before any send is no evidence for any target, and a row's terminal status and close reason score its last physical send, so a 200 stream cut mid-flight after a failover counts against the target that dropped it (`tests/server/health-scoring.test.ts`). A close discards the build, rejects waiting readers with `RequestHistoryIndexClosedError`, and removes the build files only after the worker thread exits. For 30 s after a worker build fails (other than on a replaced ledger), async readers and manual rebuilds rebuild inline instead, while routing-time reads keep reporting busy. +That index (`src/routing/history/`) rebuilds a ledger of at least `REQUEST_HISTORY_WORKER_REBUILD_MIN_BYTES` (1 MiB) on a worker thread (#6990): `rebuild-worker.ts`, driven by `rebuild-job.ts`, ingests the ledger snapshot the refresh recorded into a private `.rebuild--` file through the same `ingest.ts` the inline path uses, switches it to WAL and closes it; the serving thread then closes the old index and renames the build over it. Async readers wait for the build; the routing-time sync entry never does and throws `RequestHistoryIndexBusyError`, which health scoring reads as unknown evidence. Health scoring (`src/routing/health.ts`) counts physical sends only: a request answered locally or refused before any send is no evidence for any target, and a row's terminal status and close reason score its last physical send, so a 200 stream cut mid-flight after a failover counts against the target that dropped it (`tests/server/health-scoring.test.ts`). A close discards the build, rejects waiting readers with `RequestHistoryIndexClosedError`, and removes the build files only after the worker thread exits. For 30 s after a worker build fails (other than on a replaced ledger), async readers and manual rebuilds rebuild inline instead, while routing-time reads keep reporting busy. The conversation, API-key and profile filter indexes in `schema.ts` continue with `timestamp DESC, request_id DESC`, the page order, so a filtered page reads `limit + 1` rows from the index instead of sorting every matching row (#9103); schema version 3 introduced them, and an older index rebuilds through this path (`tests/usage/request-history-index.test.ts` asserts the plans). `src/routing/history/integrity.ts` validates an existing persisted index on first use with a read-only worker `PRAGMA quick_check` (#7966); serving refreshes retain schema/source/offset checks without a synchronous integrity scan. Async readers await initial validation; synchronous routing reports busy/unknown meanwhile. A successful fresh inline reconstruction is immediately usable, and a private worker build is integrity-checked before publication. After validation or reconstruction, the next refresh at least five minutes later starts one background check; verified reads remain available during it, and idle indexes start no timer. A check that has not answered within its bound — 30 s for small indexes, scaled by index file size at a conservative scan rate and capped at 15 minutes — is stopped and reported as an operational failure; waiting readers are released without waiting for the worker's actual exit. Operational check failures leave the index intact and delay retry for 30 s; an unverified index remains unavailable. A corrupt verdict or `SQLITE_CORRUPT`/`SQLITE_NOTADB` invalidates the live handle and enters the existing rebuild path; async history and analytics reads retry once after recovery. Close/rebuild discards stale verdicts and drains all scanners through actual thread exit before index replacement, including timed-out scanners. Neither validation nor recovery rewrites canonical `usage.jsonl`. `tests/usage/request-history-integrity.test.ts` covers scan scheduling, corruption recovery and lifecycle isolation. diff --git a/tests/usage/request-history-index.test.ts b/tests/usage/request-history-index.test.ts index e2c7918ab63..ca78da1f980 100644 --- a/tests/usage/request-history-index.test.ts +++ b/tests/usage/request-history-index.test.ts @@ -296,6 +296,58 @@ describe("request-history index (RI-02)", () => { expect(page.meta.lastError).toContain("rebuilt"); }); + test("API key, conversation and profile pages read their index in order without a sort (#9103)", async () => { + // Equal timestamps check that request_id DESC still breaks ties across cursor pages. + for (const [id, timestamp, key] of [["k1", 1000, "key-a"], ["k2", 2000, "key-b"], ["k3", 3000, "key-a"], ["k4", 3000, "key-a"], ["k5", 4000, "key-a"]] as const) { + appendUsageEntry(entry(id, timestamp, "a", "m1", { apiKeyId: key, conversationId: `conv-${key}` })); + } + const first = await queryRequestHistory({ apiKeyId: "key-a", from: 1000, to: 4000 }, undefined, 2); + expect(first.rows.map(row => row.requestId)).toEqual(["k5", "k4"]); + const second = await queryRequestHistory({ apiKeyId: "key-a", from: 1000, to: 4000 }, first.nextCursor, 2); + expect(second.rows.map(row => row.requestId)).toEqual(["k3", "k1"]); + expect(second.hasMore).toBe(false); + const byConversation = await queryRequestHistory({ conversationId: "conv-key-a" }, undefined, 10); + expect(byConversation.rows.map(row => row.requestId)).toEqual(["k5", "k4", "k3", "k1"]); + + const db = new Database(join(getConfigDir(), HISTORY_DB_FILENAME), { readonly: true }); + try { + for (const [column, index] of [["api_key_id", "idx_requests_api_key"], ["conversation_id", "idx_requests_conversation"], ["profile_id", "idx_requests_profile"]]) { + for (const extra of ["", " AND timestamp >= 0 AND timestamp <= 9999", " AND (timestamp < 3000 OR (timestamp = 3000 AND request_id < 'k4'))"]) { + const plan = (db.query( + `EXPLAIN QUERY PLAN SELECT row_json, timestamp, request_id FROM requests WHERE ${column} = ?${extra} ORDER BY timestamp DESC, request_id DESC LIMIT ?`, + ).all("x", 51) as Array<{ detail: string }>).map(row => row.detail).join("\n"); + expect(plan).toContain(`USING INDEX ${index} (${column}=?`); + expect(plan).not.toContain("TEMP B-TREE"); + } + } + } finally { + db.close(); + } + }); + + test("upgrading a version-two index rebuilds the single-column filter indexes in timestamp order", async () => { + appendUsageEntry(entry("v2-row", 1000, "a", "m1", { apiKeyId: "key-a" })); + await queryRequestHistory({}, undefined, 10); + closeRequestHistoryIndex(); + const dbFile = join(getConfigDir(), HISTORY_DB_FILENAME); + const legacy = new Database(dbFile); + legacy.exec("DROP INDEX idx_requests_api_key; CREATE INDEX idx_requests_api_key ON requests(api_key_id);"); + legacy.query("UPDATE schema_meta SET value = '2' WHERE key = 'schema_version'").run(); + legacy.close(); + + const page = await queryRequestHistory({ apiKeyId: "key-a" }, undefined, 10); + expect(page.rows.map(row => row.requestId)).toEqual(["v2-row"]); + expect(page.meta.schemaVersion).toBe(HISTORY_SCHEMA_VERSION); + expect(page.meta.lastError).toContain("rebuilt"); + const upgraded = new Database(dbFile, { readonly: true }); + try { + const { sql } = upgraded.query("SELECT sql FROM sqlite_master WHERE name = 'idx_requests_api_key'").get() as { sql: string }; + expect(sql).toContain("api_key_id, timestamp DESC, request_id DESC"); + } finally { + upgraded.close(); + } + }); + test("partial final JSONL line is skipped until it completes", async () => { for (const row of seedRows(3)) appendUsageEntry(row); const completeOffset = statSync(usageLogPath()).size; From 21197ab503c73476c764abd3756c5017307fa8d5 Mon Sep 17 00:00:00 2001 From: xurongren Date: Sat, 28 Nov 2026 01:50:21 +0800 Subject: [PATCH 09/64] fix(quota): show non-zero DeepSeek balance wallets across currencies (#9153) DeepSeek's `GET /user/balance` returns one `balance_infos` row per currency (for example both USD and CNY wallets on the same account). Previously `fetchDeepSeekQuota` unconditionally picked the USD row over CNY regardless of balance, so an account with `$0.00` USD and a positive CNY balance rendered `API balance ($0.00)` and hid the funded wallet. Parse all valid currency rows first, render every positive-balance wallet (ordered USD, CNY, then others; deduplicated per currency), and fall back to a single highest-priority row only when all valid wallets are zero. Also skip malformed or negative rows instead of letting an unusable earlier row mask a valid wallet. --- src/providers/quota/vendor-probes-key.ts | 73 ++++++++++++------- .../providers/deepseek-quota-currency.test.ts | 66 +++++++++++++++-- 2 files changed, 107 insertions(+), 32 deletions(-) diff --git a/src/providers/quota/vendor-probes-key.ts b/src/providers/quota/vendor-probes-key.ts index 8c061b4519f..e0acfd82964 100644 --- a/src/providers/quota/vendor-probes-key.ts +++ b/src/providers/quota/vendor-probes-key.ts @@ -420,10 +420,12 @@ async function fetchOpenRouterQuota(provider: string, config: OcxProviderConfig) /** * DeepSeek `GET /user/balance` — the account's granted + topped-up credit * balance. The payload places `total_balance` / `granted_balance` inside - * entries of `balance_infos` (one row per currency); the row for the account's - * currency is selected by preference. `granted_balance` is a CURRENT balance - * component, not the original grant ceiling, so no consumed percentage is - * fabricated — the balance is reported as a balance-only window. + * entries of `balance_infos` (one row per currency); every positive-balance + * currency wallet is reported (ordered USD, CNY, then others), falling back + * to the highest-priority row when all valid wallets are zero. + * `granted_balance` is a CURRENT balance component, not the original grant + * ceiling, so no consumed percentage is fabricated — each wallet is reported + * as a balance-only window. */ async function fetchDeepSeekQuota(provider: string, config: OcxProviderConfig): Promise { if (!isCanonicalDeepSeekBaseUrl(config.baseUrl)) return null; @@ -441,31 +443,48 @@ async function fetchDeepSeekQuota(provider: string, config: OcxProviderConfig): } const body = asRecord(await readQuotaJson(response)); // The payload nests balances under `balance_infos` rows keyed by currency; - // prefer a USD row, then CNY, then the first row that parses. + // parse every valid currency row, display all non-zero wallets (USD before + // CNY before others), and fall back to the top-priority row when all are zero. const infos = Array.isArray(body?.balance_infos) ? body.balance_infos as unknown[] : null; - const rows = infos - ? infos.map((raw): Record | null => asRecord(raw)).filter((r): r is Record => r !== null) - : []; - const pick = (currency: string): Record | null => - rows.find(row => String(row.currency ?? "").toUpperCase() === currency) ?? null; - const preferred = pick("USD") ?? pick("CNY") ?? rows[0] ?? null; - if (!preferred) return null; - const totalBalance = toFiniteNumber(preferred.total_balance); - const grantedBalance = toFiniteNumber(preferred.granted_balance); - const toppedUp = toFiniteNumber(preferred.topped_up_balance); - const balance = totalBalance ?? grantedBalance ?? toppedUp; - if (balance === undefined || balance < 0) return null; - // The rows are currency-scoped, so the symbol has to follow the row that was - // picked: the two glyph currencies keep their sign, any other ISO code - // prefixes the amount, and a row without one keeps the legacy dollar. - const currency = String(preferred.currency ?? "").trim().toUpperCase(); - const sign = currency === "CNY" ? "¥" : currency === "" || currency === "USD" ? "$" : `${currency} `; - const amount = (value: number) => `${sign}${value.toFixed(2)}`; - const label = grantedBalance !== undefined && grantedBalance > 0 - ? `API balance (${amount(balance)} total, ${amount(grantedBalance)} granted)` - : `API balance (${amount(balance)})`; + if (!infos) return null; + type DeepSeekWallet = { currency: string; balance: number; grantedBalance?: number }; + const wallets: DeepSeekWallet[] = []; + const seenCurrencies = new Set(); + for (const raw of infos) { + const row = asRecord(raw); + if (!row) continue; + const totalBalance = toFiniteNumber(row.total_balance); + const grantedBalance = toFiniteNumber(row.granted_balance); + const toppedUp = toFiniteNumber(row.topped_up_balance); + const balance = totalBalance ?? grantedBalance ?? toppedUp; + if (balance === undefined || balance < 0) continue; + const currency = typeof row.currency === "string" ? row.currency.trim().toUpperCase() : ""; + if (seenCurrencies.has(currency)) continue; + seenCurrencies.add(currency); + wallets.push({ + currency, + balance, + ...(grantedBalance !== undefined ? { grantedBalance } : {}), + }); + } + if (wallets.length === 0) return null; + const currencyRank = (currency: string): number => (currency === "USD" ? 0 : currency === "CNY" ? 1 : 2); + wallets.sort((a, b) => currencyRank(a.currency) - currencyRank(b.currency)); + const nonZero = wallets.filter(wallet => wallet.balance > 0); + const selected = nonZero.length > 0 ? nonZero : wallets.slice(0, 1); + // The rows are currency-scoped, so the symbol has to follow each row: + // the two glyph currencies keep their sign, any other ISO code prefixes + // the amount, and a row without one keeps the legacy dollar. + const customWindows = selected.map(wallet => { + const sign = wallet.currency === "CNY" ? "¥" : wallet.currency === "" || wallet.currency === "USD" ? "$" : `${wallet.currency} `; + const amount = (value: number) => `${sign}${value.toFixed(2)}`; + const label = wallet.grantedBalance !== undefined && wallet.grantedBalance > 0 + ? `API balance (${amount(wallet.balance)} total, ${amount(wallet.grantedBalance)} granted)` + : `API balance (${amount(wallet.balance)})`; + return { label, percent: 0 }; + }); return report(provider, "deepseek:balance", { - customWindows: [{ label, percent: 0 }], + customWindows, updatedAt: Date.now(), }); } diff --git a/tests/providers/deepseek-quota-currency.test.ts b/tests/providers/deepseek-quota-currency.test.ts index 0dd8001f4ef..7e2b1cbef66 100644 --- a/tests/providers/deepseek-quota-currency.test.ts +++ b/tests/providers/deepseek-quota-currency.test.ts @@ -25,7 +25,7 @@ function deepSeekConfig(): OcxConfig { } /** Answer the DeepSeek balance probe with exactly these `balance_infos` rows. */ -async function balanceLabel(rows: unknown[]): Promise { +async function balanceLabels(rows: unknown[]): Promise { globalThis.fetch = (async () => new Response(JSON.stringify({ is_available: true, balance_infos: rows, @@ -35,7 +35,11 @@ async function balanceLabel(rows: unknown[]): Promise { expect(result.reports).toHaveLength(1); expect(result.reports[0]?.source).toBe("deepseek:balance"); - return result.reports[0]?.quota.customWindows?.[0]?.label; + return (result.reports[0]?.quota.customWindows ?? []).map(window => window.label); +} + +async function balanceLabel(rows: unknown[]): Promise { + return (await balanceLabels(rows))[0]; } beforeEach(() => { @@ -78,8 +82,60 @@ describe("DeepSeek quota balance currency", () => { .toBe("API balance ($5.00)"); }); - test("a USD row is still preferred over a CNY row", async () => { - expect(await balanceLabel([{ currency: "CNY", total_balance: "10" }, { currency: "USD", total_balance: "7" }])) - .toBe("API balance ($7.00)"); + test("a zero USD wallet does not shadow a non-zero CNY wallet", async () => { + expect(await balanceLabels([ + { currency: "USD", total_balance: "0.00", granted_balance: "0.00", topped_up_balance: "0.00" }, + { currency: "CNY", total_balance: "6.06", granted_balance: "0.00", topped_up_balance: "6.06" }, + ])).toEqual(["API balance (¥6.06)"]); + }); + + test("a zero CNY wallet is omitted when USD has a positive balance", async () => { + expect(await balanceLabels([ + { currency: "CNY", total_balance: "0.00" }, + { currency: "USD", total_balance: "7" }, + ])).toEqual(["API balance ($7.00)"]); + }); + + test("both positive wallets are shown with USD ordered before CNY", async () => { + expect(await balanceLabels([ + { currency: "CNY", total_balance: "10" }, + { currency: "USD", total_balance: "7" }, + ])).toEqual(["API balance ($7.00)", "API balance (¥10.00)"]); + }); + + test("both positive wallets preserve per-currency granted amounts", async () => { + expect(await balanceLabels([ + { currency: "CNY", total_balance: "10", granted_balance: "4" }, + { currency: "USD", total_balance: "7", granted_balance: "2" }, + ])).toEqual([ + "API balance ($7.00 total, $2.00 granted)", + "API balance (¥10.00 total, ¥4.00 granted)", + ]); + }); + + test("all-zero wallets fall back to a single top-priority row (USD over CNY)", async () => { + expect(await balanceLabels([ + { currency: "CNY", total_balance: "0.00" }, + { currency: "USD", total_balance: "0.00" }, + ])).toEqual(["API balance ($0.00)"]); + }); + + test("malformed or negative earlier rows do not mask a valid wallet", async () => { + expect(await balanceLabels([ + { currency: "USD", total_balance: "not-a-number" }, + { currency: "CNY", total_balance: "6.06" }, + ])).toEqual(["API balance (¥6.06)"]); + + expect(await balanceLabels([ + { currency: "USD", total_balance: "-1" }, + { currency: "CNY", total_balance: "6.06" }, + ])).toEqual(["API balance (¥6.06)"]); + }); + + test("duplicate currency rows keep the first valid row per currency", async () => { + expect(await balanceLabels([ + { currency: "CNY", total_balance: "6.06" }, + { currency: "CNY", total_balance: "9.99" }, + ])).toEqual(["API balance (¥6.06)"]); }); }); From 6ed79a92903a8ce738fd60a2c5368be5128df787 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:03:33 +0900 Subject: [PATCH 10/64] docs(es): sync adapter and reference updates (#9179) --- docs-site/src/content/docs/es/reference/adapters.md | 2 +- docs-site/src/content/docs/es/reference/cli.md | 2 ++ docs-site/src/content/docs/es/reference/proxy-formats.md | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs-site/src/content/docs/es/reference/adapters.md b/docs-site/src/content/docs/es/reference/adapters.md index ffde8e011b5..fbc02bf1767 100644 --- a/docs-site/src/content/docs/es/reference/adapters.md +++ b/docs-site/src/content/docs/es/reference/adapters.md @@ -228,7 +228,7 @@ enrutamiento, añada un proveedor `jev-decision` cuyo `baseUrl` sea ese endpoint - Convierte mensajes a bloques de contenido Anthropic (texto, imagen base64, `tool_use`, `thinking`). - Las instrucciones de sistema del cliente se conservan en `system` de nivel superior de forma predeterminada, también con OAuth. El operador puede activar `providers..anthropicOAuthUserInstructions: true` para moverlas al inicio del primer turno de usuario en las solicitudes OAuth traducidas. Si el historial empieza con un mensaje del asistente, el adaptador añade un turno de usuario inicial. Las instrucciones trasladadas tienen la prioridad del rol de usuario. La identidad de compatibilidad, el contrato de herramientas de OpenCodex, las instrucciones para continuar desde un punto de control y las instrucciones de sistema de las solicitudes que inicia el proxy conservan su lugar en `system`. Si la caché de prompts está habilitada, el adaptador añade un punto de caché explícito a las instrucciones trasladadas. Las solicitudes con clave API y el passthrough nativo de Messages conservan su ubicación habitual. -- La compactación enrutada de Codex conserva el catálogo de herramientas, el prompt de sistema y las opciones de selección para mantener el prefijo de caché. Las solicitudes de resumen deshabilitan los sidecars de búsqueda y medios. Las herramientas alojadas por el proveedor conservan sus declaraciones con `tool_choice: none`, igual que una elección de herramienta obligatoria, sin cambiar el catálogo anunciado. Si la solicitud anuncia una herramienta de búsqueda sidecar, como Exa, la compactación sí cambia ese prefijo de herramientas. Un resumen que intenta llamar a una herramienta falla sin publicar la llamada ni reemplazar el historial. Un resumen correcto devuelve exactamente un elemento de compactación. Con la recuperación de contexto desactivada, se conservan la normalización de imágenes y el único reintento con reducción adicional después de HTTP 413. +- La compactación enrutada de Codex conserva el catálogo de herramientas, el prompt de sistema y las opciones de selección para mantener el prefijo de caché. Las solicitudes de resumen deshabilitan los sidecars de búsqueda y medios. Las herramientas alojadas por el proveedor conservan sus declaraciones con `tool_choice: none`, igual que una elección de herramienta obligatoria, sin cambiar el catálogo anunciado. Cuando el turno normal declararía la herramienta sidecar `web_search` (por ejemplo, Exa o el asistente de ChatGPT), el resumen declara la misma herramienta y conserva las búsquedas reproducidas con sus resultados registrados, pero nunca realiza búsquedas. Un resumen que intenta llamar a una herramienta falla sin publicar la llamada ni reemplazar el historial. Un resumen correcto devuelve exactamente un elemento de compactación. Con la recuperación de contexto desactivada, se conservan la normalización de imágenes y el único reintento con reducción adicional después de HTTP 413. - `anthropicImageContextRecovery: true` habilita un intento de recuperación tras un HTTP 413 del proveedor por contexto con imágenes. El proxy resume una parte anterior y completa de la conversación con las herramientas y el razonamiento deshabilitados y reenvía una solicitud más pequeña que conserva la imagen más reciente y el turno actual. diff --git a/docs-site/src/content/docs/es/reference/cli.md b/docs-site/src/content/docs/es/reference/cli.md index 4eefd6148e8..a91625020e5 100644 --- a/docs-site/src/content/docs/es/reference/cli.md +++ b/docs-site/src/content/docs/es/reference/cli.md @@ -149,6 +149,8 @@ ocx help models ocx help models preset show ``` +Para pools de cuentas, configuración, conexiones remotas, modelos y proveedores, la línea **Inspect first** de la ayuda de cada familia ofrece un punto de partida de solo lectura e indica si examina la configuración local o el servicio en ejecución. Un comando de solo lectura aún puede comprobar una conexión. Las consultas del catálogo en vivo pueden acceder al proveedor y reconciliar el estado de descubrimiento; utiliza la vista local o las llegadas registradas para una inspección pasiva. + Lee el capítulo correspondiente en `skills/ocx/references/01_management_surface.md` o en las páginas públicas de familias de comandos anteriores. `ocx help --all` permite acceder a la referencia completa. El inventario amplio para lectura por máquinas es opcional: ```bash diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index 4687b32c87e..ceaf79c34f7 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -232,6 +232,8 @@ Use 1-128 letras ASCII, dígitos, `.`, `_`, `:` o `-`, comenzando con una letra Utilice marcadores distintos para conversaciones distintas. Esto preserva la continuidad de la conversación para los consumidores intermedios, pero no garantiza un éxito de caché ascendente o ahorros medidos. WebSocket marcos, compactos, y count_tokens no utilizan esta promoción. +Un cliente de Responses que no envíe ninguna cabecera de sesión ni `x-session-id` puede identificar la conversación mediante `prompt_cache_key` en el cuerpo. En `POST /v1/responses`, tanto por HTTP como en tramas WebSocket, opencodex utiliza esa clave como `session_id` con las mismas reglas de caracteres y el mismo alcance de loopback y principal que un `x-session-id` promovido, para que los modelos respaldados por ChatGPT puedan reutilizar el prefijo de prompt ya almacenado en caché. Cualquier cabecera de sesión o `x-session-id` enviada por el cliente tiene prioridad; las solicitudes de Chat Completions y Messages conservan sus propias reglas de identidad. + En el despacho canónico de Responses respaldado por ChatGPT, un `session_id` explícito no vacío gana. De lo contrario, el primer alias no vacío entre `session-id`, luego `thread-id`, suministra `session_id` si su valor es seguro; un alias ganador no válido suprime la identidad más débil. Los valores de cabecera vacíos se eliminan antes de este paso en cada ruta (selección de cabecera de autenticación Responses y los puentes Claude Messages y Chat Completions), por lo que una cabecera vacía cuenta como ausente: una `session-id` vacía permite una victoria `thread-id` válida. La sesión derivada de metadatos Claude solo se aplica cuando no queda ninguna cabecera canónica no vacía o alias. Los alias mantienen sus nombres originales en el cable; sus valores de llamada sin procesar validados se reenvían como un `session_id` explícito, sin el alcance principal utilizado para el `x-session-id` promocionado. Esta conversión de salida no cambia la afinidad de entrada. Los destinos personalizados y los de clave API no cambian, y no se inventa ninguna identidad para las solicitudes sin un marcador de conversación. Para clientes de terceros, mantenga un marcador de propiedad de la persona que llama por conversación, incluidas las solicitudes repetidas de `curl`. Un prefijo de sistema/herramientas compartido `prompt_cache_key` o idéntico es una cohorte de caché, no prueba de que dos solicitudes pertenezcan a una conversación. Las solicitudes sin un marcador de conversación no reciben una sesión estable inventada. OpenCodex tampoco se hace pasar por Codex sintetizando un `originator`; un originador suministrado por la persona que llama conserva sus reglas de reenvío normales. La continuidad del encabezado no establece un éxito de caché: compare los tokens de entrada en caché informados del flujo ascendente para sus propias solicitudes de prefijo repetido. Un recuento de escritura en caché omitido no es evidencia de no escritura. From 865c04fa8978f4789312a66c8dbc53a7c53176f8 Mon Sep 17 00:00:00 2001 From: Claire Novotny <1427284+clairernovotny@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:03:42 -0500 Subject: [PATCH 11/64] feat(desktop): add macOS menu bar-only mode (#9124) * feat(desktop): add macOS menu bar-only mode * fix(desktop): serialize macOS Dock policy refreshes --- desktop/src-tauri/src/dock.rs | 116 ++++++++++++++++++ desktop/src-tauri/src/exit.rs | 4 +- desktop/src-tauri/src/lib.rs | 36 +++--- desktop/src-tauri/src/tray.rs | 13 ++ desktop/src-tauri/src/window.rs | 48 +++++--- .../src/content/docs/es/guides/desktop-app.md | 2 +- .../src/content/docs/fr/guides/desktop-app.md | 2 +- .../src/content/docs/guides/desktop-app.md | 2 +- .../src/content/docs/guides/macos-menu-bar.md | 2 + .../src/content/docs/ja/guides/desktop-app.md | 2 +- .../src/content/docs/ko/guides/desktop-app.md | 2 +- .../src/content/docs/ru/guides/desktop-app.md | 2 +- .../src/content/docs/tr/guides/desktop-app.md | 2 +- .../content/docs/zh-cn/guides/desktop-app.md | 2 +- .../content/docs/zh-tw/guides/desktop-app.md | 2 +- structure/desktop-shell.md | 10 ++ 16 files changed, 205 insertions(+), 42 deletions(-) create mode 100644 desktop/src-tauri/src/dock.rs diff --git a/desktop/src-tauri/src/dock.rs b/desktop/src-tauri/src/dock.rs new file mode 100644 index 00000000000..522526ef0a1 --- /dev/null +++ b/desktop/src-tauri/src/dock.rs @@ -0,0 +1,116 @@ +use std::{ + fs, io, + path::PathBuf, + sync::atomic::{AtomicBool, Ordering}, +}; +use tauri::{menu::CheckMenuItem, ActivationPolicy, App, AppHandle, Manager, Wry}; + +const MARKER: &str = "hide-dock-icon"; + +pub struct Preference { + marker: Option, + enabled: AtomicBool, +} + +impl Preference { + fn load(directory: Option) -> Self { + let marker = directory.map(|dir| dir.join(MARKER)); + let enabled = marker.as_ref().is_some_and(|path| path.is_file()); + Self { + marker, + enabled: AtomicBool::new(enabled), + } + } + + pub fn enabled(&self) -> bool { + self.enabled.load(Ordering::Acquire) + } + + fn set(&self, enabled: bool) -> io::Result<()> { + let marker = self.marker.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "desktop configuration directory unavailable", + ) + })?; + if enabled { + if let Some(directory) = marker.parent() { + fs::create_dir_all(directory)?; + } + match fs::File::create_new(marker) { + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::AlreadyExists && marker.is_file() => {} + Err(error) => return Err(error), + } + } else if let Err(error) = fs::remove_file(marker) { + if error.kind() != io::ErrorKind::NotFound { + return Err(error); + } + } + self.enabled.store(enabled, Ordering::Release); + Ok(()) + } +} + +pub fn prepare_launch(mut app: App) -> App { + let preference = Preference::load(app.path().app_config_dir().ok()); + if preference.enabled() { + // Stage this before the event loop starts so a saved preference applies at launch. + app.set_activation_policy(ActivationPolicy::Accessory); + app.set_dock_visibility(false); + } + app.manage(preference); + app +} + +pub fn show_in_dock(window_visible: bool, hide_dock: bool, tray_available: bool) -> bool { + window_visible && (!hide_dock || !tray_available) +} + +pub fn toggle(app: &AppHandle, item: &CheckMenuItem) { + let preference = app.state::(); + // The native menu flips the checkmark before dispatching the event. + if let Err(error) = preference.set(!preference.enabled()) { + crate::logging::log_once("could not save Hide Dock icon", &error.to_string()); + } + let _ = item.set_checked(preference.enabled()); + + crate::window::refresh_tray_policy(app); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dock_visibility_tracks_the_window_unless_menu_bar_mode_is_available() { + for hide_dock in [false, true] { + for tray_available in [false, true] { + assert!(!show_in_dock(false, hide_dock, tray_available)); + } + } + assert!(show_in_dock(true, false, true)); + assert!(!show_in_dock(true, true, true)); + assert!(show_in_dock(true, true, false)); + } + + #[test] + fn preference_survives_reloads_and_restores_the_default_when_disabled() { + let directory = std::env::temp_dir().join(format!("ocx-dock-{}", uuid::Uuid::new_v4())); + let load = || Preference::load(Some(directory.clone())); + let preference = load(); + assert!(!preference.enabled()); + preference.set(true).unwrap(); + assert!(load().enabled()); + preference.set(false).unwrap(); + assert!(!load().enabled()); + fs::remove_dir(directory).unwrap(); + } + + #[test] + fn failed_save_keeps_the_current_preference() { + let preference = Preference::load(None); + assert!(preference.set(true).is_err()); + assert!(!preference.enabled()); + } +} diff --git a/desktop/src-tauri/src/exit.rs b/desktop/src-tauri/src/exit.rs index 9c3d0040881..b5aca20f664 100644 --- a/desktop/src-tauri/src/exit.rs +++ b/desktop/src-tauri/src/exit.rs @@ -398,8 +398,8 @@ impl ExitCoordinator { self.inner().phase } - #[cfg(test)] - fn hides_to_tray(&self) -> bool { + #[cfg(any(target_os = "macos", test))] + pub fn hides_to_tray(&self) -> bool { self.inner().hides_to_tray } } diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 5966f2fc594..492e3c2877a 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -8,6 +8,8 @@ mod cli_command_windows; #[cfg(target_os = "macos")] mod companion_query; mod companion_usage; +#[cfg(target_os = "macos")] +mod dock; mod endpoint; mod exit; mod first_run; @@ -337,7 +339,7 @@ pub fn run() { .menu(menu::build) .on_menu_event(|app, event| menu::on_event(app, event.id().as_ref())); - builder + let app = builder .invoke_handler(tauri::generate_handler![ show_dashboard, hide_dashboard, @@ -424,7 +426,7 @@ pub fn run() { if startup::LaunchOrigin::detect() == startup::LaunchOrigin::User { window::show(&window); } else { - window::set_tray_policy(app.handle(), false); + window::refresh_tray_policy(app.handle()); } recovery::register(app.handle()); @@ -436,18 +438,20 @@ pub fn run() { Ok(()) }) .build(tauri::generate_context!()) - .expect("error while building OpenCodex desktop shell") - .run(|app, event| { - // Dock/Finder reopening an existing macOS app does not launch a second instance. - #[cfg(target_os = "macos")] - if let tauri::RunEvent::Reopen { .. } = event { - show_dashboard(app.clone()); - } - // Window close and the platform quit gesture arrive here as an exit request, and until - // this handler existed they went straight through to a SIGKILL of the runtime. D2 makes - // them hide; only the tray's Quit, and an update's coordinated restart, get past. - if let tauri::RunEvent::ExitRequested { code, api, .. } = event { - exit::on_exit_requested(app, code, &api); - } - }); + .expect("error while building OpenCodex desktop shell"); + #[cfg(target_os = "macos")] + let app = dock::prepare_launch(app); + app.run(|app, event| { + // Dock/Finder reopening an existing macOS app does not launch a second instance. + #[cfg(target_os = "macos")] + if let tauri::RunEvent::Reopen { .. } = event { + show_dashboard(app.clone()); + } + // Window close and the platform quit gesture arrive here as an exit request, and until + // this handler existed they went straight through to a SIGKILL of the runtime. D2 makes + // them hide; only the tray's Quit, and an update's coordinated restart, get past. + if let tauri::RunEvent::ExitRequested { code, api, .. } = event { + exit::on_exit_requested(app, code, &api); + } + }); } diff --git a/desktop/src-tauri/src/tray.rs b/desktop/src-tauri/src/tray.rs index e12f97f44fe..5171fe1f211 100644 --- a/desktop/src-tauri/src/tray.rs +++ b/desktop/src-tauri/src/tray.rs @@ -94,6 +94,15 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> { app.autolaunch().is_enabled().unwrap_or(false), None::<&str>, )?; + #[cfg(target_os = "macos")] + let hide_dock = CheckMenuItem::with_id( + app, + "hide-dock-icon", + "Hide Dock icon", + true, + app.state::().enabled(), + None::<&str>, + )?; // The tray is built before the startup sequence has decided anything, so nothing owns a // runtime yet. Ownership arrives later and reaches this item through [`set_owned`]. let owned = app @@ -127,6 +136,8 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> { &cli_command, &PredefinedMenuItem::separator(app)?, &login, + #[cfg(target_os = "macos")] + &hide_dock, &stop, &PredefinedMenuItem::separator(app)?, &check_updates, @@ -242,6 +253,8 @@ pub fn install(app: &AppHandle) -> tauri::Result<()> { } } } + #[cfg(target_os = "macos")] + "hide-dock-icon" => crate::dock::toggle(app, &hide_dock), "stop-proxy" => { // Through the coordinator, not beside it: Stop pressed twice, Stop then Quit, and // Stop during an update all have to be one execution over one child. diff --git a/desktop/src-tauri/src/window.rs b/desktop/src-tauri/src/window.rs index 7b71614c64a..131549ae0f1 100644 --- a/desktop/src-tauri/src/window.rs +++ b/desktop/src-tauri/src/window.rs @@ -170,16 +170,25 @@ pub fn shows_update_page(window: &WebviewWindow) -> bool { } pub fn show(window: &WebviewWindow) { + #[cfg(target_os = "macos")] + if window + .app_handle() + .state::() + .enabled() + { + // The status menu must also restore a minimized dashboard in menu bar mode. + let _ = window.unminimize(); + } let _ = window.show(); let _ = window.set_focus(); report_visibility(window, true); - apply_tray_policy(window.app_handle(), true); + refresh_tray_policy(window.app_handle()); } pub fn hide(window: &WebviewWindow) { let _ = window.hide(); report_visibility(window, false); - apply_tray_policy(window.app_handle(), false); + refresh_tray_policy(window.app_handle()); } /// Tell the main window's page whether its host window is visible. @@ -204,22 +213,31 @@ pub fn report_visibility(window: &WebviewWindow, visible: bool) { } #[cfg(target_os = "macos")] -fn apply_tray_policy(app: &AppHandle, visible: bool) { - let policy = if visible { - tauri::ActivationPolicy::Regular - } else { - tauri::ActivationPolicy::Accessory - }; - let _ = app.set_dock_visibility(visible); - let _ = app.set_activation_policy(policy); +pub fn refresh_tray_policy(app: &AppHandle) { + let handle = app.clone(); + // Read live state in the same main-thread turn as both native updates. Startup can + // queue this refresh from another thread while the user toggles the menu item. + let _ = app.run_on_main_thread(move || { + let visible = handle + .get_webview_window("main") + .is_some_and(|window| window.is_visible().unwrap_or(false)); + let hide_dock = handle.state::().enabled(); + let has_tray = handle + .state::() + .hides_to_tray(); + let show_dock = crate::dock::show_in_dock(visible, hide_dock, has_tray); + let policy = if show_dock { + tauri::ActivationPolicy::Regular + } else { + tauri::ActivationPolicy::Accessory + }; + let _ = handle.set_dock_visibility(show_dock); + let _ = handle.set_activation_policy(policy); + }); } #[cfg(not(target_os = "macos"))] -fn apply_tray_policy(_app: &AppHandle, _visible: bool) {} - -pub fn set_tray_policy(app: &AppHandle, visible: bool) { - apply_tray_policy(app, visible); -} +pub fn refresh_tray_policy(_app: &AppHandle) {} #[cfg(test)] mod tests { diff --git a/docs-site/src/content/docs/es/guides/desktop-app.md b/docs-site/src/content/docs/es/guides/desktop-app.md index 22a918cd378..ec6b5eee181 100644 --- a/docs-site/src/content/docs/es/guides/desktop-app.md +++ b/docs-site/src/content/docs/es/guides/desktop-app.md @@ -72,7 +72,7 @@ Usa **Open dashboard** (abrir dashboard) u **Open in browser** (abrir en el nave En Windows, aceptar **Take over** (tomar el control) permite hasta 90 segundos para detener de forma segura el entorno de ejecución existente, transferir su control e iniciar el que incluye la aplicación. El tiempo que tardes en decidir no cuenta para ese límite. Mantén la aplicación abierta mientras termina; si falla, usa **Retry** (reintentar) para volver a buscar el entorno de ejecución actual. -En macOS, cerrar el dashboard mantiene la aplicación en la barra de menús. Vuelve a abrir OpenCodex desde el Dock o Finder para recuperar el dashboard sin reiniciar el proxy. +En macOS, cerrar el dashboard mantiene la aplicación en la barra de menús. Elige **Open Dashboard** en la barra de menús o vuelve a abrir OpenCodex desde Finder para recuperar el dashboard sin reiniciar el proxy. Activa **Hide Dock icon** en el mismo menú si quieres ocultar el icono del Dock incluso con el dashboard abierto. En Windows, **Start at Login** (iniciar al abrir sesión) registra la ruta del ejecutable entre comillas para el usuario actual, incluidas las instalaciones en `Program Files`. Los registros habilitados se actualizan una vez al iniciar la aplicación. Las entradas que hayas deshabilitado desde la bandeja o el Administrador de tareas permanecen deshabilitadas. diff --git a/docs-site/src/content/docs/fr/guides/desktop-app.md b/docs-site/src/content/docs/fr/guides/desktop-app.md index 88056153260..d872f3ed407 100644 --- a/docs-site/src/content/docs/fr/guides/desktop-app.md +++ b/docs-site/src/content/docs/fr/guides/desktop-app.md @@ -57,7 +57,7 @@ L’application demande à son CLI intégré d’exécuter `ocx resolve --json` Utilisez l’action **Open dashboard** ou **Open in browser** de la zone de notification pour passer du tableau de bord intégré à votre navigateur habituel. Le menu permet aussi de rechercher les mises à jour. -Sur macOS, fermer le tableau de bord laisse l’application active dans la barre des menus. Ouvrez à nouveau OpenCodex depuis le Dock ou le Finder pour réafficher le tableau de bord sans redémarrer le proxy. +Sur macOS, fermer le tableau de bord laisse l’application active dans la barre des menus. Choisissez **Open Dashboard** dans la barre des menus ou rouvrez OpenCodex depuis le Finder pour réafficher le tableau de bord sans redémarrer le proxy. Activez **Hide Dock icon** dans le même menu pour masquer l’icône du Dock même lorsque le tableau de bord est ouvert. ## Utilisation dans la zone de notification diff --git a/docs-site/src/content/docs/guides/desktop-app.md b/docs-site/src/content/docs/guides/desktop-app.md index 731c7c26044..4d88b3168b3 100644 --- a/docs-site/src/content/docs/guides/desktop-app.md +++ b/docs-site/src/content/docs/guides/desktop-app.md @@ -109,7 +109,7 @@ runtime to stop safely, ownership to transfer, and the bundled runtime to start. deciding at the prompt does not count toward this limit. Keep the app open while it finishes; if it fails, use **Retry** to resolve the current runtime again. -On macOS, closing the dashboard keeps the app running in the menu bar. Open OpenCodex again from Dock or Finder to restore the dashboard without restarting the proxy. +On macOS, closing the dashboard keeps the app running in the menu bar. Use **Open Dashboard** from the menu bar or reopen OpenCodex from Finder to restore the dashboard without restarting the proxy. The Dock icon appears while the dashboard is open by default. Enable [**Hide Dock icon**](/guides/macos-menu-bar/#menu-bar-and-usage-panel) from the menu bar to keep it hidden. On Windows, **Start at Login** quotes the executable path in the current-user startup registration, including installations under `Program Files`. Previously enabled diff --git a/docs-site/src/content/docs/guides/macos-menu-bar.md b/docs-site/src/content/docs/guides/macos-menu-bar.md index 89ab7089dbd..d205d98f403 100644 --- a/docs-site/src/content/docs/guides/macos-menu-bar.md +++ b/docs-site/src/content/docs/guides/macos-menu-bar.md @@ -23,6 +23,8 @@ Use **Show Usage** in the tray menu to open the native panel. The panel shows to The panel has **Refresh**, **Dashboard**, and **Settings** controls. **Dashboard** opens the usage view in the desktop window; **Settings** opens the **Menu bar & widget** tab under Usage. The tray menu also offers **Open Dashboard**, **Open in Browser**, **Start at Login**, **Stop proxy**, **Check for Updates…**, an **Install update** item when one is available, and **Quit**. **Stop proxy** is always listed but is enabled only when the app started the proxy itself; a proxy you started separately keeps running. Closing the window or using Command-Q hides the app when its tray is available; use the tray's **Quit** to exit it. +To keep OpenCodex out of the Dock even while its dashboard is open, enable **Hide Dock icon** in the OpenCodex menu bar menu. You can still use **Open Dashboard** and **Quit** from that menu. OpenCodex remembers your choice after relaunch. Uncheck **Hide Dock icon** to show the Dock icon again whenever the dashboard is open. + The desktop dashboard's update button opens the app's own update page; it checks and installs the same signed update as the tray menu. The tray headline refreshes every 60 seconds. While the native panel is open, its data refreshes every 60 seconds; **Refresh** requests an immediate update. diff --git a/docs-site/src/content/docs/ja/guides/desktop-app.md b/docs-site/src/content/docs/ja/guides/desktop-app.md index 67a743a2ac8..d1bbe96efe9 100644 --- a/docs-site/src/content/docs/ja/guides/desktop-app.md +++ b/docs-site/src/content/docs/ja/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb トレイの **Open dashboard** または **Open in browser** で、埋め込みダッシュボードと通常のブラウザを切り替えられます。トレイから更新の確認もできます。 -macOS では、ダッシュボードを閉じてもアプリはメニューバーで動作し続けます。Dock または Finder から OpenCodex を再度開くと、プロキシを再起動せずにダッシュボードが再表示されます。 +macOS では、ダッシュボードを閉じてもアプリはメニューバーで動作し続けます。メニューバーの **Open Dashboard** を選ぶか、Finder から OpenCodex を再度開くと、プロキシを再起動せずにダッシュボードを表示できます。同じメニューの **Hide Dock icon** を有効にすると、ダッシュボードを開いている間も Dock アイコンを非表示にできます。 Codex の起動でプロキシが見つからない場合、同梱 CLI は独立して検証された Desktop の復旧を待ちます。Desktop に記録された所有権クレームがない場合も同様です。一致する Desktop がプロキシを停止済みか復旧を検証できないときはエラーになりますが、実行イメージ検証のないプラットフォームでは、記録された所有権クレームがありアプリが実行中なら既存の制限付き待機を維持します。プロセス名や検出ファイルだけでは通常の CLI 起動を妨げません。shim は macOS でアプリが終了しており、記録された所有権が有効な **Start at Login** 登録と一致すれば OpenCodex を開きます。自動で開き直すときはその登録の app バンドルパスを選択し、宣言されたメイン実行ファイルが登録済み Desktop の実行ファイルと一致するか確認します。登録がない・古い・不整合の場合は OpenCodex を手動で開いてください。同じバンドル識別子を持つ別コピーは代替として選択されません。shim が "activation not confirmed" と表示する場合は、シェル起動ファイルの他の PATH 設定の後に `. ~/.opencodex/codex-shell-env.sh` を追加してください。 diff --git a/docs-site/src/content/docs/ko/guides/desktop-app.md b/docs-site/src/content/docs/ko/guides/desktop-app.md index c1aff82a522..f12dc886085 100644 --- a/docs-site/src/content/docs/ko/guides/desktop-app.md +++ b/docs-site/src/content/docs/ko/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb 트레이의 **Open dashboard** 또는 **Open in browser**를 사용하면 내장 대시보드와 일반 브라우저를 오갈 수 있습니다. 트레이에서는 업데이트도 확인할 수 있습니다. -macOS에서는 대시보드를 닫아도 앱이 메뉴 막대에서 계속 실행됩니다. Dock 또는 Finder에서 OpenCodex를 다시 열면 프록시를 재시작하지 않고 대시보드가 다시 표시됩니다. +macOS에서는 대시보드를 닫아도 앱이 메뉴 막대에서 계속 실행됩니다. 메뉴 막대에서 **Open Dashboard**를 선택하거나 Finder에서 OpenCodex를 다시 열면 프록시를 재시작하지 않고 대시보드를 표시할 수 있습니다. 같은 메뉴에서 **Hide Dock icon**을 켜면 대시보드가 열려 있어도 Dock 아이콘이 숨겨집니다. ## 데스크톱 앱과 ocx CLI 함께 사용하기 diff --git a/docs-site/src/content/docs/ru/guides/desktop-app.md b/docs-site/src/content/docs/ru/guides/desktop-app.md index 308553489c5..c8c6efc2965 100644 --- a/docs-site/src/content/docs/ru/guides/desktop-app.md +++ b/docs-site/src/content/docs/ru/guides/desktop-app.md @@ -73,7 +73,7 @@ CLI подтвердил отсутствие прокси; неопределё Используйте действия **Open dashboard** или **Open in browser** в системной панели, чтобы переключаться между встроенным дашбордом и обычным браузером. Там же доступны проверки обновлений. -В macOS после закрытия дашборда приложение продолжает работать в строке меню. Откройте OpenCodex снова через Dock или Finder, чтобы вернуть дашборд без перезапуска прокси. +В macOS после закрытия дашборда приложение продолжает работать в строке меню. Выберите **Open Dashboard** в строке меню или снова откройте OpenCodex через Finder, чтобы вернуть дашборд без перезапуска прокси. Включите **Hide Dock icon** в том же меню, чтобы скрыть значок в Dock даже при открытом дашборде. Если при запуске Codex прокси не найден, встроенный CLI ждёт независимо подтверждённого восстановления Desktop — в том числе когда у Desktop нет записанного заявления о владении. Совпавший Desktop, который остановил свой прокси или чьё восстановление невозможно проверить, даёт ошибку; исключение — на платформе без проверки живого образа записанное заявление о владении при работающем приложении сохраняет существующее ограниченное ожидание. Одного имени процесса или файла-локатора недостаточно, чтобы блокировать обычный запуск CLI. Shim открывает OpenCodex в macOS, если приложение завершено и записанное владение совпадает с действительной регистрацией **Start at Login**. При автоматическом повторном открытии выбирается путь bundle приложения из этой регистрации и проверяется, что объявленный основной исполняемый файл совпадает с зарегистрированным исполняемым файлом Desktop. Если регистрация отсутствует, устарела или не согласована, откройте OpenCodex вручную: другая копия с тем же идентификатором bundle не выбирается как запасная. Если shim сообщает «activation not confirmed», добавьте `. ~/.opencodex/codex-shell-env.sh` в файл инициализации shell после остальных настроек PATH. diff --git a/docs-site/src/content/docs/tr/guides/desktop-app.md b/docs-site/src/content/docs/tr/guides/desktop-app.md index 98d09f07051..62447cb8266 100644 --- a/docs-site/src/content/docs/tr/guides/desktop-app.md +++ b/docs-site/src/content/docs/tr/guides/desktop-app.md @@ -57,7 +57,7 @@ Uygulama, paketindeki CLI'dan `ocx resolve --json` çalıştırmasını ister ve Gömülü kontrol paneli ile normal tarayıcınız arasında geçmek için tepsideki **Open dashboard** veya **Open in browser** eylemini kullanın. Tepsi, güncelleme denetimlerini de sunar. -macOS’te kontrol panelini kapattığınızda uygulama menü çubuğunda çalışmaya devam eder. Proxy’yi yeniden başlatmadan kontrol panelini geri getirmek için OpenCodex’i Dock veya Finder üzerinden yeniden açın. +macOS’te kontrol panelini kapattığınızda uygulama menü çubuğunda çalışmaya devam eder. Proxy’yi yeniden başlatmadan kontrol panelini açmak için menü çubuğunda **Open Dashboard** öğesini seçin veya OpenCodex’i Finder’dan yeniden açın. Kontrol paneli açıkken de Dock simgesini gizlemek için aynı menüde **Hide Dock icon** seçeneğini işaretleyin. ## Tepside kullanım diff --git a/docs-site/src/content/docs/zh-cn/guides/desktop-app.md b/docs-site/src/content/docs/zh-cn/guides/desktop-app.md index 432e8fc90eb..907d57c4e3d 100644 --- a/docs-site/src/content/docs/zh-cn/guides/desktop-app.md +++ b/docs-site/src/content/docs/zh-cn/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb 使用托盘中的 **Open dashboard** 或 **Open in browser**,可在内嵌仪表盘与常用浏览器之间切换。托盘也提供更新检查。 -在 macOS 上,关闭仪表盘后,应用会继续在菜单栏中运行。从 Dock 或 Finder 再次打开 OpenCodex 即可恢复仪表盘,无需重启代理。 +在 macOS 上,关闭仪表盘后,应用会继续在菜单栏中运行。在菜单栏选择 **Open Dashboard**,或从访达重新打开 OpenCodex,即可恢复仪表盘,无需重启代理。在同一菜单中启用 **Hide Dock icon**,即可在仪表盘打开时继续隐藏程序坞图标。 当 Codex 启动找不到 proxy 时,内置 CLI 会等待经过独立验证的 Desktop 恢复——即使 Desktop 没有记录在案的所有权声明也不例外。匹配到的 Desktop 已停止其 proxy,或其恢复无法验证时,会报错;但在不支持运行镜像验证的平台上,若有记录在案的所有权声明且应用仍在运行,则保留现有的有界等待。仅凭进程名或定位文件不会阻止普通的 CLI 启动。在 macOS 上,如果 shim 发现 OpenCodex 已退出且记录的所有权与有效的 **Start at Login** 注册一致,就会打开它。自动重新打开时,会选择该注册记录中的应用 bundle 路径,并检查其声明的主可执行文件是否与已注册的 Desktop 可执行文件一致。注册缺失、过期或不一致时,请手动打开 OpenCodex;具有相同 bundle 标识符的其他副本不会作为回退被选中。如果 shim 显示“activation not confirmed”,请在 shell 启动文件中的其他 PATH 设置之后添加 `. ~/.opencodex/codex-shell-env.sh`。 diff --git a/docs-site/src/content/docs/zh-tw/guides/desktop-app.md b/docs-site/src/content/docs/zh-tw/guides/desktop-app.md index 229fc0c4946..7b8eafcf37b 100644 --- a/docs-site/src/content/docs/zh-tw/guides/desktop-app.md +++ b/docs-site/src/content/docs/zh-tw/guides/desktop-app.md @@ -57,7 +57,7 @@ sudo apt install ./OpenCodex--linux-amd64.deb 透過系統匣的 **Open dashboard** 或 **Open in browser**,可以在內嵌儀表板與一般瀏覽器間切換。系統匣也提供更新檢查。 -在 macOS 上,關閉儀表板後,應用程式會繼續在選單列中執行。從 Dock 或 Finder 再次開啟 OpenCodex 即可恢復儀表板,無須重新啟動代理。 +在 macOS 上,關閉儀表板後,應用程式會繼續在選單列中執行。在選單列選擇 **Open Dashboard**,或從 Finder 重新開啟 OpenCodex,即可恢復儀表板,無須重新啟動代理。在同一選單中啟用 **Hide Dock icon**,便可在儀表板開啟時繼續隱藏 Dock 圖示。 ## 系統匣中的用量資訊 diff --git a/structure/desktop-shell.md b/structure/desktop-shell.md index 1e2c84faf57..c9bdc6c3a4f 100644 --- a/structure/desktop-shell.md +++ b/structure/desktop-shell.md @@ -137,6 +137,16 @@ window, closes the usage popup if it is open, and loads the dashboard if a hidde it. This is separate from the single-instance callback, which handles a second process notifying the existing one. +The macOS tray's **Hide Dock icon** checkbox is a local desktop preference. The +`desktop/src-tauri/src/dock.rs` marker in the desktop app configuration directory +is loaded before AppKit launches and updated before the live preference changes. +When the preference is enabled, showing the dashboard keeps the app in accessory +mode while the window can still take focus. A failed tray installation restores +Dock access when startup shows the dashboard. The shell reads the current +dashboard visibility, preference, and tray verdict in the same main-thread +turn that applies both native policies. The preference and its tray item are +macOS-only and do not depend on the proxy. + The host window also answers whether the dashboard is visible at all. Windows WebView2 is reported to keep `document.visibilityState === "visible"` while the Tauri window sits hidden in the tray (tauri issues #10592 and #6864; macOS WKWebView does flip it, measured), so a hidden dashboard went From 83dfd69d60c13d5782a6841f6cd395fa1e76e627 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 05:03:53 +0900 Subject: [PATCH 12/64] feat(logs): show interrupted WebSocket response delivery (#9136) * feat(logs): identify interrupted WebSocket response delivery * fix(logs): label interrupted streams after lifecycle or tool events relayedEvents counts every non-control response event, so an abnormal close after only response.created (protocol-prelude) or after a delivered tool call (side-effect) also relayed events with no confirmed completion. Accept those final stages while keeping the final-attempt 1006 evidence. --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../es/reference/codex-retry-diagnostics.md | 2 + .../docs/reference/codex-retry-diagnostics.md | 2 + gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/es.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/Logs.tsx | 17 ++++- gui/src/pages/logs-failure-summary.ts | 18 +++++ gui/tests/logs-upstream-faults.test.tsx | 69 +++++++++++++++++++ 17 files changed, 130 insertions(+), 2 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md b/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md index 6e97d2067be..6364ec50c48 100644 --- a/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md +++ b/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md @@ -69,6 +69,8 @@ intento para distinguirlos. Aumentar `stream_idle_timeout_ms` solo prolonga la e +En el registro de solicitudes del panel, **Transmisión interrumpida** indica que la conexión WebSocket con el proveedor se cerró de forma anómala (1006) después de enviar eventos de respuesta al cliente y antes de que el proxy observara un evento de finalización. El detalle de la solicitud muestra esta distinción. Para consultar la actividad posterior, usa el filtro junto al ID de conversación y quita el filtro de estado, si lo hay. Una conversación puede incluir varios turnos. La hora y el tamaño de las solicitudes por sí solos no permiten confirmar un reintento automático ni que el trabajo se haya recuperado. + ## Por qué la primera fila de reconexión puede estar ausente La fuente pública Codex `rust-v0.158.0-alpha.2.1` guarda la notificación de reintento de transmisión ordinaria en [`handle_response_stream_error`](https://github.com/openai/codex/blob/rust-v0.158.0-alpha.2.1/codex-rs/core/src/responses_retry.rs): diff --git a/docs-site/src/content/docs/reference/codex-retry-diagnostics.md b/docs-site/src/content/docs/reference/codex-retry-diagnostics.md index a596c37021d..ce0887f508a 100644 --- a/docs-site/src/content/docs/reference/codex-retry-diagnostics.md +++ b/docs-site/src/content/docs/reference/codex-retry-diagnostics.md @@ -113,6 +113,8 @@ sends no pings. All three keep the client's idle deadline on purpose. `pings` and `pongs` counts, which tell the three apart. Raising `stream_idle_timeout_ms` only makes them wait longer. +In the dashboard request log, **Stream interrupted** means the upstream WebSocket closed abnormally (1006) after the proxy relayed response events and before it observed a terminal event. The request details show this distinction. To inspect subsequent activity, use the filter beside the conversation ID and clear any status filter. The resulting rows belong to the same conversation, which can include multiple turns. Their timing and sizes alone cannot establish an automatic retry or successful recovery. + ## Why the first reconnect row can be absent The public Codex `rust-v0.158.0-alpha.2.1` source gates the ordinary stream-retry diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index b91a4da59ab..d9d089f3a5c 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -1390,6 +1390,8 @@ export const de: Record = { "logs.detail.stage.headersOnly": "nur Kopfzeilen", "logs.detail.stage.protocolPrelude": "Protokollvorspann", "logs.detail.stage.semanticOutput": "Ausgabe zugestellt", + "logs.status.streamInterrupted": "Stream unterbrochen", + "logs.detail.streamInterrupted1006": "Nach der Weiterleitung von Antwortereignissen wurde die WebSocket-Verbindung zum Anbieter unerwartet geschlossen (1006). Der Abschluss der Antwort wurde nicht bestätigt.", "logs.detail.stage.sideEffect": "Nebenwirkung ausgelöst", "logs.detail.stage.terminal": "Antwort zugestellt", "logs.detail.resend.permitted": "Erneut sendbar", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 1de05448b6d..8c3461e70c9 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1448,6 +1448,8 @@ export const en = { "logs.detail.stage.headersOnly": "headers only", "logs.detail.stage.protocolPrelude": "protocol prelude", "logs.detail.stage.semanticOutput": "output delivered", + "logs.status.streamInterrupted": "Stream interrupted", + "logs.detail.streamInterrupted1006": "The upstream WebSocket closed abnormally (1006) after response events were relayed. No completion was confirmed.", "logs.detail.stage.sideEffect": "side effect emitted", "logs.detail.stage.terminal": "answer delivered", "logs.detail.resend.permitted": "Could be resent", diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index 3d87942a15d..7540e81cee6 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -1435,6 +1435,8 @@ export const es = { "logs.detail.stage.headersOnly": "Solo encabezados", "logs.detail.stage.protocolPrelude": "Preludio del protocolo", "logs.detail.stage.semanticOutput": "salida entregada", + "logs.status.streamInterrupted": "Transmisión interrumpida", + "logs.detail.streamInterrupted1006": "La conexión WebSocket con el proveedor se cerró de forma anómala (1006) después de enviar eventos de respuesta al cliente. No se confirmó que la respuesta hubiera finalizado.", "logs.detail.stage.sideEffect": "efecto secundario emitido", "logs.detail.stage.terminal": "Respuesta entregada", "logs.detail.resend.permitted": "Podría ser resentido", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 3918116156e..e8570934b4c 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1429,6 +1429,8 @@ export const fr: Record = { "logs.detail.stage.headersOnly": "en-têtes seulement", "logs.detail.stage.protocolPrelude": "prélude de protocole", "logs.detail.stage.semanticOutput": "sortie livrée", + "logs.status.streamInterrupted": "Flux interrompu", + "logs.detail.streamInterrupted1006": "La connexion WebSocket en amont s’est fermée de façon anormale (1006) après la transmission d’événements de réponse. La fin de la réponse n’a pas été confirmée.", "logs.detail.stage.sideEffect": "effet de bord émis", "logs.detail.stage.terminal": "réponse livrée", "logs.detail.resend.permitted": "Peut être renvoyé", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 74a6d2f9dfc..bf4c1474fea 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1331,6 +1331,8 @@ export const ja: Record = { "logs.detail.stage.headersOnly": "ヘッダーのみ", "logs.detail.stage.protocolPrelude": "プロトコル前段", "logs.detail.stage.semanticOutput": "出力を配信済み", + "logs.status.streamInterrupted": "ストリーム中断", + "logs.detail.streamInterrupted1006": "応答イベントを転送した後、上流の WebSocket 接続が異常終了しました(1006)。応答の完了は確認できませんでした。", "logs.detail.stage.sideEffect": "副作用が発生", "logs.detail.stage.terminal": "応答を配信済み", "logs.detail.resend.permitted": "再送可能", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 5fbcc11bdf6..c94e1215ac8 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -1429,6 +1429,8 @@ export const ko: Record = { "logs.detail.stage.headersOnly": "헤더까지", "logs.detail.stage.protocolPrelude": "프로토콜 프리앰블", "logs.detail.stage.semanticOutput": "출력 전달됨", + "logs.status.streamInterrupted": "스트림 중단", + "logs.detail.streamInterrupted1006": "응답 이벤트를 전달하던 중 상류 WebSocket 연결이 비정상 종료됐습니다(1006). 응답 완료는 확인되지 않았습니다.", "logs.detail.stage.sideEffect": "부수 효과 발생", "logs.detail.stage.terminal": "응답 전달 완료", "logs.detail.resend.permitted": "재전송 가능", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index ba97c9bf919..08b15af504d 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -1443,6 +1443,8 @@ export const pt: Record = { "logs.detail.stage.headersOnly": "somente cabeçalhos", "logs.detail.stage.protocolPrelude": "preâmbulo do protocolo", "logs.detail.stage.semanticOutput": "saída entregue", + "logs.status.streamInterrupted": "Transmissão interrompida", + "logs.detail.streamInterrupted1006": "A conexão WebSocket com o provedor foi encerrada de forma anormal (1006) após o envio de eventos de resposta ao cliente. A conclusão da resposta não foi confirmada.", "logs.detail.stage.sideEffect": "efeito colateral emitido", "logs.detail.stage.terminal": "resposta entregue", "logs.detail.resend.permitted": "Poderia ser reenviada", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index dbbbf3e7523..350ceebfbd0 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1407,6 +1407,8 @@ export const ru: Record = { "logs.detail.stage.headersOnly": "только заголовки", "logs.detail.stage.protocolPrelude": "начало протокола", "logs.detail.stage.semanticOutput": "вывод доставлен", + "logs.status.streamInterrupted": "Поток прерван", + "logs.detail.streamInterrupted1006": "После передачи событий ответа соединение WebSocket с провайдером аварийно закрылось (1006). Завершение ответа не подтверждено.", "logs.detail.stage.sideEffect": "побочный эффект отправлен", "logs.detail.stage.terminal": "ответ доставлен", "logs.detail.resend.permitted": "Можно отправить повторно", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index a38e5db3d26..68b19964691 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1434,6 +1434,8 @@ export const tr: Record = { "logs.detail.stage.headersOnly": "yalnızca başlıklar", "logs.detail.stage.protocolPrelude": "protokol ön bölümü", "logs.detail.stage.semanticOutput": "çıktı iletildi", + "logs.status.streamInterrupted": "Akış kesildi", + "logs.detail.streamInterrupted1006": "Yanıt olayları iletildikten sonra sağlayıcıya giden WebSocket bağlantısı beklenmedik şekilde kapandı (1006). Yanıtın tamamlandığı doğrulanamadı.", "logs.detail.stage.sideEffect": "yan etki üretildi", "logs.detail.stage.terminal": "yanıt iletildi", "logs.detail.resend.permitted": "Yeniden gönderilebilir", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index ce4758d3694..f9c03af2f02 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -1428,6 +1428,8 @@ export const vi: Record = { "logs.detail.stage.headersOnly": "chỉ có tiêu đề", "logs.detail.stage.protocolPrelude": "phần mở đầu giao thức", "logs.detail.stage.semanticOutput": "đã gửi đầu ra", + "logs.status.streamInterrupted": "Luồng bị gián đoạn", + "logs.detail.streamInterrupted1006": "Kết nối WebSocket đến nhà cung cấp đã đóng bất thường (1006) sau khi các sự kiện phản hồi được chuyển tiếp. Chưa xác nhận được phản hồi đã hoàn tất.", "logs.detail.stage.sideEffect": "đã phát sinh tác dụng phụ", "logs.detail.stage.terminal": "đã gửi câu trả lời", "logs.detail.resend.permitted": "Có thể gửi lại", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index fa94798639e..68daf854591 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -3394,6 +3394,8 @@ export const zhTW: Record = { "logs.detail.stage.headersOnly": "僅標頭", "logs.detail.stage.protocolPrelude": "協定前導", "logs.detail.stage.semanticOutput": "已傳遞輸出", + "logs.status.streamInterrupted": "串流中斷", + "logs.detail.streamInterrupted1006": "轉送回應事件後,上游 WebSocket 連線異常關閉(1006)。無法確認回應是否完成。", "logs.detail.stage.sideEffect": "已產生副作用", "logs.detail.stage.terminal": "已傳遞答覆", "logs.detail.resend.permitted": "可以重送", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 5d3a9a107c7..2d0fcae1db2 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -1402,6 +1402,8 @@ export const zh: Record = { "logs.detail.stage.headersOnly": "仅响应头", "logs.detail.stage.protocolPrelude": "协议前导", "logs.detail.stage.semanticOutput": "已交付输出", + "logs.status.streamInterrupted": "流已中断", + "logs.detail.streamInterrupted1006": "转发响应事件后,上游 WebSocket 连接异常关闭(1006)。无法确认响应是否完成。", "logs.detail.stage.sideEffect": "已产生副作用", "logs.detail.stage.terminal": "已交付答复", "logs.detail.resend.permitted": "可以重发", diff --git a/gui/src/pages/Logs.tsx b/gui/src/pages/Logs.tsx index 5c1ac40f4bd..a6efc651ab2 100644 --- a/gui/src/pages/Logs.tsx +++ b/gui/src/pages/Logs.tsx @@ -30,7 +30,7 @@ import { logsTabKeyDown, readTabFromHash, selectLogsTab } from "./logs-tab-keydo import { isModelRerouted, modelTitle, type ModelTitleTierOutcome } from "./logs-model-title"; import { speedLabel } from "./logs-speed-label"; import { decodeRateLabelKeys } from "./logs-decode-rate"; -import { failureAttributionLabels, failureDetailLabel, failureSummary, upstreamConditionLabel } from "./logs-failure-summary"; +import { failureAttributionLabels, failureDetailLabel, failureSummary, isInterruptedWebSocketDelivery, upstreamConditionLabel } from "./logs-failure-summary"; import "./logs-decode-rate.css"; import { effectivePriorityLowerBound, estimateReasonsForBilling, formatCredits, formatEstimatedUsd, formatEstimatedUsdValue, formatUsdPrecise, summarizeEstimatedCosts, type CostBilling, type PartialCostResult, type CostEstimateReason as BillingEstimateReason } from "./logs-cost-format"; import { cacheSplit, isCursorUsageProvider, tokensTitle } from "./logs-token-title"; @@ -142,6 +142,12 @@ interface LogFailureAttribution { } interface LogAttempt extends LogFailureAttribution { + codexWsStage?: { + sent: boolean; + closeCode: number | null; + relayedEvents: number; + terminalEvent: string | null; + }; ordinal: number; provider: string; model: string; @@ -209,6 +215,8 @@ export interface LogEntry extends LogFailureAttribution { * numeric HTTP status alone and reported an incomplete 200 as a plain success. */ terminalStatus?: string; + terminalSource?: string; + transportPhase?: string; closeReason?: "terminal" | "client_cancel" | "non_stream" | "body_stall" | "body_overflow"; /** Upstream spend for the whole logical request, aggregated across attempts and combo children. */ spend?: RequestSpendTotals; @@ -963,6 +971,9 @@ export default function Logs({ apiBase }: { apiBase: string }) { {speedLabel(log) && {speedLabel(log)}} + {isInterruptedWebSocketDelivery(log) && ( + {t("logs.status.streamInterrupted")} + )} {log.requestId ?? "-"} @@ -1140,7 +1151,9 @@ function LogDetailDialog({ - {summary.description &&

{summary.description}

} + {isInterruptedWebSocketDelivery(detail) + ?

{t("logs.detail.streamInterrupted1006")}

+ : summary.description &&

{summary.description}

}

{t("logs.detail.section.basic")}

diff --git a/gui/src/pages/logs-failure-summary.ts b/gui/src/pages/logs-failure-summary.ts index b263371396b..e3145dcff1b 100644 --- a/gui/src/pages/logs-failure-summary.ts +++ b/gui/src/pages/logs-failure-summary.ts @@ -2,6 +2,7 @@ import type { TFn } from "../i18n/shared"; import type { RequestFailureCause, RequestFailureStage, ResendPermission, RequestSpendTotals } from "../../../src/usage/telemetry-contract"; import type { UpstreamCondition } from "../../../src/lib/upstream-condition"; import { boundedFailureDetail, type FailureDetailCode } from "../../../src/lib/failure-detail"; +import type { LogEntry } from "./Logs"; interface LogFailureAttribution { failureCause?: RequestFailureCause; @@ -79,6 +80,23 @@ export function failureAttributionLabels( const nonnegativeInteger = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 0; +/** Stages that prove the caller received response events: lifecycle frames, output, or a tool side effect. */ +const RELAYED_EVENT_STAGES: ReadonlySet = new Set(["protocol-prelude", "semantic-output", "side-effect"]); + +/** A failed delivery can end an attempt in an otherwise successful request. Describe only the final failure. */ +export function isInterruptedWebSocketDelivery(row: LogEntry): boolean { + if (row.status !== 502 || (row.closeReason !== undefined && row.closeReason !== "terminal") + || (row.terminalStatus !== undefined && row.terminalStatus !== "failed") + || row.terminalSource !== "synthetic" || row.transportPhase !== "mid_stream" + || row.failureStage === undefined || !RELAYED_EVENT_STAGES.has(row.failureStage) || row.failureCause !== "transport-ambiguous" + || row.attemptNormalizationDropped === true || !Array.isArray(row.attempts)) return false; + const last = row.attempts.at(-1); + const stage = last?.codexWsStage; + return last?.status === row.status && last.failureStage === row.failureStage && last.failureCause === row.failureCause + && stage?.sent === true && stage.closeCode === 1006 + && stage.terminalEvent === null && Number.isSafeInteger(stage.relayedEvents) && stage.relayedEvents > 0; +} + export function failureSummary( row: LogFailureAttribution & { spend?: RequestSpendTotals; attempts?: Array<{ sendCount: number }>; attemptNormalizationDropped?: boolean }, fallback: { label: string; description: string } | null, diff --git a/gui/tests/logs-upstream-faults.test.tsx b/gui/tests/logs-upstream-faults.test.tsx index 0dc5ba18d0b..cb41938177e 100644 --- a/gui/tests/logs-upstream-faults.test.tsx +++ b/gui/tests/logs-upstream-faults.test.tsx @@ -170,6 +170,75 @@ test.each([ } finally { await act(async () => { root.unmount(); }); } }); +function interruptedFixture() { + const row = fixture(502, "transport-ambiguous", 1); + const attempt = (row.attempts as Record[])[0]!; + const stage = { sent: true, closeCode: 1006, relayedEvents: 3, terminalEvent: null }; + const failure = { failureStage: "semantic-output", failureCause: "transport-ambiguous" }; + const last = { ...attempt, ...failure, adapter: "openai-responses", codexWsStage: stage }; + return { ...row, ...failure, terminalSource: "synthetic", transportPhase: "mid_stream", attempts: [last] }; +} + +test("a final abnormal WebSocket close after delivery is visible in the row and its detail", async () => { + const { root, container } = await show(interruptedFixture()); + try { + const row = container.querySelector("tbody tr[data-index]"); + expect(row?.textContent).toContain("502"); + expect(row?.textContent).toContain("Stream interrupted"); + expect(document.querySelector(".modal-desc")?.textContent).toBe( + "The upstream WebSocket closed abnormally (1006) after response events were relayed. No completion was confirmed.", + ); + } finally { await act(async () => { root.unmount(); }); } +}); + +test.each([ + ["lifecycle events only", "protocol-prelude"], + ["a delivered tool call", "side-effect"], +] as const)("an abnormal close after %s is also an interrupted stream", async (_name, failureStage) => { + const row = interruptedFixture(); + const attempts = [{ ...row.attempts[0]!, failureStage }]; + const { root, container } = await show({ ...row, failureStage, attempts }); + try { + expect(container.querySelector("tbody tr[data-index]")?.textContent).toContain("Stream interrupted"); + expect(document.querySelector(".modal-desc")?.textContent).toContain("(1006)"); + } finally { await act(async () => { root.unmount(); }); } +}); + +test.each([ + ["completed request", { status: 200, terminalStatus: "completed" }, {}, {}], + ["client cancellation", { closeReason: "client_cancel" }, {}, {}], + ["upstream terminal", { terminalSource: "upstream" }, {}, {}], + ["pre-response failure", { transportPhase: "pre_headers" }, {}, {}], + ["headers-only failure", { failureStage: "headers-only" }, { failureStage: "headers-only" }, {}], + ["dropped attempt", { attemptNormalizationDropped: true }, {}, {}], + ["different final cause", {}, { failureCause: "upstream-fault" }, {}], + ["normal close", {}, {}, { closeCode: 1000 }], + ["upstream failed event", {}, {}, { terminalEvent: "response.failed" }], + ["missing terminal data", {}, {}, { terminalEvent: undefined }], + ["no response events", {}, {}, { relayedEvents: 0 }], + ["malformed response count", {}, {}, { relayedEvents: "3" }], +] as const)("%s leaves the usual request status and detail intact", async (_name, rowFields, attemptFields, stageFields) => { + const row = interruptedFixture(); + const attempt = row.attempts[0]!; + const attempts = [{ ...attempt, ...attemptFields, codexWsStage: { ...attempt.codexWsStage, ...stageFields } }]; + const { root, container } = await show({ ...row, ...rowFields, attempts }); + try { + expect(container.querySelector("tbody tr[data-index]")?.textContent).not.toContain("Stream interrupted"); + expect(document.querySelector(".modal-desc")?.textContent ?? "").not.toContain("1006"); + } finally { await act(async () => { root.unmount(); }); } +}); + +test("a close on an earlier attempt does not explain a later failure", async () => { + const row = interruptedFixture(); + const first = row.attempts[0]!; + const attempts = [first, { ...first, ordinal: 2, codexWsStage: undefined }]; + const { root, container } = await show({ ...row, attempts }); + try { + expect(container.querySelector("tbody tr[data-index]")?.textContent).not.toContain("Stream interrupted"); + expect(document.querySelector(".modal-desc")?.textContent ?? "").not.toContain("1006"); + } finally { await act(async () => { root.unmount(); }); } +}); + test("a lossy normalized attempt roster does not imply retries", async () => { const row = fixture(500, "upstream-fault", 3); row.attemptNormalizationDropped = true; From 1de67a2900b63f1aadd68446b2e3f89fb7aeee3e Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 05:04:01 +0900 Subject: [PATCH 13/64] fix(responses): mask terminal diagnostics while preserving completion output (#9060) * fix(responses): redact terminal diagnostics while preserving completion output * docs(responses): keep the terminal masking contract within the structure budget * fix(responses): mask individual refusal fields before completion * test(responses): reuse the buffered credential fixture for both verdicts --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../docs/es/reference/proxy-formats.md | 4 + .../content/docs/reference/proxy-formats.md | 4 + .../responses/terminal-error-redaction.ts | 80 +++++++++++++++- structure/transports/responses-wire-shapes.md | 6 +- .../responses-pool-401-refresh.test.ts | 16 ++-- .../sse-untyped-credential-mask.test.ts | 93 +++++++++++++++++++ 6 files changed, 192 insertions(+), 11 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index ceaf79c34f7..26f36a0d6ce 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -42,6 +42,10 @@ Los clientes que esperan una respuesta completa reciben un error JSON con el est correspondiente. OpenCodex registra el fallo y el uso declarado sin guardar la respuesta para reutilizarla mediante `previous_response_id`. +El texto de rechazo por sí solo conserva el estado completado. OpenCodex enmascara las credenciales +del proveedor en cada campo de rechazo al recibirlo, incluidas las partes de rechazo de los mensajes. +La salida normal y los argumentos de las herramientas conservan su contenido original. + ## Herramientas obligatorias en rutas Chat traducidas diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index d31d2a60d79..b0163c4c142 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -63,6 +63,10 @@ OpenCodex records the failure and any reported usage without saving the response `previous_response_id` replay. Auto/none, incomplete results and unknown contracts retain their existing rules. +Refusal text alone preserves a completed response. OpenCodex masks provider credentials in individual +refusal fields as they arrive, including refusal parts in message items. Ordinary output and tool +arguments keep their original content. + ## Required tools on translated Chat routes Before sending, the proxy rejects a mandatory tool choice that the selected Chat destination cannot diff --git a/src/server/responses/terminal-error-redaction.ts b/src/server/responses/terminal-error-redaction.ts index 32a506a9844..d5c96d24418 100644 --- a/src/server/responses/terminal-error-redaction.ts +++ b/src/server/responses/terminal-error-redaction.ts @@ -28,7 +28,7 @@ const PROTOCOL_EVENT_LINE = /^event:[ \t]*(?:response\.[a-z_.]+|error|done|ping) const PROTOCOL_KEYS = new Set([ "type", "response", "error", "last_error", "message", "code", "param", "status", "id", "object", "incomplete_details", "reason", "output", "usage", "metadata", "sequence_number", "model", "created_at", - "retryable", + "retryable", "refusal", ]); function withEscapedSpelling(part: string): string[] { @@ -195,6 +195,79 @@ function createRedactionTools(outboundHeaders: Record, maskCrede return { redactDiagnostic, maskExtensionLines, maskUnstructuredBlock, redactUpstreamCopyBlock }; } +const EARLY_REFUSAL_EVENTS = new Set([ + "response.refusal.delta", "response.refusal.done", "response.content_part.added", + "response.content_part.done", "response.output_item.added", "response.output_item.done", +]); + +/** Refusal diagnostics can share a frame with ordinary output and tool arguments. */ +function maskResponseDiagnostics( + event: Record, + redactDiagnostic: (value: unknown) => unknown, +): { present: boolean; changed: boolean } { + let present = false; + let changed = false; + const maskPart = (part: unknown): unknown => { + if (!part || typeof part !== "object" || !("type" in part) || part.type !== "refusal") return part; + present = true; + const safe = redactDiagnostic(part); + if (JSON.stringify(part) !== JSON.stringify(safe)) changed = true; + return safe; + }; + const maskItem = (item: unknown) => { + if (!item || typeof item !== "object" || !("type" in item) || item.type !== "message" + || !("content" in item) || !Array.isArray(item.content)) return; + for (const [index, part] of item.content.entries()) item.content[index] = maskPart(part); + }; + switch (event.type) { + case "response.refusal.delta": + case "response.refusal.done": { + const key = event.type === "response.refusal.delta" ? "delta" : "refusal"; + if (typeof event[key] !== "string") return { present: false, changed: false }; + // Each wire field is independent here. Ordinary output deltas take no diagnostic rewrite. + const safe = redactDiagnostic({ refusal: event[key] }) as { refusal: string }; + changed = safe.refusal !== event[key]; + event[key] = safe.refusal; + return { present: true, changed }; + } + case "response.content_part.added": + case "response.content_part.done": + event.part = maskPart(event.part); + return { present, changed }; + case "response.output_item.added": + case "response.output_item.done": + maskItem(event.item); + return { present, changed }; + case "response.completed": break; + default: return { present: false, changed: false }; + } + const maskField = (entry: Record, key: string) => { + if (entry[key] == null) return; + present = true; + // Use a diagnostic envelope so the error's type is treated as an error class, + // not the protocol type of the SSE event. + const envelope = { error: entry[key] }; + const safe = keepPolicyEvidence(envelope, redactDiagnostic(envelope)) as { error: unknown }; + if (JSON.stringify(entry[key]) !== JSON.stringify(safe.error)) { + entry[key] = safe.error; + changed = true; + } + }; + for (const carrier of [event, event.response]) { + if (!carrier || typeof carrier !== "object" || Array.isArray(carrier)) continue; + const entry = carrier as Record; + maskField(entry, "error"); + maskField(entry, "last_error"); + const details = entry.incomplete_details; + if (carrier === event.response && details && typeof details === "object" && !Array.isArray(details)) { + const diagnostic = details as Record; + if (typeof diagnostic.message === "string") maskField(diagnostic, "message"); + } + if (Array.isArray(entry.output)) for (const item of entry.output) maskItem(item); + } + return { present, changed }; +} + /** * Redaction the terminal boundary applies to a typed bare `error` frame it forwards to the client, * after it has reduced the frame's verdict from the original. Running it inside the boundary keeps @@ -238,6 +311,11 @@ export function createTerminalErrorRedactionBlockRewrite( return [terminalFrame ? maskUnstructuredBlock(block, payload) : block]; } if (isUntypedBareUpstreamError(event) || event?.type === "error") return [block]; + if (!terminalFrame && (event?.type === "response.completed" + || (typeof event?.type === "string" && EARLY_REFUSAL_EVENTS.has(event.type)))) { + const { present, changed } = maskResponseDiagnostics(event, redactDiagnostic); + if (present) return [maskExtensionLines(changed ? replaceSseDataPayload(block, JSON.stringify(event)) : block)]; + } if (event?.type !== "response.failed" && event?.type !== "response.incomplete") { // A terminal event line over another JSON payload is upstream copy throughout, masked field by // field so recognized classes survive for every reader. diff --git a/structure/transports/responses-wire-shapes.md b/structure/transports/responses-wire-shapes.md index e349085d85d..3dc3de3c926 100644 --- a/structure/transports/responses-wire-shapes.md +++ b/structure/transports/responses-wire-shapes.md @@ -376,8 +376,8 @@ destination receives unchanged whenever a caller sends one itself. ## Passthrough SSE stream shapes (#314) -Native passthrough SSE has TWO shapes, selected per request in -`src/server/responses/core.ts`; both apply the client-only [hosted-image projection](../data-planes/images.md#hosted-responses-image-display) after continuation-cache observers: `src/lib/errors.ts` selects the first nonblank string in the canonical upstream message precedence (error, last_error, response error, incomplete details, then a flat error event). Malformed or blank fields cannot hide a later valid diagnostic; retained text is not rewritten. +`src/server/responses/core.ts` selects one of two native passthrough SSE shapes per request. Both apply the client-only [hosted-image projection](../data-planes/images.md#hosted-responses-image-display) after continuation-cache observers. On client delivery, both mask credentials in completed-response diagnostics and refusal parts while preserving the event type, ordinary message content and tool arguments. +`src/lib/errors.ts` selects the first nonblank string in the canonical upstream message precedence (error, last_error, response error, incomplete details, then a flat error event). Malformed or blank fields cannot hide a later valid diagnostic; retained text is not rewritten. - **Default outside Windows: tee + background inspection.** `upstreamResponse.body.tee()` sends branch[0] through a terminal-aware client relay while branch[1] is @@ -437,7 +437,7 @@ Deferred inspection checks cancellation after each yield and commits serving-rou after the final abort check; a disconnect returns 499 without publishing that state or a terminal. This buffered path makes no tee/eager choice. Failed and incomplete terminals mask selected outbound credentials across the full event, including nested output and metadata, before JSON or SSE delivery; -synthetic stream failures use the same credential mask in both streaming relays. +synthetic stream failures use the same credential mask in both streaming relays. Refusal delta, part and item events are masked field by field before delivery. Buffered error-bearing completions use `deliverFailedCompletion` in `src/server/responses/passthrough-delivery.ts` to mask their JSON error. > Decision record: [ADR-6162](../decisions/ADR-6162-responses-http-sse.md) diff --git a/tests/responses/responses-pool-401-refresh.test.ts b/tests/responses/responses-pool-401-refresh.test.ts index 760ed7d1d4a..253ebe9f9b3 100644 --- a/tests/responses/responses-pool-401-refresh.test.ts +++ b/tests/responses/responses-pool-401-refresh.test.ts @@ -536,23 +536,25 @@ describe("ordinary pool 401 refresh and replay (#2887)", () => { expect(expandPreviousResponseInput(next)).toEqual(next); }); - test("bare upstream SSE error masks the selected pool credential in buffered JSON and diagnostics", async () => { + test.each(["error", "response.completed"] as const)("%s masks the selected pool credential in buffered JSON", async type => { const harness = installHarness({ responseForSend(authorization) { - return new Response(`event: error\ndata: ${JSON.stringify({ - type: "error", - error: { type: "server_error", code: "upstream_error", message: `rejected ${authorization.slice(7)}` }, - })}\n\n`, { headers: { "content-type": "text/event-stream" } }); + const message = `rejected ${authorization.slice(7)}`; + const event = type === "error" ? { type, error: { type: "server_error", code: "upstream_error", message } } + : { type, response: { id: "resp_buffered_verdict", status: "completed", output: [], + error: { type: "rate_limit_error", code: "rate_limit_exceeded", message } } }; + return new Response(`event: ${type}\ndata: ${JSON.stringify(event)}\n\n`, { headers: { "content-type": "text/event-stream" } }); }, }); const logCtx = { model: "", provider: "" } as RequestLogContext; const response = await handleResponses(request("/v1/responses"), config(), logCtx); const body = await response.text(); expect(harness.sends).toEqual(["Bearer rejected-access"]); - expect(response.status).toBe(502); + expect(response.status).toBe(type === "error" ? 502 : 429); + if (type === "response.completed") expect(JSON.parse(body)).toMatchObject({ error: { code: "rate_limit_exceeded" } }); expect(body).not.toContain("rejected-access"); expect(body).toContain("[REDACTED]"); - expect(JSON.stringify(logCtx)).not.toContain("rejected-access"); + if (type === "error") expect(JSON.stringify(logCtx)).not.toContain("rejected-access"); }); test("disconnect during buffered replay does not record a pool conversation-state issuer", async () => { diff --git a/tests/responses/sse-untyped-credential-mask.test.ts b/tests/responses/sse-untyped-credential-mask.test.ts index 1b3654d5f7e..8e1436ac7ac 100644 --- a/tests/responses/sse-untyped-credential-mask.test.ts +++ b/tests/responses/sse-untyped-credential-mask.test.ts @@ -12,6 +12,99 @@ import { reduceBareUpstreamEvidence } from "../../src/server/bare-upstream-error const encoder = new TextEncoder(); const decoder = new TextDecoder(); +describe("completed response diagnostics", () => { + const marker = "demo-mask-80452719"; + const rewrite = createTerminalErrorRedactionBlockRewrite({ "x-api-key": marker }); + const message = { type: "message", content: [{ type: "output_text", text: "ordinary answer" }] }; + const call = { type: "function_call", arguments: JSON.stringify({ example: "Bearer placeholder12345" }) }; + const frame = (value: unknown) => "event: response.completed\ndata: " + JSON.stringify(value); + const read = (block: string) => JSON.parse(sseDataPayload(rewrite(block)[0]!)!); + + test("masks diagnostic fields on both carriers while preserving normal content and error class", () => { + const error = { type: "invalid_request_error", code: "rate_limit_exceeded", message: marker }; + const original = { type: "response.completed", error, last_error: marker, + response: { status: "completed", error: marker, last_error: error, output: [message, call] } }; + const safe = read(frame(original)); + expect(safe).toEqual({ type: original.type, error: { ...error, message: REDACTED_SECRET }, + last_error: REDACTED_SECRET, response: { status: "completed", error: REDACTED_SECRET, + last_error: { ...error, message: REDACTED_SECRET }, output: [message, call] } }); + }); + + test("masks only refusal parts when a completed message has mixed content", () => { + const ordinaryPart = message.content[0]!; + const makeMessage = (refusal: string) => ({ type: "message", content: [ordinaryPart, { type: "refusal", refusal }] }); + const input = { type: "response.completed", output: [makeMessage(marker)], response: { output: [makeMessage(marker), call] } }; + expect(read(frame(input))).toEqual({ type: input.type, output: [makeMessage(REDACTED_SECRET)], + response: { output: [makeMessage(REDACTED_SECRET), call] } }); + }); + + test("keeps original wire formatting when the payload needs no masking", () => { + for (const response of [{ output: [message, call] }, { last_error: "test diagnostic", output: [] }, + { incomplete_details: { reason: "max_output_tokens" }, output: [message] }]) { + const block = frame({ type: "response.completed", response }).replace("data: {", "data: { "); + expect(rewrite(block)).toEqual([block]); + } + }); + + test("masks the incomplete-details message and preserves its reason and ordinary content", () => { + const original = { type: "response.completed", response: { + incomplete_details: { reason: "max_output_tokens", message: marker }, output: [message, call], + } }; + expect(read(frame(original))).toEqual({ type: original.type, response: { + incomplete_details: { reason: "max_output_tokens", message: REDACTED_SECRET }, output: [message, call], + } }); + }); + + test("keeps the refusal field name and discriminator when the mask matches protocol vocabulary", () => { + const mask = createTerminalErrorRedactionBlockRewrite({ "x-api-key": "refusal" }); + const part = { type: "refusal", refusal: "sample refusal" }; + const block = frame({ type: "response.completed", response: { output: [{ type: "message", content: [part] }, call] } }); + expect(JSON.parse(sseDataPayload(mask(block)[0]!)!).response.output).toEqual([ + { type: "message", content: [{ type: "refusal", refusal: "sample " + REDACTED_SECRET }] }, call, + ]); + }); + + test.each(["response.refusal.delta", "response.refusal.done", "response.content_part.added", + "response.content_part.done", "response.output_item.added", "response.output_item.done"])( + "%s masks the refusal field and preserves its envelope", type => { + const event = (value: string) => { + const part = { type: "refusal", refusal: value }; + const identity = { type, sequence_number: 3, output_index: 0, content_index: 1 }; + if (type === "response.refusal.delta") return { ...identity, delta: value }; + if (type === "response.refusal.done") return { ...identity, refusal: value }; + if (type.startsWith("response.content_part.")) return { ...identity, part }; + return { ...identity, item: { ...message, content: [...message.content, part] } }; + }; + const block = "event: " + type + "\ndata: " + JSON.stringify(event(marker)); + expect(read(block)).toEqual(event(REDACTED_SECRET)); + const safe = "event: " + type + "\r\ndata: " + JSON.stringify(event("ordinary refusal")); + expect(rewrite(safe)).toEqual([safe]); + }, + ); + + test("early ordinary text and function arguments keep their original wire bytes", () => { + for (const event of [ + { type: "response.output_text.delta", delta: marker }, + { type: "response.content_part.done", part: { type: "output_text", text: marker } }, + { type: "response.output_item.done", item: { type: "function_call", arguments: marker } }, + ]) { + const block = "event: " + event.type + "\r\ndata: " + JSON.stringify(event); + expect(rewrite(block)).toEqual([block]); + } + }); + + test("tee and eager delivery retain the completed verdict and masked diagnostic", async () => { + const original = { type: "response.completed", response: { status: "completed", last_error: marker, output: [message] } }; + for (const mode of ["tee", "eager"] as const) { + const delivered = await deliver(mode, { "x-api-key": marker }, [original, "[DONE]"]); + expect(terminalTypes(delivered)).toEqual(["response.completed"]); + expect(delivered).toContain(REDACTED_SECRET); + expect(delivered).not.toContain(marker); + expect(delivered).toContain("ordinary answer"); + } + }); +}); + function sourceStream(chunks: readonly string[]): ReadableStream { let i = 0; return new ReadableStream({ From c66beeb9a499b8b64ca65da47be61b2c6b17908f Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 05:04:09 +0900 Subject: [PATCH 14/64] fix(images): bound inline inputs on the xAI edit relay (#9116) * fix(images): bound inline inputs on the xAI edit relay * Honor the decoded limit and identify the fixed xAI edit ceiling * docs(images): mirror the xAI edit input limits in the Spanish guide The English image-bridge guide gained the xAI edit relay limits; the Spanish guide had no counterpart, which docs-spanish-localization.test.ts rejects (guides/image-bridge.md inline and model identifiers). --------- Co-authored-by: Epinephrine <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../content/docs/es/guides/image-bridge.md | 2 + .../es/reference/inbound-body-admission.md | 2 +- .../fr/reference/inbound-body-admission.md | 2 +- .../src/content/docs/guides/image-bridge.md | 5 + .../ja/reference/inbound-body-admission.md | 2 +- .../ko/reference/inbound-body-admission.md | 2 +- .../docs/reference/inbound-body-admission.md | 2 +- .../ru/reference/inbound-body-admission.md | 2 +- .../tr/reference/inbound-body-admission.md | 2 +- .../zh-cn/reference/inbound-body-admission.md | 2 +- .../zh-tw/reference/inbound-body-admission.md | 2 +- src/images/artifacts.ts | 2 +- src/server/images.ts | 133 +++++++++++------- src/server/request-decompress.ts | 5 +- src/server/responses/core-errors.ts | 4 +- structure/data-planes/images.md | 9 +- tests/server/server-images-xai-relay.test.ts | 75 +++++++++- 17 files changed, 186 insertions(+), 67 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/image-bridge.md b/docs-site/src/content/docs/es/guides/image-bridge.md index d04a3bc52de..5747e7afae4 100644 --- a/docs-site/src/content/docs/es/guides/image-bridge.md +++ b/docs-site/src/content/docs/es/guides/image-bridge.md @@ -18,6 +18,8 @@ Cuando enrutas Codex mediante un modelo distinto de OpenAI (Claude, Gemini, Grok El relé solo administra esa ruta si no se ha configurado un proveedor de imágenes: requiere `images.bridgeEnabled` en `true` y que se omita `images.provider`. Si estableces `images.provider` explícitamente, `/v1/images` usa ese proveedor y devuelve sus errores de validación sin volver a intentar mediante xAI. + En las ediciones enrutadas a xAI, el menor entre `maxInboundBodyBytes` y 100 MiB limita la solicitud JSON descomprimida. Cada imagen en línea puede contener unos 66,7 MiB de texto base64. Las imágenes en línea distintas comparten un presupuesto de 100 MiB de datos codificados. Las URL de imagen HTTPS cuentan para el límite de cinco fuentes y no añaden datos de imagen en línea. + ```json { "providers": { diff --git a/docs-site/src/content/docs/es/reference/inbound-body-admission.md b/docs-site/src/content/docs/es/reference/inbound-body-admission.md index b2cbbe5267f..7624ad2e96a 100644 --- a/docs-site/src/content/docs/es/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/es/reference/inbound-body-admission.md @@ -40,7 +40,7 @@ Establecer explícitamente `maxConcurrentInboundBodyBytes` en `2147483648` elige La reserva reducida se mantiene durante el trabajo asíncrono y la espera del proveedor hasta el fin del flujo, un error o la cancelación completada. Analizar el cuerpo no la libera. Si el cliente se desconecta, se conserva hasta que termina la cancelación del productor. Se libera exactamente una vez, incluso si compiten errores, abortos y cancelaciones. -Los destinos POST cubiertos son `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits` y `/v1/alpha/search`. Las imágenes, la búsqueda y el recuento de tokens conservan sus límites configurables por cuerpo. Las llamadas internas de traducción directa y de Combos no reservan una segunda capacidad HTTP. No cambian los límites de administración, audio, historial de contexto ni WebSocket. +Los destinos POST cubiertos son `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits` y `/v1/alpha/search`. Las imágenes, la búsqueda y el recuento de tokens conservan sus límites configurables por cuerpo. Las ediciones enviadas mediante el puente de xAI también tienen un límite fijo de 100 MiB por solicitud. Se aplica el menor de los dos límites. Las llamadas internas de traducción directa y de Combos no reservan una segunda capacidad HTTP. No cambian los límites de administración, audio, historial de contexto ni WebSocket. Este control adicional solo se activa cuando `maxInboundBodyBytes` efectivo supera 256 MiB. Omitir esa opción o usar `0` conserva los 256 MiB predeterminados y deja el control inactivo. Omitir o poner a cero `maxConcurrentInboundBodyBytes` elige los 512 MiB compartidos predeterminados; no desactiva un control que ya esté activo. Se mantienen los demás límites de solicitudes y recursos. diff --git a/docs-site/src/content/docs/fr/reference/inbound-body-admission.md b/docs-site/src/content/docs/fr/reference/inbound-body-admission.md index cc3cc9efd6f..118e981ab94 100644 --- a/docs-site/src/content/docs/fr/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/fr/reference/inbound-body-admission.md @@ -75,7 +75,7 @@ Les points de terminaison POST concernés sont `/v1/responses`, `/v1/responses/c `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits` et `/v1/alpha/search`. Les images, la recherche et le comptage de jetons conservent leurs limites configurables -existantes par corps. Les traductions directes internes et les appels combo ne réservent pas +existantes par corps. Les modifications d’images via le pont xAI ont aussi un plafond fixe de 100 MiB par requête. La limite la plus basse s’applique. Les traductions directes internes et les appels combo ne réservent pas une deuxième marge HTTP. Les limites de gestion, d'audio, d'historique de contexte et de WebSocket restent inchangées. diff --git a/docs-site/src/content/docs/guides/image-bridge.md b/docs-site/src/content/docs/guides/image-bridge.md index 3e0495ea109..49c8a1b9a38 100644 --- a/docs-site/src/content/docs/guides/image-bridge.md +++ b/docs-site/src/content/docs/guides/image-bridge.md @@ -30,6 +30,11 @@ xAI Grok Imagine, so the model you're actually chatting with can still generate `images.provider` explicitly hands `/v1/images` to that provider, and its own validation errors are returned as-is rather than being retried through xAI. + For edits routed to xAI, the smaller of `maxInboundBodyBytes` and 100 MiB limits the + decompressed JSON request. Each inline image can contain about 66.7 MiB of base64 text. + Distinct inline images share a 100 MiB encoded-data budget. HTTPS image URLs count toward + the five-source limit and add no inline image data. + ```json { "providers": { diff --git a/docs-site/src/content/docs/ja/reference/inbound-body-admission.md b/docs-site/src/content/docs/ja/reference/inbound-body-admission.md index f2ac83d5542..b54e7a78909 100644 --- a/docs-site/src/content/docs/ja/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/ja/reference/inbound-body-admission.md @@ -36,7 +36,7 @@ description: リクエスト本文の上限引き上げが、同時 HTTP リク 減量後の予約は、非同期処理やプロバイダーの応答待ちの間も保持され、レスポンスストリームの EOF、エラー、またはキャンセル処理の完了時に解放されます。解析だけでは解放されません。クライアントが切断しても、生成側のキャンセル処理が完了するまで保持されます。エラー、中断、キャンセルが競合しても、解放は正確に 1 回だけ行われます。 -対象となる POST エンドポイントは `/v1/responses`、`/v1/responses/compact`、`/v1/chat/completions`、`/v1/messages`、`/v1/messages/count_tokens`、`/v1/images/generations`、`/v1/images/edits`、`/v1/alpha/search` です。画像、検索、トークン計数には、従来の設定可能な本文ごとの上限も適用されます。内部の直接変換やコンボ呼び出しは、HTTP の許容量を二重に予約しません。管理、音声、コンテキスト履歴、WebSocket の制限は変わりません。 +対象となる POST エンドポイントは `/v1/responses`、`/v1/responses/compact`、`/v1/chat/completions`、`/v1/messages`、`/v1/messages/count_tokens`、`/v1/images/generations`、`/v1/images/edits`、`/v1/alpha/search` です。画像、検索、トークン計数には、従来の設定可能な本文ごとの上限も適用されます。xAI ブリッジ経由の画像編集には 1 リクエストあたり 100 MiB の固定上限もあり、小さい方の上限が適用されます。内部の直接変換やコンボ呼び出しは、HTTP の許容量を二重に予約しません。管理、音声、コンテキスト履歴、WebSocket の制限は変わりません。 この追加の同時実行ゲートは、適用される `maxInboundBodyBytes` が 256 MiB を超える場合にのみ有効です。このリクエスト単位の設定を省略するか `0` にすると、デフォルトの 256 MiB が使われ、ゲートは無効のままです。一方、`maxConcurrentInboundBodyBytes` を省略または `0` にすると共有予算のデフォルト 512 MiB が選ばれ、有効なゲートを無効にはしません。既存のリクエスト件数やその他のリソース制限は引き続き適用されます。 diff --git a/docs-site/src/content/docs/ko/reference/inbound-body-admission.md b/docs-site/src/content/docs/ko/reference/inbound-body-admission.md index 45ccb681fd7..d1c1349d33d 100644 --- a/docs-site/src/content/docs/ko/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/ko/reference/inbound-body-admission.md @@ -36,7 +36,7 @@ description: 요청 본문 한도를 높였을 때 동시 HTTP 요청, 재시도 줄어든 예약량은 비동기 작업과 프로바이더 응답 대기 중에도 유지되며, 응답 스트림의 끝(EOF), 오류 또는 취소 완료 시점에 해제됩니다. 파싱만 끝났다고 해제하지 않습니다. 클라이언트 연결이 끊겨도 응답 생산자의 취소 처리가 끝날 때까지 유지합니다. 오류·요청 중단·취소가 겹치더라도 해제는 정확히 한 번만 일어납니다. -적용 대상 POST 엔드포인트는 `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits`, `/v1/alpha/search`입니다. 이미지, 검색, 토큰 계산에는 기존의 설정 가능한 본문별 한도가 계속 적용됩니다. 내부 직접 변환 호출과 콤보 호출은 HTTP 허용량을 두 번 예약하지 않습니다. 관리 API, 오디오, 컨텍스트 기록, WebSocket의 한도는 그대로입니다. +적용 대상 POST 엔드포인트는 `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits`, `/v1/alpha/search`입니다. 이미지, 검색, 토큰 계산에는 기존의 설정 가능한 본문별 한도가 계속 적용됩니다. xAI 브리지를 거치는 이미지 편집 요청에는 100 MiB 고정 한도도 적용되며, 두 한도 중 작은 값이 우선합니다. 내부 직접 변환 호출과 콤보 호출은 HTTP 허용량을 두 번 예약하지 않습니다. 관리 API, 오디오, 컨텍스트 기록, WebSocket의 한도는 그대로입니다. 이 추가 동시 처리 게이트는 적용된 `maxInboundBodyBytes`가 256 MiB를 넘을 때만 켜집니다. 이 요청별 설정을 생략하거나 `0`으로 두면 기본값인 256 MiB가 유지되어 게이트가 꺼져 있습니다. 반면 `maxConcurrentInboundBodyBytes`를 생략하거나 `0`으로 두면 공유 기본값인 512 MiB를 선택하며, 이미 켜진 게이트를 끄지는 않습니다. 기존 요청 수 제한과 다른 자원 제한은 계속 적용됩니다. diff --git a/docs-site/src/content/docs/reference/inbound-body-admission.md b/docs-site/src/content/docs/reference/inbound-body-admission.md index 52533905a45..41353c99350 100644 --- a/docs-site/src/content/docs/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/reference/inbound-body-admission.md @@ -70,7 +70,7 @@ including when errors, aborts, and cancellation race. The covered POST endpoints are `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits`, and `/v1/alpha/search`. -Images, search, and token counting keep their existing configurable per-body limits. +Images, search, and token counting keep their existing configurable per-body limits. Edits routed through the xAI bridge also have a fixed 100 MiB request limit. The smaller limit applies. Internal direct translation and combo calls do not reserve a second HTTP allowance. Management, audio, context-history, and WebSocket limits are unchanged. diff --git a/docs-site/src/content/docs/ru/reference/inbound-body-admission.md b/docs-site/src/content/docs/ru/reference/inbound-body-admission.md index 09dd53caad8..effe35b668c 100644 --- a/docs-site/src/content/docs/ru/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/ru/reference/inbound-body-admission.md @@ -74,7 +74,7 @@ description: Как увеличение лимита тела запроса в Охватываются POST-эндпоинты `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits` и `/v1/alpha/search`. -Для изображений, поиска и подсчёта токенов сохраняются их настраиваемые лимиты тела. +Для изображений, поиска и подсчёта токенов сохраняются их настраиваемые лимиты тела. Для запросов на редактирование изображений через мост xAI также действует фиксированный предел в 100 MiB. Применяется меньший из двух лимитов. Внутренний прямой перевод запросов и вызовы combo не резервируют второй HTTP-допуск. Лимиты управления, аудио, истории контекста и WebSocket не меняются. diff --git a/docs-site/src/content/docs/tr/reference/inbound-body-admission.md b/docs-site/src/content/docs/tr/reference/inbound-body-admission.md index 17bbfdec6d5..9221a349083 100644 --- a/docs-site/src/content/docs/tr/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/tr/reference/inbound-body-admission.md @@ -78,7 +78,7 @@ Kapsanan POST uç noktaları `/v1/responses`, `/v1/responses/compact`, `/v1/chat/completions`, `/v1/messages`, `/v1/messages/count_tokens`, `/v1/images/generations`, `/v1/images/edits` ve `/v1/alpha/search` yollarıdır. Görseller, arama ve belirteç sayımı mevcut yapılandırılabilir gövde başı -sınırlarını korur. İç doğrudan çeviri ve kombo çağrıları ikinci bir HTTP alanı +sınırlarını korur. xAI köprüsünden geçen görsel düzenleme istekleri için ayrıca 100 MiB sabit sınır vardır. İki sınırdan küçük olanı uygulanır. İç doğrudan çeviri ve kombo çağrıları ikinci bir HTTP alanı ayırmaz. Yönetim, ses, bağlam geçmişi ve WebSocket sınırları değişmez. Bu ek eşzamanlılık kapısı yalnızca etkin `maxInboundBodyBytes` 256 MiB'ı aştığında uygulanır. diff --git a/docs-site/src/content/docs/zh-cn/reference/inbound-body-admission.md b/docs-site/src/content/docs/zh-cn/reference/inbound-body-admission.md index ba5cb27d8bb..5b14b54faa1 100644 --- a/docs-site/src/content/docs/zh-cn/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/zh-cn/reference/inbound-body-admission.md @@ -36,7 +36,7 @@ description: 提高请求体上限如何影响并发 HTTP 请求、重试和内 减少后的预留量在异步处理及等待提供商响应期间仍会保留,直到响应流 EOF、发生错误或取消处理完成。仅完成解析不会释放预留量。客户端断开连接时,也要等待响应生成端的取消处理完成后才释放。即使错误、中止和取消同时发生,释放也只执行一次。 -受约束的 POST 端点包括 `/v1/responses`、`/v1/responses/compact`、`/v1/chat/completions`、`/v1/messages`、`/v1/messages/count_tokens`、`/v1/images/generations`、`/v1/images/edits` 和 `/v1/alpha/search`。图像、搜索和 token 计数仍遵守各自现有的可配置单请求体上限。内部直接转换和 combo 调用不会再次预留 HTTP 额度。管理、音频、上下文历史和 WebSocket 的上限不变。 +受约束的 POST 端点包括 `/v1/responses`、`/v1/responses/compact`、`/v1/chat/completions`、`/v1/messages`、`/v1/messages/count_tokens`、`/v1/images/generations`、`/v1/images/edits` 和 `/v1/alpha/search`。图像、搜索和 token 计数仍遵守各自现有的可配置单请求体上限。经 xAI 桥接的图像编辑请求还受 100 MiB 固定上限约束,取两者中的较小值。内部直接转换和 combo 调用不会再次预留 HTTP 额度。管理、音频、上下文历史和 WebSocket 的上限不变。 这一额外的并发门槛仅在最终生效的 `maxInboundBodyBytes` 大于 256 MiB 时启用。省略该单请求设置或设为 `0` 会保留其 256 MiB 默认值,因此不会启用门槛。省略 `maxConcurrentInboundBodyBytes` 或设为 `0` 则会选择 512 MiB 共享默认值,不会关闭已启用的门槛。现有请求数量及其他资源限制仍然适用。 diff --git a/docs-site/src/content/docs/zh-tw/reference/inbound-body-admission.md b/docs-site/src/content/docs/zh-tw/reference/inbound-body-admission.md index 9c526b48664..618f761d722 100644 --- a/docs-site/src/content/docs/zh-tw/reference/inbound-body-admission.md +++ b/docs-site/src/content/docs/zh-tw/reference/inbound-body-admission.md @@ -39,7 +39,7 @@ description: 提高請求主體上限如何影響並行 HTTP 請求、重試與 涵蓋的 POST 端點包括 `/v1/responses`、`/v1/responses/compact`、 `/v1/chat/completions`、`/v1/messages`、`/v1/messages/count_tokens`、 `/v1/images/generations`、`/v1/images/edits` 與 `/v1/alpha/search`。 -圖片、搜尋與 token 計數仍沿用各自可設定的單一主體上限。內部直接轉譯與 combo 呼叫不會再次預留 HTTP 額度。管理、音訊、上下文歷史及 WebSocket 的上限不變。 +圖片、搜尋與 token 計數仍沿用各自可設定的單一主體上限。經 xAI 橋接的圖片編輯請求另有 100 MiB 的固定上限,取兩者中較小的值。內部直接轉譯與 combo 呼叫不會再次預留 HTTP 額度。管理、音訊、上下文歷史及 WebSocket 的上限不變。 這道額外的並行閘門只在實際生效的 `maxInboundBodyBytes` 超過 256 MiB 時啟用。省略該單次請求設定或設為 `0`,會保留其 256 MiB 預設值,因此不會啟用閘門。省略 `maxConcurrentInboundBodyBytes` 或設為 `0`,則會選擇 512 MiB 共用預設值,不會關閉已啟用的閘門。現有的請求數及其他資源限制仍然適用。 diff --git a/src/images/artifacts.ts b/src/images/artifacts.ts index e09ccb51da2..cde1ca72ead 100644 --- a/src/images/artifacts.ts +++ b/src/images/artifacts.ts @@ -8,7 +8,7 @@ import { pinnedHttpGet, type PinnedAddress } from "../lib/pinned-http"; export type { PinnedAddress } from "../lib/pinned-http"; -const MAX_DECODED_BYTES_PER_IMAGE = 50 * 1024 * 1024; +export const MAX_DECODED_BYTES_PER_IMAGE = 50 * 1024 * 1024; const MAX_DECODED_BYTES_PER_RESPONSE = 100 * 1024 * 1024; /** Hard cap for remote image downloads (also enforced inside pinnedHttpsGet). */ export const MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024; // 50 MiB diff --git a/src/server/images.ts b/src/server/images.ts index 641b5408269..0a0d9ca115d 100644 --- a/src/server/images.ts +++ b/src/server/images.ts @@ -50,6 +50,7 @@ import { ANTIGRAVITY_REQUEST_UA } from "../adapters/google-antigravity-wire"; import { decodeValidatedImageBase64, fetchPublicHttpsImage, + MAX_DECODED_BYTES_PER_IMAGE, MAX_ENCODED_BYTES_PER_IMAGE, sniffImageExtension, type PinnedDownloadFn, @@ -81,6 +82,12 @@ const IMAGES_UPSTREAM_TIMEOUT_MS = 300_000; */ export const IMAGES_RESPONSE_MAX_BYTES = 100 * 1024 * 1024; +/** + * xAI edit requests are rebuilt as JSON after ingress parsing. Keep that second request-sized + * allocation below the shared 256 MiB default even when an operator raises the general cap. + */ +export const XAI_EDIT_MAX_REQUEST_BYTES = 100 * 1024 * 1024; + interface ImageResponseBytesOptions { signal?: AbortSignal; /** Smaller values are used only by focused reader tests. */ @@ -133,11 +140,9 @@ export async function readImageResponseBytes( const CCA_IMAGE_MODEL = "gemini-3.1-flash-image"; const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -/** An edit source xAI can fetch: an https URL without credentials, or a base64 image data URL. */ -function isXaiEditSourceUrl(value: string): boolean { - const header = /^data:image\/(?:png|jpeg|jpg|webp);base64,/i.exec(value); - if (header) { - const start = header[0].length; +/** An edit source xAI can fetch: an https URL without credentials, or a canonical image data URL. */ +function isXaiEditSourceUrl(value: string, start: number): boolean { + if (start > 0) { if (value.length === start || (value.length - start) % 4 !== 0) return false; const nonAlphabet = /[^A-Za-z0-9+/]/g; nonAlphabet.lastIndex = start; @@ -157,6 +162,59 @@ function isXaiEditSourceUrl(value: string): boolean { } } +/** Collect every caller-supplied source before authentication or outbound serialization. */ +export function collectXaiEditSources( + obj: Record, + limits: { maxDecodedBytesPerImage: number; maxAggregateEncodedBytes: number } = { + maxDecodedBytesPerImage: MAX_DECODED_BYTES_PER_IMAGE, + maxAggregateEncodedBytes: XAI_EDIT_MAX_REQUEST_BYTES, + }, +): { sources: string[]; unusable: boolean; oversized: boolean } { + const sources = new Set(); + let unusable = false; + let oversized = false; + let aggregateEncodedBytes = 0; + const add = (value: unknown) => { + const url = typeof value === "string" ? value.trim() : ""; + const headerLength = /^data:image\/(?:png|jpeg|jpg|webp);base64,/i.exec(url)?.[0].length ?? 0; + const encodedBytes = headerLength ? url.length - headerLength : 0; + if (encodedBytes > 4 * Math.ceil(limits.maxDecodedBytesPerImage / 3)) { oversized = true; return; } + if (sources.has(url)) return; + if (!isXaiEditSourceUrl(url, headerLength)) { unusable = true; return; } + if (headerLength) { + const padding = url.endsWith("==") ? 2 : url.endsWith("=") ? 1 : 0; + if (encodedBytes / 4 * 3 - padding > limits.maxDecodedBytesPerImage) { oversized = true; return; } + } + if (encodedBytes > limits.maxAggregateEncodedBytes - aggregateEncodedBytes) { + oversized = true; + return; + } + // One extra source records overflow. Later entries are still inspected so none are dropped. + if (sources.size <= XAI_MAX_EDIT_IMAGES) { + sources.add(url); + aggregateEncodedBytes += encodedBytes; + } + }; + if (obj.image !== undefined) add(obj.image); + if (obj.image_url !== undefined) add(obj.image_url); + if (obj.images !== undefined) { + if (!Array.isArray(obj.images)) unusable = true; + else for (const entry of obj.images) { + if (typeof entry === "string") { add(entry); continue; } + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { unusable = true; continue; } + const rec = entry as Record; + if (rec.image_url === undefined && rec.url === undefined) { unusable = true; continue; } + if (rec.image_url !== undefined) { + const nested = rec.image_url; + if (nested && typeof nested === "object" && !Array.isArray(nested)) add((nested as Record).url); + else add(nested); + } + if (rec.url !== undefined) add(rec.url); + } + } + return { sources: [...sources], unusable, oversized }; +} + /** * The model this request names, or undefined when it names none. * @@ -505,17 +563,15 @@ async function tryCcaImageGeneration( * Codex's client-side image_gen POSTs here. When the Grok Imagine bridge is * opted in, send that request to api.x.ai instead of ChatGPT. */ -async function tryXaiImageRelay( +async function handleXaiImageRelay( body: unknown, config: OcxConfig, + found: NonNullable>, logCtx: RequestLogContext, signal: AbortSignal | undefined, endpoint: ImagesEndpoint, admission: DataPlaneAdmission | undefined, -): Promise { - if (config.images?.bridgeEnabled !== true) return undefined; - const found = findXaiProvider(config); - if (!found) return undefined; +): Promise { const bridgeModel = config.images?.bridgeModel ?? XAI_DEFAULT_IMAGE_MODEL; // The bridge sends this request to the configured xAI provider and the bridge // model regardless of the selector in the body, so that is what the key is @@ -541,44 +597,15 @@ async function tryXaiImageRelay( let imageUrl: string | undefined; let imageUrls: string[] | undefined; if (endpoint === "edits") { - const sources = new Set(); // Every supplied source must be a usable URL: silently dropping one would buy an edit // missing an image the caller sent. xAI takes a public https URL or a base64 image data URL; // an explicit null counts as supplied. - let unusable = false; - const add = (value: unknown) => { - const url = typeof value === "string" ? value.trim() : ""; - if (sources.has(url)) return; - if (!isXaiEditSourceUrl(url)) { - unusable = true; - return; - } - // One extra source records overflow. A later invalid source still takes precedence. - if (sources.size <= XAI_MAX_EDIT_IMAGES) sources.add(url); - }; - if (obj.image !== undefined) add(obj.image); - if (obj.image_url !== undefined) add(obj.image_url); - if (obj.images !== undefined) { - if (!Array.isArray(obj.images)) unusable = true; - else for (const entry of obj.images) { - if (typeof entry === "string") { add(entry); continue; } - if (!entry || typeof entry !== "object" || Array.isArray(entry)) { unusable = true; continue; } - // Every URL-bearing property of an entry is a supplied source; an entry with none - // (a file_id, say) cannot be represented. - const rec = entry as Record; - if (rec.image_url === undefined && rec.url === undefined) { unusable = true; continue; } - if (rec.image_url !== undefined) { - const nested = rec.image_url; - if (nested && typeof nested === "object" && !Array.isArray(nested)) add((nested as Record).url); - else add(nested); - } - if (rec.url !== undefined) add(rec.url); - } - } - if (unusable) return formatErrorResponse(400, "invalid_request_error", "xAI image edits need every image as a URL"); + const collected = collectXaiEditSources(obj); + if (collected.unusable) return formatErrorResponse(400, "invalid_request_error", "xAI image edits need every image as a URL"); + if (collected.oversized) return formatErrorResponse(400, "invalid_request_error", "xAI image edit inline data exceeds the size limit"); // Same rule as callXaiImages: duplicates collapse first, then the five-source limit applies. - if (sources.size > XAI_MAX_EDIT_IMAGES) return formatErrorResponse(400, "invalid_request_error", "xAI image edits accept at most 5 images"); - [imageUrl, ...imageUrls] = sources; + if (collected.sources.length > XAI_MAX_EDIT_IMAGES) return formatErrorResponse(400, "invalid_request_error", "xAI image edits accept at most 5 images"); + [imageUrl, ...imageUrls] = collected.sources; if (!imageUrl) return formatErrorResponse(400, "invalid_request_error", "image edits require an image URL"); } const timeoutMs = config.images?.timeoutMs ?? IMAGES_UPSTREAM_TIMEOUT_MS; @@ -707,22 +734,24 @@ export async function handleImages( turnAdmissionLease?: AdmissionLease, admission?: DataPlaneAdmission, ): Promise { + // The standalone bridge destination is selected by configuration before reading the body. + // An explicit provider owns its route, including its own validation errors. + const xai = config.images?.provider === undefined && config.images?.bridgeEnabled === true + ? findXaiProvider(config) : undefined; + const configuredLimit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes); + const fixedEditLimit = !!xai && endpoint === "edits" && configuredLimit >= XAI_EDIT_MAX_REQUEST_BYTES; + const bodyLimit = fixedEditLimit ? XAI_EDIT_MAX_REQUEST_BYTES : configuredLimit; let body: unknown; try { - body = await readJsonRequestBody(req, undefined, resolveInboundBodyLimitBytes(config.maxInboundBodyBytes)); + body = await readJsonRequestBody(req, undefined, bodyLimit); } catch (err) { - return decodeRequestErrorResponse(err, "images"); + return decodeRequestErrorResponse(err, "images", fixedEditLimit ? "xai-edit" : undefined); } const model = (body as { model?: unknown } | null)?.model; if (typeof model === "string" && model) logCtx.model = model; + if (xai) return handleXaiImageRelay(body, config, xai, logCtx, req.signal, endpoint, admission); const candidates = selectImagesProvider(config); - // Explicit images.provider owns the route, including its validation errors. - // Do not divert that selection to the xAI Imagine relay. - if (config.images?.provider === undefined) { - const xaiRelay = await tryXaiImageRelay(body, config, logCtx, req.signal, endpoint, admission); - if (xaiRelay) return xaiRelay; - } if (candidates.error && (config.images?.provider !== undefined || !candidates.paused)) { return formatErrorResponse(candidates.paused ? 403 : 400, candidates.paused ? "permission_error" : "invalid_request_error", candidates.error); } diff --git a/src/server/request-decompress.ts b/src/server/request-decompress.ts index da72d9ae678..956bbe7cb6e 100644 --- a/src/server/request-decompress.ts +++ b/src/server/request-decompress.ts @@ -138,7 +138,7 @@ export class DecompressedBodyTooLargeError extends Error { * wording deliberately avoids "context window"/"context length", which `classifyError` treats * as evidence of an upstream context verdict. */ -export function describeInboundBodyRefusal(error: DecompressedBodyTooLargeError): string { +export function describeInboundBodyRefusal(error: DecompressedBodyTooLargeError, limitSource?: "xai-edit"): string { if (error instanceof CompressionRatioExceededError) return error.message; // A lower-bound measurement stopped counting at the cap; reporting it as exact would be a lie. const approximate = error.measurement === "declared_wire" || error.measurement === "decoded_exact" @@ -150,6 +150,9 @@ export function describeInboundBodyRefusal(error: DecompressedBodyTooLargeError) : observed === null ? `the body is above the ${limit} MB inbound admission limit` : `the body is ${approximate}${observed} MB, above the ${limit} MB inbound admission limit`; + if (limitSource === "xai-edit") { + return `OpenCodex refused this xAI image edit: ${sizes}. Reduce the edit payload to fit the fixed per-request limit.`; + } return `OpenCodex refused this request before reading it: ${sizes}. ` + "This is a local proxy limit, not a provider refusal. Raise \"maxInboundBodyBytes\" in " + `config.json (ceiling ${INBOUND_CEILING_MB} MB) and restart the proxy, or compact the ` diff --git a/src/server/responses/core-errors.ts b/src/server/responses/core-errors.ts index d82e3f59fda..d119e3e1a14 100644 --- a/src/server/responses/core-errors.ts +++ b/src/server/responses/core-errors.ts @@ -83,7 +83,7 @@ export function normalizeUpstreamErrorText(text: string, fallback: string): Norm -export function decodeRequestErrorResponse(err: unknown, label: string): Response { +export function decodeRequestErrorResponse(err: unknown, label: string, limitSource?: "xai-edit"): Response { if (isTranslatorBudgetExceededError(err)) { return markProxyError(formatErrorResponse(413, "request_too_large", "request translation buffer exceeded the safe limit", { code: "translation_buffer_limit", @@ -93,7 +93,7 @@ export function decodeRequestErrorResponse(err: unknown, label: string): Respons return markProxyError(formatErrorResponse(415, "invalid_request_error", err.message)); } if (err instanceof DecompressedBodyTooLargeError) { - return markProxyError(formatErrorResponse(413, "inbound_body_too_large", describeInboundBodyRefusal(err)), "inbound"); + return markProxyError(formatErrorResponse(413, "inbound_body_too_large", describeInboundBodyRefusal(err, limitSource)), "inbound"); } console.warn(`[${label}] request body decode/parse failed: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`); return markProxyError(formatErrorResponse(400, "invalid_request_error", "Invalid JSON body")); diff --git a/structure/data-planes/images.md b/structure/data-planes/images.md index 55434367917..ebd744d198f 100644 --- a/structure/data-planes/images.md +++ b/structure/data-planes/images.md @@ -50,7 +50,14 @@ source URLs in caller order; both drop duplicate URLs first and then apply the l checks it before resolving credentials or sending a request. The relay refuses the request when any supplied source, an explicit `null` included, is not an https URL or a canonical base64 PNG/JPEG/WebP data URL (for example a `file_id` or plain text) instead of dropping it. It checks the base64 alphabet -and padding directly in the supplied text. Every URL-bearing property of an `images[]` entry +and padding directly in the supplied text. An xAI bridge edit has a 100 MiB decompressed JSON request +cap even when the deployment raises the general inbound limit. At this fixed cap the refusal asks +for a smaller edit payload. Canonical base64 padding determines each source's exact decoded length +against the 50 MiB ceiling (about 66.7 MiB encoded), and unique inline payloads have a 100 MiB +aggregate encoded ceiling. Those bounds are checked before credentials are resolved or the outbound +JSON is serialized; HTTPS sources do not consume the inline-data budget. Generations, explicit Images +providers and non-xAI edit routes retain the configured general inbound limit. Every URL-bearing +property of an `images[]` entry (`image_url`, `image_url.url`, `url`) counts as a source. The `image_gen` bridge tool sends one source. Safe upstream validation details are reconstructed from a closed vocabulary of quality, field, resolution and bounded keyframe tokens; diff --git a/tests/server/server-images-xai-relay.test.ts b/tests/server/server-images-xai-relay.test.ts index b7dbb3993cf..bdde9336389 100644 --- a/tests/server/server-images-xai-relay.test.ts +++ b/tests/server/server-images-xai-relay.test.ts @@ -1,5 +1,9 @@ import { afterEach, expect, spyOn, test } from "bun:test"; -import { handleImages } from "../../src/server/images"; +import { + collectXaiEditSources, + handleImages, + XAI_EDIT_MAX_REQUEST_BYTES, +} from "../../src/server/images"; import type { OcxConfig } from "../../src/types"; const oldFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = oldFetch; }); @@ -42,6 +46,75 @@ test("relay validates canonical edit data URLs without decoding their payloads", } }); +test("relay enforces per-image and aggregate inline budgets with synthetic limits", () => { + const limits = { maxDecodedBytesPerImage: 6, maxAggregateEncodedBytes: 12 }; + const accepted = collectXaiEditSources({ + image: "https://example.com/source.png", + image_url: "data:image/png;base64,aGk=", + images: [{ image_url: { url: "data:image/jpeg;base64,QUFBQUFB" }, url: "data:image/png;base64,aGk=" }], + }, limits); + expect(accepted).toEqual({ + sources: [ + "https://example.com/source.png", + "data:image/png;base64,aGk=", + "data:image/jpeg;base64,QUFBQUFB", + ], + unusable: false, + oversized: false, + }); + + expect(collectXaiEditSources({ image: "data:image/png;base64,QUFBQUFBQUFB" }, limits).oversized).toBe(true); + expect(collectXaiEditSources({ + images: ["data:image/png;base64,aGk=aGk=", "data:image/jpeg;base64,aG8="], + }, { maxDecodedBytesPerImage: 12, maxAggregateEncodedBytes: 8 }).unusable).toBe(true); + expect(collectXaiEditSources({ + images: ["data:image/png;base64,aGk=", "data:image/jpeg;base64,aG8=", "data:image/webp;base64,Ynk="], + }, { maxDecodedBytesPerImage: 6, maxAggregateEncodedBytes: 8 }).oversized).toBe(true); +}); + +test("the decoded per-image limit accepts both padding lengths and rejects one byte over", () => { + // Like 50 MiB, five bytes need two quartets. Four and six bytes use the same encoded length. + const limits = { maxDecodedBytesPerImage: 5, maxAggregateEncodedBytes: 8 }; + for (const [encoded, accepted] of [["QUJDRA==", true], ["QUJDREU=", true], ["QUJDREVG", false]] as const) { + const url = "data:image/png;base64," + encoded; + const { sources, unusable, oversized } = collectXaiEditSources({ image: url }, limits); + expect({ sources, unusable, oversized }).toEqual({ + sources: accepted ? [url] : [], unusable: false, oversized: !accepted, + }); + } +}); + +test("only edits routed to the xAI bridge use its request limit", async () => { + const raised = { ...config, maxInboundBodyBytes: 200 * 1024 * 1024 }; + // A small invalid JSON body distinguishes admission (413) from parsing (400). + // Use the reader's declared-length check without allocating a large image. + const submit = (cfg: OcxConfig, endpoint: "edits" | "generations", declaredBytes: number) => { + const req = new Request("http://localhost/v1/images/" + endpoint, { + method: "POST", headers: { "content-length": String(declaredBytes) }, body: "{", + }); + return handleImages(req, cfg, endpoint, { model: "", provider: "" }); + }; + const status = async (...args: Parameters) => (await submit(...args)).status; + const over = XAI_EDIT_MAX_REQUEST_BYTES + 1; + expect(await status(raised, "edits", XAI_EDIT_MAX_REQUEST_BYTES)).toBe(400); + for (const configuredLimit of [XAI_EDIT_MAX_REQUEST_BYTES, raised.maxInboundBodyBytes]) { + const fixed = await submit({ ...raised, maxInboundBodyBytes: configuredLimit }, "edits", over); + expect(fixed.status).toBe(413); + const { error } = await fixed.json(); + expect(error.code).toBe("inbound_body_too_large"); + expect(error.message).toContain("Reduce the edit payload"); + expect(error.message).not.toContain("maxInboundBodyBytes"); + } + expect(await status(raised, "generations", over)).toBe(400); + expect(await status({ ...raised, images: { ...raised.images, provider: "custom" } }, "edits", over)).toBe(400); + expect(await status({ ...raised, images: { ...raised.images, bridgeEnabled: false } }, "edits", over)).toBe(400); + expect(await status({ ...raised, providers: {} }, "edits", over)).toBe(400); + const lower = 1024 * 1024; + const configured = await submit({ ...raised, maxInboundBodyBytes: lower }, "edits", lower + 1); + expect(configured.status).toBe(413); + expect((await configured.json()).error.message).toContain("maxInboundBodyBytes"); +}); + test("relay keeps five distinct sources in order and validates entries after the limit", async () => { const sources = Array.from({ length: 5 }, (_, i) => `https://example.com/${i}.png`); const calls: string[][] = []; From f641077435eb5de8d0b16f8727358d3d2ffcdd19 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 05:04:17 +0900 Subject: [PATCH 15/64] fix(step-cli): require current user text to start a conversation (#9117) * fix(step-cli): require current user text to start a conversation * fix(step-cli): preserve held calls on blank follow-ups * fix(step-cli): restrict held-call follow-ups to the current input * fix(step-cli): recognize fresh tool outputs after restored history * docs(step-cli): keep the input boundary contract within the structure budget * fix(step-cli): rebase the current-input boundary when replayed search is stripped Stripping replayed hosted web-search pairs removed messages without moving the index that marks where the caller's current input begins, so the boundary could land past fresh input or before already answered text. Rename the field to _currentInputMessageStart and recompute it while stripping. When the search pairs are kept, projection now skips the replayed search result so a deferred replay never wins over a fresh tool result. Stateless requests get the same treatment. * fix(step-cli): deliver the held call's result when steering text follows it latestToolResult looked only at the newest current message, so a turn ending [toolResult call-9, user] treated the held call-9 as abandoned: StepCode was answered with an empty error for a tool that had already run, and the query was restarted. Codex records text the user steers with during a tool call after the call's output, so this is an ordinary shape. Return the newest current tool result instead. Results restored from history still sit before the current-input start and never match, so a conversation still cannot start from a tool result alone. The held call's own result is delivered and its query continues, as on dev; a result for another call still abandons the held one. --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../src/content/docs/es/guides/step-cli.md | 3 + docs-site/src/content/docs/guides/step-cli.md | 4 +- src/adapters/step-cli/adapter.ts | 30 ++- src/adapters/step-cli/projection.ts | 59 ++--- src/adapters/step-cli/session-pool.ts | 7 +- src/responses/parser.ts | 11 +- src/types/request.ts | 2 + src/web-search/sidecar-search-replay.ts | 25 ++- src/web-search/synthetic-tool.ts | 7 +- structure/providers/chat-compat.md | 3 + structure/providers/step-cli-transport.md | 6 + tests/adapters/step-cli-run-turn.test.ts | 206 +++++++++++++++++- tests/adapters/step-cli-session.test.ts | 2 + 13 files changed, 305 insertions(+), 60 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/step-cli.md b/docs-site/src/content/docs/es/guides/step-cli.md index 60ed925993b..30c19be4f92 100644 --- a/docs-site/src/content/docs/es/guides/step-cli.md +++ b/docs-site/src/content/docs/es/guides/step-cli.md @@ -60,6 +60,9 @@ aprobarlas y ejecutarlas: Si las ocho plazas están ocupadas, las conversaciones existentes pueden continuar. Una nueva recibe el error `step_cli_pool_full` y puede reintentarse cuando se libere una plaza. Las sesiones inactivas siguen contando hasta que termina su cierre tras diez minutos de inactividad. + Para iniciar una conversación, envía texto de usuario. Un resultado de herramienta por sí solo + puede reanudar la llamada correspondiente en una conversación existente. + Un mensaje en blanco o que contenga solo historial restaurado devuelve `step_cli_no_user_text` y permite reanudar la llamada de herramienta pendiente. - **Límites de sesión.** Si una herramienta tarda más de dos minutos en devolver un resultado, el turno informa del error `step_cli_tool_result_too_late`. El protocolo no permite reemplazar el mensaje de sistema de la sesión. OpenCodex antepone las instrucciones del cliente al turno. diff --git a/docs-site/src/content/docs/guides/step-cli.md b/docs-site/src/content/docs/guides/step-cli.md index 469211f17c9..97dcf01cc4f 100644 --- a/docs-site/src/content/docs/guides/step-cli.md +++ b/docs-site/src/content/docs/guides/step-cli.md @@ -58,7 +58,9 @@ StepCode: - **Conversation capacity:** A proxy can keep eight StepCode sessions per OpenCodex home. When all slots are occupied, existing conversations can continue. A new one receives `step_cli_pool_full` and can retry after a slot frees up. Idle sessions still count until - cleanup after the ten-minute idle timeout completes. + cleanup after the ten-minute idle timeout completes. Send user text to start a conversation. + A tool result on its own can resume its matching call in an existing conversation. + A blank follow-up or one containing only restored history returns `step_cli_no_user_text` and leaves a pending tool call available to resume. - **Two documented limits:** a tool that takes longer than two minutes to come back exceeds the CLI's own tool-result window and the turn reports `step_cli_tool_result_too_late`; and the CLI's session system prompt cannot be replaced through this protocol, so your instructions are prepended diff --git a/src/adapters/step-cli/adapter.ts b/src/adapters/step-cli/adapter.ts index 11bfd85def7..8bdac08a965 100644 --- a/src/adapters/step-cli/adapter.ts +++ b/src/adapters/step-cli/adapter.ts @@ -158,9 +158,15 @@ export function createStepCliAdapter( ? { handle: identified, sessionId: "" } : sessions.nextRef(); + const userText = pendingUserText(parsed); let session!: StepConversationSession; try { - session = await sessions.open(ref); + const acquired = await sessions.open(ref, { existingOnly: userText === undefined }); + if (!acquired) { + emit(noUserText()); + return; + } + session = acquired; await session.handshake(); } catch (error) { await session?.close(); @@ -177,6 +183,7 @@ export function createStepCliAdapter( session, ref, tools, + userText, setTimer: deps.setTimeout ?? setTimeout, clearTimer: deps.clearTimeout ?? clearTimeout, }), @@ -229,6 +236,14 @@ async function startQueryWithBusyRetry( } } +function noUserText(): AdapterEvent { + return refusal( + "StepCode carries conversation history inside its own process, so a turn must end with either user text or a tool result.", + 400, + "step_cli_no_user_text", + ); +} + function emitPreDispatchAbort(emit: (event: AdapterEvent) => void): void { emit({ type: "error", message: "StepCode turn was aborted before start.", retryable: false }); } @@ -242,6 +257,7 @@ async function driveTurn( session: StepConversationSession; ref: StepConversationRef; tools: ReturnType; + userText: string | undefined; setTimer: typeof setTimeout; clearTimer: typeof clearTimeout; }, @@ -275,15 +291,11 @@ async function driveTurn( // Text is suppressed ONLY when this turn really is the answer to the held call; a turn that // abandoned the call still carries the user's message and must keep it. - const userText = continuedQuery ? undefined : pendingUserText(parsed); + const userText = continuedQuery ? undefined : context.userText; if (!continuedQuery && !userText) { - emit( - refusal( - "StepCode carries conversation history inside its own process, so a turn must end with either user text or a tool result.", - 400, - "step_cli_no_user_text", - ), - ); + // An empty replacement leaves the original call available for its result. + if (held) sessions.rememberHeldTool(ref, held); + emit(noUserText()); return; } diff --git a/src/adapters/step-cli/projection.ts b/src/adapters/step-cli/projection.ts index cc603199a47..0375d5b8c48 100644 --- a/src/adapters/step-cli/projection.ts +++ b/src/adapters/step-cli/projection.ts @@ -1,6 +1,7 @@ import type { OcxParsedRequest, OcxUsage } from "../../types"; import type { IncomingMeta } from "../base"; import { buildSystemPrompt } from "../coding-agent/protocol"; +import { isReplayedSearchResult } from "../../web-search/synthetic-tool"; import { CODING_AGENT_TOOL_LIMITS } from "../coding-agent/tool-catalog"; import { STEP_CLI_CONTINUATION_KEY, STEP_CLI_TOOL_SERVER } from "./constants"; import type { StepConversationRef } from "./session-pool"; @@ -91,16 +92,17 @@ export function projectToolResultContent( export function latestToolResult( parsed: OcxParsedRequest, ): { content: readonly unknown[]; isError?: boolean; toolCallId: string } | undefined { - for (let index = parsed.context.messages.length - 1; index >= 0; index -= 1) { - const message = parsed.context.messages[index]; - if (!message || message.role !== "toolResult") continue; - return { - content: projectToolResultContent(message.content), - toolCallId: message.toolCallId, - ...(message.isError ? { isError: true } : {}), - }; - } - return undefined; + // The newest CURRENT result, not only the newest message: Codex records text the user steers + // with during a tool call after the call's output, so a turn can end [toolResult, user]. The + // caller matches this against the held call id; a result restored from history sits before the + // current-input start and never matches. + const message = latestCurrentMessage(parsed, candidate => candidate.role === "toolResult"); + if (message?.role !== "toolResult") return undefined; + return { + content: projectToolResultContent(message.content), + toolCallId: message.toolCallId, + ...(message.isError ? { isError: true } : {}), + }; } export function toUsage(usage: Record): OcxUsage | undefined { @@ -190,7 +192,21 @@ export function asRecord(value: unknown): Record { : {}; } -/** Translate a transport failure into the actionable error an operator can act on. */ +function latestCurrentMessage( + parsed: OcxParsedRequest, + accept: (message: OcxParsedRequest["context"]["messages"][number]) => boolean = () => true, +) { + const messages = parsed.context.messages; + const start = parsed._currentInputMessageStart ?? (parsed._replayPrefixLen ? messages.length : 0); + const cells = parsed._replayedWebSearchCells; + const replayedIds = cells?.length ? new Set(cells.map(cell => cell.callId)) : undefined; + for (let index = messages.length - 1; index >= start; index--) { + const message = messages[index]; + if (!message || message.role === "developer") continue; + if (replayedIds && isReplayedSearchResult(message, replayedIds)) continue; + if (accept(message)) return message; + } +} /** * The text StepCode should be asked for on this turn. @@ -199,22 +215,13 @@ export function asRecord(value: unknown): Record { * because the wire reduces every message to text and images. */ export function pendingUserText(parsed: OcxParsedRequest): string | undefined { - for (let index = parsed.context.messages.length - 1; index >= 0; index -= 1) { - const message = parsed.context.messages[index]; - if (!message || message.role !== "user") continue; - if (!Array.isArray(message.content)) { - return typeof message.content === "string" && message.content.length > 0 - ? message.content - : undefined; - } - const text = message.content - .filter(part => part.type === "text") - .map(part => (part as { text: string }).text) - .join("") - .trim(); - if (text.length > 0) return text; + const message = latestCurrentMessage(parsed); + if (message?.role !== "user") return undefined; + if (!Array.isArray(message.content)) { + return typeof message.content === "string" && /\S/.test(message.content) ? message.content : undefined; } - return undefined; + const text = message.content.filter(part => part.type === "text").map(part => part.text).join("").trim(); + return text.length > 0 ? text : undefined; } /** diff --git a/src/adapters/step-cli/session-pool.ts b/src/adapters/step-cli/session-pool.ts index 10a39257301..50ae9855f45 100644 --- a/src/adapters/step-cli/session-pool.ts +++ b/src/adapters/step-cli/session-pool.ts @@ -54,6 +54,7 @@ interface PoolEntry { export interface StepConversationHost { get(ref: StepConversationRef | undefined): StepConversationSession | undefined; open(ref: StepConversationRef): Promise; + open(ref: StepConversationRef, options: { existingOnly: boolean }): Promise; nextRef(): StepConversationRef; rememberHeldTool(ref: StepConversationRef, held: StepHeldTool): void; takeHeldTool(ref: StepConversationRef): StepHeldTool | undefined; @@ -107,7 +108,9 @@ export class StepSessionPool implements StepConversationHost { } /** Open a session for a conversation, coalescing concurrent opens of the same handle. */ - async open(ref: StepConversationRef): Promise { + async open(ref: StepConversationRef): Promise; + async open(ref: StepConversationRef, options: { existingOnly: boolean }): Promise; + async open(ref: StepConversationRef, options?: { existingOnly: boolean }): Promise { if (this.#closing) throw new StepSessionError("StepCode session pool is closing."); const existing = this.get(ref); if (existing) return existing; @@ -122,6 +125,8 @@ export class StepSessionPool implements StepConversationHost { "step_cli_pool_full", ); } + // A tool result may join an opening session and wait for its turn, but cannot start a conversation. + if (options?.existingOnly) return undefined; const opening = (async () => { const session = await StepCliSession.open(this.#options.buildOptions(), this.#handlers, this.#deps, owned => { this.#sessions.add(owned); diff --git a/src/responses/parser.ts b/src/responses/parser.ts index fd25bef18ec..ab08e79afae 100644 --- a/src/responses/parser.ts +++ b/src/responses/parser.ts @@ -277,6 +277,7 @@ export function parseRequest( let decodedCheckpoint = false; let contextCompactionBoundary = false; let continuationConversationMessageIndex: number | undefined; + let replayedContextMessageCount: number | undefined; if (typeof data.instructions === "string" && data.instructions.length > 0) { // #5217: this is the stored session instruction block. A sub-agent spawned on a DIFFERENT model @@ -300,6 +301,11 @@ export function parseRequest( const item = inputItems[itemIndex]; // Boundaries are measured on the caller's input, before any replayed-search rewrite. const inputIndex = webSearchReplay?.sourceIndexes[itemIndex] ?? itemIndex; + // Fresh tool results belong to the input delta even when they precede the point where + // developer guidance can be inserted. Keep those two positions independent. + if (replayedInputPrefixLength > 0 && replayedContextMessageCount === undefined && inputIndex >= replayedInputPrefixLength) { + replayedContextMessageCount = messages.length; + } if (itemIndex > 0 && isAnthropicProgressMirror(item, anthropicProgressEnvelope(inputItems[itemIndex - 1]))) continue; const effectiveType = (item as { type?: string }).type ?? ("role" in item ? "message" : undefined); const itemRole = (item as { role?: string }).role; @@ -757,7 +763,10 @@ export function parseRequest( stream: data.stream === true, options, _rawBody: body, - ...(replayedInputPrefixLength > 0 ? { _replayPrefixLen: replayedInputPrefixLength } : {}), + ...(replayedInputPrefixLength > 0 ? { + _replayPrefixLen: replayedInputPrefixLength, + _currentInputMessageStart: replayedContextMessageCount ?? messages.length, + } : {}), ...(continuationConversationMessageIndex !== undefined ? { _continuationConversationMessageIndex: continuationConversationMessageIndex } : {}), diff --git a/src/types/request.ts b/src/types/request.ts index 9ed2989f51b..de6b1e981e7 100644 --- a/src/types/request.ts +++ b/src/types/request.ts @@ -110,6 +110,8 @@ export interface OcxParsedRequest { * CLIENT already carried that history verbatim and the proxy skipped the prepend. */ _replayPrefixLen?: number; + /** First parsed message eligible as current input. Recomputed when a projection removes historical messages. */ + _currentInputMessageStart?: number; /** Parsed-message index before the first conversational item in a continuation's current delta. */ _continuationConversationMessageIndex?: number; /** diff --git a/src/web-search/sidecar-search-replay.ts b/src/web-search/sidecar-search-replay.ts index 922224f9be0..ad3f660636f 100644 --- a/src/web-search/sidecar-search-replay.ts +++ b/src/web-search/sidecar-search-replay.ts @@ -16,7 +16,7 @@ */ import type { OcxMessage, OcxParsedRequest, OcxReasoningReplayScopeRef } from "../types"; import { peekBridgeSearchReplay, rememberBridgeSearchReplay } from "../responses/bridge-search-replay-cache"; -import { WEB_SEARCH_TOOL_NAME } from "./synthetic-tool"; +import { isReplayedSearchResult, WEB_SEARCH_TOOL_NAME } from "./synthetic-tool"; export function sidecarSearchReplayScope(scope: OcxReasoningReplayScopeRef | undefined): string | undefined { if (!scope?.clientPrincipalId || !scope.clientThreadId) return undefined; @@ -78,19 +78,22 @@ export function stripReplayedSearchPairs(parsed: OcxParsedRequest): void { const cells = parsed._replayedWebSearchCells; if (!cells?.length) return; const ids = new Set(cells.map(cell => cell.callId)); - const isPair = (part: { type: string; id?: string; name?: string }) => - part.type === "toolCall" && part.name === WEB_SEARCH_TOOL_NAME && part.id !== undefined && ids.has(part.id); const kept: OcxMessage[] = []; - for (const message of parsed.context.messages) { - if (message.role === "toolResult" && message.toolName === WEB_SEARCH_TOOL_NAME && ids.has(message.toolCallId)) continue; - if (message.role === "assistant" && message.content.some(isPair)) { - const content = message.content.filter(part => !isPair(part)); - if (!content.some(part => part.type !== "thinking")) continue; - kept.push({ ...message, content }); - continue; + const previousStart = parsed._currentInputMessageStart; + let currentStart = 0; + for (const [index, message] of parsed.context.messages.entries()) { + if (message.role === "assistant") { + const content = message.content.filter(part => !(part.type === "toolCall" && part.name === WEB_SEARCH_TOOL_NAME && ids.has(part.id))); + if (content.length === message.content.length) kept.push(message); + else if (content.some(part => part.type !== "thinking")) kept.push({ ...message, content }); + // The removed assistant turn still separates old input from what the caller sent next. + else currentStart = kept.length; + } else if (!isReplayedSearchResult(message, ids)) { + kept.push(message); } - kept.push(message); + if (previousStart !== undefined && index < previousStart) currentStart = kept.length; } + if (previousStart !== undefined || currentStart > 0) parsed._currentInputMessageStart = currentStart; parsed.context.messages = kept; delete parsed._replayedWebSearchCells; } diff --git a/src/web-search/synthetic-tool.ts b/src/web-search/synthetic-tool.ts index 5d38d1dd5b8..802b02818fb 100644 --- a/src/web-search/synthetic-tool.ts +++ b/src/web-search/synthetic-tool.ts @@ -1,8 +1,13 @@ -import type { OcxTool } from "../types"; +import type { OcxMessage, OcxTool } from "../types"; /** The function name the chat model sees + the name the loop intercepts. */ export const WEB_SEARCH_TOOL_NAME = "web_search"; +/** True only for the result half of a hosted search pair constructed by the parser. */ +export function isReplayedSearchResult(message: OcxMessage, callIds: ReadonlySet): boolean { + return message.role === "toolResult" && message.toolName === WEB_SEARCH_TOOL_NAME && callIds.has(message.toolCallId); +} + /** * Find the hosted `{type:"web_search", ...}` entry in a Responses request's `tools[]` and return it * verbatim (so its config — external_web_access/filters/user_location/search_context_size — can be diff --git a/structure/providers/chat-compat.md b/structure/providers/chat-compat.md index f68373068f1..171a89a95d3 100644 --- a/structure/providers/chat-compat.md +++ b/structure/providers/chat-compat.md @@ -107,6 +107,9 @@ nonblank `id`/`name`/`namespace`, and fully representable nonempty text/image ou existing continuation conversation-boundary calculation. The metadata is structural, not authentication. Unknown/opaque/malformed parts reject the entire conversion; ordinary missing/empty tool call ids retain the existing translated-route 400 guard. +On an expanded continuation, `src/responses/parser.ts` records where the new wire input starts +in the parsed messages. This includes leading tool results. Developer guidance still follows +those results and precedes the next conversational message. Passthrough and routed-compaction raw-body repairs emit it as a user turn (`externalTaskInputResponsesContent`, #6764); the direct native `/responses/compact` forward keeps its raw-body handling. The leaf imports no optional subsystem. Stateful developer-guidance injection reuses that validator for its raw insertion diff --git a/structure/providers/step-cli-transport.md b/structure/providers/step-cli-transport.md index bd974780d10..08f3356d237 100644 --- a/structure/providers/step-cli-transport.md +++ b/structure/providers/step-cli-transport.md @@ -32,6 +32,10 @@ that query's declared catalog. Other permissions are denied. A `sdk_tool.invoke` is answered on the client's **next** request, with the original query and catalog. Changing the catalog while returning a held result closes the session. Abandoning a held call detaches its owner, interrupts it and confirms its input end before registering a replacement turn. +An empty user follow-up returns `step_cli_no_user_text` and preserves the hold for a matching result. +Restored Responses history supplies neither replacement text nor an answer to a held call. +The parser marks where current input starts in parsed history. Removing hosted-search pairs adjusts that position; +retaining the pairs keeps their generated results out of held-call matching. A new result can resume the call without user text. After acquiring the conversation lock, a cancelled turn leaves held state untouched. Cancellation also stops new query starts, busy retries and input that has yet to be sent. @@ -43,6 +47,8 @@ permission denials. each session before workspace setup, so shutdown can close an opening session before it spawns. At eight owned sessions a home pool refuses new conversations with retryable `step_cli_pool_full`. Existing handles and coalesced opens still work. Only confirmed cleanup releases capacity. +A fresh session requires user text. A turn containing only a tool result can join its existing or +opening conversation, where the conversation lock and held-call checks decide whether it resumes. The pool retains ownership of adapter, idle-timer and sweep closes until termination is confirmed. Shutdown drains those receipts and propagates failures. Closing handles refuse replacement. Session close is idempotent and clears held-request timers. diff --git a/tests/adapters/step-cli-run-turn.test.ts b/tests/adapters/step-cli-run-turn.test.ts index 83f54f91421..cc1699b304a 100644 --- a/tests/adapters/step-cli-run-turn.test.ts +++ b/tests/adapters/step-cli-run-turn.test.ts @@ -7,12 +7,13 @@ import { clearStepCliSessions, createStepCliAdapter } from "../../src/adapters/s import { withConversationLock } from "../../src/adapters/step-cli/conversation"; import { handleReverseRequest, handleRuntimeEvent } from "../../src/adapters/step-cli/events"; import { classifyStepChildError } from "../../src/adapters/step-cli/errors"; -import { latestToolResult, projectToolResultContent } from "../../src/adapters/step-cli/projection"; -import type { - StepConversationHost, - StepConversationRef, - StepConversationSession, - StepHeldTool, +import { latestToolResult, pendingUserText, projectToolResultContent } from "../../src/adapters/step-cli/projection"; +import { + StepSessionPool, + type StepConversationHost, + type StepConversationRef, + type StepConversationSession, + type StepHeldTool, } from "../../src/adapters/step-cli/session-pool"; import { encodeStepFrame, @@ -28,6 +29,9 @@ import { runOptionalShutdownHooks, } from "../../src/lib/optional-shutdown-hooks"; import type { AdapterEvent, OcxParsedRequest } from "../../src/types"; +import { parseRequest } from "../../src/responses/parser"; +import { expandPreviousResponseInput, rememberResponseState } from "../../src/responses/state"; +import { stripReplayedSearchPairs } from "../../src/web-search/sidecar-search-replay"; /** * A fake StepCode process. @@ -200,6 +204,76 @@ function parsed(messages: unknown[]): OcxParsedRequest { const USER_ASK = [{ role: "user", content: "run it", timestamp: 0 }]; +test("starting a conversation without user text refuses before preparing a StepCode session", async () => { + let preparations = 0; + const pool = new StepSessionPool({ + openCodexHome: "unused", idleTimeoutMs: 60_000, + buildOptions() { preparations++; throw new Error("unexpected session preparation"); }, + }, { onEvent() {} }); + const adapter = createStepCliAdapter(provider(), { openSession: pool }); + try { + const noInput = [ + [], + [...USER_ASK, { role: "assistant", content: "Earlier reply" }], + [...USER_ASK, { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "done" }], + [...USER_ASK, { role: "user", content: " " }], + [...USER_ASK, { role: "user", content: [{ type: "text", text: "\n" }] }], + ]; + const replayOnly = { ...parsed(USER_ASK), previousResponseId: "prev", _replayPrefixLen: 3 }; + for (const turn of [...noInput.map(parsed), replayOnly]) { + const events: AdapterEvent[] = []; + await adapter.runTurn!(turn, THREAD_META, event => events.push(event)); + expect(events).toMatchObject([{ type: "error", status: 400, code: "step_cli_no_user_text", + errorType: "invalid_request_error", retryable: false }]); + } + expect(preparations).toBe(0); + } finally { await pool.closeAll(); } +}); + +function hostedSearchHistory() { + return { type: "web_search_call", id: "ws_history", status: "completed", action: { type: "search", query: "old search" } }; +} + +test("fresh user input survives stripping restored search history and copying the remaining messages", () => { + const model = "step-5-preview"; + const prior = `resp_${crypto.randomUUID()}`; + rememberResponseState({ model, input: [{ role: "user", content: "Old question" }] }, + { id: prior, status: "completed", output: [hostedSearchHistory()] }); + const body = expandPreviousResponseInput({ + model, previous_response_id: prior, tools: [{ type: "web_search" }], + input: [{ role: "user", content: "Next question" }, { role: "developer", content: "Answer briefly" }], + }); + const turn = parseRequest(body); + expect(turn._replayedWebSearchCells).toHaveLength(1); + expect(pendingUserText(turn)).toBe("Next question"); + stripReplayedSearchPairs(turn); + expect(turn.context.messages.map(m => m.role)).toEqual(["user", "user", "developer"]); + const copied = { ...turn, context: { ...turn.context, messages: turn.context.messages.map(m => ({ ...m })) } }; + expect(pendingUserText(copied)).toBe("Next question"); + // A later sidecar iteration appends an actual, current tool result to the parsed context. + copied.context.messages.push({ role: "toolResult", toolCallId: "sidecar-1", toolName: "web_search", content: "found", isError: false, timestamp: 1 }); + expect(latestToolResult(copied)?.toolCallId).toBe("sidecar-1"); +}); + +test.each([false, true])("stateless hosted search history never shadows fresh input (stripped=%s)", strip => { + const tools = [{ type: "function", name: "shell", parameters: { type: "object" } }, { type: "web_search" }]; + const withResult = parseRequest({ model: "step-5-preview", tools, input: [ + { role: "user", content: "run it" }, + { type: "function_call", name: "shell", call_id: "call-1", arguments: "{}" }, + hostedSearchHistory(), + { type: "function_call_output", call_id: "call-1", output: "done" }, + ] }); + const searchOnly = parseRequest({ model: "step-5-preview", tools, input: [ + { role: "user", content: "Old question" }, hostedSearchHistory(), + ] }); + expect(withResult._replayedWebSearchCells).toHaveLength(1); + expect(searchOnly._replayedWebSearchCells).toHaveLength(1); + if (strip) { stripReplayedSearchPairs(withResult); stripReplayedSearchPairs(searchOnly); } + expect(latestToolResult(withResult)?.toolCallId).toBe("call-1"); + // The answered question sits before the search the model already ran; it is not pending input. + expect(pendingUserText(searchOnly)).toBeUndefined(); +}); + describe("StepCode reverse requests are always answered", () => { test("a permission request with no turn is denied", () => { const session = new FakeSession(); @@ -268,7 +342,79 @@ describe("StepCode runTurn, two turns through one conversation", () => { expect(session.delivered).toHaveLength(0); }); - test("turn 2 with the matching result continues the same query", async () => { + test.each([ + ["function_call_output", false], ["function_call_output", true], + ["custom_tool_call_output", false], ["custom_tool_call_output", true], + ] as const)("fresh %s resumes the held query with stripped hosted search=%s", async (outputType, strip) => { + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", toolName: "shell", input: {}, toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, () => {}); + expect(session.queries).toHaveLength(1); + const heldResult = { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "done", isError: false, timestamp: 1 }; + const continuation = { previousResponseId: "resp-1", _replayPrefixLen: 3 }; + const blank = [" \t ", [{ type: "text", text: " \n " }], []]; + const unusable = [ + ...blank.map(content => parsed([...USER_ASK, { role: "user", content }])), + { ...parsed(USER_ASK), ...continuation }, + { ...parsed([...USER_ASK, heldResult]), ...continuation }, + { ...parsed([...USER_ASK, { ...heldResult, toolCallId: "other" }]), ...continuation, _currentInputMessageStart: 1 }, + ]; + for (const turn of unusable) { + const events: AdapterEvent[] = []; + session.stream = [TURN_COMPLETE]; + await adapter.runTurn!(turn, THREAD_META, e => events.push(e)); + expect(events).toMatchObject([{ type: "error", code: "step_cli_no_user_text" }]); + expect(session.queries).toHaveLength(1); + expect(session.inputs).toHaveLength(1); + expect(session.interrupts).toHaveLength(0); + expect(session.delivered).toHaveLength(0); + } + const result: AdapterEvent[] = []; + const model = "step-5-preview"; + const prior = `resp_${crypto.randomUUID()}`; + rememberResponseState( + { model, input: [{ role: "user", content: "run it" }] }, + { id: prior, status: "completed", output: [ + { type: "function_call", name: "shell", call_id: "call-9", arguments: "{}" }, hostedSearchHistory(), + ] }, + ); + const continuationBody = { + model, previous_response_id: prior, + tools: [{ type: "function", name: "shell", description: "run", parameters: { type: "object" } }, { type: "web_search" }], + }; + const restored = parseRequest(expandPreviousResponseInput({ ...continuationBody, input: [] })); + expect(restored._replayPrefixLen).toBeGreaterThan(0); + restored._reasoningReplayScope = parsed(USER_ASK)._reasoningReplayScope; + const declined: AdapterEvent[] = []; + await adapter.runTurn!(restored, THREAD_META, e => declined.push(e)); + expect(declined).toMatchObject([{ type: "error", code: "step_cli_no_user_text" }]); + const fresh = parseRequest(expandPreviousResponseInput({ + ...continuationBody, input: [{ type: outputType, call_id: "call-9", output: "done" }], + })); + expect(fresh._replayPrefixLen).toBeGreaterThan(0); + expect(fresh._replayedWebSearchCells).toHaveLength(1); + expect(fresh.context.messages.filter(m => m.role === "toolResult").map(m => m.toolCallId)).toEqual([ + "call-9", fresh._replayedWebSearchCells![0]!.callId, + ]); + expect(fresh._continuationConversationMessageIndex).toBe(fresh.context.messages.length); + if (strip) stripReplayedSearchPairs(fresh); + fresh._reasoningReplayScope = parsed(USER_ASK)._reasoningReplayScope; + await adapter.runTurn!(fresh, THREAD_META, e => result.push(e)); + expect(result.find(e => e.type === "done")).toMatchObject({ stopReason: "stop" }); + expect(session.delivered).toHaveLength(1); + expect(session.queries).toHaveLength(1); + }); + + test.each([true, false])("a matching tool result continues the same query (user history: %s)", async includeHistory => { const session = new FakeSession(); const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); @@ -293,7 +439,7 @@ describe("StepCode runTurn, two turns through one conversation", () => { ]; await adapter.runTurn!( parsed([ - ...USER_ASK, + ...(includeHistory ? USER_ASK : []), { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "LIVE_BRIDGE_OK", isError: false, timestamp: 1 }, ]), THREAD_META, @@ -312,7 +458,8 @@ describe("StepCode runTurn, two turns through one conversation", () => { expect(second.find(event => event.type === "done")).toMatchObject({ stopReason: "stop" }); }); - test("turn 2 that does NOT answer the held call refuses it and keeps the user's message", async () => { + test("new user text after another call's result replaces the held call", async () => { + const staleCall = "call-SOMEONE-ELSE"; // Regression: the code set `continuedQuery = true` whenever a held call existed, so a client that // sent a new user message instead of the result had that message swallowed and its request // answered with `step_cli_turn_abandoned`. @@ -337,7 +484,7 @@ describe("StepCode runTurn, two turns through one conversation", () => { await adapter.runTurn!( parsed([ ...USER_ASK, - { role: "toolResult", toolCallId: "call-SOMEONE-ELSE", toolName: "shell", content: "stale", isError: false, timestamp: 1 }, + { role: "toolResult", toolCallId: staleCall, toolName: "shell", content: "stale", isError: false, timestamp: 1 }, { role: "user", content: "actually do this instead", timestamp: 2 }, ]), THREAD_META, @@ -352,6 +499,45 @@ describe("StepCode runTurn, two turns through one conversation", () => { expect(session.inputs.at(-1)?.text).toContain("actually do this instead"); }); + test("the held call's own result followed by steering text is delivered, not discarded", async () => { + // Codex records text the user steers with during a tool call after the call's output, so the + // turn ends [toolResult call-9, user]. The tool already ran: answering it with an empty error + // would tell the model it failed and invite a second run of whatever side effects it had. + const session = new FakeSession(); + const adapter = createStepCliAdapter(provider(), { openSession: host(session) }); + session.stream = [ + requestFrame("req_101", "permission.request", { + toolName: "ocx__shell", input: {}, toolUseId: "perm_100", + decisionReason: "tool execution requires approval", timeoutMs: 60_000, + }), + requestFrame("req_102", "sdk_tool.invoke", { + serverName: "ocx", + toolName: "shell", + input: { cmd: "echo LIVE_BRIDGE_OK" }, + toolUseId: "call-9", timeoutMs: 120_000, + }), + ]; + await adapter.runTurn!(parsed(USER_ASK), THREAD_META, () => {}); + + session.stream = [TURN_COMPLETE]; + await adapter.runTurn!( + parsed([ + ...USER_ASK, + { role: "toolResult", toolCallId: "call-9", toolName: "shell", content: "LIVE_BRIDGE_OK", isError: false, timestamp: 1 }, + { role: "user", content: "and then summarize it", timestamp: 2 }, + ]), + THREAD_META, + () => {}, + ); + + const delivered = session.delivered[0]?.result as { content: Array<{ text: string }>; isError?: boolean }; + expect(delivered.isError).toBeUndefined(); + expect(delivered.content[0]?.text).toBe("LIVE_BRIDGE_OK"); + // The held query continues; nothing is interrupted or restarted. + expect(session.interrupts).toEqual([]); + expect(session.queries).toHaveLength(1); + }); + test("an identity-less request is not routed onto the conversation host's own handle", async () => { const session = new FakeSession(); const conversation = host(session); diff --git a/tests/adapters/step-cli-session.test.ts b/tests/adapters/step-cli-session.test.ts index 3a266467bd7..367628c0a37 100644 --- a/tests/adapters/step-cli-session.test.ts +++ b/tests/adapters/step-cli-session.test.ts @@ -406,11 +406,13 @@ describe("StepCode session pool", () => { try { const opening = refs.map(ref => pool.open(ref)); const reuse = pool.open(refs[0]!); + const continuation = pool.open(refs[0]!, { existingOnly: true }); await expect(pool.open(next).catch(mapSessionFailure)).resolves.toMatchObject({ status: 503, code: "step_cli_pool_full", errorType: "server_error", retryable: true, }); const sessions = await Promise.all(opening); expect(await reuse).toBe(sessions[0]!); + expect(await continuation).toBe(sessions[0]!); expect(await pool.open(refs[1]!)).toBe(sessions[1]!); expect(children).toHaveLength(8); From ec003c8d32922d5076323c881c994916fdc90994 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 05:08:30 +0900 Subject: [PATCH 16/64] fix(link): complete restart recovery and retry scheduled disconnect handoff (#9135) * fix(link): complete restart recovery and retry scheduled disconnect handoff * fix(link): bound rollback ownership checks during config lock contention * test(link): cover config lock release on the final rollback wait * fix(link): honor a pending connection before reporting rollback failure * fix(link): route rollback bind failures through locked ownership check --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../src/content/docs/es/guides/remote-link.md | 2 +- .../src/content/docs/guides/remote-link.md | 2 +- .../src/content/docs/ja/guides/remote-link.md | 2 + .../src/content/docs/ko/guides/remote-link.md | 2 + .../src/content/docs/ru/guides/remote-link.md | 2 + .../content/docs/zh-cn/guides/remote-link.md | 2 + src/client/runtime-recycle.ts | 65 ++++++++--- src/client/runtime-restart.ts | 2 +- src/client/runtime-rollback.ts | 19 ++- src/client/runtime.ts | 108 ++++++++++++++---- structure/remote-link.md | 2 +- tests/clients/client-link-runtime.test.ts | 54 +++++++++ .../clients/client-link-stop-recovery.test.ts | 56 +++++++++ .../clients/client-recycle-exclusion.test.ts | 61 +++++++++- .../client-restart-rollback-lock.test.ts | 15 ++- tests/clients/client-runtime-restart.test.ts | 2 +- tests/fixtures/client-link-stop-runner.ts | 101 +++++++++++++++- tests/helpers/client-link-stop.ts | 9 +- 18 files changed, 439 insertions(+), 67 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/remote-link.md b/docs-site/src/content/docs/es/guides/remote-link.md index 11fcc2fa067..262fbd27daf 100644 --- a/docs-site/src/content/docs/es/guides/remote-link.md +++ b/docs-site/src/content/docs/es/guides/remote-link.md @@ -59,7 +59,7 @@ En el equipo que debe utilizar los proveedores de Home: La conexión se reinicia OpenCodex en este equipo. Codex turnos que ya se están ejecutando terminan primero, y las nuevas solicitudes pueden fallar hasta por un minuto mientras se reinicia. El tablero de instrumentos se recarga por sí mismo y muestra el enlace Child. Codex sigue usando `http://127.0.0.1:/v1` en este equipo, sin token y sin variable de entorno para establecer: el local OpenCodex retransmite cada solicitud al Home, que le sirve con sus propios proveedores y cuentas. -El Child espera su puerto configurado mientras el proceso anterior lo libera. Si aún falla un reinicio administrado CLI, ejecute `ocx start` en el Child y verifique `~/.opencodex/restart-handoff.log`. En la aplicación de escritorio, la aplicación inicia y supervisa el reemplazo automáticamente. +El Child espera su puerto configurado mientras el proceso anterior lo libera. Si falla un reinicio gestionado por la CLI y no se puede restaurar la escucha anterior, OpenCodex informa del fallo de recuperación. Para recuperarlo, ejecute `ocx start` en el Child y verifique `~/.opencodex/restart-handoff.log`. En la aplicación de escritorio, la aplicación inicia y supervisa el reemplazo automáticamente. Al desconectar desde el panel, OpenCodex reintenta durante un máximo de 30 segundos si el bloqueo está ocupado. Si el bloqueo sigue ocupado, no se inicia el proceso independiente. Consulta `ocx status` y reinicia OpenCodex. Un `ocx stop` explícito en un Child de Remote Link detiene su proxy y, si se completa la restauración compartida, restaura el enrutamiento nativo de Codex, su catálogo y los metadatos respaldados del historial de reanudación, y elimina la configuración administrada de Grok. La conexión guardada con Home se conserva; usa `ocx disconnect` para eliminarla. diff --git a/docs-site/src/content/docs/guides/remote-link.md b/docs-site/src/content/docs/guides/remote-link.md index 59031001338..528413b813c 100644 --- a/docs-site/src/content/docs/guides/remote-link.md +++ b/docs-site/src/content/docs/guides/remote-link.md @@ -51,7 +51,7 @@ On the computer that should use the Home's providers: Connecting restarts OpenCodex on this computer. Codex turns that are already running finish first, and new requests can fail for up to a minute while it restarts. The dashboard then reloads by itself and shows the Child link. Codex keeps using `http://127.0.0.1:/v1` on this computer, with no token and no environment variable to set: the local OpenCodex relays each request to the Home, which serves it with its own providers and accounts. -The Child waits for its configured port while the old process releases it. If a CLI-managed restart still fails, run `ocx start` on the Child and check `~/.opencodex/restart-handoff.log`. In the desktop app, the app starts and supervises the replacement automatically. +The Child waits for its configured port while the old process releases it. If a CLI-managed restart fails and the previous listener cannot be restored, OpenCodex reports a restart recovery failure. To recover, run `ocx start` on the Child and check `~/.opencodex/restart-handoff.log`. In the desktop app, the app starts and supervises the replacement automatically. A dashboard disconnect retries temporary lock conflicts for up to 30 seconds. If the lock stays busy, the standalone replacement does not start. Check `ocx status` and restart OpenCodex. An explicit `ocx stop` on a Remote Link Child stops its proxy and, when shared restoration succeeds, restores native Codex routing, its catalog and backed-up resume-history metadata and removes the managed Grok configuration. Before stopping the process or service, it removes file integrations created by the Link (such as Pi or OpenCode), preserving pre-existing standalone integrations and user edits. If cleanup is refused, the listener stays bound with synchronization paused; repair the reported configuration or ownership evidence and retry `ocx stop`. To leave Home after a refused stop, `ocx disconnect --recover-config --yes` completes configuration recovery and restarts the retained Child as standalone OpenCodex. A stop or recovery still in progress continues to refuse restart. If the running Child cannot prove support for safe stop, update and restart it through its supervisor before retrying. The saved Home connection is kept; use `ocx disconnect` to remove that connection. diff --git a/docs-site/src/content/docs/ja/guides/remote-link.md b/docs-site/src/content/docs/ja/guides/remote-link.md index 614cd37b461..a240e045e26 100644 --- a/docs-site/src/content/docs/ja/guides/remote-link.md +++ b/docs-site/src/content/docs/ja/guides/remote-link.md @@ -47,6 +47,8 @@ Home のプロバイダーを使うコンピューターで次の操作を行い 接続すると、このコンピューターの OpenCodex が再起動します。すでに実行中の Codex ターンは先に完了し、再起動中の最大 1 分間は新しいリクエストが失敗することがあります。その後ダッシュボードは自動的に再読み込みされ、Child のリンクを表示します。Codex はこのコンピューターの `http://127.0.0.1:/v1` を使い続け、トークンや環境変数の設定は不要です。ローカルの OpenCodex が各リクエストを Home に中継し、Home が自身のプロバイダーとアカウントで応答します。 +CLI からの再起動が失敗し、以前のリスナーも復元できない場合、OpenCodex は復旧失敗を報告します。Child で `ocx start` を実行し、`~/.opencodex/restart-handoff.log` を確認してください。ダッシュボードから接続を解除するときにロックが使用中なら、OpenCodex は最長 30 秒間再試行します。それでもロックを取得できない場合はスタンドアロンのプロセスを起動しません。`ocx status` で状態を確認し、OpenCodex を再起動してください。 + **Child** にこのコンピューターを先にペアリングするよう表示された場合は、このコンピューターに設定された HTTP ループバック IP アドレスのダッシュボード(例: `http://127.0.0.1:`)を開いてください。ローカルのペアリングフォームは、ペアリングが必要で、ダッシュボードと API が同じループバックオリジンを使う場合にのみ表示されます。フォームの `ocx gui pair --origin "http://127.0.0.1:"` コマンドをコピーしてこのコンピューターのターミナルで実行し、使い捨てコードをフォームに貼り付けてください。フォームに表示された正確なオリジンを使ってください。プロバイダーの API キーや管理者トークンはペアリングコードではありません。ペアリングの不足と設定されたポートの不一致は別の原因です。 **Child** の役割には、OpenCodex がスタンドアロンモードで設定されたポートで動作していることも必要です。Child はまさにそのポートで再起動するためです。設定されたポートで動作していないとダッシュボードに表示された場合は、先にそのポートで OpenCodex を再起動してください。 diff --git a/docs-site/src/content/docs/ko/guides/remote-link.md b/docs-site/src/content/docs/ko/guides/remote-link.md index 6a9e24e7f04..64dd295958f 100644 --- a/docs-site/src/content/docs/ko/guides/remote-link.md +++ b/docs-site/src/content/docs/ko/guides/remote-link.md @@ -47,6 +47,8 @@ Home의 프로바이더를 사용할 컴퓨터에서 다음을 진행합니다. 연결하면 이 컴퓨터의 OpenCodex가 다시 시작됩니다. 이미 실행 중인 Codex 작업은 먼저 끝나고, 다시 시작되는 동안 최대 1분 정도 새 요청이 실패할 수 있습니다. 그 뒤 대시보드가 스스로 새로 고쳐지고 Child 링크를 보여 줍니다. Codex는 이 컴퓨터의 `http://127.0.0.1:/v1`을 그대로 사용하며 토큰이나 환경 변수를 설정할 필요가 없습니다. 로컬 OpenCodex가 각 요청을 Home으로 전달하고, Home은 자신의 프로바이더와 계정으로 응답합니다. +CLI에서 재시작에 실패해 기존 리스너도 복구할 수 없으면 OpenCodex가 복구 실패를 보고합니다. Child에서 `ocx start`를 실행하고 `~/.opencodex/restart-handoff.log`를 확인하세요. 대시보드에서 연결을 해제할 때 잠금이 사용 중이면 최대 30초 동안 재시도합니다. 기한까지 잠금이 풀리지 않으면 독립 실행 프로세스가 시작되지 않습니다. `ocx status`로 상태를 확인한 뒤 OpenCodex를 재시작하세요. + Child에서 `ocx stop`을 실행하면 프로세스나 서비스를 종료하기 전에 Link가 만든 Pi·OpenCode 등의 파일 통합을 정리합니다. 연결 전부터 쓰던 독립형 통합과 사용자가 수정한 내용은 보존합니다. 파일이 충돌하거나 소유권을 확인할 수 없으면 종료를 거부하고, 동기화를 멈춘 채 로컬 포트를 유지합니다. 표시된 설정이나 소유권 기록을 복구한 뒤 `ocx stop`을 다시 실행하세요. 종료가 거부된 뒤 Home 연결도 끊으려면 `ocx disconnect --recover-config --yes`를 실행할 수 있습니다. 설정 복구가 완전히 끝나면 남아 있던 Child가 독립형 OpenCodex로 다시 시작합니다. 종료나 복구가 아직 진행 중이면 재시작을 계속 거부합니다. 실행 중인 Child가 안전한 종료 지원을 증명하지 못하는 구버전이라면, 해당 서비스를 관리하는 프로그램을 통해 업데이트하고 다시 시작한 뒤 재시도하세요. Home 연결 정보는 남으며, 연결 자체를 지우려면 `ocx disconnect`를 사용합니다. 다시 사용하려면 Child를 시작한 뒤 Home에 연결할 수 있는 상태에서 `ocx sync --restart-codex`를 실행하세요. 시작만으로는 통합 설정을 다시 적용하지 않습니다. 종료 신호를 처리하면서 파일 정리 이후 Codex 기본 설정이나 Grok 복원이 거부된 경우에도 Child는 동기화를 멈추고 로컬 포트를 유지합니다. 표시된 기록을 복구한 뒤 `ocx stop`을 다시 실행하세요. 이 Child의 종료를 실제로 맡은 상위 프로세스를 확인한 경우에만 Codex 기본 설정과 Grok 복원을 넘깁니다. 종료 기록만으로 파일 정리나 동기화 차단을 생략하지 않으며, 오래되거나 읽을 수 없는 기록만 남아 있으면 포트와 복구 기록을 유지합니다. 명시적인 중단 명령도 이전 복구 기록 때문에 기본 설정을 복원할 수 없는 경우에는 프로세스를 종료하기 전에 거부합니다. 명시적인 `ocx stop`은 Child가 종료된 뒤 기본 설정 복원을 시도하므로, 이 단계에서 복원이 거부되면 포트는 이미 닫힌 상태이고 미완료 복원과 남은 복구 기록을 알려 줍니다. **Child**에 이 컴퓨터를 먼저 페어링하라는 안내가 나오면, 이 컴퓨터에 설정된 IP 주소 형식의 HTTP 루프백 대시보드(예: `http://127.0.0.1:`)를 여세요. 로컬 페어링 양식은 페어링이 필요하고 대시보드와 API가 같은 루프백 출처를 사용할 때만 표시됩니다. 양식의 `ocx gui pair --origin "http://127.0.0.1:"` 명령을 복사해 이 컴퓨터의 터미널에서 실행한 뒤, 일회용 코드를 양식에 붙여 넣으세요. 양식에 표시된 정확한 출처를 사용해야 하며, 프로바이더 API 키나 관리자 토큰은 페어링 코드가 아닙니다. 페어링 누락과 설정된 포트의 불일치는 서로 다른 사유입니다. diff --git a/docs-site/src/content/docs/ru/guides/remote-link.md b/docs-site/src/content/docs/ru/guides/remote-link.md index 5730ea661aa..6bf5f74bf81 100644 --- a/docs-site/src/content/docs/ru/guides/remote-link.md +++ b/docs-site/src/content/docs/ru/guides/remote-link.md @@ -47,6 +47,8 @@ Host devbox При подключении OpenCodex на этом компьютере перезапустится. Уже идущие запросы Codex сначала завершатся, а новые запросы могут не проходить до минуты, пока идёт перезапуск. Затем панель перезагрузится сама и покажет связь Child. Codex продолжит использовать `http://127.0.0.1:/v1` на этом компьютере без токена и без переменных окружения: локальный OpenCodex передаёт каждый запрос на Home, а Home обслуживает его своими провайдерами и учётными записями. +Если перезапуск через CLI завершился ошибкой и прежний слушатель восстановить не удалось, OpenCodex сообщает о сбое восстановления. Выполните `ocx start` на Child и проверьте `~/.opencodex/restart-handoff.log`. Если при отключении через панель блокировка занята, OpenCodex повторяет попытку в течение не более 30 секунд. Если блокировка не освободилась, автономный процесс не запускается. Проверьте `ocx status` и перезапустите OpenCodex. + Если **Child** просит сначала выполнить сопряжение этого компьютера, откройте на нём HTTP-панель по настроенному IP-адресу обратной петли, например `http://127.0.0.1:`. Локальная форма сопряжения появляется только при отсутствии сопряжения, когда панель и API используют один и тот же origin обратной петли. Скопируйте из формы команду `ocx gui pair --origin "http://127.0.0.1:"`, выполните её в терминале на этом компьютере и вставьте одноразовый код в форму. Используйте точно тот origin, который показан в форме; API-ключ провайдера или токен администратора не является кодом сопряжения. Отсутствие сопряжения и несовпадение настроенного порта — разные причины. Роль **Child** также требует, чтобы OpenCodex работал в автономном режиме на настроенном порту, потому что Child перезапускается именно на нём. Если панель сообщает, что OpenCodex работает не на настроенном порту, сначала перезапустите его на этом порту. diff --git a/docs-site/src/content/docs/zh-cn/guides/remote-link.md b/docs-site/src/content/docs/zh-cn/guides/remote-link.md index 1f63372ee3a..d0112266a51 100644 --- a/docs-site/src/content/docs/zh-cn/guides/remote-link.md +++ b/docs-site/src/content/docs/zh-cn/guides/remote-link.md @@ -47,6 +47,8 @@ Host devbox 连接会重启这台电脑上的 OpenCodex。已在运行的 Codex 请求会先完成,重启期间新的请求可能在最多一分钟内失败。随后控制台会自动重新加载并显示子机链接。Codex 继续使用这台电脑上的 `http://127.0.0.1:/v1`,无需设置令牌或环境变量:本地 OpenCodex 会把每个请求转发给主机,由主机用它自己的提供商和账户提供服务。 +如果通过 CLI 重启失败且无法恢复原有监听器,OpenCodex 会报告恢复失败。请在子机运行 `ocx start`,并检查 `~/.opencodex/restart-handoff.log`。从控制台断开连接时,如果锁被占用,OpenCodex 会重试最多 30 秒。如果锁仍未释放,独立进程不会启动。请运行 `ocx status` 检查状态,再重启 OpenCodex。 + 如果 **Child** 提示先配对这台电脑,请在这台电脑上打开配置的 HTTP 回环 IP 地址控制台,例如 `http://127.0.0.1:`。只有在缺少配对且控制台与 API 使用同一个回环源时,才会显示本地配对表单。复制表单中的 `ocx gui pair --origin "http://127.0.0.1:"` 命令,在这台电脑的终端中运行,再将一次性代码粘贴到表单中。必须使用表单显示的确切源;提供商 API 密钥或管理员令牌不是配对代码。缺少配对与配置端口不匹配是不同的原因。 选择 **Child** 角色还要求 OpenCodex 以独立运行模式在其配置的端口上运行,因为子机会在正好这个端口上重启。如果控制台提示 OpenCodex 未在其配置的端口上运行,请先在该端口上重启它。 diff --git a/src/client/runtime-recycle.ts b/src/client/runtime-recycle.ts index e0fb65498b3..54ae42265c7 100644 --- a/src/client/runtime-recycle.ts +++ b/src/client/runtime-recycle.ts @@ -1,8 +1,22 @@ -import { withConfigMutationLockSync } from "../config"; +import { readDesktopDisconnectReceipt } from "../claude/desktop-remote-store"; +import { ConfigMutationLockError, withConfigMutationLockSync } from "../config"; import type { OcxClientConnectionConfig } from "../types"; -import { withLinkApply } from "./link-home"; +import { LinkApplyBusyError, withLinkApply } from "./link-home"; import { clientConnectionEnded } from "./runtime-restart"; -import { pendingClientConnectMayOwnToken, readClientConnectionStateWithEvidence } from "./state"; +import { pendingClientConnectMayOwnToken, readClientConnectionStateWithEvidence, sameClientConnectionOwner } from "./state"; + +interface ScheduledRecycle { + current: () => boolean; + now?: () => number; + sleep?: (ms: number) => Promise; +} + +function recycleLockBusy(error: unknown): boolean { + if (error instanceof LinkApplyBusyError) return true; + const cause = error instanceof ConfigMutationLockError ? error.cause : undefined; + return !!cause && typeof cause === "object" && "code" in cause + && (cause.code === "SQLITE_BUSY" || cause.code === "SQLITE_LOCKED"); +} /** * Called outside L: Link apply exclusion is outermost in the apply -> N -> L -> C order. @@ -12,18 +26,39 @@ export async function runClientRecycleWithAdmission( served: OcxClientConnectionConfig, allowed: () => boolean, teardown: () => Promise, + scheduled?: ScheduledRecycle, ): Promise { - let admitted = false; - try { - return await withLinkApply(async () => { - admitted = withConfigMutationLockSync(() => allowed() && !pendingClientConnectMayOwnToken() - && clientConnectionEnded(served, readClientConnectionStateWithEvidence())); - if (!admitted) return false; - await teardown(); - return true; - }); - } catch (error) { - if (admitted) throw error; // A started teardown must not masquerade as an admission refusal. - return false; + const now = scheduled?.now ?? (() => performance.now()); + const deadline = now() + 30_000; + let delay = 50; + for (let retried = false; ; retried = true) { + if (scheduled && !scheduled.current()) return false; + if (retried && now() >= deadline) { + console.warn("[client] disconnect recycle timed out waiting for a Link lock; check ocx status and restart"); + return false; + } + let admitted = false; + try { + return await withLinkApply(async () => { + admitted = withConfigMutationLockSync(() => { + if ((scheduled && !scheduled.current()) || !allowed() || pendingClientConnectMayOwnToken()) return false; + const current = readClientConnectionStateWithEvidence(); + // A new connection committed while this disconnect waited owns its own transition. + if (!retried) return clientConnectionEnded(served, current); + if (current.kind !== "disconnected") return false; + const receipt = readDesktopDisconnectReceipt(); + return receipt.kind === "absent" || (receipt.kind === "valid" && receipt.value.phase === "complete" + && sameClientConnectionOwner(receipt.value.owner, served) && receipt.value.tokenFingerprint === served.tokenFingerprint); + }); + if (!admitted) return false; + await teardown(); + return true; + }); + } catch (error) { + if (admitted) throw error; + if (!scheduled || !recycleLockBusy(error)) return false; + } + await (scheduled.sleep ?? Bun.sleep)(Math.max(0, Math.min(delay, deadline - now()))); + delay = Math.min(delay * 2, 1_000); } } diff --git a/src/client/runtime-restart.ts b/src/client/runtime-restart.ts index 9b17da3f809..f37685744a4 100644 --- a/src/client/runtime-restart.ts +++ b/src/client/runtime-restart.ts @@ -130,7 +130,7 @@ export function createClientRestartController(io: ClientRestartIo): ClientRestar try { await io.spawnReplacement(acceptedAt + CLIENT_RESTART_READY_BY_MS); } catch (error) { - warn(`[client] restart: the replacement did not start (${failureCode(error)}); this runtime keeps serving`); + warn(`[client] restart: the replacement did not start (${failureCode(error)}); attempting recovery`); try { await io.resume(); } catch (resumeError) { diff --git a/src/client/runtime-rollback.ts b/src/client/runtime-rollback.ts index f2e0380377b..08a3c4882c9 100644 --- a/src/client/runtime-rollback.ts +++ b/src/client/runtime-rollback.ts @@ -10,20 +10,19 @@ export function retryableClientRollbackLock(error: unknown): boolean { return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED"; } -/** Each busy attempt must close its unpublished listener before this helper may yield. */ -export async function retryClientRollback( - attempt: (remainingMs: number) => Promise, - io: { now?: () => number; sleep?: (ms: number) => Promise; budgetMs?: number } = {}, -): Promise { +/** Only transient contention is retried, up to the shared recovery deadline. A bind attempt closes its unpublished listener before yielding. */ +export async function retryClientRollback( + attempt: (remainingMs: number) => T | Promise, + io: { now?: () => number; sleep?: (ms: number) => Promise; budgetMs?: number; deadline?: number } = {}, +): Promise { const now = io.now ?? (() => performance.now()); - const deadline = now() + (io.budgetMs ?? CLIENT_RESTART_REBIND_WAIT_MS); + const deadline = io.deadline ?? now() + (io.budgetMs ?? CLIENT_RESTART_REBIND_WAIT_MS); while (now() < deadline) { const result = await attempt(Math.max(0, deadline - now())); - if (result === "published") return true; - if (result !== "busy") return false; + if (result !== "busy") return result; const remaining = deadline - now(); - if (remaining <= 0) return false; + if (remaining <= 0) break; await (io.sleep ?? Bun.sleep)(Math.min(50, remaining)); } - return false; + return "busy"; } diff --git a/src/client/runtime.ts b/src/client/runtime.ts index ace5c261520..c1d85c62721 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -15,6 +15,7 @@ import { createLocalAttestationSecret } from "../lib/local-management-attestatio import { loadServiceTokenFromFile, serviceApiTokenFingerprint } from "../lib/service-secrets"; import { handledSignalExitCode } from "../lib/handled-signal-exit"; import { + CLIENT_RESTART_REBIND_WAIT_MS, DESKTOP_RESTART_EXIT_CODE, DESKTOP_SUPERVISED_ENV, DESKTOP_SUPERVISED_PORT_WAIT_MS, @@ -61,7 +62,7 @@ let clientStopping = false; let explicitClientStopRequested: boolean | undefined; let explicitClientStopOwner: ClientStopOwner | undefined; let standaloneRecycleAllowed = () => !clientStopping; -let activeLinkForRecycle: OcxClientConnectionConfig | undefined; +let activeLinkForRecycle: { connection: OcxClientConnectionConfig; isServingGeneration: () => boolean } | undefined; /** * When this runtime's process started (OCX-6, P5): what `/healthz` reports as `startedAt` and the @@ -170,12 +171,22 @@ export function standaloneRecycleEnv( } export function scheduleStandaloneRecycle(disconnectedTokenFingerprint: string): void { - if (recycleScheduled || !standaloneRecycleAllowed()) return; + const listener = activeServer; + const served = activeLinkForRecycle; + if (recycleScheduled || recycleFlight) return; + if (served) { + if (!listener || served.connection.tokenFingerprint !== disconnectedTokenFingerprint || !served.isServingGeneration()) return; + } else if (!standaloneRecycleAllowed()) return; recycleScheduled = true; + const current = () => recycleScheduled && activeServer === listener && activeLinkForRecycle === served + && (!served || served.isServingGeneration()); recycleTimer = setTimeout(() => { recycleTimer = undefined; - if (!standaloneRecycleAllowed()) { recycleScheduled = false; return; } - recycleFlight = recycleStandalone(disconnectedTokenFingerprint).finally(() => { recycleFlight = null; }); + if (!current() || (!served && !standaloneRecycleAllowed())) { recycleScheduled = false; return; } + recycleFlight = recycleStandalone(disconnectedTokenFingerprint, {}, current).finally(() => { + recycleScheduled = false; + recycleFlight = null; + }); void recycleFlight.catch(error => { if (!clientStopping) throw error; }); }, 50); if (typeof recycleTimer === "object" && "unref" in recycleTimer) recycleTimer.unref(); @@ -198,6 +209,7 @@ function errorCode(error: unknown): string { export async function recycleStandalone( disconnectedTokenFingerprint: string, io: StandaloneRecycleIo = {}, + scheduledCurrent?: () => boolean, ): Promise { // The configured port when the listener never recorded one: the recycle still owes a proxy. const port = activePort ?? (io.configuredPort ?? configuredTcpPort)(); @@ -229,10 +241,8 @@ export async function recycleStandalone( await flushLinkDiagnostics(); }; if (activeLinkForRecycle) { - if (!(await runClientRecycleWithAdmission(activeLinkForRecycle, standaloneRecycleAllowed, teardown))) { - recycleScheduled = false; - return; - } + const scheduled = scheduledCurrent ? { current: scheduledCurrent } : undefined; + if (!(await runClientRecycleWithAdmission(activeLinkForRecycle.connection, standaloneRecycleAllowed, teardown, scheduled))) return; } else await teardown(); // Recycling back to standalone after `ocx disconnect` must actually bring a standalone // proxy back, under every launch shape. @@ -443,7 +453,10 @@ export async function startClientRuntime( clientLinkOwner }); }; const activate = (): void => { - activeLinkForRecycle = linkMode ? state.value : undefined; + activeLinkForRecycle = linkMode ? { + connection: state.value, + isServingGeneration: () => !shuttingDown && readRuntimePort(process.pid)?.servingGeneration === servingGeneration, + } : undefined; activeServer = server; activePort = boundPort; servedPort = boundPort; @@ -520,22 +533,26 @@ export async function startClientRuntime( }; let shuttingDown = false; - standaloneRecycleAllowed = () => { + const completedDisconnectOwnership = () => { try { - if (shuttingDown || observeExplicitStop()) return false; - if (!clientStopping) return true; - // A retained sync fence is not an active exit. Only a completed disconnect of this exact - // served owner permits recovery; partial cleanup, a new connect or uncertain state cannot. return withConfigMutationLockSync(() => { - if (observeExplicitStop()) return false; + if (shuttingDown || observeExplicitStop()) return false; const receipt = readDesktopDisconnectReceipt(); return ownerProven() && !pendingClientConnectMayOwnToken() && readClientConnectionStateWithEvidence().kind === "disconnected" && receipt.kind === "valid" && receipt.value.phase === "complete" && sameClientConnectionOwner(receipt.value.owner, state.value) && receipt.value.tokenFingerprint === state.value.tokenFingerprint; - }); - } catch { return false; } + }) ? "owned" : "refused"; + } catch (error) { + return retryableClientRollbackLock(error) ? "busy" : "refused"; + } + }; + standaloneRecycleAllowed = () => { + // A retained sync fence is not an active exit. Only this owner's completed disconnect + // permits recovery after that fence. + try { return !shuttingDown && !observeExplicitStop() && (!clientStopping || completedDisconnectOwnership() === "owned"); } + catch { return false; } }; const restartController: ClientRestartController = createClientRestartController({ stopping: () => !standaloneRecycleAllowed(), @@ -567,8 +584,21 @@ export async function startClientRuntime( ); }, resume: async () => { - const recycleAfterRollback = () => { - if (standaloneRecycleAllowed()) return recycleStandalone(state.value.tokenFingerprint); + const deadline = performance.now() + CLIENT_RESTART_REBIND_WAIT_MS; + const recycleAfterRollback = async () => { + if (standaloneRecycleAllowed()) await recycleStandalone(state.value.tokenFingerprint); + // An admitted recycle exits this process. A refused one may return after the original + // listener stopped. Fail only while this generation still owns the completed disconnect. + const current = () => !activeServer && activeLinkForRecycle?.connection === state.value && activeLinkForRecycle.isServingGeneration(); + const probe = () => current() ? completedDisconnectOwnership() : "refused"; + let proof = await retryClientRollback(probe, { deadline }); + // The rebind can use the whole budget. Still take one immediate, locked observation + // before reporting unresolved ownership; this does not start another wait. + if (proof === "busy") proof = probe(); + if (proof === "owned" && current() && !observeExplicitStop()) { + throw Object.assign(new Error("Could not hand off the disconnected Link listener"), { code: "client_recycle_unpublished" }); + } + if (proof === "busy" && current()) console.warn("[client] restart: could not verify disconnect ownership before the recovery deadline; check ocx status"); }; // The connection may have changed while the replacement was starting (`ocx disconnect`, a // new connect). Serving the old one again would be a stale runtime nothing recycles; hand @@ -577,11 +607,39 @@ export async function startClientRuntime( await recycleAfterRollback(); return; } - if (!(await retryClientRollback(async remainingMs => { - observeExplicitStop(); - if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return "refused"; - return serve({ port: servedPort, portWaitMs: remainingMs }); - }))) { + let rollbackResult: ClientRollbackAttempt | "bind_failed"; + let bindError: unknown; + try { + rollbackResult = await retryClientRollback(async remainingMs => { + observeExplicitStop(); + if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return "refused"; + return serve({ port: servedPort, portWaitMs: remainingMs }); + }, { deadline }); + } catch (error) { + if (!linkMode) throw error; + bindError = error; + rollbackResult = "bind_failed"; + } + if (rollbackResult !== "published") { + // The old config can still be current after a new connect claims its credential. + // Take the final snapshot under C, which excludes publication of that pending marker. + if (linkMode && clientRestartRollbackAction(state.value, readClientConnectionStateWithEvidence()) === "resume") { + let action: "defer" | "resume" | "recycle"; + try { + action = withConfigMutationLockSync(() => shuttingDown || observeExplicitStop() || pendingClientConnectMayOwnToken() + ? "defer" : clientRestartRollbackAction(state.value, readClientConnectionStateWithEvidence())); + } catch { + console.warn("[client] restart: could not verify ownership of the unpublished Link listener; check ocx status"); + return; + } + if (action === "defer") return; + if (action === "resume") { + throw Object.assign( + new Error("Could not republish the Link listener", bindError !== undefined ? { cause: bindError } : undefined), + { code: "client_rollback_unpublished" }, + ); + } + } await recycleAfterRollback(); } }, @@ -603,8 +661,8 @@ export async function startClientRuntime( if (recycleTimer) { clearTimeout(recycleTimer); recycleTimer = undefined; - recycleScheduled = false; } + recycleScheduled = false; const fenceSync = () => { if (!linkMode) return true; try { markClientRuntimeStopping({ pid: process.pid, port: servedPort, attestationSecret }); return true; } diff --git a/structure/remote-link.md b/structure/remote-link.md index a129e65454e..64b89f05e9d 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -21,7 +21,7 @@ A discovery miss requires independent standalone proof or a matching manager reg An explicit parent stop sets `clientStopRequested: true` and writes its nonce, owner PID and process creation identity in the same exact-runtime C transaction. A deferred-teardown receipt with that nonce and creation identity must be written before manager or process stop. `src/config/process-state.ts` accepts both boolean values only with `clientStopping: true`. Before releasing its ownership mutation lease, the CLI finalizer clears only the matching request and retains the sync fence. A finalization refusal keeps the fence and preserves the original stop result. The runtime observes it only for its own PID/port/attestation, rejects further restart admission and the pre-fence stage of an already-admitted restart, and preserves both active and finished states under C when publishing a failed-restart rollback. A retained fence blocks unchanged, pending, new or unverified connections. Only a validated disconnected config and a complete disconnect receipt for the served owner and token, checked together under C with no pending connect, admit a serialized standalone recycle after the parent stop finishes. A verified active or unverified parent stop blocks recovery, as does signal shutdown. Only a dead PID or a positively different creation identity is confirmed stale. A malformed identity or an unrecognized invocation at the same incarnation is unverified. A receipt whose owner cannot be verified remains outstanding and blocks parent recovery. The check covers a previously scheduled timer and a restart awaiting its final supervisor check. After a completed disconnect, a finished request or confirmed-stale owner permits recovery. Signal shutdown cancels a pending recycle timer and frees its scheduling slot for eligible recovery if the listener is retained. Shutdown still waits for a recycle already in flight. A fresh process has a new attestation and does not inherit a stale request. The owning runtime passes `linkStopFence: true` to `src/client/machine-listener.ts`, which advertises it in attested health. Link preflight requires that capability before writing the marker or files; older or unknown running builds refuse with supervisor update/restart guidance. A Hub stop does not require the Link fence. A native listener that does not report a Link fence must publish its Hub identity and still have a saved Hub connection. Older native listeners without a published owner refuse until updated and restarted through their supervisor. Ordinary restart has no explicit-stop marker, so a failed replacement still publishes a new generation and admits fresh sync. Rollback closes an unpublished rebound listener before yielding on lifecycle/configuration lock contention, retries within one shared rebind deadline, and rechecks connection ownership and explicit-stop evidence before each new bind and publication. It starts the tunnel supervisor and credential observer only after publication. The overlap and ordinary-rollback control use real runtime records and file writers in `tests/clients/client-link-stop-recovery.test.ts`. -`src/client/runtime-recycle.ts` holds the Link apply exclusion from admission through listener drain and routing cleanup. Admission rechecks the served connection and explicit-stop policy under the configuration mutation lock; a pending transition, unchanged connection or retained stop obligation refuses teardown. The exclusion is released before replacement startup. `src/client/runtime-rollback.ts` retries only proven lifecycle or SQLite lock contention, with at most 50 ms between attempts and one remaining-time budget shared with listener rebinding. Coverage: `tests/clients/client-recycle-exclusion.test.ts`, `tests/clients/client-restart-rollback-lock.test.ts`, and the rollback controls in `tests/clients/client-link-stop-recovery.test.ts`. +`src/client/runtime-recycle.ts` holds the Link apply exclusion from admission through listener drain and routing cleanup. Admission rechecks the served connection and explicit-stop policy under the configuration mutation lock; a pending transition, unchanged connection or retained stop obligation refuses teardown. The exclusion is released before replacement startup. A scheduled disconnect retries proven apply or SQLite lock contention for up to 30 seconds. Each delayed attempt checks the listener generation, stop state, connection state and disconnect receipt before admission. Errors after teardown starts propagate to the caller. `src/client/runtime-rollback.ts` retries only proven lifecycle or SQLite lock contention, with at most 50 ms between attempts and one remaining-time budget shared with listener rebinding. If the replacement fails and the original Link still owns recovery, exhausting the rebind budget without publishing a listener fails the restart. A confirmed disconnect whose immediate handoff is refused also fails recovery while the same runtime still owns it. Coverage: `tests/clients/client-recycle-exclusion.test.ts`, `tests/clients/client-restart-rollback-lock.test.ts`, and the rollback controls in `tests/clients/client-link-stop-recovery.test.ts`. `src/link/ssh-argv.ts` and `src/link/remote-windows.ts` build every gated Child command through `remoteGatedOcxArgv` and `windowsGatedOcxArgv`: the script selects one executable, reads its version inside the remote script, refuses below the command's minimum with a named `ocx-fanout:` marker and exit 121, and only then runs the arguments. Every gated script exports `OCX_NO_DESKTOP_HANDOFF=1` before the version probe and the run, so a package launcher answers for itself and a Desktop handoff cannot pass the gate on behalf of an older launcher. The pinned sync is the 2.93.0 instance and executes `sync --expect-link`; the Home adds `--restart-app-server-only` or `--restart-codex` only for a restarting sync (the Child operation runners below and `ocx sync --restart-children`), never on Windows (the builder refuses it, `unsupported:windows-restart`) or for a link recorded as `ocx-child`, and withholds it for a link whose relayed model traffic is in flight (`src/cli/sync-fanout.ts`, `src/link/sync-then-restart.ts`). A link whose `childKind` is not recorded can receive the flag on that second sync, which is how the selected-kind marker reports `ocx-child`; `ocx-child` ignores it. The update builders in `src/link/child-gated-ocx.ts` require 2.97.0 inside the script, so the Home never sends `update` to an ocx that reports an older version; they refuse a selected `ocx-child` by file name (`ocx-fanout:child-ocx-ephemeral`) and on POSIX report `ocx-fanout:entry:pair|binary` (Windows reads no census, so its script prints no entry marker and the Home infers `binary`); the plan probe also reports the Child's clock, and the shipped builders refuse Windows apply. A Windows command that would exceed the encoded command-line budget throws `windows-command-too-long`; the plan probe fits a Home version of at least 40 characters. `src/link/child-update-contract.ts` is the Home's own strict copy of the Child's `update.orchestrated/1` plan and result documents and maps every apply exit to a closed verdict. `src/link/child-observations.ts` keeps a tolerant per-link cache in `/link/child-observations.json` beside the strict `links.json`: it drops unknown keys, prunes removed links on write and reads damage as empty. The per-Child sync classifier lives in `src/link/sync-fanout-classify.ts`. The plan probe is wired to the observe operation (`src/link/child-observe.ts`, below), which always passes the resolved platform to `classifyUpdatePlanProbe`; the apply builder and the sync restart flag are called from the Child operation runners (below) and `ocx sync --restart-children`; nothing runs on a timer except the Child-ops scheduler (below), which submits no-restart `sync` jobs and restarts app-servers only for idle Children under `childCodexRestart: "app-server-when-idle"`. The relay, not `onAuthenticatedCatalog` (which fires on admission and keeps driving the supervisor and the enrollment wait), records each Child's catalog pulls. Coverage: `tests/clients/link-gated-ocx-argv.test.ts`, `tests/clients/link-child-update-contract.test.ts`, `tests/clients/link-child-observations.test.ts`. Fan-out platform discovery in `src/link/remote-platform.ts` accepts a Windows marker on any stdout line or one framed uname line, so login-shell output cannot decide the platform. The Home requires one valid selection marker on stderr and one stdout delimiter, and classifies only the text after that delimiter; login-shell output before them is ignored. Oversized version probes are skipped. POSIX version capture and watchdog readiness use a private temporary directory, removed before execution or on refusal. The Home's `src/cli/sync-command.ts` fans out only after its catalog is current; the Child may still restart its own OpenCodex client runtime after applying changed Home settings. With `--overwrite-conflict` the pinned sync gate requires 2.100.0 and refuses ephemeral Children before executing; explicit client selection is forwarded. Known ephemeral links receive plain catalog sync. Coverage: `tests/clients/link-pinned-sync-overwrite.test.ts`, `tests/cli/cli-sync-fanout-ephemeral.test.ts`. diff --git a/tests/clients/client-link-runtime.test.ts b/tests/clients/client-link-runtime.test.ts index d4299b341e0..d438184c7b8 100644 --- a/tests/clients/client-link-runtime.test.ts +++ b/tests/clients/client-link-runtime.test.ts @@ -155,6 +155,60 @@ test.each(["SIGINT", "SIGTERM", "restart"])("%s shutdown persists queued diagnos } }, watchdogMs(60_000)); +test("an accepted Home disconnect recycles once after a competing apply releases its lock", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-scheduled-recycle-")); + const source = ` + import { mock } from "bun:test"; + import { existsSync } from "node:fs"; + import { join } from "node:path"; + import { getDefaultConfig, saveConfig } from ${JSON.stringify(repoPath("src/config.ts"))}; + import { handleMachineApi } from ${JSON.stringify(repoPath("src/client/machine-api.ts"))}; + const homeModule = ${JSON.stringify(repoPath("src/client/link-home.ts"))}; + const home = await import(homeModule), hold = home.withLinkApply; + const busy = Promise.withResolvers(); + mock.module(homeModule, () => ({ ...home, withLinkApply: async (...args) => { + try { return await hold(...args); } + catch (error) { if (error instanceof home.LinkApplyBusyError) busy.resolve(); throw error; } + } })); + const replacement = ${JSON.stringify(repoPath("src/server/restart-replacement.ts"))}; + mock.module(replacement, () => ({ spawnReplacementStart: async () => console.log("replacement") })); + const { startClientRuntime } = await import(${JSON.stringify(repoPath("src/client/runtime.ts"))}); + const config = getDefaultConfig(), connection = ${JSON.stringify(linkClientState())}; + config.port = ${freePort()}; config.runtimeRole = "client"; config.client = connection; saveConfig(config); + let machine; + await startClientRuntime({ block: false }, { startListener: (port, deps) => { + machine = deps.machineApi; + return Bun.serve({ hostname: "127.0.0.1", port, fetch: () => new Response(null) }); + } }); + await hold(async () => { + const url = new URL("http://localhost/api/machine/disconnect"); + const response = await handleMachineApi(new Request(url, { method: "POST", body: "{}" }), url, connection, { + ...machine, disconnect: async () => { delete config.client; config.runtimeRole = "standalone"; saveConfig(config); return {}; }, + }); + if (response.status !== 202) throw new Error("disconnect was not accepted"); + machine.scheduleStandaloneRecycle(connection.tokenFingerprint); + await busy.promise; + if (!existsSync(join(process.env.OPENCODEX_HOME, "runtime-port.json"))) throw new Error("teardown ran under contention"); + console.log("accepted while busy"); + }); + `; + const child = Bun.spawn([process.execPath, "-e", source], { + cwd: root, env: { ...process.env, HOME: root, USERPROFILE: root, CODEX_HOME: join(root, "codex"), + OPENCODEX_HOME: join(root, "ocx"), OCX_SERVICE: "", OCX_DESKTOP_SUPERVISED: "" }, + stdout: "pipe", stderr: "pipe", + }); + const out = new Response(child.stdout).text(), err = new Response(child.stderr).text(); + try { + const exit = await waitFor(() => child.exitCode, "scheduled disconnect recycle"); + expect({ exit, stderr: await err }).toEqual({ exit: 0, stderr: "" }); + expect((await out).match(/accepted while busy|replacement/g)).toEqual(["accepted while busy", "replacement"]); + } finally { + if (child.exitCode === null) child.kill(); + await child.exited; + removeTreeWithRetry(root); + } +}, watchdogMs(60_000)); + test("an ended link recycles a connected sibling after listener cleanup", async () => { const root = mkdtempSync(join(tmpdir(), "ocx-client-sibling-recycle-")); const home = join(root, "ocx"); diff --git a/tests/clients/client-link-stop-recovery.test.ts b/tests/clients/client-link-stop-recovery.test.ts index 8cab87d947f..025d379f46a 100644 --- a/tests/clients/client-link-stop-recovery.test.ts +++ b/tests/clients/client-link-stop-recovery.test.ts @@ -151,6 +151,17 @@ test("ordinary restart rollback keeps file routes and admits fresh sync", async expect(report.protectedUnchanged).toBe(true); }, 20_000); +for (const mode of ["file-restart-control", "file-restart-overlap"] as const) { + test(`unchanged Link rollback exhaustion ${mode === "file-restart-control" ? "reports failed resume" : "defers to the parent stop"}`, async () => { + const report = await runStop({ mode, preserve: "restart-rollback", retryRollbackPublication: "exhausted", fileOnly: true }); + expect(report.result).toMatchObject({ + closedBeforeYield: true, published: false, bound: false, rollbackBinds: 1, replacementAttempts: 1, + }); + expect(report.result.rollbackExit).toBe(mode === "file-restart-control" ? 1 : undefined); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + test("a finished parent stop preserves the retained sync fence through restart rollback", async () => { const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], finishStopBeforeRollback: true }); expect(report.result).toEqual({ preflight: null, rolledBack: true, bound: true, stopping: true, explicitStop: false, retainedStop: true, @@ -158,6 +169,51 @@ test("a finished parent stop preserves the retained sync fence through restart r expect(report.fileAfter.pi).not.toContain("127.0.0.1"); }, 20_000); +for (const finalRollbackProof of ["pending", "config-held"] as const) { + test(`unchanged Link rollback exhaustion defers exit when ownership is ${finalRollbackProof}`, async () => { + const report = await runStop({ mode: "file-restart-control", preserve: "restart-rollback", fileOnly: true, + retryRollbackPublication: "exhausted", finalRollbackProof }); + expect(report.result).toMatchObject({ closedBeforeYield: true, published: false, bound: false, replacementAttempts: 1 }); + expect(report.result.rollbackExit).toBeUndefined(); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + +for (const contention of ["unchanged", "pending", "stop"] as const) { + test(`rollback port contention ${contention === "unchanged" ? "fails unchanged Link recovery" : `defers exit under concurrent ${contention}`}`, async () => { + const report = await runStop({ + mode: contention === "stop" ? "file-restart-overlap" : "file-restart-control", + preserve: "restart-rollback", + fileOnly: true, + rollbackBindContention: contention, + }); + expect(report.result).toMatchObject({ published: false, rollbackBinds: 0, replacementAttempts: 1 }); + expect(report.result.rollbackExit).toBe(contention === "unchanged" ? 1 : undefined); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + +for (const receipt of ["complete", "pending", "other-owner"] as const) { + test(`a refused recycle after rollback exits only for its own completed disconnect (${receipt})`, async () => { + const report = await runStop({ mode: "file-restart-control", preserve: "restart-rollback", refusedDisconnectRecycle: receipt }); + expect(report.result).toMatchObject({ replacementAttempts: 1, recycleAdmissions: 1, runtimePresent: true }); + expect(report.result.rollbackExit).toBe(receipt === "complete" ? 1 : undefined); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + +for (const [contention, waits, exit] of [ + ["config-release", 1, 1], ["config-held", 2, undefined], + ["config-takeover", 1, undefined], ["config-at-deadline", 2, 1], +] as const) { + test(`a listenerless rollback rechecks completed disconnect ownership after config contention (${contention})`, async () => { + const report = await runStop({ mode: "file-restart-control", preserve: "restart-rollback", refusedDisconnectRecycle: contention }); + expect(report.result).toMatchObject({ replacementAttempts: 1, recycleAdmissions: 1, runtimePresent: true, proofWaits: waits }); + expect(report.result.rollbackExit).toBe(exit); + expect(report.protectedUnchanged).toBe(true); + }, 20_000); +} + test("a pending restart admission cannot leave routing behind on signal shutdown", async () => { const report = await runStop({ mode: "runtime", preserve: "restart" }); expect(report.after).toBe('model = "native"\n'); diff --git a/tests/clients/client-recycle-exclusion.test.ts b/tests/clients/client-recycle-exclusion.test.ts index 34359c711b7..e15385a9546 100644 --- a/tests/clients/client-recycle-exclusion.test.ts +++ b/tests/clients/client-recycle-exclusion.test.ts @@ -1,9 +1,10 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; import { Database } from "bun:sqlite"; -import { writeFileSync } from "node:fs"; +import { mkdirSync, writeFileSync } from "node:fs"; import { getDefaultConfig, saveConfig } from "../../src/config"; import { prepareConfigMutationDatabasePathForWrite } from "../../src/config/mutation-lock"; import { LinkApplyBusyError, withLinkApply } from "../../src/client/link-home"; +import { readDesktopDisconnectReceipt } from "../../src/claude/desktop-remote-store"; import { markClientConnectPending } from "../../src/client/state"; import { runClientRecycleWithAdmission } from "../../src/client/runtime-recycle"; import type { OcxClientConnectionConfig } from "../../src/types"; @@ -62,6 +63,62 @@ for (const state of ["same-connection", "unreadable", "pending-connect", "stop-r } test("a failure after teardown begins is propagated instead of reported as an admission refusal", async () => { - await expect(runClientRecycleWithAdmission(served, () => true, async () => { throw new LinkApplyBusyError(); })) + await expect(runClientRecycleWithAdmission(served, () => true, async () => { throw new LinkApplyBusyError(); }, + { current: () => true, sleep: () => { throw new Error("unexpected retry after teardown"); } })) .rejects.toBeInstanceOf(LinkApplyBusyError); }); + +for (const change of ["none", "new-connection", "new-receipt", "same-receipt", "pending", "stopping", "new-generation", "expired"] as const) { + test("deferred disconnect rechecks authority after apply contention: " + change, async () => { + let release!: () => void; + const held = withLinkApply(() => new Promise(resolve => { release = resolve; })); + let stop = false, current = true, clock = 0, teardowns = 0; + const delays: number[] = []; + const next = { ...served, apiKeyId: "new-client", tokenFingerprint: "d".repeat(64) }; + try { + const result = await runClientRecycleWithAdmission(served, () => !stop, async () => { teardowns++; }, { + current: () => current, now: () => clock, + sleep: async delay => { + delays.push(delay); + release(); await held; + if (change === "new-connection") saveConfig({ ...getDefaultConfig(), runtimeRole: "client", client: next }); + if (change === "new-receipt" || change === "same-receipt") { + const owner = change === "same-receipt" ? served : next; + mkdirSync(home.path("desktop-remote"), { recursive: true, mode: 0o700 }); + writeFileSync(home.path("desktop-remote", "disconnect.json"), JSON.stringify({ + version: 1, owner: { serverUrl: owner.serverUrl, apiKeyId: owner.apiKeyId, connectedAt: owner.connectedAt }, + phase: "complete", tokenFingerprint: owner.tokenFingerprint, keepCatalog: false, + }), { mode: 0o600 }); + expect(readDesktopDisconnectReceipt().kind).toBe("valid"); + } + if (change === "pending") markClientConnectPending(next.tokenFingerprint); + stop = change === "stopping"; + current = change !== "new-generation"; + clock += change === "expired" ? 60_000 : delay; + }, + }); + expect(delays).toEqual([50]); + const canFinish = change === "none" || change === "same-receipt"; + expect(result).toBe(canFinish); + expect(teardowns).toBe(canFinish ? 1 : 0); + } finally { release(); await held; } + }); +} + +test("a scheduled disconnect waits for a busy config transaction without tearing down twice", async () => { + const lock = new Database(prepareConfigMutationDatabasePathForWrite()); + lock.exec("BEGIN IMMEDIATE"); + let teardowns = 0; + const delays: number[] = []; + try { + expect(await runClientRecycleWithAdmission(served, () => true, async () => { teardowns++; }, { + current: () => true, + sleep: async delay => { + delays.push(delay); + if (delays.length === 2) lock.exec("ROLLBACK"); + }, + })).toBe(true); + expect(delays).toEqual([50, 100]); + expect(teardowns).toBe(1); + } finally { lock.close(); } +}); diff --git a/tests/clients/client-restart-rollback-lock.test.ts b/tests/clients/client-restart-rollback-lock.test.ts index 50d1bc7807d..d695952fc8d 100644 --- a/tests/clients/client-restart-rollback-lock.test.ts +++ b/tests/clients/client-restart-rollback-lock.test.ts @@ -22,7 +22,7 @@ test("rollback closes each busy attempt before yielding and keeps one remaining listener = false; return "busy"; }, { budgetMs: 200, now: () => clock, sleep: async ms => { expect(listener).toBe(false); clock += ms; - } })).toBe(true); + } })).toBe("published"); expect(remaining).toEqual([200, 140, 80]); expect(listener).toBe(true); }); @@ -31,7 +31,7 @@ test("rollback contention exhaustion never extends its budget", async () => { let clock = 0, calls = 0; expect(await retryClientRollback(async () => { calls++; clock += 20; return "busy"; }, { budgetMs: 100, now: () => clock, sleep: async ms => { clock += ms; }, - })).toBe(false); + })).toBe("busy"); expect({ clock, calls }).toEqual({ clock: 100, calls: 2 }); }); @@ -39,6 +39,15 @@ test("a changed owner or non-contention refusal stops rollback retries immediate let clock = 0, calls = 0; expect(await retryClientRollback(async () => ++calls === 1 ? "busy" : "refused", { now: () => clock, sleep: async ms => { clock += ms; }, - })).toBe(false); + })).toBe("refused"); expect(calls).toBe(2); }); + +test("publication and the subsequent ownership probe share one rollback deadline", async () => { + let clock = 0; + const io = { deadline: 70, now: () => clock, sleep: async (ms: number) => { clock += ms; } }; + expect(await retryClientRollback(() => clock === 0 ? "busy" : "refused", io)).toBe("refused"); + let probes = 0; + expect(await retryClientRollback(() => { probes++; return "busy"; }, io)).toBe("busy"); + expect({ clock, probes }).toEqual({ clock: 70, probes: 1 }); +}); diff --git a/tests/clients/client-runtime-restart.test.ts b/tests/clients/client-runtime-restart.test.ts index 8d7f3fd1690..d51b368f1fe 100644 --- a/tests/clients/client-runtime-restart.test.ts +++ b/tests/clients/client-runtime-restart.test.ts @@ -243,7 +243,7 @@ describe("client restart controller", () => { await controller.settled(); expect(calls).toEqual([ `stop:${CLIENT_RESTART_DRAIN_MS}`, - "warn:[client] restart: the replacement did not start (not_ready); this runtime keeps serving", + "warn:[client] restart: the replacement did not start (not_ready); attempting recovery", "resume", ]); // The latch is released: a later restart is accepted afresh. diff --git a/tests/fixtures/client-link-stop-runner.ts b/tests/fixtures/client-link-stop-runner.ts index 0f55b317e81..c02985250b8 100644 --- a/tests/fixtures/client-link-stop-runner.ts +++ b/tests/fixtures/client-link-stop-runner.ts @@ -37,6 +37,7 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { missingStopRecord?: "absent" | "invalid"; startIdentityChanges?: "request" | "escalation"; failedRollback?: "before-rebind" | "during-rebind"; + refusedDisconnectRecycle?: "complete" | "pending" | "other-owner" | "config-release" | "config-held" | "config-takeover" | "config-at-deadline"; legacyOwnerRecord?: boolean; stopConnectionDrift?: "invalid" | "mismatched" | "disconnected" | "other-link" | "hub"; driftDuringFallback?: boolean; @@ -47,7 +48,9 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { danglingServiceRecord?: boolean; busyStopFence?: boolean; busyRollbackPublication?: boolean; - retryRollbackPublication?: "lifecycle" | "config" | "owner-changed"; + retryRollbackPublication?: "lifecycle" | "config" | "owner-changed" | "exhausted"; + rollbackBindContention?: "unchanged" | "pending" | "stop"; + finalRollbackProof?: "pending" | "config-held"; terminationPlatform?: "linux" | "darwin"; siblingEscalation?: "stopping" | "different-generation"; removeToken?: boolean; @@ -344,25 +347,99 @@ if (options.mode === "retry") { let observeRollback!: (closed: boolean) => void; const rollbackTurn = new Promise(resolve => { observeRollback = resolve; }); let restartSettled: (() => Promise) | undefined; + let rollbackExit: number | undefined; const replaceSavedConnection = () => { config.client!.connectedAt = "2026-11-17T00:00:00.000Z"; saveConfig(config); protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); }; - if (options.failedRollback || options.retryRollbackPublication) { + let recycleAdmissions = 0; + let proofWaits = 0, proofLock: Database | undefined; + const contendProof = options.refusedDisconnectRecycle?.startsWith("config-"); + if (options.refusedDisconnectRecycle) { + const apply = await import("../../src/client/link-home"); + const withApply = apply.withLinkApply; + mock.module("../../src/client/link-home", () => ({ ...apply, withLinkApply: (work: () => Promise, lockPath?: string) => { + if (!replacementAttempts) return withApply(work, lockPath); + recycleAdmissions++; + if (contendProof) { + proofLock = new Database(prepareConfigMutationDatabasePathForWrite()); + proofLock.exec("BEGIN IMMEDIATE"); + return withApply(work, lockPath); + } + throw new apply.LinkApplyBusyError(); + } })); + } + if (options.failedRollback || options.retryRollbackPublication || options.rollbackBindContention || options.refusedDisconnectRecycle) { const controller = await import("../../src/client/runtime-restart"); const create = controller.createClientRestartController; mock.module("../../src/client/runtime-restart", () => ({ ...controller, createClientRestartController: (...args: Parameters) => { - const result = create(...args); + const result = options.retryRollbackPublication === "exhausted" || options.rollbackBindContention || options.refusedDisconnectRecycle + ? create({ ...args[0], exitProcess: code => { rollbackExit = code; } }) + : create(...args); restartSettled = result.settled; return result; } })); } + let portHolder: ReturnType | undefined; + if (options.rollbackBindContention) { + const rollback = await import("../../src/client/runtime-rollback"); + const retry = rollback.retryClientRollback; + mock.module("../../src/client/runtime-rollback", () => ({ ...rollback, + retryClientRollback: (attempt: Parameters[0]) => retry(attempt, { deadline: performance.now() + 250 }), + })); + } + if (options.retryRollbackPublication === "exhausted" || contendProof) { + if (!contendProof) lock(() => {}, lifecycleLockDeps); + const rollback = await import("../../src/client/runtime-rollback"); + const retry = rollback.retryClientRollback; + let now = 0; + mock.module("../../src/client/runtime-rollback", () => ({ ...rollback, + retryClientRollback: (attempt: Parameters[0]) => retry(attempt, { + now: () => now, deadline: contendProof ? 100 : 50, sleep: async ms => { + now += ms; + if (options.finalRollbackProof) { + await rollbackTurn; + if (options.finalRollbackProof === "pending") { + const { markClientConnectPending } = await import("../../src/client/state"); + lock(() => markClientConnectPending("a".repeat(64)), lifecycleLockDeps); + } else { + proofLock = new Database(prepareConfigMutationDatabasePathForWrite()); + proofLock.exec("BEGIN IMMEDIATE"); + } + } + if (!contendProof) return; + proofWaits++; + if (options.refusedDisconnectRecycle === "config-held" || (options.refusedDisconnectRecycle === "config-at-deadline" && now < 100)) return; + proofLock!.close(); proofLock = undefined; + if (options.refusedDisconnectRecycle === "config-takeover") (await import("../../src/client/state")).markClientConnectPending(expected.tokenFingerprint); + }, + }), + })); + } if (options.preserve?.startsWith("restart-rollback")) { const replacement = await import("../../src/server/restart-replacement"); mock.module("../../src/server/restart-replacement", () => ({ ...replacement, spawnReplacementStart: async () => { replacementAttempts++; + if (options.refusedDisconnectRecycle && replacementAttempts === 1) { + saveConfig({ ...config, runtimeRole: "standalone", client: undefined }); + const owner = { serverUrl: expected.serverUrl, apiKeyId: expected.apiKeyId, + connectedAt: options.refusedDisconnectRecycle === "other-owner" ? "2026-11-17T00:00:00.000Z" : expected.connectedAt }; + mkdirSync(join(home, "desktop-remote"), { recursive: true, mode: 0o700 }); + writeFileSync(join(home, "desktop-remote", "disconnect.json"), JSON.stringify({ + version: 1, owner, tokenFingerprint: expected.tokenFingerprint, keepCatalog: false, phase: "complete", + }), { mode: 0o600 }); + if (options.refusedDisconnectRecycle === "pending") (await import("../../src/client/state")).markClientConnectPending(expected.tokenFingerprint); + protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); + } + if (options.rollbackBindContention && replacementAttempts === 1) { + portHolder = Bun.serve({ hostname: "127.0.0.1", port: config.port, fetch: () => new Response("occupied") }); + if (options.rollbackBindContention === "pending") { + const { markClientConnectPending } = await import("../../src/client/state"); + lock(() => markClientConnectPending("a".repeat(64)), lifecycleLockDeps); + } + } if (options.failedRollback === "before-rebind") replaceSavedConnection(); if (replacementAttempts === 1) throw Object.assign(new Error("fixture replacement refused"), { code: "not_ready" }); }, @@ -382,7 +459,7 @@ if (options.mode === "retry") { ? { ...deps, restart: { ...deps.restart, linkStopFence: undefined } } : deps); if ((options.busyRollbackPublication || options.retryRollbackPublication) && replacementAttempts === 1 && !publicationHeld) { publicationHeld = true; - const lock = new Database(options.retryRollbackPublication === "lifecycle" + const lock = new Database(options.retryRollbackPublication === "lifecycle" || options.retryRollbackPublication === "exhausted" ? lifecycleLockDeps.lockPath : prepareConfigMutationDatabasePathForWrite()); lock.exec("BEGIN IMMEDIATE"); const stop = server.stop.bind(server); @@ -427,16 +504,28 @@ if (options.mode === "retry") { if (options.retryRollbackPublication) { const closedBeforeYield = await rollbackTurn; await restartSettled!(); + proofLock?.close(); const after = readRuntimePort(process.pid)!; const published = after.servingGeneration !== before.servingGeneration; const bound = published && (await fetch(`http://127.0.0.1:${config.port}/healthz`)).ok; report({ preflight, closedBeforeYield, published, bound, rollbackBinds, replacementAttempts, - stopping: after.clientStopping, explicitStop: after.clientStopRequested }); + stopping: after.clientStopping, explicitStop: after.clientStopRequested, rollbackExit }); + process.exit(0); + } + if (options.rollbackBindContention) { + await restartSettled!(); + await portHolder?.stop(true); + const after = readRuntimePort(process.pid); + report({ preflight, published: after !== null && after.servingGeneration !== before.servingGeneration, + rollbackBinds, replacementAttempts, rollbackExit, + stopping: after?.clientStopping, explicitStop: after?.clientStopRequested }); process.exit(0); } - if (options.failedRollback) { + if (options.failedRollback || options.refusedDisconnectRecycle) { await restartSettled!(); + proofLock?.close(); report({ preflight, replacementAttempts, runtimePresent: readRuntimePort(process.pid) !== null, + ...(options.refusedDisconnectRecycle ? { rollbackExit, recycleAdmissions, proofWaits } : {}), explicitStop: readRuntimePort(process.pid)?.clientStopRequested }); process.exit(0); } diff --git a/tests/helpers/client-link-stop.ts b/tests/helpers/client-link-stop.ts index bc4084fe100..8167c3ef914 100644 --- a/tests/helpers/client-link-stop.ts +++ b/tests/helpers/client-link-stop.ts @@ -76,7 +76,14 @@ export async function runStop(options: Record) { expect(stderr).toContain("Link Child Codex routing restore refused"); } else if (String(options.preserve).startsWith("restart-rollback")) { expect(exit, stdout).toBe(0); - expect(stderr.trim()).toBe("[client] restart: the replacement did not start (not_ready); this runtime keeps serving"); + const first = "[client] restart: the replacement did not start (not_ready); attempting recovery"; + const code = ["complete", "config-release", "config-at-deadline"].includes(String(options.refusedDisconnectRecycle)) ? "client_recycle_unpublished" + : ((options.retryRollbackPublication === "exhausted" && options.mode === "file-restart-control" && !options.finalRollbackProof) + || options.rollbackBindContention === "unchanged") ? "client_rollback_unpublished" : undefined; + const extra = code ? `\n[client] restart: this runtime could not serve again (${code}); run 'ocx start'` + : options.finalRollbackProof === "config-held" ? "\n[client] restart: could not verify ownership of the unpublished Link listener; check ocx status" + : options.refusedDisconnectRecycle === "config-held" ? "\n[client] restart: could not verify disconnect ownership before the recovery deadline; check ocx status" : ""; + expect(stderr.trim()).toBe(first + extra); } else expect({ exit, stderr }, stdout).toEqual({ exit: 0, stderr: "" }); const report = JSON.parse(readFileSync(join(home, "result.json"), "utf8")); const atExit = JSON.parse(readFileSync(join(home, "exit.json"), "utf8")); From ef63ed0c30aca8427c7be6c138f5ef6e1dedd92c Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:08:40 +0900 Subject: [PATCH 17/64] fix(clients): surface Codex Desktop env_key shim-bypass caveat for Hub-connected clients (#9180) * fix(clients): surface Codex Desktop env_key shim-bypass caveat for Hub-connected clients * fix(doctor): always surface GUI env_key caveat and check PATH shadowing for legacy shim --- .../docs/es/reference/cli/lifecycle.md | 2 +- .../content/docs/reference/cli/lifecycle.md | 10 +++- src/cli/codex-shim-readiness.ts | 19 +++++++ src/cli/connect.ts | 10 ++++ src/cli/doctor.ts | 55 ++++++++++++++++++- structure/runtime.md | 2 +- tests/cli/cli-connect-readiness.test.ts | 54 +++++++++++++++++- .../doctor-codex-envkey-readiness.test.ts | 48 +++++++++++++++- 8 files changed, 193 insertions(+), 7 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 1287d547a3d..cb81010ce41 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -707,7 +707,7 @@ Uso `ocx service` para un proxy de fondo siempre activo (recomendado). Uso `ocx En un enlace que no es de loopback, el proveedor inyectado lleva `env_key = "OPENCODEX_API_AUTH_TOKEN"`. Esa línea indica a Codex qué variable leer; no la crea. Codex se niega a iniciar una solicitud cuando falta la variable (`Missing environment variable: OPENCODEX_API_AUTH_TOKEN`), y el proxy nunca se alcanza. El valor vive en `$OPENCODEX_HOME/service-api-token`; el proceso de lanzamiento debe suministrarlo en el entorno de Codex. -Utilice la shim mantenida instalada por `ocx codex-shim install`. Cuando el contexto de lanzamiento resuelve esta shim, lee el archivo de token creado por OpenCodex y suministra la variable a Codex. Los lanzamientos de escritorio, cron y servicio deben usar una ruta PATH o un trazado de lanzamiento que seleccione la shim; la instalación no configura esos entornos automáticamente. Los propios procesos hijo de Codex aún pueden heredar el token. +Utilice la shim mantenida instalada por `ocx codex-shim install`. Cuando el contexto de lanzamiento resuelve esta shim, lee el archivo de token creado por OpenCodex y suministra la variable a Codex. Los lanzamientos de escritorio, cron y servicio deben usar una ruta PATH o un trazado de lanzamiento que seleccione la shim; la instalación no configura esos entornos automáticamente. Codex Desktop y otros lanzadores gráficos que ejecutan su propio binario `codex` directamente omiten una shim CLI saludable y fallan con `Missing environment variable: OPENCODEX_API_AUTH_TOKEN` en modo Hub salvo que el entorno de la aplicación reciba la variable desde `$OPENCODEX_HOME/service-api-token` o la máquina se conecte mediante [Remote Link](/es/guides/remote-link/) (cuyo relé loopback local adjunta la clave sin `env_key`; `--desktop-authless` es inerte en un cliente conectado). `ocx connect`, `ocx connect status` y `ocx doctor` informan de esta limitación sin imprimir ningún token. Los propios procesos hijo de Codex aún pueden heredar el token. No exporte este token portador desde un archivo de inicio de shell ni lo copie en `config.toml`. El archivo `service-api-token` contiene el token sin procesar, no las asignaciones `NAME=value`, por lo que no se puede usar directamente como un systemd `EnvironmentFile=`. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 1bd71b3bf76..bd49dee32cf 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -1331,8 +1331,14 @@ must supply it in Codex's environment. Use the maintained shim installed by `ocx codex-shim install`. When the launching context resolves this shim, it reads the token file created by OpenCodex and supplies the variable to Codex. Desktop, cron, and service launches must use a PATH or launcher path that selects the shim; -installation does not configure those environments automatically. Codex's own child processes -may still inherit the token. +installation does not configure those environments automatically. Codex Desktop and other GUI +launchers that spawn their own `codex` binary directly bypass a healthy CLI shim and will fail with +`Missing environment variable: OPENCODEX_API_AUTH_TOKEN` in Hub mode unless that app's environment +receives the variable from `$OPENCODEX_HOME/service-api-token` or the machine connects via +[Remote Link](/guides/remote-link/) (whose local loopback relay attaches the link key with no +`env_key`; `--desktop-authless` is inert on a connected client). `ocx connect`, `ocx connect status`, +and `ocx doctor` surface this GUI shim-bypass caveat without printing any token material. Codex's +own child processes may still inherit the token. Do not export this bearer token from a shell startup file or copy it into `config.toml`. The `service-api-token` file contains the raw token, not `NAME=value` assignments, so it cannot be used diff --git a/src/cli/codex-shim-readiness.ts b/src/cli/codex-shim-readiness.ts index e1b25a6e96a..641ad830883 100644 --- a/src/cli/codex-shim-readiness.ts +++ b/src/cli/codex-shim-readiness.ts @@ -7,6 +7,7 @@ import { diagnoseCodexShim, type CodexShimDiagnostic } from "../codex/shim"; import { overlayActivationHint } from "../codex/shim-overlay"; import { findFirstCodexOnPath, type CodexPathCandidate } from "../codex/shim-path-resolution"; import { loadConfig, resolveEnvValue } from "../config"; +import type { OcxConnectedClientId } from "../types"; const PROXY_ENV_KEYS = [ "HTTP_PROXY", @@ -42,6 +43,24 @@ const CODEX_TOKEN_NOTE = "The connected Codex config uses OPENCODEX_API_AUTH_TOK + '"Missing environment variable".'; const CODEX_TOKEN_ACTION = `${CODEX_TOKEN_NOTE} Run 'ocx codex-shim install' to repair it.`; +export const HUB_CODEX_DESKTOP_NOTE = + 'Codex Desktop / GUI apps: direct launches bypass the CLI shim, so Hub-mode Codex (env_key = "OPENCODEX_API_AUTH_TOKEN") ' + + 'fails with "Missing environment variable: OPENCODEX_API_AUTH_TOKEN" unless launched with that variable in its environment ' + + '(from service-api-token) or connected via Remote Link (local loopback relay, no env var; --desktop-authless is inert on a connected client).'; + +/** + * Secret-free caveat for Hub-connected Codex clients (#9171): the CLI shim covers PATH-resolved + * CLI launches only, while Codex Desktop spawns its own binary directly. Remote Link runs a + * local loopback relay with no env_key, so it does not emit this Hub-mode caveat. + */ +export function hubCodexDesktopReadinessLine( + selectedClients: readonly OcxConnectedClientId[] | undefined, + transport: "hub" | "link" | undefined = "hub", +): string | null { + if (transport === "link" || !selectedClients?.includes("codex")) return null; + return HUB_CODEX_DESKTOP_NOTE; +} + export function codexConnectShimReadiness(inputs: { diagnosis: Pick; commandPath: string | null; diff --git a/src/cli/connect.ts b/src/cli/connect.ts index da6f44aa9f3..bb6645abb73 100644 --- a/src/cli/connect.ts +++ b/src/cli/connect.ts @@ -48,10 +48,13 @@ import { type RuntimeApiDeps, } from "./runtime-api"; import { + hubCodexDesktopReadinessLine, inspectCodexShimForConnect, type CodexConnectShimReadiness, } from "./codex-shim-readiness"; +export { hubCodexDesktopReadinessLine } from "./codex-shim-readiness"; + export interface ClientCommandDeps extends RuntimeApiDeps { lifecycleLockDeps?: ClientLifecycleLockDeps; catalogProbeDeps?: ClientCatalogProbeDeps; @@ -431,6 +434,9 @@ export function clientConnectionStatusLines(status: ClientConnectionStatus): str ? " (run 'ocx connect rotate' with a fresh pairing code)" : ""}`] : []), `Catalog: ${status.catalog}${status.catalogAgeSeconds !== undefined ? ` (${status.catalogAgeSeconds}s old)` : ""}`, + ...(hubCodexDesktopReadinessLine(status.selectedClients, status.transport) + ? [hubCodexDesktopReadinessLine(status.selectedClients, status.transport)!] + : []), ]; } @@ -509,6 +515,8 @@ async function runHubConnect(argv: string[], deps: ClientCommandDeps): Promise { const serviceTokenPresent = Boolean(readInstalledServiceToken()?.trim()); const codexShim = diagnoseCodexShim(); const codexShimLines = formatCodexShimDoctorLines(codexShim); + const legacyPathCommand = codexShim.healthy && codexShim.runnable === undefined + ? (() => { try { return findFirstCodexOnPath(); } catch { return null; } })() + : undefined; const codexEnvKeyReadiness = collectCodexEnvKeyReadiness( codexConfigText, process.env, codexShim, serviceTokenPresent, codexShimLines.length > 0, + legacyPathCommand, + ); + const codexDesktopEnvKeyNotice = collectCodexDesktopEnvKeyNotice( + codexConfigText, + doctorConfig.runtimeRole === "client", ); // Use the same attested live startup verdict as `ocx status` when the proxy is already // identity-verified. A shell-local systemd probe can be a false negative for a system-wide @@ -1601,6 +1650,10 @@ export async function runDoctor(args: string[] = []): Promise { } else { console.log(" ok no broken OpenCodex env_key launch path detected"); } + if (codexDesktopEnvKeyNotice) { + console.log(` note ${codexDesktopEnvKeyNotice.detail}`); + console.log(` Action: ${codexDesktopEnvKeyNotice.action}`); + } console.log("\nRunning proxy process proxy env (presence only)"); if (runningProxyEnv.status === "not_running") { diff --git a/structure/runtime.md b/structure/runtime.md index de83bcfbac0..77179eb66f4 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -345,7 +345,7 @@ The server exposes read-only authenticated `GET /api/stop` with `schema: "ocx-st Windows client/Desktop lifecycle acquisition retains its stable per-user lock namespace and verifies an already-private runtime-directory ACL before repeating inheritable mutations across retained lock files. Failed verification still requires hardening before the callback can run; the database file is hardened independently. The scoped directory-owner policy and identity/deadline checks are documented in [Background Service And Sidecars](ops/service-and-sidecars.md). `src/cli/connect.ts` resolves only through the first valid local Codex runtime for catalog readiness, then reads that runtime's effort ladder without persisting its selection. Rejected preferred candidates still fall back in priority order. General `ocx status` retains full runtime -discovery and passes its resolved command into readiness, avoiding a second version probe without adding cache state. `ocx connect` also prints a secret-free Codex shim readiness line from `src/cli/codex-shim-readiness.ts`: ready when the healthy shim is active on PATH, unhealthy when wrapper/native validation fails, missing/not active with the source command for a runnable inactive overlay, or unverified when the PATH scan throws. `ocx status`, `ocx codex-shim status`, and `ocx doctor` skip shim auto-repair; doctor retains unset-token warnings and recommends activation for inactive overlays rather than reinstalling them. +discovery and passes its resolved command into readiness, avoiding a second version probe without adding cache state. `ocx connect` also prints a secret-free Codex shim readiness line from `src/cli/codex-shim-readiness.ts`: ready when the healthy shim is active on PATH, unhealthy when wrapper/native validation fails, missing/not active with the source command for a runnable inactive overlay, or unverified when the PATH scan throws. For Hub-mode connections (`transport !== "link"`) that select Codex, `ocx connect` and `ocx connect status` additionally print a secret-free Codex Desktop / GUI caveat noting that direct-binary GUI launches bypass the CLI shim, require `OPENCODEX_API_AUTH_TOKEN` in the app environment unless using Remote Link's loopback relay, and that `--desktop-authless` is inert on a connected client; Remote Link and Claude-only connections omit that caveat. `ocx status`, `ocx codex-shim status`, and `ocx doctor` skip shim auto-repair; doctor retains unset-token warnings (including when a healthy legacy in-place shim is shadowed by another executable first on PATH), recommends activation for inactive overlays rather than reinstalling them, and prints a secret-free conditional GUI shim-bypass notice whenever `config.toml` selects `model_provider = "opencodex"` with `env_key` — even if that variable is set in the doctor shell process, because independently launched GUI apps do not inherit it. `ocx config [show]`, including flags-only display, stays outside that lifecycle path. Argument selection follows the [config reader contract](config.md). `src/cli/config-command.ts` reads the validated config snapshot and the bounded service-token observation needed for its `_remoteHub` annotation; diff --git a/tests/cli/cli-connect-readiness.test.ts b/tests/cli/cli-connect-readiness.test.ts index c4833ff7bf7..75b1af8999a 100644 --- a/tests/cli/cli-connect-readiness.test.ts +++ b/tests/cli/cli-connect-readiness.test.ts @@ -20,7 +20,12 @@ import { COLD_SPAWN_WARMUP_HOOK_BUDGET_MS, warmColdSpawn } from "../helpers/cold import { removeTreeWithRetry } from "../helpers/remove-tree"; import { repoRoot } from "../helpers/repo-root"; import { INTERNAL_DEADLINE_MS, SPAWN_BUDGET_MS } from "../helpers/test-budget"; -import { codexShimReadinessLine, connectCompletionReport } from "../../src/cli/connect"; +import { + clientConnectionStatusLines, + codexShimReadinessLine, + connectCompletionReport, + hubCodexDesktopReadinessLine, +} from "../../src/cli/connect"; import { codexConnectShimReadiness, inspectCodexShimForConnect } from "../../src/cli/codex-shim-readiness"; import { findFirstCodexOnPath } from "../../src/codex/shim-path-resolution"; import { dispatchCommand } from "../../src/cli/dispatch"; @@ -429,6 +434,8 @@ describe("#4207 connected-client readiness", () => { expect(probe.status.readiness).toBe("ready"); expect(probe.status.readinessReason).toBeUndefined(); expect(probe.lines[1]).toBe("Local Codex CLI: ready"); + expect(probe.lines.at(-1)).toContain("Codex Desktop / GUI apps:"); + expect(probe.lines.at(-1)).toContain("Missing environment variable: OPENCODEX_API_AUTH_TOKEN"); }); test("an unobservable runtime is unverified, never incompatible", () => { @@ -760,6 +767,51 @@ describe("Codex shim readiness on connect", () => { }); expect(line).toBeNull(); }); + + test("Hub-mode connect and status surface the Codex Desktop env_key caveat (#9171)", () => { + const hubLine = hubCodexDesktopReadinessLine(["codex"], "hub"); + expect(hubLine).not.toBeNull(); + expect(hubLine).toContain("Codex Desktop"); + expect(hubLine).toContain("OPENCODEX_API_AUTH_TOKEN"); + expect(hubLine).toContain("Missing environment variable: OPENCODEX_API_AUTH_TOKEN"); + expect(hubLine).toContain("Remote Link"); + expect(hubLine).toContain("--desktop-authless"); + expect(hubLine).not.toContain("ocx_data_"); + + // Default/legacy hub connections (omitted transport) also carry the notice. + expect(hubCodexDesktopReadinessLine(["codex"], undefined)).toBe(hubLine); + // Remote Link runs a local loopback relay without env_key, and Claude-only does not touch Codex. + expect(hubCodexDesktopReadinessLine(["codex"], "link")).toBeNull(); + expect(hubCodexDesktopReadinessLine(["claude"], "hub")).toBeNull(); + + const baseStatus = { + state: "connected" as const, + serverUrl: "https://hub.example.test", + managementUrl: "https://hub.example.test", + managementTransport: "direct" as const, + protocolVersion: 1, + apiKeyId: "client-key-1", + selectedClients: ["codex"] as ("codex" | "claude")[], + catalog: "present" as const, + token: "owned" as const, + rotation: "clean" as const, + readiness: "ready" as const, + }; + const hubLines = clientConnectionStatusLines({ ...baseStatus, transport: "hub" }); + expect(hubLines[0]).toBe("Connection: connected"); + expect(hubLines[1]).toBe("Local Codex CLI: ready"); + expect(hubLines.at(-1)).toBe(hubLine); + + const linkLines = clientConnectionStatusLines({ ...baseStatus, transport: "link" }); + expect(linkLines.join("\n")).not.toContain("Codex Desktop / GUI apps"); + + const claudeOnlyLines = clientConnectionStatusLines({ + ...baseStatus, + transport: "hub", + selectedClients: ["claude"], + }); + expect(claudeOnlyLines.join("\n")).not.toContain("Codex Desktop / GUI apps"); + }); }); /** diff --git a/tests/service/doctor-codex-envkey-readiness.test.ts b/tests/service/doctor-codex-envkey-readiness.test.ts index 3bf11db4dc2..8a7543def56 100644 --- a/tests/service/doctor-codex-envkey-readiness.test.ts +++ b/tests/service/doctor-codex-envkey-readiness.test.ts @@ -1,6 +1,10 @@ import { isolateCodexShimEnvironment, withInstalledShim } from "../helpers/codex-shim-install-fixture"; import { describe, expect, test } from "bun:test"; -import { collectCodexEnvKeyReadiness, formatCodexShimDoctorLines } from "../../src/cli/doctor"; +import { + collectCodexDesktopEnvKeyNotice, + collectCodexEnvKeyReadiness, + formatCodexShimDoctorLines, +} from "../../src/cli/doctor"; import { diagnoseCodexShim, type CodexShimDiagnostic } from "../../src/codex/shim"; import { join } from "node:path"; @@ -81,6 +85,48 @@ describe("doctor Codex env_key launch readiness", () => { const row = collectCodexEnvKeyReadiness(config, {}, missingShim, Boolean(token)); expect(JSON.stringify(row)).not.toContain(token); }); + + test("notes Codex Desktop / GUI shim bypass whenever config.toml requires env_key, even if set in the doctor shell (#9171)", () => { + // Doctor's own shell environment cannot establish what an independently launched GUI app sees. + expect(collectCodexEnvKeyReadiness(config, { OPENCODEX_API_AUTH_TOKEN: "secret" }, healthyShim, true)).toBeNull(); + const clientNotice = collectCodexDesktopEnvKeyNotice(config, true); + expect(clientNotice).not.toBeNull(); + expect(clientNotice?.envName).toBe("OPENCODEX_API_AUTH_TOKEN"); + expect(clientNotice?.detail).toContain("Codex Desktop"); + expect(clientNotice?.detail).toContain("bypass"); + expect(clientNotice?.detail).toContain("do not inherit a shell-only OPENCODEX_API_AUTH_TOKEN"); + expect(clientNotice?.detail).toContain("Missing environment variable: OPENCODEX_API_AUTH_TOKEN"); + expect(clientNotice?.action).toContain("Remote Link"); + expect(clientNotice?.action).toContain("--desktop-authless"); + expect(JSON.stringify(clientNotice)).not.toContain("ocx_data_"); + + const nonClientNotice = collectCodexDesktopEnvKeyNotice(config, false); + expect(nonClientNotice?.action).toContain("loopback"); + expect(nonClientNotice?.action).not.toContain("--desktop-authless"); + + // Stays silent when Codex uses loopback without env_key (including Remote Link Child), + // another active provider, or no config. + expect(collectCodexDesktopEnvKeyNotice('openai_base_url = "http://127.0.0.1:10100/v1"\n', true)).toBeNull(); + expect(collectCodexDesktopEnvKeyNotice(config.replace('model_provider = "opencodex"', 'model_provider = "openai"'), true)).toBeNull(); + expect(collectCodexDesktopEnvKeyNotice(null, true)).toBeNull(); + }); + + test("warns when a healthy legacy in-place shim is shadowed by another executable first on PATH (#9171)", () => { + const shadowed = collectCodexEnvKeyReadiness(config, {}, healthyShim, true, false, { + path: "/usr/local/bin/codex", + isShim: false, + }); + expect(shadowed?.shimState).toBe("inactive"); + expect(shadowed?.detail).toContain("/usr/local/bin/codex"); + expect(shadowed?.detail).toContain("OPENCODEX_API_AUTH_TOKEN"); + expect(shadowed?.action).toContain("ahead of /usr/local/bin/codex on PATH"); + + const activeLegacy = collectCodexEnvKeyReadiness(config, {}, healthyShim, true, false, { + path: "/opt/homebrew/bin/codex", + isShim: true, + }); + expect(activeLegacy).toBeNull(); + }); }); describe.skipIf(process.platform === "win32")("doctor general Codex shim guidance", () => { From 83854558ddd96c3825d409351644abb2d4e66e8b Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:49:21 +0900 Subject: [PATCH 18/64] fix(desktop): collapse macOS native tray popover on toggle click (#9183) * fix(desktop): collapse macOS native tray popover on toggle click Previously, clicking the macOS status bar icon while the usage panel was open caused the panel to dismiss on mouseDown (via the outside-click monitor or focus loss) and immediately reopen on mouseUp when Tauri's tray click handler called toggle. 1. Add NativeTrayHitTest to ignore clicks on the status bar button in NativeTrayPanel's outside-click monitor. 2. Record dismissal timestamp and proximity to the status button. 3. Introduce NativeTrayTogglePolicy in Popover to treat mouseUp calls arriving within the dismissal grace period near the button as the closing half of a toggle rather than a new present request. 4. Add unit test coverage in NativeTrayTests. * fix(desktop): scope tray popover toggle suppression to button mouse-down * fix(desktop): scope tray popover toggle suppression to left-button clicks * fix(desktop): forget a tray button press on unrelated dismissal The status-button press recorded by the outside-click monitor survived an outside click, a right click, or Escape that dismissed the panel, so a quick later click on the icon could be swallowed as the closing half of a toggle. Keep the press in a small NativeTrayButtonPress value: the monitor records it, every other dismissal and each presentation clear it, and the toggle that follows consumes it. NativeTrayTests now drive the press through the same event sequences the panel sees. Co-authored-by: Yuxin Qiao <104957188+Yuxin-Qiao@users.noreply.github.com> * fix(desktop): hit-test the tray press where it happened The outside-click monitor classified a press on the status button by the live pointer position. Global-monitor events arrive after the fact, so a press on the icon followed by a quick move could be read as an outside click, dismissing the panel only for the mouse-up toggle to reopen it. Hit-test the event's own location instead. A windowless event, which is what a global monitor delivers, already reports locationInWindow in screen coordinates; an event with a window is converted through it. --------- Co-authored-by: Yuxin Qiao <104957188+Yuxin-Qiao@users.noreply.github.com> --- app/Sources/NativeTray/Panel.swift | 41 ++++++++++++- app/Sources/NativeTray/Popover.swift | 67 ++++++++++++++++++++- app/Sources/NativeTrayTests/main.swift | 82 ++++++++++++++++++++++++++ 3 files changed, 186 insertions(+), 4 deletions(-) diff --git a/app/Sources/NativeTray/Panel.swift b/app/Sources/NativeTray/Panel.swift index c53a368aef4..ed14a80b0bd 100644 --- a/app/Sources/NativeTray/Panel.swift +++ b/app/Sources/NativeTray/Panel.swift @@ -1,12 +1,30 @@ import AppKit +public enum NativeTrayHitTest { + public static func isNearButton(buttonFrame: NSRect, point: NSPoint, tolerance: CGFloat = 4) -> Bool { + buttonFrame.insetBy(dx: -tolerance, dy: -tolerance).contains(point) + } + + /// Where a mouse event happened, in screen coordinates. Global-monitor events arrive after the + /// fact, so the live pointer (`NSEvent.mouseLocation`) may already have left the icon; the event + /// keeps its own position. A windowless event, which is what a global monitor delivers, already + /// reports `locationInWindow` in screen coordinates. + @MainActor + public static func screenLocation(of event: NSEvent) -> NSPoint { + guard let window = event.window else { return event.locationInWindow } + return window.convertPoint(toScreen: event.locationInWindow) + } +} + /// Adapted from the native companion's PopoverPanel in commit 38a5ab9fc4. /// A key-capable panel avoids the accessory NSPopover keyboard failure measured /// there on macOS 27, while leaving application/runtime ownership with Tauri. @MainActor final class NativeTrayPanel: NSPanel { var onDismiss: (() -> Void)? + var buttonPress = NativeTrayButtonPress() private var outsideMonitor: Any? + private weak var statusButton: NSStatusBarButton? init() { super.init(contentRect: NSRect(x: 0, y: 0, width: 420, height: 660), @@ -28,6 +46,8 @@ final class NativeTrayPanel: NSPanel { override var canBecomeMain: Bool { false } func present(from button: NSStatusBarButton) { + buttonPress.clear() + statusButton = button guard let buttonWindow = button.window else { return } let visible = (buttonWindow.screen ?? NSScreen.main)?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1024, height: 768) @@ -40,8 +60,19 @@ final class NativeTrayPanel: NSPanel { y: max(visible.minY + 8, anchor.minY - size.height - 6))) makeKeyAndOrderFront(nil) if outsideMonitor == nil { - outsideMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] _ in - self?.dismiss() + outsideMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.leftMouseDown, .rightMouseDown]) { [weak self] event in + guard let self else { return } + if event.type == .leftMouseDown, let button = self.statusButton, let buttonWindow = button.window { + let mouse = NativeTrayHitTest.screenLocation(of: event) + let buttonFrame = buttonWindow.convertToScreen(button.convert(button.bounds, to: nil)) + if NativeTrayHitTest.isNearButton(buttonFrame: buttonFrame, point: mouse) { + self.buttonPress.record() + return + } + } + // An outside or right click is not the status button's toggle. + self.buttonPress.clear() + self.dismiss() } } } @@ -50,11 +81,15 @@ final class NativeTrayPanel: NSPanel { guard isVisible else { return } if let outsideMonitor { NSEvent.removeMonitor(outsideMonitor) } outsideMonitor = nil + statusButton = nil orderOut(nil) onDismiss?() } - override func cancelOperation(_ sender: Any?) { dismiss() } + override func cancelOperation(_ sender: Any?) { + buttonPress.clear() + dismiss() + } override func resignKey() { super.resignKey() dismiss() diff --git a/app/Sources/NativeTray/Popover.swift b/app/Sources/NativeTray/Popover.swift index cc33e87d55d..923655b7272 100644 --- a/app/Sources/NativeTray/Popover.swift +++ b/app/Sources/NativeTray/Popover.swift @@ -1,6 +1,61 @@ import AppKit import SwiftUI +public enum NativeTrayToggleAction: Equatable { + case dismiss + case ignoreRecentDismissal + case present +} + +public enum NativeTrayTogglePolicy { + public static let dismissGrace: TimeInterval = 0.35 + + public static func evaluate( + toggle: Bool, + isVisible: Bool, + unconsumedButtonMouseDown: Bool, + lastDismissedAt: Date?, + now: Date = Date() + ) -> NativeTrayToggleAction { + if toggle && isVisible { + return .dismiss + } + if toggle && unconsumedButtonMouseDown, let lastDismissed = lastDismissedAt, + now.timeIntervalSince(lastDismissed) < dismissGrace { + return .ignoreRecentDismissal + } + return .present + } +} + +/// A left press on the panel's own status button while the panel is open. +/// +/// The panel's global outside-click monitor sees that press before Tauri delivers the matching +/// mouse-up toggle, so the press is recorded instead of dismissing; the toggle that follows then +/// closes the panel once instead of reopening it. Any other dismissal forgets the press, so a +/// stale press can never swallow a later, unrelated click on the icon. +public struct NativeTrayButtonPress: Equatable { + public private(set) var pressedAt: Date? + + public init() {} + + public mutating func record(at now: Date = Date()) { pressedAt = now } + + public mutating func clear() { pressedAt = nil } + + /// Decides one toggle and consumes the recorded press. + public mutating func toggle(isVisible: Bool, now: Date = Date()) -> NativeTrayToggleAction { + defer { pressedAt = nil } + return NativeTrayTogglePolicy.evaluate( + toggle: true, + isVisible: isVisible, + unconsumedButtonMouseDown: pressedAt != nil, + lastDismissedAt: pressedAt, + now: now + ) + } +} + // All ABI calls run on Tauri's AppKit main thread. Swift copies the borrowed JSON // synchronously and never retains a Rust buffer or owns an application/run loop. @MainActor @@ -31,7 +86,17 @@ private final class NativeTrayPopover: NSObject { func show(_ pointer: UnsafeMutableRawPointer, toggle: Bool, callback: @escaping @convention(c) (Int32) -> Void) { self.callback = callback - if toggle && panel.isVisible { panel.dismiss(); return } + if toggle { + switch panel.buttonPress.toggle(isVisible: panel.isVisible) { + case .dismiss: + panel.dismiss() + return + case .ignoreRecentDismissal: + return + case .present: + break + } + } let item = Unmanaged.fromOpaque(pointer).takeUnretainedValue() guard let button = item.button, button.window != nil else { return } if panel.isVisible { return } diff --git a/app/Sources/NativeTrayTests/main.swift b/app/Sources/NativeTrayTests/main.swift index c519376e69b..f0f4c872154 100644 --- a/app/Sources/NativeTrayTests/main.swift +++ b/app/Sources/NativeTrayTests/main.swift @@ -1,3 +1,4 @@ +import AppKit import Foundation import NativeTray @@ -142,4 +143,85 @@ let unrelatedError = try decode(["errors": ["Usage unavailable"], "providers": [ check(!NativeTraySwitch.settles(snapshot: unrelatedError, pendingRow: "pool-b:0"), "An unrelated error does not settle") let failedSwitch = try decode(["errors": ["The runtime refused that account right now."], "switchFailed": true, "refreshing": false, "providers": []]) check(NativeTraySwitch.settles(snapshot: failedSwitch, pendingRow: "pool-b:0"), "The host's failure marker settles at once") + +// Toggle policy and hit testing: ensure status bar icon toggle collapses rather than loops reopen +let testNow = Date() +check( + NativeTrayTogglePolicy.evaluate(toggle: false, isVisible: true, unconsumedButtonMouseDown: false, lastDismissedAt: nil, now: testNow) == .present, + "Show action without toggle always presents even when visible" +) +check( + NativeTrayTogglePolicy.evaluate(toggle: true, isVisible: true, unconsumedButtonMouseDown: false, lastDismissedAt: nil, now: testNow) == .dismiss, + "Toggle when panel is visible dismisses the panel" +) +check( + NativeTrayTogglePolicy.evaluate( + toggle: true, + isVisible: false, + unconsumedButtonMouseDown: true, + lastDismissedAt: testNow.addingTimeInterval(-0.1), + now: testNow + ) == .ignoreRecentDismissal, + "Toggle right after status-button mouse-down dismissal stays dismissed" +) +check( + NativeTrayTogglePolicy.evaluate( + toggle: true, + isVisible: false, + unconsumedButtonMouseDown: true, + lastDismissedAt: testNow.addingTimeInterval(-0.5), + now: testNow + ) == .present, + "Toggle after grace period presents the panel" +) +check( + NativeTrayTogglePolicy.evaluate( + toggle: true, + isVisible: false, + unconsumedButtonMouseDown: false, + lastDismissedAt: testNow.addingTimeInterval(-0.1), + now: testNow + ) == .present, + "Toggle after dismissal without button mouse-down presents the panel" +) + +let buttonRect = NSRect(x: 100, y: 100, width: 30, height: 22) +check(NativeTrayHitTest.isNearButton(buttonFrame: buttonRect, point: NSPoint(x: 110, y: 110)), "Inside button frame hits") +check(NativeTrayHitTest.isNearButton(buttonFrame: buttonRect, point: NSPoint(x: 98, y: 100)), "Within button margin hits") +check(!NativeTrayHitTest.isNearButton(buttonFrame: buttonRect, point: NSPoint(x: 50, y: 50)), "Outside button frame misses") + +// A global monitor's press keeps the position it happened at, wherever the pointer is now. +let pressPoint = NSPoint(x: NSEvent.mouseLocation.x + 400, y: NSEvent.mouseLocation.y + 300) +let windowlessPress = NSEvent.mouseEvent( + with: .leftMouseDown, location: pressPoint, modifierFlags: [], timestamp: 0, + windowNumber: 0, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)! +check(MainActor.assumeIsolated { NativeTrayHitTest.screenLocation(of: windowlessPress) } == pressPoint, + "A windowless press is hit-tested where it happened, not at the live pointer") + +// Button-press sequences, in the order AppKit and Tauri deliver them. +var press = NativeTrayButtonPress() +press.record(at: testNow) +check(press.toggle(isVisible: true, now: testNow.addingTimeInterval(0.05)) == .dismiss, + "A press on the icon followed by its toggle closes the open panel") +check(press.toggle(isVisible: false, now: testNow.addingTimeInterval(0.1)) == .present, + "That toggle consumed the press, so the next click on the icon opens the panel") + +press = NativeTrayButtonPress() +press.record(at: testNow) +press.clear() +check(press.toggle(isVisible: false, now: testNow.addingTimeInterval(0.1)) == .present, + "An outside or right click dismissal forgets an earlier press, so a quick click reopens") + +press = NativeTrayButtonPress() +press.record(at: testNow) +check(press.toggle(isVisible: false, now: testNow.addingTimeInterval(0.1)) == .ignoreRecentDismissal, + "A panel hidden between the icon's press and its toggle stays closed") +check(press.toggle(isVisible: false, now: testNow.addingTimeInterval(0.15)) == .present, + "Only one toggle is absorbed per press") + +press = NativeTrayButtonPress() +press.record(at: testNow) +check(press.toggle(isVisible: false, now: testNow.addingTimeInterval(1)) == .present, + "An expired press does not suppress a later click") + print("PASS: \(assertions) native tray contract/formatting assertions") From da106c75d106e09f5231db44e61caa366787115a Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 05:49:31 +0900 Subject: [PATCH 19/64] fix(videos): hold active turn capacity through content delivery (#9156) * fix(videos): account for polling and streaming downloads in turn admission * test(server): accept per-route turn options after the threaded log context The video route now calls runAdmittedHttpTurn with an options object after { requestId, start, logCtx }, so the source oracle in workflow-budget.test.ts counted it as a call site that threads no log context (expected 1, got 2). The log context is threaded; allow an optional trailing options object. The oracle still requires every call site but count_tokens to carry it. --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../content/docs/es/guides/video-bridge.md | 6 + .../src/content/docs/guides/video-bridge.md | 5 + src/images/openai-video-client.ts | 12 +- src/server/admitted-http-turn.ts | 5 +- src/server/index/serve-options.ts | 8 +- src/server/videos.ts | 131 +++++++++++++----- structure/data-planes/images.md | 11 +- tests/lib/workflow-budget.test.ts | 4 +- tests/server/server-videos-routes.test.ts | 87 ++++++++++-- tests/server/server-videos.test.ts | 68 ++++++++- 10 files changed, 277 insertions(+), 60 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/video-bridge.md b/docs-site/src/content/docs/es/guides/video-bridge.md index b7733a2e1d3..3b70caa061f 100644 --- a/docs-site/src/content/docs/es/guides/video-bridge.md +++ b/docs-site/src/content/docs/es/guides/video-bridge.md @@ -133,6 +133,12 @@ Los clientes que hablan la API de OpenAI Videos pueden apuntar a OpenCodex. Se a Las rutas aplican las mismas comprobaciones de autenticación y origen que `/v1/images/generations`, una clave con alcance queda limitada a sus proveedores y modelos en las tres, y cada llamada se registra en `usage.jsonl`. No se atienden las rutas de listado, borrado, remezcla, edición ni extensión. +Crear un trabajo, consultar su estado y descargar su contenido requieren una plaza de solicitud +activa. Una descarga ocupa su plaza hasta que termina la transmisión. Si todas las plazas están +ocupadas, vuelve a intentarlo tras el plazo indicado en la cabecera `Retry-After` de la respuesta +HTTP 503. Puedes consultar o descargar un trabajo existente aunque el flujo que lo creó haya +agotado su presupuesto. + ## Cómo funciona 1. opencodex detecta un modelo enrutado no OpenAI con `videoBridgeEnabled: true` diff --git a/docs-site/src/content/docs/guides/video-bridge.md b/docs-site/src/content/docs/guides/video-bridge.md index c7fe01a02f1..855f8e0896f 100644 --- a/docs-site/src/content/docs/guides/video-bridge.md +++ b/docs-site/src/content/docs/guides/video-bridge.md @@ -176,6 +176,11 @@ The routes take the same authentication and origin checks as `/v1/images/generat is held to its providers and models on all three, and each call is recorded in `usage.jsonl`. List, delete, remix, edit and extension routes are not served. +Creating a job, checking its status and downloading its content each use an active request slot. +A download holds its slot until the stream ends. If all slots are busy, retry after the delay in +the `Retry-After` header of the HTTP 503 response. An existing job can still be checked or +downloaded when its creation workflow has reached its budget. + ## How It Works 1. opencodex detects a non-OpenAI routed model with `videoBridgeEnabled: true` diff --git a/src/images/openai-video-client.ts b/src/images/openai-video-client.ts index 5a76bd605e8..f70e588ae05 100644 --- a/src/images/openai-video-client.ts +++ b/src/images/openai-video-client.ts @@ -124,6 +124,16 @@ export async function fetchOpenAiVideoContent( options: { variant?: string; signal?: AbortSignal } = {}, dependencies: VideoOutboundDependencies = {}, ): Promise { + return (await fetchOpenAiVideoContentWithDeadline(id, auth, options, dependencies)).response; +} + +/** The public download route also observes this same deadline while its consumer is idle. */ +export async function fetchOpenAiVideoContentWithDeadline( + id: string, + auth: VideoProviderAuth, + options: { variant?: string; signal?: AbortSignal } = {}, + dependencies: VideoOutboundDependencies = {}, +): Promise<{ response: Response; signal: AbortSignal }> { if (options.variant !== undefined && !OPENAI_VIDEO_CONTENT_VARIANTS.has(options.variant)) { throw new Error("video content variant is not supported"); } @@ -134,7 +144,7 @@ export async function fetchOpenAiVideoContent( signal: deadline, }, videoOutboundDependencies(dependencies)); if (!resp.ok) throw await upstreamFailure("OpenAI videos content API", resp, deadline); - return resp; + return { response: resp, signal: deadline }; } const SHORT_SIDE: Readonly> = { "480p": 480, "720p": 720, "1080p": 1080 }; diff --git a/src/server/admitted-http-turn.ts b/src/server/admitted-http-turn.ts index 9e7567cde91..8a6f43569e3 100644 --- a/src/server/admitted-http-turn.ts +++ b/src/server/admitted-http-turn.ts @@ -8,6 +8,8 @@ import { sessionLaneIdFromRequest } from "./request-log-conversation"; import { admitHttpWorkflowTurn, workflowDecisionRefusalResponse, type WorkflowRefusalLog } from "./workflow-refusal"; export interface AdmittedHttpTurnOptions { + /** Polling or downloading a previously created job uses listener capacity without starting model work. */ + existingJobRead?: boolean; mapRefusal?: (response: Response) => Response; onAdmissionError?: (error: unknown) => Response; } @@ -32,7 +34,8 @@ export function createAdmittedHttpTurn( return options?.mapRefusal ? withCors(map(response), req, policy) : response; } let workflow: ReturnType; - try { workflow = admitHttpWorkflowTurn(req.headers); } + const existingJobRead = req.method === "GET" && options?.existingJobRead; + try { workflow = existingJobRead ? undefined : admitHttpWorkflowTurn(req.headers); } catch (error) { lease.release(); throw error; } if (workflow && !workflow.admitted) { lease.release(); diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index 3532f54a13b..b59634515a9 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -1326,7 +1326,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { }, { requestId, start, logCtx }); } - // Public OpenAI Videos routes (#9110): images-endpoint admission; only the paid create takes a turn slot. + // Public OpenAI Videos routes (#9110): images-endpoint admission; every upstream call takes a turn slot. const videoRoute = url.pathname.startsWith("/v1/videos") ? matchVideoRoute(req.method, url.pathname) : undefined; if (videoRoute) { // A create keeps the listener timeout until its body is read, so a stalled upload cannot hold its slots. @@ -1344,14 +1344,14 @@ export function createServeOptions(ctx: ServeOptionsContext) { ...requestMetricsLogContext, client: classifyUsageClient(req.headers), ...admissionFields(admission), }; - const run = async (lease?: import("../../lib/admission").AdmissionLease): Promise => { + const run = async (lease: import("../../lib/admission").AdmissionLease): Promise => { const response = await handleVideos(req, url, config, videoRoute, logCtx, admission, { - ...(lease ? { lease } : {}), onRequestBodyRead: () => disableResponsesRequestTimeout(req, requestServer), + lease, onRequestBodyRead: () => disableResponsesRequestTimeout(req, requestServer), }); addFinalRequestLog(requestId, start, logCtx, response.status, response.status === 499 ? { closeReason: "client_cancel" } : undefined); return withCors(response, req, policy); }; - return videoRoute.kind === "create" ? runAdmittedHttpTurn(req, policy, lease => run(lease), { requestId, start, logCtx }) : run(); + return runAdmittedHttpTurn(req, policy, run, { requestId, start, logCtx }, { existingJobRead: videoRoute.kind !== "create" }); } if (req.method === "GET" && url.pathname.startsWith("/v1/opencodex/artifacts/")) { diff --git a/src/server/videos.ts b/src/server/videos.ts index 390d7be8ba5..ca4bea3d047 100644 --- a/src/server/videos.ts +++ b/src/server/videos.ts @@ -15,7 +15,7 @@ import { formatErrorResponse } from "../bridge"; import { sanitizeUpstreamErrorText } from "../adapters/upstream-http-error"; import { createOpenAiVideo, - fetchOpenAiVideoContent, + fetchOpenAiVideoContentWithDeadline, OPENAI_VIDEO_CONTENT_VARIANTS, retrieveOpenAiVideo, VideoUpstreamError, @@ -146,7 +146,7 @@ export function setVideoCreateBodyTimeoutForTests(ms: number | undefined): void } export interface VideoRouteOptions { - /** The create's turn lease: shutdown aborts the upstream create through it. */ + /** The route's turn lease: shutdown aborts upstream work and content retains it while streaming. */ lease?: AdmissionLease; /** Called once the create body is read, when the listener timeout may be lifted. */ onRequestBodyRead?: () => void; @@ -273,57 +273,122 @@ async function openHandle( return { claims, auth: row.auth }; } -async function handleRetrieve(req: Request, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission): Promise { +async function handleRetrieve(req: Request, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission, options: VideoRouteOptions): Promise { const opened = await openHandle(req, config, handle, logCtx, admission); if (opened instanceof Response) return opened; + const operation = new AbortController(); + if (options.lease) registerTurn(operation, options.lease); try { - const job = await retrieveOpenAiVideo(opened.claims.upstreamId, opened.auth, req.signal, outboundDependencies); + const job = await retrieveOpenAiVideo(opened.claims.upstreamId, opened.auth, AbortSignal.any([req.signal, operation.signal]), outboundDependencies); return Response.json(publicVideoJob(job, handle, opened.claims.model)); } catch (error) { + if (operation.signal.aborted && !req.signal.aborted) return formatErrorResponse(503, "server_draining", "video retrieve stopped during shutdown"); return failureResponse(error, req, "video retrieve"); + } finally { + if (options.lease) unregisterTurn(operation); } } -function cappedBody(body: ReadableStream, maxBytes: number): ReadableStream { +function cappedBody( + body: ReadableStream, signal: AbortSignal, operation: AbortController, release: () => void, +): ReadableStream { + const reader = body.getReader(); + let output: ReadableStreamDefaultController; let total = 0; - return body.pipeThrough(new TransformStream({ - transform(chunk, controller) { - total += chunk.byteLength; - if (total > maxBytes) { - controller.error(new Error("video content exceeds size cap")); - return; - } - controller.enqueue(chunk); + let reading = false; + let ended = false; + let settled = false; + + function finish() { + settled = true; + signal.removeEventListener("abort", onAbort); + release(); + } + function stop(reason: unknown) { + if (settled) return; + finish(); + output.error(reason); + operation.abort(reason); + void reader.cancel(reason).catch(() => {}); + } + function onAbort() { stop(signal.reason); } + function close() { + if (settled) return; + finish(); + output.close(); + } + + return new ReadableStream({ + start(controller) { + output = controller; + signal.addEventListener("abort", onAbort, { once: true }); + // The source can fail while the consumer is idle. Its final read can also close the + // reader before that read's last chunk has been handed to the consumer. + void reader.closed.then(() => { ended = true; if (!reading) close(); }, stop); + if (signal.aborted) onAbort(); }, - })); + async pull() { + reading = true; + try { + const { value, done } = await reader.read(); + if (settled) return; + if (!done) { + total += value.byteLength; + if (total > VIDEO_CONTENT_MAX_BYTES) { stop(new Error("video content exceeds size cap")); return; } + output.enqueue(value); + } + if (done || ended) close(); + } catch (error) { stop(error); } + finally { reading = false; } + }, + cancel: stop, + }, { highWaterMark: 0 }); } -async function handleContent(req: Request, url: URL, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission): Promise { +async function handleContent(req: Request, url: URL, config: OcxConfig, handle: string, logCtx: RequestLogContext, admission: DataPlaneAdmission, options: VideoRouteOptions): Promise { const variant = url.searchParams.get("variant") ?? undefined; if (variant !== undefined && !OPENAI_VIDEO_CONTENT_VARIANTS.has(variant)) return invalid("variant must be video, thumbnail or spritesheet"); const opened = await openHandle(req, config, handle, logCtx, admission); if (opened instanceof Response) return opened; - let upstream: Response; + const operation = new AbortController(); + if (options.lease) registerTurn(operation, options.lease); + const finishOperation = () => { if (options.lease) unregisterTurn(operation); }; + let upstream: Response | undefined; + let streaming = false; try { - upstream = await fetchOpenAiVideoContent(opened.claims.upstreamId, opened.auth, { - signal: req.signal, ...(variant !== undefined ? { variant } : {}), + const download = await fetchOpenAiVideoContentWithDeadline(opened.claims.upstreamId, opened.auth, { + signal: AbortSignal.any([req.signal, operation.signal]), ...(variant !== undefined ? { variant } : {}), }, outboundDependencies); + upstream = download.response; + download.signal.throwIfAborted(); + const declared = upstream.headers.get("content-length"); + if (declared !== null && /^\d+$/.test(declared) && Number(declared) > VIDEO_CONTENT_MAX_BYTES) { + return formatErrorResponse(502, "upstream_error", "video content exceeds size cap"); + } + const type = (upstream.headers.get("content-type") ?? "").toLowerCase().split(";")[0]!.trim(); + const headers: Record = { + "content-type": CONTENT_TYPES.has(type) && type !== "application/json" ? type : "application/octet-stream", + "cache-control": "private, no-store", + "x-content-type-options": "nosniff", + }; + if (declared !== null && /^\d+$/.test(declared)) headers["content-length"] = declared; + if (!upstream.body) return new Response(null, { status: 200, headers }); + const body = cappedBody(upstream.body, download.signal, operation, finishOperation); + const response = new Response(body, { status: 200, headers }); + streaming = true; + return response; } catch (error) { + if (operation.signal.aborted && !req.signal.aborted) return formatErrorResponse(503, "server_draining", "video content stopped during shutdown"); return failureResponse(error, req, "video content"); + } finally { + if (!streaming) { + finishOperation(); + if (upstream?.body) { + operation.abort(); + if (!upstream.body.locked) void upstream.body.cancel().catch(() => {}); + } + } } - const declared = upstream.headers.get("content-length"); - if (declared !== null && /^\d+$/.test(declared) && Number(declared) > VIDEO_CONTENT_MAX_BYTES) { - try { await upstream.body?.cancel(); } catch { /* ignore */ } - return formatErrorResponse(502, "upstream_error", "video content exceeds size cap"); - } - const type = (upstream.headers.get("content-type") ?? "").toLowerCase().split(";")[0]!.trim(); - const headers: Record = { - "content-type": CONTENT_TYPES.has(type) && type !== "application/json" ? type : "application/octet-stream", - "cache-control": "private, no-store", - "x-content-type-options": "nosniff", - }; - if (declared !== null && /^\d+$/.test(declared)) headers["content-length"] = declared; - return new Response(upstream.body ? cappedBody(upstream.body, VIDEO_CONTENT_MAX_BYTES) : null, { status: 200, headers }); } export async function handleVideos( @@ -337,8 +402,8 @@ export async function handleVideos( ): Promise { try { if (route.kind === "create") return await handleCreate(req, config, logCtx, admission, options); - if (route.kind === "retrieve") return await handleRetrieve(req, config, route.handle, logCtx, admission); - return await handleContent(req, url, config, route.handle, logCtx, admission); + if (route.kind === "retrieve") return await handleRetrieve(req, config, route.handle, logCtx, admission, options); + return await handleContent(req, url, config, route.handle, logCtx, admission, options); } catch (error) { // The handle key file is the one local failure left; it names no secret. if (isVideoHandleKeyError(error)) { diff --git a/structure/data-planes/images.md b/structure/data-planes/images.md index ebd744d198f..06e7beac549 100644 --- a/structure/data-planes/images.md +++ b/structure/data-planes/images.md @@ -134,9 +134,14 @@ collapse onto another path of the same host. Bridge arguments map to `seconds`, `src/server/videos.ts` serves `POST /v1/videos`, `GET /v1/videos/{id}` and `GET /v1/videos/{id}/content` (`src/lib/video-routes.ts` matches them; other methods and subpaths reach the JSON `/v1/*` 404). The dispatcher applies the Images admission: draining refusal, `resolveApiAuth`, origin policy and a -request-log row (`usage.jsonl`); only the paid create takes an admitted turn slot and the inbound body gate -(`/v1/videos` is in `CONFIGURABLE_JSON_BODY_ROUTES`). Its upstream POST is bound to that turn lease, so shutdown aborts -it with a 503, and it keeps the listener request timeout until its body is read. The body read also has a 60 s +request-log row (`usage.jsonl`). Every create, retrieve and content request takes an active turn slot. +Creation also passes model workflow admission and the inbound body gate (`/v1/videos` is in +`CONFIGURABLE_JSON_BODY_ROUTES`). Reads of an existing job use the slot without reserving model workflow capacity. Each +credentialed upstream operation is bound to its turn, so shutdown aborts work before response headers with a +503. A retrieve releases the turn after its bounded upstream JSON is parsed, while content transfers the turn to +the capped response body. EOF, an upstream error, the download deadline, or cancellation releases its slot, +including when the client has paused reads. The create keeps the +listener request timeout until its body is read. The body read also has a 60 s whole-body deadline (the idle timeout alone bounds only silence), after which the reader is cancelled and the create answers 408 before any send, so neither a stalled nor a trickling upload can hold either slot. The loopback listener and Remote Link admit the same three shapes. diff --git a/tests/lib/workflow-budget.test.ts b/tests/lib/workflow-budget.test.ts index 53d9895c2f2..123c9de3390 100644 --- a/tests/lib/workflow-budget.test.ts +++ b/tests/lib/workflow-budget.test.ts @@ -575,7 +575,9 @@ describe("a refusal an operator can read, name and clear (#4546)", () => { await Bun.file(repoPath("src/server/admitted-http-turn.ts")).text(), ].join("\n"); const callSites = source.match(/return runAdmittedHttpTurn\(/g) ?? []; - const threaded = source.match(/, \{ requestId, start, logCtx \}\);/g) ?? []; + // A call site may pass per-route turn options after the log context (the video route marks + // existing-job reads); the log context is still threaded. + const threaded = source.match(/, \{ requestId, start, logCtx \}(?:, \{[^{}]*\})?\);/g) ?? []; expect(callSites.length).toBeGreaterThan(1); // Exactly one surface has no log context to thread: /v1/messages/count_tokens opens no // request-log row at all. Every other one must, or a refusal there leaves no trace. diff --git a/tests/server/server-videos-routes.test.ts b/tests/server/server-videos-routes.test.ts index b6baa4fa5cf..c1fcea89e24 100644 --- a/tests/server/server-videos-routes.test.ts +++ b/tests/server/server-videos-routes.test.ts @@ -3,7 +3,7 @@ * config schema acceptance of `videoApi`, the persisted handle key, the real outbound policy against * a local fake upstream, and one usage.jsonl row per call. No paid API, no real credential. */ -import { afterEach, beforeEach, expect, setDefaultTimeout, test } from "bun:test"; +import { afterEach, beforeEach, expect, setDefaultTimeout, spyOn, test } from "bun:test"; import { existsSync, mkdtempSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -11,7 +11,8 @@ import { getDefaultConfig, saveConfig } from "../../src/config"; import { startServer } from "../../src/server"; import { VIDEO_HANDLE_KEY_FILE } from "../../src/server/video-handle"; import { setVideoCreateBodyTimeoutForTests } from "../../src/server/videos"; -import { getActiveTurnCount } from "../../src/server/lifecycle"; +import * as lifecycle from "../../src/server/lifecycle"; +import { admitWorkflowTurn } from "../../src/lib/workflow-budget"; import { inboundBodyBudget } from "../../src/server/inbound-body-budget"; import { MAX_CONFIGURABLE_INBOUND_BODY_BYTES } from "../../src/server/request-decompress"; import type { OcxProviderConfig } from "../../src/types"; @@ -59,13 +60,17 @@ afterEach(async () => { if (home) removeTreeWithRetry(home); }); -test("create, poll and content flow through the proxy to the row's own upstream and are each logged", async () => { +function localVideoConfig() { const config = getDefaultConfig(); config.providers.aistudio = { adapter: "openai-chat", baseUrl: `http://127.0.0.1:${upstream!.port}/v1`, apiKey: KEY, authMode: "key", allowPrivateNetwork: true, noProxy: "127.0.0.1", videoApi: "openai", } as OcxProviderConfig; - saveConfig(config); + return config; +} + +test("create, poll and content flow through the proxy to the row's own upstream and are each logged", async () => { + saveConfig(localVideoConfig()); const server = startServer(0); try { const created = await fetch(new URL("/v1/videos", server.url), { @@ -106,12 +111,68 @@ test("create, poll and content flow through the proxy to the row's own upstream } }); +test("authenticated job reads require an active turn and remain available after the creation workflow fills", async () => { + const config = localVideoConfig(); + const rootId = "video-test-workflow"; + const apiKey = "ocx_data_" + "a".repeat(40); + config.apiKeys = [{ id: "video-owner", name: "video", key: apiKey, createdAt: "2026-01-01T00:00:00.000Z" }]; + config.workflowBudget = { maxConcurrentChildren: 2 }; + saveConfig(config); + const headers = { authorization: "Bearer " + apiKey, "x-codex-parent-thread-id": rootId }; + const server = startServer(0); + const createJob = () => fetch(new URL("/v1/videos", server.url), { + method: "POST", headers: { ...headers, "content-type": "application/json" }, + body: JSON.stringify({ model: "aistudio/m", prompt: "a heron" }), + }); + try { + const created = await createJob(); + expect(created.status).toBe(200); + const { id } = await created.json() as { id: string }; + const pollUrl = new URL("/v1/videos/" + id, server.url); + const contentUrl = new URL(pollUrl.pathname + "/content", server.url); + const baseline = lifecycle.getActiveTurnCount(); + const admit = lifecycle.tryAdmitTurn; + // Exercise a full gate with one real lease, independently of the production capacity. + const singleSlot = spyOn(lifecycle, "tryAdmitTurn").mockImplementation((...args) => + lifecycle.getActiveTurnCount() === baseline ? admit(...args) : null); + const held = lifecycle.tryAdmitTurn(); + try { + expect(held).not.toBeNull(); + for (const url of [pollUrl, contentUrl]) { + const busy = await fetch(url, { headers }); + expect(busy.status).toBe(503); + expect(busy.headers.get("retry-after")).toBe("1"); + expect(await busy.json()).toMatchObject({ error: { code: "server_busy" } }); + } + expect(seen.map(row => row.method)).toEqual(["POST"]); + } finally { + held?.release(); + singleSlot.mockRestore(); + } + + const workflow = [admitWorkflowTurn(rootId, "interactive"), admitWorkflowTurn(rootId, "interactive")]; + try { + expect(workflow.every(turn => turn?.admitted)).toBe(true); + const denied = await createJob(); + expect(denied.status).toBe(429); + expect(await denied.json()).toMatchObject({ error: { code: "rate_limit_exceeded", message: expect.stringContaining("no free concurrency slot") } }); + const poll = await fetch(pollUrl, { headers }); + expect(poll.status).toBe(200); + expect(await poll.json()).toMatchObject({ id, status: "completed" }); + const content = await fetch(contentUrl, { headers }); + expect(content.status).toBe(200); + expect(new Uint8Array(await content.arrayBuffer())).toEqual(MP4); + expect(seen.map(row => row.method)).toEqual(["POST", "GET", "GET"]); + } finally { + for (const turn of workflow) if (turn?.admitted) turn.lease.release(); + } + } finally { + await server.stop(true); + } +}); + test("a trickling create upload through the real server is refused at the deadline and releases its turn and body slots", async () => { - const config = getDefaultConfig(); - config.providers.aistudio = { - adapter: "openai-chat", baseUrl: `http://127.0.0.1:${upstream!.port}/v1`, apiKey: KEY, authMode: "key", - allowPrivateNetwork: true, noProxy: "127.0.0.1", videoApi: "openai", - } as OcxProviderConfig; + const config = localVideoConfig(); // A raised body limit puts the create under the shared inbound body budget, so a reservation is taken. config.maxInboundBodyBytes = MAX_CONFIGURABLE_INBOUND_BODY_BYTES; saveConfig(config); @@ -119,7 +180,7 @@ test("a trickling create upload through the real server is refused at the deadli const server = startServer(0); let tick: ReturnType | undefined; try { - const baseline = getActiveTurnCount(); + const baseline = lifecycle.getActiveTurnCount(); const encoder = new TextEncoder(); const body = new ReadableStream({ start(controller) { @@ -134,7 +195,7 @@ test("a trickling create upload through the real server is refused at the deadli // While the upload trickles, the create holds one turn slot and one body reservation. let held = false; for (let i = 0; i < 100 && !held; i++) { - held = getActiveTurnCount() === baseline + 1 && inboundBodyBudget.snapshot().activeLeases === 1; + held = lifecycle.getActiveTurnCount() === baseline + 1 && inboundBodyBudget.snapshot().activeLeases === 1; if (!held) await Bun.sleep(10); } expect(held).toBe(true); @@ -144,8 +205,8 @@ test("a trickling create upload through the real server is refused at the deadli await response.text(); clearInterval(tick); // Settlement is asynchronous after the response; wait for the slots to come back, bounded. - for (let i = 0; i < 100 && (getActiveTurnCount() !== baseline || inboundBodyBudget.snapshot().activeLeases !== 0); i++) await Bun.sleep(10); - expect(getActiveTurnCount()).toBe(baseline); + for (let i = 0; i < 100 && (lifecycle.getActiveTurnCount() !== baseline || inboundBodyBudget.snapshot().activeLeases !== 0); i++) await Bun.sleep(10); + expect(lifecycle.getActiveTurnCount()).toBe(baseline); expect(inboundBodyBudget.snapshot()).toMatchObject({ activeLeases: 0, reservedBytes: 0 }); expect(seen).toEqual([]); } finally { diff --git a/tests/server/server-videos.test.ts b/tests/server/server-videos.test.ts index 1160c3ffba3..4820f60ecfe 100644 --- a/tests/server/server-videos.test.ts +++ b/tests/server/server-videos.test.ts @@ -3,18 +3,20 @@ * Handler-level cases on a fake resolver and pinned transport; nothing opens a socket and a raw * fetch fails the test. */ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { VideoOutboundDependencies } from "../../src/images/xai-video-client"; +import { OPENAI_VIDEO_CONTENT_TIMEOUT_MS } from "../../src/images/openai-video-client"; import { resolvePublicAddresses } from "../../src/lib/destination-policy"; import { MODEL_NOT_ALLOWED_FOR_KEY } from "../../src/server/admission-model-scope"; import type { DataPlaneAdmission } from "../../src/server/auth-cors"; import type { RequestLogContext } from "../../src/server/request-log"; import { setVideoHandleKeyForTests } from "../../src/server/video-handle"; import { matchVideoRoute } from "../../src/lib/video-routes"; -import { handleVideos, setVideoCreateBodyTimeoutForTests, setVideoOutboundDependenciesForTests } from "../../src/server/videos"; +import { handleVideos, setVideoCreateBodyTimeoutForTests, setVideoOutboundDependenciesForTests, type VideoRouteOptions } from "../../src/server/videos"; +import { getActiveTurnCount, tryAdmitTurn } from "../../src/server/lifecycle"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { repoPath } from "../helpers/repo-root"; @@ -95,14 +97,14 @@ function config(overrides: Partial = {}, rows: Record ({ model: "video", provider: "unknown" } as RequestLogContext); -async function call(cfg: OcxConfig, method: string, path: string, body?: BodyInit, admission = ALICE, headers: Record = { "content-type": "application/json" }, secret = secretFor(admission)) { +async function call(cfg: OcxConfig, method: string, path: string, body?: BodyInit, admission = ALICE, headers: Record = { "content-type": "application/json" }, secret = secretFor(admission), options?: VideoRouteOptions) { const url = new URL("http://localhost" + path); headers = { ...headers, authorization: "Bearer " + secret }; const route = matchVideoRoute(method, url.pathname); if (!route) throw new Error("no video route for " + method + " " + path); const logCtx = logContext(); const req = new Request(url, { method, headers, ...(body !== undefined ? { body } : {}) }); - const response = await handleVideos(req, url, cfg, route, logCtx, admission); + const response = await handleVideos(req, url, cfg, route, logCtx, admission, options); return { response, logCtx }; } @@ -235,6 +237,64 @@ describe("GET /v1/videos/{id} and /content", () => { expect(sent).toEqual([{ method: "GET", url: "https://" + HOST + "/v1/videos/video_up_1/content", address: "93.184.216.34", authorization: "Bearer " + KEY }]); }); + test.each(["eof", "cancel", "error"] as const)("content retains its admitted turn until %s", async finish => { + const handle = await handleFor(); + let source!: ReadableStreamDefaultController; + answer = () => new Response(new ReadableStream({ + start(controller) { source = controller; controller.enqueue(MP4); }, + }), { headers: { "content-type": "video/mp4" } }); + const baseline = getActiveTurnCount(); + const lease = tryAdmitTurn(); + expect(lease).not.toBeNull(); + try { + const { response } = await call(config(), "GET", "/v1/videos/" + handle + "/content", undefined, ALICE, {}, ALICE_SECRET, { lease: lease! }); + const reader = response.body!.getReader(); + expect((await reader.read()).value).toEqual(MP4); + expect(getActiveTurnCount()).toBe(baseline + 1); + if (finish === "eof") { + source.close(); + expect((await reader.read()).done).toBe(true); + } else if (finish === "error") { + source.error(new Error("synthetic source error")); + await Bun.sleep(0); + expect(getActiveTurnCount()).toBe(baseline); + await expect(reader.read()).rejects.toThrow("synthetic source error"); + } else { + await reader.cancel("client stopped download"); + } + expect(getActiveTurnCount()).toBe(baseline); + } finally { + lease?.release(); + } + }); + + test("the download deadline releases an unread response and cancels its source", async () => { + const handle = await handleFor(); + const deadline = new AbortController(); + let cancelled = false; + answer = () => new Response(new ReadableStream({ + cancel() { cancelled = true; }, + }), { headers: { "content-type": "video/mp4" } }); + const baseline = getActiveTurnCount(); + const lease = tryAdmitTurn(); + expect(lease).not.toBeNull(); + const timeout = AbortSignal.timeout.bind(AbortSignal); + const clock = spyOn(AbortSignal, "timeout").mockImplementation(ms => + ms === OPENAI_VIDEO_CONTENT_TIMEOUT_MS ? deadline.signal : timeout(ms)); + try { + const { response } = await call(config(), "GET", "/v1/videos/" + handle + "/content", undefined, ALICE, {}, ALICE_SECRET, { lease: lease! }); + expect(response.status).toBe(200); + expect(getActiveTurnCount()).toBe(baseline + 1); + deadline.abort(new Error("synthetic download deadline")); + expect(getActiveTurnCount()).toBe(baseline); + expect(cancelled).toBe(true); + await expect(response.arrayBuffer()).rejects.toThrow("synthetic download deadline"); + } finally { + clock.mockRestore(); + lease?.release(); + } + }); + test("content never relays an active media type and passes only known variants", async () => { const handle = await handleFor(); answer = () => new Response("", { headers: { "content-type": "text/html" } }); From eff399c9fb340395c9db149f48726786c6b4882e Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:49:39 +0900 Subject: [PATCH 20/64] feat(agy-acp): expand seeded models and allow Claude models (#9192) * feat(agy-acp): expand seeded models and allow Claude models * fix(agy-acp): enforce Gemini/Claude family consistency and update error messages * fix(agy-acp): normalize dotted labels and update docs-site catalog * fix(agy-acp): reject namespaced disallowed models regardless of display name * fix(agy-acp): fix protocol tests, multi-segment family check, retain gemini-3.7-flash, and sync docs Co-authored-by: jbamlee --------- Co-authored-by: joon --- .../content/docs/es/guides/api-key-catalog.md | 2 +- .../content/docs/guides/api-key-catalog.md | 7 +-- src/adapters/agy-acp/adapter.ts | 14 +++--- src/adapters/agy-acp/options.ts | 44 ++++++++++++++----- src/config/schema/agy-acp-references.ts | 10 ++--- src/providers/registry/agy-acp-models.ts | 14 +++++- src/providers/registry/entries-extended.ts | 16 ++++++- structure/adapters/registry.md | 6 +-- tests/adapters/agy-acp-adapter.test.ts | 41 +++++++++++------ tests/adapters/agy-acp-protocol.test.ts | 14 +++--- tests/cli/cli-init-port.test.ts | 4 +- tests/config/agy-acp-config.test.ts | 12 ++--- 12 files changed, 123 insertions(+), 61 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index d964e899ed0..0c12f312948 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -411,7 +411,7 @@ OpenCodex puede usar una suscripción de Google Antigravity a través de la prop - **Sin credenciales guardadas:** la CLI es dueña de su inicio de sesión de Google. OpenCodex nunca lo lee, lo guarda ni lo reenvía, y la fila rechaza una clave API, un grupo de claves, la conmutación de cuentas o un ajuste OAuth. Hay una sola cuenta, la de la CLI, y no hay rotación. Al seleccionar este preajuste en `ocx init`, se omite la pregunta sobre la clave API. `ocx login antigravity-acp` muestra el comando para iniciar sesión en el host. - **Solo uso interactivo:** las respuestas del personal de Google en el foro de desarrolladores permiten que una aplicación personal inicie el binario oficial `agy acp` para la propia cuenta del usuario cuando el uso es interactivo y dirigido por el usuario, no un grupo de trabajadores desatendido ni un bucle de agente automatizado, y remiten las cargas programáticas a una clave API de Gemini o a Vertex AI ([respuesta del foro](https://discuss.ai.google.dev/t/tos-clarification-is-t3-code-official-antigravity-acp-agent-permitted-under-the-antigravity-terms-of-service/192027/2), [respuesta del foro](https://discuss.ai.google.dev/t/policy-question-omp-hosting-unmodified-antigravity-acp-for-one-user/199753)). OpenCodex aplica lo que puede saber con certeza: rechaza con HTTP 403 `agy_acp_interactive_only` un turno de subagente de Codex (`x-codex-parent-thread-id`), un turno que Codex marca como hilo generado o como su proceso de memoria, un miembro de combo, la llamada interna de decisión de un combo y una ruta elegida por la reserva de subagentes, y la configuración rechaza este proveedor como destino de combo, como `decisionModel` de un combo, como reserva de subagentes, como modelo predeterminado de subagentes administrados, como destino de compactación automática, como fase de `memoryModels` o como destino de `shadowCallIntercept`. La compactación manual sí admite ACP. - **Conexiones locales en el host del proxy:** OpenCodex determina si la solicitud es local según el origen de la conexión observada y el listener que la recibe. Las conexiones de la LAN, los enlaces del hub y el listener de gestión del hub se rechazan con HTTP 403 `agy_acp_local_only`. Las cabeceras de reenvío reconocidas, como `Forwarded`, `X-Forwarded-For`, `X-Real-IP`, `Via`, `CF-Connecting-IP` y `Tailscale-User-Login`, también provocan el rechazo. Solo en el listener público se rechazan además las conexiones desde direcciones declaradas en `dashboardTrustedProxy.proxyAddresses`. Un intermediario en loopback sin declarar o un reenvío de puerto por SSH puede parecer local si no transmite ninguna cabecera de reenvío reconocida. Declara el proxy inverso para el listener público o evita reenviar este puerto. Evita reenviar también los otros listeners locales, ya que ese ajuste solo protege el listener público. -- **Solo modelos Gemini:** la lista estática es `gemini-3.8-flash`, `gemini-4-argon` y `gemini-3.7-flash`. En cada turno el modelo también debe ser un modelo Gemini que ofrezca la CLI, confirmado antes de enviar el prompt; cualquier otro se rechaza. El esfuerzo de razonamiento de Codex selecciona el nivel de pensamiento de la CLI (`xhigh` selecciona Extra). OpenCodex enmascara las credenciales que reconoce en las respuestas y el texto de razonamiento de la CLI. +- **Solo modelos Gemini y Claude:** la lista estática es `gemini-3.8-flash`, `gemini-4-neon`, `gemini-4-carbon`, `gemini-4-argon`, `gemini-4-hydrogen`, `gemini-3.7-flash`, `gemini-pro-orchestrator-neon`, `gemini-pro-orchestrator`, `gemini-pro-orchestrator-argon`, `claude-opus-5-5` y `claude-sonnet-5-5`. En cada turno el modelo también debe ser un modelo Gemini o Claude que ofrezca la CLI, confirmado antes de enviar el prompt; cualquier otra familia de modelos se rechaza. El esfuerzo de razonamiento de Codex selecciona el nivel de pensamiento de la CLI (`xhigh` selecciona Extra). OpenCodex enmascara las credenciales que reconoce en las respuestas y el texto de razonamiento de la CLI. - **Espacio de trabajo y permisos:** cada turno se ejecuta en un directorio privado nuevo y vacío fuera del directorio de OpenCodex. El motor de permisos de la CLI pregunta antes de cada comando y antes de acceder a archivos fuera de ese directorio, y OpenCodex rechaza todas esas solicitudes. `--sandbox` pide a la CLI que ejecute sus comandos de terminal en su sandbox del sistema; Google documenta que no tiene efecto donde ese sandbox no está disponible (por ejemplo Windows 10 o algunos contenedores Linux), así que es un refuerzo adicional, no una garantía. Las reglas de permiso que configures en tus propios ajustes de agy siguen aplicándose sin preguntar. En Windows, OpenCodex exige una lista de control de acceso privada para el directorio antes de iniciar la CLI. La comprobación de versión y cada turno usan espacios de trabajo separados dentro del directorio temporal del diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 9729fd87d98..7592380f139 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -937,9 +937,10 @@ once per turn and talks to it over the Agent Client Protocol on stdin and stdout An undeclared loopback relay or SSH port forward can appear local when it passes no recognized forwarding headers. Declare the reverse proxy for the public listener or keep this port out of the relay. Keep the other local listeners out of relays, since the declared-proxy setting applies only to the public listener. -- **Gemini models only:** the static roster is `gemini-3.8-flash`, `gemini-4-argon` and `gemini-3.7-flash`. At each - turn the model must also be a Gemini model the CLI offers, confirmed before the prompt is sent; anything else is - refused. Codex reasoning effort selects the CLI's thinking level (`xhigh` selects Extra). OpenCodex masks +- **Gemini and Claude models only:** the static roster is `gemini-3.8-flash`, `gemini-4-neon`, `gemini-4-carbon`, + `gemini-4-argon`, `gemini-4-hydrogen`, `gemini-3.7-flash`, `gemini-pro-orchestrator-neon`, `gemini-pro-orchestrator`, + `gemini-pro-orchestrator-argon`, `claude-opus-5-5` and `claude-sonnet-5-5`. At each turn the model must also be a + Gemini or Claude model the CLI offers, confirmed before the prompt is sent; other model families are refused. Codex reasoning effort selects the CLI's thinking level (`xhigh` selects Extra). OpenCodex masks recognized credentials in answer and reasoning text from the CLI. - **Workspace and permissions:** each turn runs in a new empty private directory outside the OpenCodex home. The CLI's permission engine asks before every command and before file access outside that directory, and OpenCodex refuses diff --git a/src/adapters/agy-acp/adapter.ts b/src/adapters/agy-acp/adapter.ts index b9fed29b7b4..3056e21d81f 100644 --- a/src/adapters/agy-acp/adapter.ts +++ b/src/adapters/agy-acp/adapter.ts @@ -2,7 +2,7 @@ * Antigravity CLI over the Agent Client Protocol (`agy acp`): one ACP session per turn (plan 080). * * The official binary owns its own sign-in; this adapter never reads, stores or forwards a Google - * credential. One account (the CLI's), no rotation, local requests only, Gemini models only, and + * credential. One account (the CLI's), no rotation, local requests only, Gemini and Claude models only, and * interactive use only (see ./policy.ts). runTurn-only: a JSON-RPC session over a child process has no * fetch-shaped request, so buildRequest is an identity placeholder and parseStream is disabled. * @@ -50,9 +50,9 @@ const FAILURE_MESSAGES: Record, st agy_acp_turn_limit: "The Antigravity CLI stopped at its turn request limit before finishing the answer.", agy_acp_cancelled: "The Antigravity CLI cancelled the turn (for example after a refused permission request).", agy_acp_protocol: "The Antigravity CLI ended the turn without a valid ACP answer.", - agy_acp_model_unproven: "The Antigravity CLI did not confirm the selected Gemini model, so the turn was not sent.", - agy_acp_model_switched: "The Antigravity CLI switched away from the selected Gemini model during the turn; the turn was cancelled.", - agy_acp_unsupported_selection: "The Antigravity CLI did not advertise a single model selector, so a Gemini model cannot be selected.", + agy_acp_model_unproven: "The Antigravity CLI did not confirm the selected model, so the turn was not sent.", + agy_acp_model_switched: "The Antigravity CLI switched away from the selected model during the turn; the turn was cancelled.", + agy_acp_unsupported_selection: "The Antigravity CLI did not advertise a single model selector, so a supported model cannot be selected.", agy_acp_unavailable: "The Antigravity CLI could not be started.", }; @@ -192,8 +192,8 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep if (incoming.abortSignal?.aborted) return; const requested = wireModelId(parsed.modelId); - if (!/^gemini[-.]/i.test(requested)) { - emit(invalidRequest("agy_acp_model_not_gemini", "The Antigravity CLI (ACP) provider serves Gemini models only.")); + if (!/^(?:gemini|claude)[-.]/i.test(requested)) { + emit(invalidRequest("agy_acp_model_not_gemini", "The Antigravity CLI (ACP) provider serves Gemini and Claude models only.")); return; } const effort = parsed.options.reasoning; @@ -430,7 +430,7 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep if (!proof.ok) { if (proof.reason === "no_selector" || proof.reason === "ambiguous_selector") return fail("agy_acp_unsupported_selection"); if (proof.reason === "requested_not_offered" || proof.reason === "requested_ambiguous") { - return finish(invalidRequest("agy_acp_model_not_offered", "The requested Gemini model is not offered by this Antigravity CLI.")); + return finish(invalidRequest("agy_acp_model_not_offered", "The requested model is not offered by this Antigravity CLI.")); } return fail("agy_acp_model_unproven"); } diff --git a/src/adapters/agy-acp/options.ts b/src/adapters/agy-acp/options.ts index 3626f4fb2df..9ae7e03499c 100644 --- a/src/adapters/agy-acp/options.ts +++ b/src/adapters/agy-acp/options.ts @@ -1,5 +1,5 @@ /** - * ACP session config options for `agy acp`: model and thought-level selection, and the Gemini-only + * ACP session config options for `agy acp`: model and thought-level selection, and the Gemini/Claude * model proof (plan 080, revision 4). * * Config options arrive as a complete state on session/new, on every session/set_config_option reply @@ -80,8 +80,8 @@ export function findSelector(state: readonly AcpConfigOption[], category: "model return byId.length === 1 ? { ok: true, selector: byId[0]! } : { ok: false, reason: "missing" }; } -/** Lower-case, trimmed, whitespace collapsed to hyphens. */ -export const normalizeLabel = (value: string): string => value.trim().toLowerCase().replace(/\s+/g, "-"); +/** Lower-case, trimmed, whitespace and dots collapsed to hyphens. */ +export const normalizeLabel = (value: string): string => value.trim().toLowerCase().replace(/[\s.]+/g, "-"); export type ValueMatch = { ok: true; value: AcpSelectValue } | { ok: false; reason: "none" | "ambiguous" }; @@ -97,12 +97,34 @@ export function matchValue(values: readonly AcpSelectValue[], wanted: readonly s } const GEMINI_MODEL = /^gemini[-\s.]/i; -const NON_GEMINI_MODEL = /^(?:claude|gpt|o[134]|grok|deepseek|qwen|llama|gemma|mistral|mixtral)(?:[-\s./]|$)/i; +const CLAUDE_MODEL = /^claude[-\s.]/i; +const NON_ALLOWED_MODEL = /^(?:gpt|o[134]|grok|deepseek|qwen|llama|gemma|mistral|mixtral)(?:[-\s./]|$)/i; + +type ModelFamily = "gemini" | "claude" | "other" | null; + +function classifyModelFamily(raw: string): ModelFamily { + const segments = raw.split("/").map(segment => segment.trim()).filter(Boolean); + let allowed: "gemini" | "claude" | null = null; + for (const segment of segments) { + if (NON_ALLOWED_MODEL.test(segment)) return "other"; + const hit: "gemini" | "claude" | null = GEMINI_MODEL.test(segment) + ? "gemini" + : CLAUDE_MODEL.test(segment) ? "claude" : null; + if (hit) { + if (allowed && allowed !== hit) return "other"; + allowed = hit; + } + } + return allowed; +} -/** Either field can establish the family, unless the other explicitly contradicts it. */ +/** Either field can establish an allowed family (Gemini or Claude), unless the other contradicts it. */ export function isGeminiValue(value: AcpSelectValue): boolean { - const fields = [value.value.trim(), value.name.trim()]; - return fields.some(field => GEMINI_MODEL.test(field)) && !fields.some(field => NON_GEMINI_MODEL.test(field)); + const vf = classifyModelFamily(value.value); + const nf = classifyModelFamily(value.name); + if (vf === "other" || nf === "other") return false; + if (vf && nf && vf !== nf) return false; + return vf === "gemini" || vf === "claude" || nf === "gemini" || nf === "claude"; } /** The advertised value the selector currently holds, when it resolves to exactly one. */ @@ -133,13 +155,13 @@ export type ModelProof = | { ok: false; reason: "no_selector" | "ambiguous_selector" | "unknown_current" | "not_gemini" | "requested_not_offered" | "requested_ambiguous" | "not_requested" }; /** - * Phase-aware Gemini proof (plan 080 R3-1). + * Phase-aware Gemini/Claude model proof (plan 080 R3-1). * - initial (after session/new): one selector with a resolvable current value; the requested model - * matches exactly one advertised Gemini option (the current value may still differ); without a - * request the current value itself must be Gemini. + * matches exactly one advertised Gemini or Claude option (the current value may still differ); without a + * request the current value itself must be Gemini or Claude. * - pending (a model setter is outstanding): the selector exists and its current value resolves. * - selected (after the setter, before and during the prompt): the current value is the requested - * option (or, without a request, a Gemini option). + * option (or, without a request, a Gemini or Claude option). */ export function proveModel(state: readonly AcpConfigOption[], phase: ModelPhase, requested: string | undefined): ModelProof { const found = findSelector(state, "model"); diff --git a/src/config/schema/agy-acp-references.ts b/src/config/schema/agy-acp-references.ts index e9a9c02323e..9160751e20d 100644 --- a/src/config/schema/agy-acp-references.ts +++ b/src/config/schema/agy-acp-references.ts @@ -41,7 +41,7 @@ export interface ConfigLike { export interface AgyAcpConfigIssue { path: (string | number)[]; message: string } const isRecord = (value: unknown): value is Record => !!value && typeof value === "object" && !Array.isArray(value); -const GEMINI_ID = /^gemini[-.]/i; +const GEMINI_ID = /^(?:gemini|claude)[-.]/i; const EFFORT_SUFFIX = /(?:[-@:](?:minimal|low|medium|high|xhigh|max|none))$/i; export function isAgyAcpProvider(name: string, provider: unknown): boolean { @@ -173,17 +173,17 @@ export function agyAcpProviderFieldIssues(config: ConfigLike): AgyAcpConfigIssue if (Array.isArray(provider.models)) { provider.models.forEach((model, i) => { if (typeof model !== "string" || !GEMINI_ID.test(model)) { - issues.push({ path: ["providers", name, "models", i], message: "The Antigravity CLI (ACP) provider serves Gemini models only." }); + issues.push({ path: ["providers", name, "models", i], message: "The Antigravity CLI (ACP) provider serves Gemini and Claude models only." }); } }); } if (isRecord(provider.modelAliases)) { for (const native of Object.keys(provider.modelAliases)) { - if (!GEMINI_ID.test(native)) issues.push({ path: ["providers", name, "modelAliases", native], message: "The Antigravity CLI (ACP) provider serves Gemini models only." }); + if (!GEMINI_ID.test(native)) issues.push({ path: ["providers", name, "modelAliases", native], message: "The Antigravity CLI (ACP) provider serves Gemini and Claude models only." }); } } if (provider.defaultModel !== undefined && (typeof provider.defaultModel !== "string" || !GEMINI_ID.test(provider.defaultModel))) { - issues.push({ path: at("defaultModel"), message: "The Antigravity CLI (ACP) provider serves Gemini models only." }); + issues.push({ path: at("defaultModel"), message: "The Antigravity CLI (ACP) provider serves Gemini and Claude models only." }); } } return issues; @@ -196,7 +196,7 @@ export function agyAcpConfigIssues(config: ConfigLike): AgyAcpConfigIssue[] { const issues = agyAcpProviderFieldIssues(config); for (const row of customModelEntries(config)) { if (acp.has(row.provider) && (typeof row.modelId !== "string" || !GEMINI_ID.test(row.modelId))) { - issues.push({ path: ["customModels", row.index, "modelId"], message: "The Antigravity CLI (ACP) provider serves Gemini models only." }); + issues.push({ path: ["customModels", row.index, "modelId"], message: "The Antigravity CLI (ACP) provider serves Gemini and Claude models only." }); } } for (const [id, combo] of comboEntries(config)) { diff --git a/src/providers/registry/agy-acp-models.ts b/src/providers/registry/agy-acp-models.ts index f2bfb98d11d..ef5a9edca0c 100644 --- a/src/providers/registry/agy-acp-models.ts +++ b/src/providers/registry/agy-acp-models.ts @@ -1,3 +1,15 @@ /** Static catalog metadata shared by registry derivation and structural config validation. */ export const AGY_ACP_DEFAULT_MODEL = "gemini-3.8-flash"; -export const AGY_ACP_SEED_MODELS = [AGY_ACP_DEFAULT_MODEL, "gemini-4-argon", "gemini-3.7-flash"] as const; +export const AGY_ACP_SEED_MODELS = [ + AGY_ACP_DEFAULT_MODEL, + "gemini-4-neon", + "gemini-4-carbon", + "gemini-4-argon", + "gemini-4-hydrogen", + "gemini-3.7-flash", + "gemini-pro-orchestrator-neon", + "gemini-pro-orchestrator", + "gemini-pro-orchestrator-argon", + "claude-opus-5-5", + "claude-sonnet-5-5", +] as const; diff --git a/src/providers/registry/entries-extended.ts b/src/providers/registry/entries-extended.ts index 139c610b536..547916446ab 100644 --- a/src/providers/registry/entries-extended.ts +++ b/src/providers/registry/entries-extended.ts @@ -1954,10 +1954,22 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ // Static seed; the ACP model options the CLI advertises at turn time decide what is accepted. models: [...AGY_ACP_SEED_MODELS], liveModels: false, - modelContextWindows: { "gemini-3.8-flash": 1_048_576, "gemini-4-argon": 1_048_576, "gemini-3.7-flash": 1_048_576 }, + modelContextWindows: { + "gemini-3.8-flash": 1_048_576, + "gemini-4-neon": 1_048_576, + "gemini-4-carbon": 1_048_576, + "gemini-4-argon": 1_048_576, + "gemini-4-hydrogen": 1_048_576, + "gemini-3.7-flash": 1_048_576, + "gemini-pro-orchestrator-neon": 1_048_576, + "gemini-pro-orchestrator": 1_048_576, + "gemini-pro-orchestrator-argon": 1_048_576, + "claude-opus-5-5": 1_000_000, + "claude-sonnet-5-5": 1_000_000, + }, // ACP prompts carry text only; client function tools are not offered to the model. inputModalities: ["text"], reasoningEfforts: ["low", "medium", "high", "xhigh", "max"], - note: "Drives the official Antigravity CLI (`agy acp`, 1.5.3 or newer) as a local child process over the Agent Client Protocol. The CLI owns its Google sign-in (`agy acp --login`); OpenCodex never reads or stores it, so no key or account belongs on this row. Google permits this only for interactive, user-directed use: OpenCodex refuses subagent, spawned-thread and Codex memory turns, combo members and decision calls, subagent-fallback routing and requests classified as remote from the observed connection. An undeclared loopback relay that forwards no recognized forwarding headers can appear local. On the public listener, declare a reverse proxy in dashboardTrustedProxy or keep this port out of the relay. OpenCodex serves Gemini models only. Use a Gemini API key or Vertex AI for programmatic or shared workloads. Each turn runs in an empty private workspace with `--sandbox`, every permission request is refused, and client tools are not offered; allow rules in your own agy settings still apply.", + note: "Drives the official Antigravity CLI (`agy acp`, 1.5.3 or newer) as a local child process over the Agent Client Protocol. The CLI owns its Google sign-in (`agy acp --login`); OpenCodex never reads or stores it, so no key or account belongs on this row. Google permits this only for interactive, user-directed use: OpenCodex refuses subagent, spawned-thread and Codex memory turns, combo members and decision calls, subagent-fallback routing and requests classified as remote from the observed connection. An undeclared loopback relay that forwards no recognized forwarding headers can appear local. On the public listener, declare a reverse proxy in dashboardTrustedProxy or keep this port out of the relay. OpenCodex serves Gemini and Claude models only. Use a Gemini API key or Vertex AI for programmatic or shared workloads. Each turn runs in an empty private workspace with `--sandbox`, every permission request is refused, and client tools are not offered; allow rules in your own agy settings still apply.", }, ]; diff --git a/structure/adapters/registry.md b/structure/adapters/registry.md index 83ef6d842f1..16c2df63efc 100644 --- a/structure/adapters/registry.md +++ b/structure/adapters/registry.md @@ -64,7 +64,7 @@ The shared `src/adapters/coding-agent/turn.ts` calls the synchronous `IncomingMe refuses ACP before any request. Key-optional LiteLLM still accepts a key or an environment reference. Structural config validation (`src/config/schema/agy-acp-references.ts`) shares the static model roster in `src/providers/registry/agy-acp-models.ts` with the registry and refuses keys, pools, account settings, - non-Gemini models and any use as a combo target, a combo's `decisionModel`, a subagent fallback, a managed subagent default, automatic compaction, a `memoryModels` phase or the + non-Gemini/Claude models and any use as a combo target, a combo's `decisionModel`, a subagent fallback, a managed subagent default, automatic compaction, a `memoryModels` phase or the `shadowCallIntercept` target. Validation masks credential-shaped diagnostic path segments. A disk read drops an ACP memory phase and ACP subagent fallback entries, disables an ACP shadow-call target or managed subagent default sync, and removes the automatic trigger from an ACP compaction override. Per-model fallback chains emptied by the repair are removed individually. File diagnostics @@ -93,9 +93,9 @@ The shared `src/adapters/coding-agent/turn.ts` calls the synchronous `IncomingMe Compact turns are refused before reasoning retention can write an archive. In a combo, the preflight refusal excludes the candidate without treating it as an attempted send. Each `session/prompt` reserves and reports one physical inference send from - the shared request budget, including a retried turn. Model selection is phase-aware and fails closed when the Gemini model is not + the shared request budget, including a retried turn. Model selection is phase-aware and fails closed when the selected Gemini or Claude model is not confirmed against the current complete selector, including after a reply that reuses an opaque model ID. - Explicit non-Gemini evidence in the model ID or label invalidates the selection. The adapter checks the model and thinking level again after processing all complete frames in the current stdout batch and before spending the dispatch permit. + Explicit disallowed or contradictory model-family evidence in the model ID or label invalidates the selection. The adapter checks the model and thinking level again after processing all complete frames in the current stdout batch and before spending the dispatch permit. Selection rejects duplicate setting IDs, oversized snapshots and nested groups. The adapter ignores updates until it has a session ID and accepts updates only for that session. Permission requests are answered `cancelled`. Selection errors use fixed text. Answer and reasoning diff --git a/tests/adapters/agy-acp-adapter.test.ts b/tests/adapters/agy-acp-adapter.test.ts index 7cbe6cc7767..0a871dcfc89 100644 --- a/tests/adapters/agy-acp-adapter.test.ts +++ b/tests/adapters/agy-acp-adapter.test.ts @@ -216,12 +216,19 @@ describe("agy acp turn", () => { }); test.each([ - ["gemini-3.8-flash", "Claude Opus 5.5", false], - ["claude-opus-5-5", "Gemini 3.8 Flash", false], - ["gemini-3.8-flash", "Recommended", true], - ["opaque", "Gemini 3.8 Flash", true], - ] as const)("requires consistent Gemini evidence for %s / %s", async (value, name, allowed) => { - const h = await run(script(undefined, { initial: [modelOption(value, [], { options: [{ value, name }] })] })); + ["gemini-3.8-flash", "GPT-5", "gemini-3.8-flash", false], + ["gpt-5", "Gemini 3.8 Flash", "gemini-3.8-flash", false], + ["openai/gpt-4o", "Claude Opus 5.5", "claude-opus-5-5", false], + ["gemini-a/claude-x", "Gemini A", "gemini-a", false], + ["provider/gpt-5/claude-x", "Claude X", "claude-x", false], + ["gemini-3.8-flash", "Claude Opus 5.5", "claude-opus-5-5", false], + ["claude-opus-5-5", "Gemini 3.8 Flash", "claude-opus-5-5", false], + ["claude-opus-5-5", "Claude Opus 5.5", "claude-opus-5-5", true], + ["opaque-claude", "Claude Opus 5.5", "claude-opus-5-5", true], + ["gemini-3.8-flash", "Recommended", "gemini-3.8-flash", true], + ["opaque", "Gemini 3.8 Flash", "gemini-3.8-flash", true], + ] as const)("requires consistent Gemini/Claude evidence for %s / %s (%s)", async (value, name, modelId, allowed) => { + const h = await run(script(undefined, { initial: [modelOption(value, [], { options: [{ value, name }] })] }), { parsed: parsed({ modelId }) }); expect(methods(h).includes("session/prompt")).toBe(allowed); expect(terminal(h)).toEqual(allowed ? [{ type: "done" }] : [expect.objectContaining({ code: "agy_acp_model_not_offered" })]); }); @@ -654,7 +661,7 @@ describe("agy acp turn", () => { const agent = script(undefined, { initial: [model, thought] }); const modelError = await run(agent, { parsed: parsed({ modelId: "gemini-" + adminShape }) }); const thoughtError = await run(agent, { parsed: parsed({}, "max") }); - expect(terminal(modelError)[0]).toMatchObject({ message: "The requested Gemini model is not offered by this Antigravity CLI." }); + expect(terminal(modelError)[0]).toMatchObject({ message: "The requested model is not offered by this Antigravity CLI." }); expect(terminal(thoughtError)[0]).toMatchObject({ message: "The requested reasoning effort is not offered by this Antigravity CLI." }); }); @@ -962,18 +969,24 @@ describe("agy acp turn", () => { expect(terminal(h)).toEqual([{ type: "done" }]); }); - test("Gemini only: a non-Gemini request never spawns and an unoffered model returns a fixed error", async () => { - const claude = await run(script(), { parsed: parsed({ modelId: "claude-opus-5-5" }) }); - expect(claude.spawned).toBe(0); - expect(errorCode(claude)).toBe("agy_acp_model_not_gemini"); + test("Gemini and Claude only: an unsupported model request never spawns, Claude succeeds, and an unoffered model returns a fixed error", async () => { + const gpt = await run(script(), { parsed: parsed({ modelId: "gpt-5" }) }); + expect(gpt.spawned).toBe(0); + expect(errorCode(gpt)).toBe("agy_acp_model_not_gemini"); + const claude = await run( + script(undefined, { initial: [modelOption("gemini-3.8-flash", OFFERED)] }), + { parsed: parsed({ modelId: "claude-opus-5-5" }) }, + ); + expect(claude.sent[2]!.params).toEqual({ sessionId: "s1", configId: "model", value: "claude-opus-5-5" }); + expect(terminal(claude)).toEqual([{ type: "done" }]); const missing = await run(script(), { parsed: parsed({ modelId: "gemini-9-ultra" }) }); const error = terminal(missing)[0] as { status: number; code: string; message: string }; expect(error).toMatchObject({ status: 400, code: "agy_acp_model_not_offered" }); - expect(error.message).toBe("The requested Gemini model is not offered by this Antigravity CLI."); + expect(error.message).toBe("The requested model is not offered by this Antigravity CLI."); expect(methods(missing)).not.toContain("session/prompt"); }); - test("the CLI's non-Gemini default is never used", async () => { + test("the CLI's default is never used when another model is requested", async () => { const h = await run(script(undefined, { initial: [modelOption("claude-opus-5-5", OFFERED)] })); // The requested Gemini model is selected instead, then proved. expect(h.sent[2]!.params.value).toBe("gemini-3.8-flash"); @@ -998,7 +1011,7 @@ describe("agy acp turn", () => { for (const h of [unknown, none]) expect(methods(h)).not.toContain("session/prompt"); }); - test("a mid-turn switch to a non-Gemini model, or a removed selector, cancels the turn", async () => { + test("a mid-turn switch to a different model, or a removed selector, cancels the turn", async () => { for (const replacement of [[modelOption("claude-opus-5-5", OFFERED)], [thoughtOption("high")]]) { const h = await run(script((frame, api) => { if (frame.method !== "session/prompt") return; diff --git a/tests/adapters/agy-acp-protocol.test.ts b/tests/adapters/agy-acp-protocol.test.ts index b4bd03f28c7..938d750f08a 100644 --- a/tests/adapters/agy-acp-protocol.test.ts +++ b/tests/adapters/agy-acp-protocol.test.ts @@ -42,7 +42,7 @@ describe("frames", () => { }); }); -describe("config options and the Gemini proof", () => { +describe("config options and the Gemini/Claude proof", () => { const state = (current: string, values: string[]) => parseConfigOptions([{ id: "model", name: "Model", category: "model", type: "select", currentValue: current, options: values.map(value => ({ value, name: value })) }])!; test("matching is exact first, then normalized value or name; ambiguity is refused", () => { @@ -54,13 +54,15 @@ describe("config options and the Gemini proof", () => { }); test("phase-aware proof", () => { - const s = state("gemini-a", ["gemini-a", "gemini-b", "claude-x"]); - // initial: the requested option need not be current yet. + const s = state("gemini-a", ["gemini-a", "gemini-b", "claude-x", "gpt-x"]); + // initial: the requested option need not be current yet; Gemini and Claude are allowed, others rejected. expect(proveModel(s, "initial", "gemini-b")).toMatchObject({ ok: true, target: { value: "gemini-b" } }); - expect(proveModel(s, "initial", "claude-x")).toEqual({ ok: false, reason: "requested_not_offered" }); - // selected: the current value must be the requested target. + expect(proveModel(s, "initial", "claude-x")).toMatchObject({ ok: true, target: { value: "claude-x" } }); + expect(proveModel(s, "initial", "gpt-x")).toEqual({ ok: false, reason: "requested_not_offered" }); + // selected: the current value must be the requested target (or an allowed family when unrequested). expect(proveModel(s, "selected", "gemini-b")).toEqual({ ok: false, reason: "not_requested" }); - expect(proveModel(state("claude-x", ["gemini-a", "claude-x"]), "selected", undefined)).toEqual({ ok: false, reason: "not_gemini" }); + expect(proveModel(state("claude-x", ["gemini-a", "claude-x"]), "selected", undefined)).toMatchObject({ ok: true, target: { value: "claude-x" } }); + expect(proveModel(state("gpt-x", ["gemini-a", "gpt-x"]), "selected", undefined)).toEqual({ ok: false, reason: "not_gemini" }); expect(proveModel(state("??", ["gemini-a"]), "pending", "gemini-a")).toEqual({ ok: false, reason: "unknown_current" }); expect(proveModel([], "selected", "gemini-a")).toEqual({ ok: false, reason: "no_selector" }); }); diff --git a/tests/cli/cli-init-port.test.ts b/tests/cli/cli-init-port.test.ts index 12e7cf45424..32fc7e54cb4 100644 --- a/tests/cli/cli-init-port.test.ts +++ b/tests/cli/cli-init-port.test.ts @@ -77,9 +77,9 @@ describe("setup port validation", () => { const choice = providers.findIndex(provider => provider.id === "antigravity-acp") + 1; expect(choice).toBeGreaterThan(0); const run = await runWizard([ - ["Select default provider (number):", String(choice)], ["Default model", "claude-test"], [PORT_PROMPT, ""], + ["Select default provider (number):", String(choice)], ["Default model", "gpt-test"], [PORT_PROMPT, ""], ]); - expect(run.stderr).toContain("providers.antigravity-acp.defaultModel: The Antigravity CLI (ACP) provider serves Gemini models only."); + expect(run.stderr).toContain("providers.antigravity-acp.defaultModel: The Antigravity CLI (ACP) provider serves Gemini and Claude models only."); expect(run.exitCode).toBe(1); expect(run.config).toBeUndefined(); }, 30_000); diff --git a/tests/config/agy-acp-config.test.ts b/tests/config/agy-acp-config.test.ts index 15d32ca975f..a8dcbea1365 100644 --- a/tests/config/agy-acp-config.test.ts +++ b/tests/config/agy-acp-config.test.ts @@ -50,7 +50,7 @@ describe("antigravity-acp configuration", () => { const aliasKey = "sk-proj-" + "q".repeat(44); const key = "fixture.opaque-key"; const raw = config({}, { "local-agy": { - ...acp, apiKey: key, defaultModel: "claude-opus", models: ["claude-opus", ...acp.models, "gpt-example"], + ...acp, apiKey: key, defaultModel: "gpt-example", models: ["gpt-example", ...acp.models, "deepseek-example"], modelAliases: { [aliasKey]: "ignored", "gemini-3.8-flash": "local-flash" }, } }); expect(messages(validateConfigCandidate(raw))).toContain("providers.local-agy.apiKey"); @@ -252,10 +252,10 @@ describe("antigravity-acp configuration", () => { expect(validateConfigCandidate(config({}, { "antigravity-acp": { ...acp, apiKey: "" } })).ok).toBe(true); }); - test("Gemini models and aliases only, on the canonical row and on a custom agy-acp row", () => { - expect(messages(validateConfigCandidate(config({}, { "antigravity-acp": { ...acp, models: ["claude-opus-5-5"] } })))).toContain("Gemini models only"); - expect(messages(validateConfigCandidate(config({}, { "my-agy": { ...acp, models: ["gpt-6-sol"] } })))).toContain("Gemini models only"); - expect(messages(validateConfigCandidate(config({}, { "antigravity-acp": { ...acp, modelAliases: { "claude-x": "cx" } } })))).toContain("Gemini models only"); + test("Gemini and Claude models and aliases only, on the canonical row and on a custom agy-acp row", () => { + expect(validateConfigCandidate(config({}, { "antigravity-acp": { ...acp, models: ["claude-opus-5-5"] } })).ok).toBe(true); + expect(messages(validateConfigCandidate(config({}, { "my-agy": { ...acp, models: ["gpt-6-sol"] } })))).toContain("Gemini and Claude models only"); + expect(messages(validateConfigCandidate(config({}, { "antigravity-acp": { ...acp, modelAliases: { "gpt-x": "gx" } } })))).toContain("Gemini and Claude models only"); // A stale canonical row saved with another adapter is still the ACP provider. expect(messages(validateConfigCandidate(config({}, { "antigravity-acp": { ...acp, adapter: "google", apiKey: "AIza-test" } })))).toContain("uses the CLI's own sign-in"); }); @@ -408,7 +408,7 @@ describe("antigravity-acp configuration", () => { subagentModelFallback: ["gemini-9-extra"], customModels: [{ provider: "antigravity-acp", modelId: "gemini-9-extra" }], })))).toContain("cannot be a subagent fallback"); - expect(messages(validateConfigCandidate(config({ customModels: [{ provider: "antigravity-acp", modelId: "claude-x" }] })))).toContain("Gemini models only"); + expect(messages(validateConfigCandidate(config({ customModels: [{ provider: "antigravity-acp", modelId: "gpt-x" }] })))).toContain("Gemini and Claude models only"); // Provider and model aliases are matched case-insensitively by the router. expect(messages(validateConfigCandidate(config({ subagentModelFallback: ["AGY/gemini-3.8-flash"] }, { "antigravity-acp": { ...acp, alias: "agy" } })))).toContain("cannot be a subagent fallback"); expect(messages(validateConfigCandidate(config({ subagentModelFallback: ["Flash-ACP"] }, { "antigravity-acp": { ...acp, modelAliases: { "gemini-3.8-flash": "flash-acp" } } })))).toContain("cannot be a subagent fallback"); From e5662cdf80d0de42b1b4340d4ee818eda1c1521c Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:49:51 +0900 Subject: [PATCH 21/64] feat(agy-acp): relay Codex host tools and multimodal conversation history (#9193) * feat(agy-acp): relay interactive host tools and multimodal conversation history * fix(agy-acp): retain inline images and captured calls across replay boundaries * fix(agy-acp): drop failed/cancelled same-batch tool calls by ID and bound inline image bytes * fix(agy-acp): validate image base64/MIME, cap serialized prompt frame bytes, and lock tool capture after prompt reply Co-authored-by: ethorxmomo777 <246461029+ethorxmomo777@users.noreply.github.com> --------- Co-authored-by: ethorxmomo777 <246461029+ethorxmomo777@users.noreply.github.com> --- .../content/docs/es/guides/api-key-catalog.md | 3 +- .../content/docs/guides/api-key-catalog.md | 4 +- src/adapters/agy-acp/acp.ts | 163 +++++++++++-- src/adapters/agy-acp/adapter.ts | 120 ++++++++- src/adapters/agy-acp/client-tools.ts | 51 ++++ structure/adapters/registry.md | 8 +- tests/adapters/agy-acp-adapter.test.ts | 230 +++++++++++++++++- 7 files changed, 538 insertions(+), 41 deletions(-) create mode 100644 src/adapters/agy-acp/client-tools.ts diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index 0c12f312948..0870ae87e80 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -407,6 +407,8 @@ OpenCodex puede usar una suscripción de Google Antigravity a través de la prop } ``` +En un chat interactivo de Codex, Gemini puede solicitar las herramientas que ofrece ese chat, incluidas las del proyecto y las aplicaciones conectadas. Codex ejecuta la llamada con sus permisos habituales y devuelve el resultado en el mismo chat. Los adjuntos y las imágenes devueltas por herramientas como `view_image` requieren entrada de imágenes tanto en la configuración del modelo de Codex como en la sesión ACP. + - **Requisitos:** Antigravity CLI 1.5.3 o posterior en `PATH` (o `OPENCODEX_AGY_BIN` con su ruta absoluta), con la sesión iniciada una vez en el host del proxy mediante `agy acp --login` o una sesión interactiva de `agy`. Si falla el inicio de sesión antes de comenzar la respuesta, la respuesta HTTP es 401 con el código `agy_login_required`. Si la respuesta ya se está transmitiendo, el flujo de eventos incluye `agy_login_required`. - **Sin credenciales guardadas:** la CLI es dueña de su inicio de sesión de Google. OpenCodex nunca lo lee, lo guarda ni lo reenvía, y la fila rechaza una clave API, un grupo de claves, la conmutación de cuentas o un ajuste OAuth. Hay una sola cuenta, la de la CLI, y no hay rotación. Al seleccionar este preajuste en `ocx init`, se omite la pregunta sobre la clave API. `ocx login antigravity-acp` muestra el comando para iniciar sesión en el host. - **Solo uso interactivo:** las respuestas del personal de Google en el foro de desarrolladores permiten que una aplicación personal inicie el binario oficial `agy acp` para la propia cuenta del usuario cuando el uso es interactivo y dirigido por el usuario, no un grupo de trabajadores desatendido ni un bucle de agente automatizado, y remiten las cargas programáticas a una clave API de Gemini o a Vertex AI ([respuesta del foro](https://discuss.ai.google.dev/t/tos-clarification-is-t3-code-official-antigravity-acp-agent-permitted-under-the-antigravity-terms-of-service/192027/2), [respuesta del foro](https://discuss.ai.google.dev/t/policy-question-omp-hosting-unmodified-antigravity-acp-for-one-user/199753)). OpenCodex aplica lo que puede saber con certeza: rechaza con HTTP 403 `agy_acp_interactive_only` un turno de subagente de Codex (`x-codex-parent-thread-id`), un turno que Codex marca como hilo generado o como su proceso de memoria, un miembro de combo, la llamada interna de decisión de un combo y una ruta elegida por la reserva de subagentes, y la configuración rechaza este proveedor como destino de combo, como `decisionModel` de un combo, como reserva de subagentes, como modelo predeterminado de subagentes administrados, como destino de compactación automática, como fase de `memoryModels` o como destino de `shadowCallIntercept`. La compactación manual sí admite ACP. @@ -419,7 +421,6 @@ OpenCodex puede usar una suscripción de Google Antigravity a través de la prop o a que se termine el árbol de procesos y se cierre el proceso principal en Windows, antes de eliminar el espacio de trabajo. Si no puede confirmar la limpieza, registra una advertencia, conserva el espacio de trabajo y da por fallido el turno afectado. Los espacios de trabajo conservados pueden acumularse tras fallos repetidos. -- **Solo texto:** los prompts de ACP llevan texto, así que las herramientas de función del cliente y las imágenes no se ofrecen al modelo, y el uso de herramientas propio de la CLI queda dentro de la CLI. diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 7592380f139..714d4dc8b20 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -913,6 +913,8 @@ once per turn and talks to it over the Agent Client Protocol on stdin and stdout } ``` +In an interactive Codex chat, Gemini can request tools advertised by that chat, including project tools and connected apps. Codex executes the call with its usual approvals and returns the result in the same chat. Inline attachments and images returned by tools such as `view_image` require image input in both the selected Codex model entry and the ACP session. + - **Prerequisites:** Antigravity CLI 1.5.3 or newer on `PATH` (or `OPENCODEX_AGY_BIN` set to its absolute path), signed in once on the proxy host with `agy acp --login` or an interactive `agy` session. A sign-in failure returns HTTP 401 with code `agy_login_required` before the response starts. If the response is already streaming, @@ -952,8 +954,6 @@ once per turn and talks to it over the Agent Client Protocol on stdin and stdout for its leader and process group on POSIX, or for tree termination and leader closure on Windows, before removing the workspace. If cleanup cannot be confirmed, OpenCodex logs a warning, retains the workspace and fails any affected turn. Retained workspaces can accumulate after repeated failures. -- **Text only:** ACP prompts carry text, so client function tools and images are not offered to the model, and the - CLI's own tool use stays inside the CLI. ## A6API credit quota diff --git a/src/adapters/agy-acp/acp.ts b/src/adapters/agy-acp/acp.ts index aee9b955e18..5c13b0396bf 100644 --- a/src/adapters/agy-acp/acp.ts +++ b/src/adapters/agy-acp/acp.ts @@ -12,6 +12,7 @@ * directions may reuse an id), stop reasons map through a complete terminal table instead of passing * through, and nothing child-authored ever reaches an error message. */ +import { parseDataUrl } from "../image"; import type { AdapterEvent, OcxParsedRequest, OcxToolCall, OcxUsage } from "../../types"; /** Hard ceiling on a single buffered stdout line. */ @@ -20,6 +21,10 @@ export const MAX_ACP_LINE_BYTES = 8 * 1024 * 1024; export const MAX_ACP_TOTAL_BYTES = 64 * 1024 * 1024; /** Ceiling on the flattened conversation handed to one ACP prompt. */ export const MAX_ACP_PROMPT_CHARS = 200_000; +/** Hard ceiling on base64-encoded bytes for one inline ACP image block. */ +export const MAX_ACP_IMAGE_ENCODED_BYTES = 4 * 1024 * 1024; +/** Hard ceiling on aggregate base64-encoded bytes across all inline ACP image blocks in one prompt. */ +export const MAX_ACP_TOTAL_IMAGE_ENCODED_BYTES = 6 * 1024 * 1024; /** ACP v1 "Authentication required". */ export const ACP_AUTH_REQUIRED = -32000; /** JSON-RPC "Method not found". */ @@ -36,8 +41,8 @@ export function initializeFrame(id: JsonRpcId, clientVersion: string): Frame { }; } -export function sessionNewFrame(id: JsonRpcId, cwd: string, systemPrompt?: string): Frame { - const params: Frame = { cwd, mcpServers: [] }; +export function sessionNewFrame(id: JsonRpcId, cwd: string, systemPrompt?: string, mcpServers: readonly object[] = []): Frame { + const params: Frame = { cwd, mcpServers }; if (systemPrompt) params.systemPrompt = { mode: "append", content: [{ type: "text", text: systemPrompt }] }; return { jsonrpc: "2.0", id, method: "session/new", params }; } @@ -46,8 +51,8 @@ export function setConfigOptionFrame(id: JsonRpcId, sessionId: string, configId: return { jsonrpc: "2.0", id, method: "session/set_config_option", params: { sessionId, configId, value } }; } -export function sessionPromptFrame(id: JsonRpcId, sessionId: string, text: string): Frame { - return { jsonrpc: "2.0", id, method: "session/prompt", params: { sessionId, prompt: [{ type: "text", text }] } }; +export function sessionPromptFrame(id: JsonRpcId, sessionId: string, prompt: string | AcpPromptBlock[]): Frame { + return { jsonrpc: "2.0", id, method: "session/prompt", params: { sessionId, prompt: typeof prompt === "string" ? [{ type: "text", text: prompt }] : prompt } }; } export function sessionCancelFrame(sessionId: string): Frame { @@ -102,40 +107,152 @@ export function acpSystemText(parsed: OcxParsedRequest): string { return parsed.context.systemPrompt?.filter(line => line.trim().length > 0).join("\n") ?? ""; } +/** Keep both ends of a priority block and preserve image placeholders as indivisible units. */ +function clipPromptBlock(text: string, limit: number, imagePattern?: RegExp): string { + if (text.length <= limit) return text; + const cut = "\n[...truncated...]\n"; + const images = imagePattern ? Array.from(text.matchAll(imagePattern)) : []; + const imageChars = images.reduce((sum, image) => sum + image[0].length, 0); + const half = Math.floor((limit - cut.length - imageChars) / 2); + if (half < 1) throw new UnsupportedAcpMedia("The inline images exceed the ACP replay budget."); + let left = half; + let right = text.length - half; + const middle: string[] = []; + for (const image of images) { + const start = image.index; + const end = start + image[0].length; + if (end <= left || start >= right) continue; + left = Math.min(left, start); + right = Math.max(right, end); + middle.push(image[0]); + } + return text.slice(0, left) + cut + middle.join("") + text.slice(right); +} + /** * Flatten the conversation into the single text block one ACP prompt carries. ACP has no * multi-message history on session/prompt. System text is included only when the CLI did not * advertise `sessionCapabilities.systemPrompt` (then it travels on session/new instead, never both). */ -export function buildAcpPrompt(parsed: OcxParsedRequest, includeSystem: boolean): string { - const blocks: string[] = []; +export function buildAcpPrompt(parsed: OcxParsedRequest, includeSystem: boolean, imagePattern?: RegExp): string { + const messages = parsed.context.messages; + const latestUser = messages.findLastIndex(message => message.role === "user"); + const blocks: { text: string; priority: boolean }[] = []; + const add = (text: string, priority = false) => blocks.push({ text, priority }); const system = includeSystem ? acpSystemText(parsed) : ""; - if (system) blocks.push(fence("System", system)); - for (const message of parsed.context.messages) { + if (system) add(fence("System", system), true); + + // A short "go ahead" can refer to both an earlier request and the preceding proposal. + const before = messages.slice(0, Math.max(latestUser, 0)); + const priorUser = before.findLastIndex(m => m.role === "user"); + const priorReply = before.findLastIndex(m => m.role === "assistant" && m.content.some(p => p.type === "text")); + const final = messages.at(-1); + const pairedCall = final?.role === "toolResult" ? messages.findLastIndex(m => + m.role === "assistant" && m.content.some(p => p.type === "toolCall" && p.id === final.toolCallId)) : -1; + for (const [index, message] of messages.entries()) { + const priority = index === latestUser || index === priorUser || index === priorReply + || index === pairedCall || index === messages.length - 1; if (message.role === "toolResult") { const body = typeof message.content === "string" ? message.content : JSON.stringify(message.content ?? ""); - blocks.push(fence("Tool", `[result id=${message.toolCallId}]\n${body}`)); + const status = message.isError ? " error" : ""; + add(fence("Tool", `[result${status} id=${message.toolCallId}]\n${body}`), priority); continue; } const parts = typeof message.content === "string" ? [] : message.content; - let text = typeof message.content === "string" - ? message.content - : parts.map(p => (p.type === "text" ? p.text : "")).filter(Boolean).join("\n"); - if (message.role === "assistant" && Array.isArray(parts)) { - const calls = parts - .filter((p): p is OcxToolCall => p.type === "toolCall") - .map(c => `[call ${c.name} id=${c.id}]\n${JSON.stringify(c.arguments ?? {})}`) - .join("\n\n"); - if (calls) text = text ? `${text}\n\n${calls}` : calls; + let text = typeof message.content === "string" ? message.content + : parts.map(p => p.type === "text" ? p.text : "").filter(Boolean).join("\n"); + if (message.role === "assistant") { + const calls = message.content.filter((p): p is OcxToolCall => p.type === "toolCall") + .map(c => `[call ${c.name} id=${c.id}]\n${JSON.stringify(c.arguments ?? {})}`); + text = [text, ...calls].filter(Boolean).join("\n\n"); } if (!text.trim()) continue; const label = message.role === "assistant" ? "Assistant" : message.role === "developer" ? "System" : "User"; - blocks.push(fence(label, text)); + add(fence(label, text), priority); + } + if (!blocks.length) return "(empty)"; + const joined = blocks.map(block => block.text).join("\n\n"); + if (joined.length <= MAX_ACP_PROMPT_CHARS) return joined; + + // Keep the decision, approved scope, paired call and outcome in order under pressure. + // Reserve space for both ends of each anchor (a command result often ends with its exit status). + const header = "[truncated]\n"; + let remaining = MAX_ACP_PROMPT_CHARS - header.length; + const count = Math.max(1, blocks.filter(b => b.priority).length); + const allowance = Math.floor(remaining / count) - 2; + const kept = new Map(); + for (const [i, block] of blocks.entries()) { + if (!block.priority) continue; + const text = clipPromptBlock(block.text, allowance, imagePattern); + kept.set(i, text); + remaining -= text.length + 2; + } + for (let i = blocks.length - 1; i >= 0; i--) { + const block = blocks[i]!; + if (block.priority || block.text.length + 2 > remaining) continue; + kept.set(i, block.text); + remaining -= block.text.length + 2; + } + return header + blocks.flatMap((_, i) => kept.has(i) ? [kept.get(i)!] : []).join("\n\n"); +} + +export type AcpPromptBlock = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; +export class UnsupportedAcpMedia extends Error {} + +const SAFE_ACP_IMAGE_MIME = /^image\/[a-z0-9.+-]+$/i; +const MAX_ACP_IMAGE_MIME_LENGTH = 64; +const VALID_ACP_IMAGE_BASE64 = /^[A-Za-z0-9+/]+={0,2}$/; + +/** Preserve the transcript positions of images, including MCP tool results. + * Compact text with the existing history policy before substituting image bytes. + */ +export function acpPromptBlocks(parsed: OcxParsedRequest, includeSystem: boolean, prefix?: string): AcpPromptBlock[] { + const images: AcpPromptBlock[] = []; + let totalImageBytes = 0; + const marker = crypto.randomUUID(); + const messages = parsed.context.messages.map(message => { + if (message.role === "assistant" || typeof message.content === "string") return message; + const content = message.content.map(part => { + if (part.type === "document") return { type: "text" as const, text: part.text }; + if (part.type !== "image") return part; + const image = parseDataUrl(part.imageUrl); + if ( + message.role === "developer" + || !image + || image.mediaType.length > MAX_ACP_IMAGE_MIME_LENGTH + || !SAFE_ACP_IMAGE_MIME.test(image.mediaType) + || !image.base64 + || image.base64.length % 4 === 1 + || (image.base64.includes("=") && image.base64.length % 4 !== 0) + || !VALID_ACP_IMAGE_BASE64.test(image.base64) + ) { + throw new UnsupportedAcpMedia("Gemini ACP requires inline image attachments in user messages or tool results."); + } + const encodedBytes = Buffer.byteLength(image.base64, "utf8"); + if (encodedBytes > MAX_ACP_IMAGE_ENCODED_BYTES) { + throw new UnsupportedAcpMedia("An inline image exceeds the ACP per-image encoded byte limit."); + } + totalImageBytes += encodedBytes; + if (totalImageBytes > MAX_ACP_TOTAL_IMAGE_ENCODED_BYTES) { + throw new UnsupportedAcpMedia("Inline images exceed the ACP aggregate encoded byte limit."); + } + const index = images.push({ type: "image", data: image.base64, mimeType: image.mediaType }) - 1; + return { type: "text" as const, text: marker + index + marker }; + }); + return { ...message, content }; + }); + const pattern = new RegExp(marker + "(\\d+)" + marker, "g"); + const text = buildAcpPrompt({ ...parsed, context: { ...parsed.context, messages } }, includeSystem, images.length ? pattern : undefined); + const blocks: AcpPromptBlock[] = []; + if (prefix) blocks.push({ type: "text", text: prefix + "\n\n" }); + let offset = 0; + for (const match of text.matchAll(pattern)) { + if (match.index > offset) blocks.push({ type: "text", text: text.slice(offset, match.index) }); + blocks.push(images[Number(match[1])]!); + offset = match.index + match[0].length; } - if (blocks.length === 0) return "(empty)"; - const joined = blocks.join("\n\n"); - // Keep the newest turns when trimming: the tail is what the agent is answering. - return joined.length > MAX_ACP_PROMPT_CHARS ? `[truncated]\n${joined.slice(joined.length - MAX_ACP_PROMPT_CHARS)}` : joined; + if (offset < text.length) blocks.push({ type: "text", text: text.slice(offset) }); + return blocks; } function chunkText(content: unknown): string { diff --git a/src/adapters/agy-acp/adapter.ts b/src/adapters/agy-acp/adapter.ts index 3056e21d81f..ceebac6ed7e 100644 --- a/src/adapters/agy-acp/adapter.ts +++ b/src/adapters/agy-acp/adapter.ts @@ -22,7 +22,7 @@ import { getConfigDir } from "../../config/paths"; import { SendBudgetExhaustedError } from "../../lib/upstream-retry"; import { ACP_AUTH_REQUIRED, MAX_ACP_LINE_BYTES, MAX_ACP_TOTAL_BYTES, acpSystemText, acpTerminal, acpUpdateToEvents, - buildAcpPrompt, classifyFrame, initializeFrame, mapAcpUsage, methodNotFoundFrame, permissionCancelledFrame, + acpPromptBlocks, UnsupportedAcpMedia, classifyFrame, initializeFrame, mapAcpUsage, methodNotFoundFrame, permissionCancelledFrame, sessionCancelFrame, sessionNewFrame, sessionPromptFrame, setConfigOptionFrame, type AcpFailureCode, type JsonRpcId, } from "./acp"; import { @@ -32,6 +32,7 @@ import { import { AGY_ACP_MIN_VERSION, AGY_INSTALL_HINT, MAX_AGY_VERSION_OUTPUT_LENGTH, probeAgyVersion, readAgyExecutable, resolveAgyBinary, type AgyVersionProbe } from "./binary"; import { AgyAcpCleanupError, AgyAcpTreeCleanupError, agySpawnCreatedNoProcess, createTurnWorkspace, defaultAgyAcpSpawn, reapProcessTree, type AgyAcpChild, type AgyAcpSpawn, type TurnWorkspace } from "./process"; import { AcpTurnOutput } from "./output-redaction"; +import { stageClientTools } from "./client-tools"; import { agyAcpPolicyRefusal } from "./policy"; /** Identity only: the transport is stdio. Never fetched. */ @@ -217,6 +218,14 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep } try { + let tools: Awaited>; + try { + tools = await stageClientTools(parsed, workspace.tmp); + } catch { + await cleanup(workspace); + emit(invalidRequest("agy_acp_tool_catalog", "The client tool catalog could not be prepared.")); + return; + } const executable = readAgyExecutable(binary); if (incoming.abortSignal?.aborted || !executable) { await cleanup(workspace); @@ -234,7 +243,7 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep return; } } - await driveTurn({ binary: executable.path, workspace, parsed, incoming, emit, requested, thoughtWanted }); + await driveTurn({ binary: executable.path, tools, workspace, parsed, incoming, emit, requested, thoughtWanted }); } catch (error) { if (!(error instanceof AgyAcpCleanupError)) throw error; emit({ type: "error", status: 502, errorType: "upstream_error", code: "agy_acp_protocol", message: error.message }); @@ -243,10 +252,10 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep }; async function driveTurn(turn: { - binary: string; workspace: TurnWorkspace; parsed: OcxParsedRequest; incoming: IncomingMeta; + tools: Awaited>; binary: string; workspace: TurnWorkspace; parsed: OcxParsedRequest; incoming: IncomingMeta; emit: (event: AdapterEvent) => void; requested: string; thoughtWanted: readonly string[] | undefined; }): Promise { - const { workspace, parsed, incoming, emit, requested, thoughtWanted } = turn; + const { tools, workspace, parsed, incoming, emit, requested, thoughtWanted } = turn; let child: AgyAcpChild; try { child = spawnChild(turn.binary, [...AGY_ACP_ARGS], { cwd: workspace.dir, env: childEnv(workspace) }); @@ -263,12 +272,21 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep let spawnFailed = false; let sessionId: string | undefined; let systemOnSession = false; + let allowsImage = false; let state: AcpConfigOption[] = []; let target: AcpSelectValue | undefined; const { stdin, stdout, stderr } = child; let modelSetterPending = false; let prompting = false; let usage: OcxUsage | undefined; + let pendingTool: ReturnType; + let pendingToolSettleScheduled = false; + const permissionCancelledCalls = new Set(); + const rejectedToolCalls = new Set(); + type DeferredPromptOutcome = + | { kind: "done"; stopReason?: Extract, { kind: "done" }>["stopReason"]; usage?: OcxUsage } + | { kind: "cancelled" }; + let deferredPromptOutcome: DeferredPromptOutcome | undefined; let sawFrame = false; let buffer = ""; let totalBytes = 0; @@ -308,7 +326,12 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep output.flush(); } }).then(() => { - if (!aborted && !incoming.abortSignal?.aborted && terminal) emit(terminal); + if (!aborted && !incoming.abortSignal?.aborted && terminal) { + if (terminal.type === "done" && terminal.stopReason === "tool_use") { + for (const event of pendingTool?.events ?? []) emit(event); + } + emit(terminal); + } if (refusal) rejectTurn(refusal.error); else resolveTurn(); }).catch(rejectTurn); @@ -377,7 +400,15 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep if (!checkSelectedModel() || !checkSelectedThinking()) return; const refuse = (error: unknown): void => finish(undefined, false, { error }); try { - const prompt = buildAcpPrompt(parsed, !systemOnSession); + const prompt = acpPromptBlocks(parsed, !systemOnSession, systemOnSession ? undefined : tools.instruction); + if (!allowsImage && prompt.some(block => block.type === "image")) { + return finish(invalidRequest("unsupported_input_modality", "This ACP session did not advertise image input.")); + } + const promptId = nextId++; + const promptLine = `${JSON.stringify(sessionPromptFrame(promptId, sessionId!, prompt))}\n`; + if (Buffer.byteLength(promptLine, "utf8") > MAX_ACP_LINE_BYTES) { + return finish(invalidRequest("unsupported_input_modality", "The ACP prompt exceeds the maximum frame size.")); + } const decision = incoming.sendBudget?.reserveDispatch({ sendClass: "transient", targetKey: AGY_ACP_IDENTITY_URL }); if (decision && !decision.allowed) return refuse(new SendBudgetExhaustedError()); const permit = decision?.permit; @@ -393,7 +424,8 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep if (permit && !permit.use()) return refuse(new SendBudgetExhaustedError()); prompting = true; incoming.onPhysicalSend?.({ ordinal: 1 }); - request("prompt", id => sessionPromptFrame(id, sessionId!, prompt)); + outstanding.set(promptId, "prompt"); + stdin.write(promptLine); } catch (error) { refuse(error); } @@ -401,6 +433,7 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep const sending = permit?.execute ? permit.execute(dispatch) : dispatch(); void sending.catch(refuse).finally(() => permit?.release()); } catch (error) { + if (error instanceof UnsupportedAcpMedia) return finish(invalidRequest("unsupported_input_modality", error.message)); refuse(error); } } @@ -414,10 +447,11 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep const r = result && typeof result === "object" ? result as Record : {}; if (kind === "initialize") { if (r.protocolVersion !== 1) return fail("agy_acp_protocol", "initialize: unsupported protocol version"); - const caps = r.agentCapabilities as { sessionCapabilities?: { systemPrompt?: unknown } } | undefined; - const system = acpSystemText(parsed); + const caps = r.agentCapabilities as { promptCapabilities?: { image?: boolean }; sessionCapabilities?: { systemPrompt?: unknown } } | undefined; + allowsImage = caps?.promptCapabilities?.image === true; + const system = [acpSystemText(parsed), tools.instruction].filter(Boolean).join("\n\n"); systemOnSession = !!system && !!caps?.sessionCapabilities?.systemPrompt && typeof caps.sessionCapabilities.systemPrompt === "object"; - request("session/new", id => sessionNewFrame(id, workspace.dir, systemOnSession ? system : undefined)); + request("session/new", id => sessionNewFrame(id, workspace.dir, systemOnSession ? system : undefined, tools.servers)); return; } if (kind === "session/new") { @@ -455,16 +489,78 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep usage = mapAcpUsage(r.usage) ?? usage; const terminal = acpTerminal(r.stopReason, incoming.abortSignal?.aborted === true); if (terminal.kind === "aborted") return finish(undefined, true); - if (terminal.kind === "error") return fail(terminal.code); + if (terminal.kind === "error") { + // agy can acknowledge our cancelled permission in the same read as its captured call. + if (terminal.code === "agy_acp_cancelled" && pendingTool && permissionCancelledCalls.has(pendingTool.id)) { + deferredPromptOutcome = { kind: "cancelled" }; + return; + } + return fail(terminal.code); + } if (terminal.kind === "refusal") return finish({ type: "incomplete", reason: "content_filter", retryable: false, usage }); + if (pendingTool) { + deferredPromptOutcome = { kind: "done", stopReason: terminal.stopReason, usage }; + return; // The captured call settles after this batch of frames. + } + if (tools.required) return fail("agy_acp_protocol", "required client tool was not called"); finish({ type: "done", ...(usage ? { usage } : {}), ...(terminal.stopReason ? { stopReason: terminal.stopReason } : {}) }); } + function schedulePendingToolSettle(): void { + if (pendingToolSettleScheduled) return; + pendingToolSettleScheduled = true; + queueMicrotask(() => { + pendingToolSettleScheduled = false; + if (settled || incoming.abortSignal?.aborted) return; + if (pendingTool) { + if (!checkSelectedModel() || !checkSelectedThinking()) return; + finish({ type: "done", stopReason: "tool_use", endTurn: false, usage }); + return; + } + const deferred = deferredPromptOutcome; + deferredPromptOutcome = undefined; + if (!deferred) return; + if (deferred.kind === "cancelled") return fail("agy_acp_cancelled"); + if (tools.required) return fail("agy_acp_protocol", "required client tool was not called"); + finish({ type: "done", ...(deferred.usage ? { usage: deferred.usage } : {}), ...(deferred.stopReason ? { stopReason: deferred.stopReason } : {}) }); + }); + } + + function captureClientCall(call: unknown, permission = false): boolean { + if (!prompting || settled || incoming.abortSignal?.aborted) return false; + const record = call && typeof call === "object" ? call as Record : undefined; + const id = typeof record?.toolCallId === "string" ? record.toolCallId : undefined; + const status = record?.status; + if (id) { + if (status === "failed" || (status === "cancelled" && !permissionCancelledCalls.has(id))) { + rejectedToolCalls.add(id); + permissionCancelledCalls.delete(id); + if (pendingTool?.id === id) pendingTool = undefined; + return true; + } + if (rejectedToolCalls.has(id)) return true; + } + if (deferredPromptOutcome) return false; + const captured = tools.capture(call); + if (!captured || !checkSelectedModel()) return false; + if (permission && (!pendingTool || pendingTool.id === captured.id)) { + permissionCancelledCalls.add(captured.id); + } + if (pendingTool) return true; + pendingTool = captured; + schedulePendingToolSettle(); + return true; + } + function handle(raw: unknown): void { const frame = classifyFrame(raw); if (frame.kind === "invalid") return fail("agy_acp_protocol", "malformed frame"); if (frame.kind === "request") { + const params = frame.params as { sessionId?: unknown; toolCall?: unknown } | undefined; send(frame.method === "session/request_permission" ? permissionCancelledFrame(frame.id) : methodNotFoundFrame(frame.id)); + if (frame.method === "session/request_permission" && sessionId && params?.sessionId === sessionId) { + captureClientCall(params.toolCall, true); + } return; } if (frame.kind === "response") { @@ -485,6 +581,8 @@ export function createAgyAcpAdapter(provider: OcxProviderConfig, deps: AgyAcpDep return; } if (!prompting) return; + if ((update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") + && captureClientCall(update)) return; for (const event of acpUpdateToEvents(update)) { if (event.type !== "text_delta" && event.type !== "thinking_delta") { emit(event); diff --git a/src/adapters/agy-acp/client-tools.ts b/src/adapters/agy-acp/client-tools.ts new file mode 100644 index 00000000000..ceda4c24945 --- /dev/null +++ b/src/adapters/agy-acp/client-tools.ts @@ -0,0 +1,51 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { randomUUID } from "node:crypto"; +import type { AdapterEvent, OcxParsedRequest } from "../../types"; +import { buildCodeBuddyToolBridge, CODEBUDDY_MCP_TOOL_PREFIX, CODEBUDDY_MCP_SERVER_NAME } from "../codebuddy/tool-bridge"; +import { codeBuddyMcpInvocation } from "../coding-agent/turn"; + +// Adapt the capture-only MCP transport from OpenCodex PR 8776. The client +// executes the resulting structured call with its regular sandbox and approvals. +export async function stageClientTools(parsed: OcxParsedRequest, tmp: string) { + const bridge = buildCodeBuddyToolBridge(parsed); + const names = new Map(bridge.tools.map(tool => [ + `mcp_${CODEBUDDY_MCP_SERVER_NAME}_${tool.name}`, + { wire: bridge.emittedNameMap.get(CODEBUDDY_MCP_TOOL_PREFIX + tool.name)!, schema: tool.inputSchema }, + ])); + const servers = []; + if (names.size) { + const catalog = join(tmp, "client-tools.json"); + await writeFile(catalog, JSON.stringify(bridge.tools), { mode: 0o600, flag: "wx" }); + const helper = fileURLToPath(new URL("../codebuddy/mcp-server.ts", import.meta.url)); + servers.push({ name: CODEBUDDY_MCP_SERVER_NAME, command: process.execPath, args: codeBuddyMcpInvocation(helper, catalog), env: [] }); + } + function capture(raw: unknown): { id: string; events: AdapterEvent[] } | undefined { + if (!raw || typeof raw !== "object") return; + const call = raw as Record; + if (typeof call.name !== "string" || typeof call.toolCallId !== "string") return; + if (call.status === "failed" || call.status === "cancelled") return; + const tool = names.get(call.name); + const input = call.rawInput ?? call.args; + if (!tool || !input || typeof input !== "object" || Array.isArray(input)) return; + const args = { ...input } as Record; + const props = tool.schema.properties; + if (!(props && typeof props === "object" && Object.hasOwn(props, "toolSummary"))) delete args.toolSummary; + // Each ACP session may number calls starting at one. Responses ids must be unique across sessions. + return { id: call.toolCallId, events: [ + { type: "tool_call_start", id: "call_" + randomUUID(), name: tool.wire }, + { type: "tool_call_delta", arguments: JSON.stringify(args) }, + { type: "tool_call_end" }, + ] }; + } + const instruction = names.size ? [ + 'The user is working in the Codex App project. Use the tools of the "opencodex" MCP server for work on that project. Your own temporary directory is separate.', + 'Use one client tool at a time. Its result will appear in the conversation history. Continue from actual results; report command output and changes you have verified.', + 'This is a replay of the same App conversation. Apply the latest user request to the preceding proposal. A clear go-ahead authorizes that proposal within its scope; preserve host approvals and sandbox limits.', + 'Tool calls and results are execution records. Use the actual outputs and exit codes. When the requested work and checks are complete, return the result and end the turn. Repeat a check only if something changed or the result left a specific question unanswered.', + 'The following pairs map client tool names to their callable MCP names:', + JSON.stringify(Array.from(names, ([alias, tool]) => [tool.wire, alias])), + ].join("\n") : ""; + return { servers, instruction, required: bridge.requireToolCall, capture }; +} diff --git a/structure/adapters/registry.md b/structure/adapters/registry.md index 16c2df63efc..674fab8fbc8 100644 --- a/structure/adapters/registry.md +++ b/structure/adapters/registry.md @@ -98,6 +98,12 @@ The shared `src/adapters/coding-agent/turn.ts` calls the synchronous `IncomingMe Explicit disallowed or contradictory model-family evidence in the model ID or label invalidates the selection. The adapter checks the model and thinking level again after processing all complete frames in the current stdout batch and before spending the dispatch permit. Selection rejects duplicate setting IDs, oversized snapshots and nested groups. The adapter ignores updates until it has a session ID and accepts updates only for that session. Permission requests are answered `cancelled`. + Caller-advertised tools use the capture-only CodeBuddy MCP helper. Each leg returns at most one + matching call to the host after child cleanup; the host executes it under its own tool permissions. + Updates are tracked by call ID so a same-batch failure or non-permission cancellation drops a pending call. + Inline user and tool-result images require ACP image capability and enforce per-image and aggregate + encoded byte limits before sending `session/prompt`. Text replay under pressure keeps + the latest request, preceding proposal and paired tool result within the prompt limit. Selection errors use fixed text. Answer and reasoning deltas each pass through a bounded streaming redactor for minted OpenCodex credentials, Bearer values, OAuth token fields, and token-shaped JWT and API-key strings. Long values stay masked across frames. @@ -112,7 +118,7 @@ The shared `src/adapters/coding-agent/turn.ts` calls the synchronous `IncomingMe child can start. Retained workspaces can accumulate when cleanup repeatedly cannot be confirmed. A confirmed spawn failure without an assigned PID leaves no process to reap. Deferred startup errors are handled even if the child has no pipes. The adapter parses a final stdout reply without a trailing newline and fails an unanswered turn at EOF. - The version probe and each turn start with a fresh private workspace containing only an empty temp directory. + The probe and turn workspaces start empty. A turn with caller tools stages a private catalog in its temp directory. On POSIX, workspace removal follows confirmed leader exit and a group check returning ESRCH after SIGKILL or ESRCH. Descendants that deliberately leave the process group are outside that check. Removing the workspace exposes no pre-existing user files. Windows requires successful diff --git a/tests/adapters/agy-acp-adapter.test.ts b/tests/adapters/agy-acp-adapter.test.ts index 0a871dcfc89..071b9f8cd2a 100644 --- a/tests/adapters/agy-acp-adapter.test.ts +++ b/tests/adapters/agy-acp-adapter.test.ts @@ -10,7 +10,12 @@ import { join } from "node:path"; import { PassThrough } from "node:stream"; import { createAgyAcpAdapter, AGY_ACP_ARGS, type AgyAcpDeps } from "../../src/adapters/agy-acp/adapter"; import { clearAgyVersionCacheForTests } from "../../src/adapters/agy-acp/binary"; -import { MAX_ACP_LINE_BYTES } from "../../src/adapters/agy-acp/acp"; +import { + MAX_ACP_IMAGE_ENCODED_BYTES, + MAX_ACP_LINE_BYTES, + MAX_ACP_PROMPT_CHARS, + MAX_ACP_TOTAL_IMAGE_ENCODED_BYTES, +} from "../../src/adapters/agy-acp/acp"; import { AgyAcpTreeCleanupError, createTurnWorkspace, reapProcessTree, type AgyAcpChild } from "../../src/adapters/agy-acp/process"; import * as windowsAcl from "../../src/lib/windows-secret-acl"; import { runWithRequestPeer } from "../../src/lib/request-peer-scope"; @@ -23,6 +28,7 @@ import { removeTreeWithRetry } from "../helpers/remove-tree"; type Frame = Record; interface AgentApi { reply(id: unknown, result: unknown): void; + batch(frames: Frame[]): void; replyWithUpdate(id: unknown, result: unknown, update: Frame): void; endStdout(id?: unknown, result?: unknown): void; error(id: unknown, code: number, message: string): void; @@ -65,7 +71,7 @@ function parsed(overrides: Partial = {}, reasoning?: string): interface Harness { events: AdapterEvent[]; sent: Frame[]; spawned: number; probed: number; args: string[]; env: Record; cwd: string; removed: boolean } /** The default agent: answers every phase; `onFrame` may intercept a frame first. */ -function script(onFrame?: (frame: Frame, api: AgentApi, state: { config: Frame[] }) => boolean | void, options: { initial?: Frame[]; systemPrompt?: boolean; stopReason?: string } = {}) { +function script(onFrame?: (frame: Frame, api: AgentApi, state: { config: Frame[] }) => boolean | void, options: { initial?: Frame[]; systemPrompt?: boolean; image?: boolean; stopReason?: string } = {}) { return (child: FakeChild, sent: Frame[]) => { const state = { config: options.initial ?? [modelOption("gemini-3.8-flash", OFFERED), thoughtOption("high")] }; const encode = (frame: Frame) => `${JSON.stringify(frame)}\n`; @@ -73,6 +79,7 @@ function script(onFrame?: (frame: Frame, api: AgentApi, state: { config: Frame[] const updateFrame = (update: Frame, sessionId = "s1") => ({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update } }); const api: AgentApi = { reply: (id, result) => write({ jsonrpc: "2.0", id, result }), + batch: frames => child.stdout.write(frames.map(encode).join("")), replyWithUpdate: (id, result, update) => child.stdout.write(encode({ jsonrpc: "2.0", id, result }) + encode(updateFrame(update))), endStdout: (id, result) => child.stdout.end(id === undefined ? "" : JSON.stringify({ jsonrpc: "2.0", id, result })), error: (id, code, message) => write({ jsonrpc: "2.0", id, error: { code, message } }), @@ -90,7 +97,7 @@ function script(onFrame?: (frame: Frame, api: AgentApi, state: { config: Frame[] buffer = buffer.slice(index + 1); sent.push(frame); if (onFrame?.(frame, api, state)) continue; - if (frame.method === "initialize") api.reply(frame.id, { protocolVersion: 1, agentCapabilities: options.systemPrompt ? { sessionCapabilities: { systemPrompt: {} } } : {} }); + if (frame.method === "initialize") api.reply(frame.id, { protocolVersion: 1, agentCapabilities: { ...(options.systemPrompt ? { sessionCapabilities: { systemPrompt: {} } } : {}), ...(options.image ? { promptCapabilities: { image: true } } : {}) } }); else if (frame.method === "session/new") api.reply(frame.id, { sessionId: "s1", configOptions: state.config }); else if (frame.method === "session/set_config_option") { state.config = state.config.map(option => option.id === frame.params.configId ? { ...option, currentValue: frame.params.value } : option); @@ -1130,3 +1137,220 @@ describe("agy acp use policy at runTurn", () => { expect(old.spawned).toBe(0); }); }); + +describe("host tools and multimodal replay", () => { + const tool = { name: "read_fixture", description: "Read a test fixture", parameters: { type: "object", properties: {} } }; + function withTool(): OcxParsedRequest { + const request = parsed(); + request.context.tools = [tool]; + return request; + } + const call = { toolCallId: "local-1", name: "mcp_opencodex_read_fixture", rawInput: { toolSummary: "Read fixture" } }; + + test("returns a declared call to the host after cleanup and replays its image result alongside the attachment", async () => { + const request = withTool(); + const first = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.request(101, "session/request_permission", { sessionId: "s1", toolCall: call }); + return true; + }), { parsed: request, deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(existsSync(first.cwd)).toBe(false); + expect(first.sent.find(frame => frame.id === 101)?.result).toEqual({ outcome: { outcome: "cancelled" } }); + const start = first.events.find(event => event.type === "tool_call_start"); + expect(start?.name).toBe(tool.name); + expect(first.events.find(event => event.type === "tool_call_delta")).toMatchObject({ arguments: "{}" }); + expect(terminal(first)).toMatchObject([{ type: "done", stopReason: "tool_use" }]); + + const image = (data: string) => ({ type: "image" as const, imageUrl: "data:image/png;base64," + data }); + request.context.messages = [ + { role: "user", content: [image("AQ==")], timestamp: 0 }, + { role: "assistant", content: [{ type: "toolCall", name: tool.name, id: start!.id, arguments: {} }], timestamp: 0 }, + { role: "toolResult", toolName: tool.name, toolCallId: start!.id, content: [image("Ag==")], timestamp: 0, isError: false }, + ]; + request.options.toolChoice = "none"; + const second = await run(script(frame => { + if (frame.method === "session/new") expect(frame.params.mcpServers).toEqual([]); + }, { image: true }), { parsed: request }); + const blocks = second.sent.find(frame => frame.method === "session/prompt")?.params.prompt; + expect(blocks.filter((block: Frame) => block.type === "image").map((block: Frame) => block.data)).toEqual(["AQ==", "Ag=="]); + expect(terminal(second)).toMatchObject([{ type: "done" }]); + const unsupported = await run(script(), { parsed: request }); + expect(errorCode(unsupported)).toBe("unsupported_input_modality"); + expect(methods(unsupported)).not.toContain("session/prompt"); + }); + + test("captures a permission request followed by its cancellation in one stdout read", async () => { + const result = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.batch([ + { jsonrpc: "2.0", id: 101, method: "session/request_permission", params: { sessionId: "s1", toolCall: call } }, + { jsonrpc: "2.0", id: frame.id, result: { stopReason: "cancelled" } }, + ]); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(terminal(result)).toMatchObject([{ type: "done", stopReason: "tool_use" }]); + expect(result.events.filter(event => event.type === "tool_call_start")).toHaveLength(1); + expect(result.sent.find(frame => frame.id === 101)?.result.outcome.outcome).toBe("cancelled"); + }); + + test("long latest user input keeps its inline images in order and checks vision capability", async () => { + const request = parsed(); + const large = { type: "text" as const, text: "x".repeat(MAX_ACP_PROMPT_CHARS) }; + const images = ["AQ==", "Ag=="].map(data => ({ type: "image" as const, imageUrl: "data:image/png;base64," + data })); + request.context.messages = [{ role: "user", timestamp: 0, content: [large, ...images, large] }]; + const result = await run(script(undefined, { image: true }), { parsed: request }); + const blocks = result.sent.find(frame => frame.method === "session/prompt")!.params.prompt as Frame[]; + expect(blocks.filter(block => block.type === "image").map(block => block.data)).toEqual(["AQ==", "Ag=="]); + expect(blocks.map(block => block.text ?? "").join("").length).toBeLessThanOrEqual(MAX_ACP_PROMPT_CHARS); + const unsupported = await run(script(), { parsed: request }); + expect(errorCode(unsupported)).toBe("unsupported_input_modality"); + expect(methods(unsupported)).not.toContain("session/prompt"); + }); + + test("a session can request only the exact tool names advertised for this turn", async () => { + const result = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.request(201, "session/request_permission", { sessionId: "s1", toolCall: { ...call, name: "shell" } }); + api.request(202, "session/request_permission", { sessionId: "another-session", toolCall: call }); + api.notify({ sessionUpdate: "tool_call", ...call, status: "failed" }); + api.reply(frame.id, { stopReason: "end_turn" }); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + for (const id of [201, 202]) { + expect(result.sent.find(frame => frame.id === id)?.result.outcome.outcome).toBe("cancelled"); + } + expect(result.events.some(event => event.type === "tool_call_start")).toBe(false); + expect(terminal(result)).toMatchObject([{ type: "done" }]); + }); + + test("discards a captured call when the model changes in the same stdout batch", async () => { + const result = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.request(201, "session/request_permission", { sessionId: "s1", toolCall: { ...call, name: "shell" } }); + api.notify({ sessionUpdate: "tool_call", ...call }); + api.notify({ sessionUpdate: "config_option_update", configOptions: [modelOption("claude-opus-5-5", OFFERED)] }); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(errorCode(result)).toBe("agy_acp_model_switched"); + expect(result.events.some(event => event.type === "tool_call_start")).toBe(false); + }); + + test("large tool output retains the scope, confirmation, call identity and final result", async () => { + const request = parsed(); + request.context.messages = [ + { role: "user", content: "Fix delta.", timestamp: 0 }, + { role: "assistant", content: [{ type: "text", text: "I will edit and test." }], timestamp: 0 }, + { role: "user", content: "Go ahead.", timestamp: 0 }, + { role: "assistant", content: [{ type: "toolCall", name: "test_delta", id: "result-1", arguments: {} }], timestamp: 0 }, + { role: "toolResult", toolName: "test_delta", toolCallId: "result-1", isError: false, timestamp: 0, + content: "start of output\n" + "a".repeat(MAX_ACP_PROMPT_CHARS * 2) + "\n3 tests passed" }, + ]; + const result = await run(script(), { parsed: request }); + const text = result.sent.find(frame => frame.method === "session/prompt")?.params.prompt[0].text; + expect(text.length).toBeLessThanOrEqual(MAX_ACP_PROMPT_CHARS); + const markers = ["Fix delta.", "I will edit and test.", "Go ahead.", "[call test_delta id=result-1]", "[result id=result-1]", "3 tests passed"]; + let end = 0; + for (const marker of markers) { + const index = text.indexOf(marker, end); + expect(index).toBeGreaterThanOrEqual(end); + end = index + marker.length; + } + }); + + test("drops a pending tool call when the same stdout batch reports it failed or non-permission cancelled", async () => { + for (const status of ["failed", "cancelled"] as const) { + const result = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.batch([ + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call", ...call } } }, + // ACP tool_call_update frequently carries only toolCallId + status. + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call_update", toolCallId: call.toolCallId, status } } }, + { jsonrpc: "2.0", id: frame.id, result: { stopReason: "end_turn" } }, + ]); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(result.events.some(event => event.type === "tool_call_start")).toBe(false); + expect(terminal(result)).toMatchObject([{ type: "done" }]); + } + }); + + test("drops a permission-captured call on same-batch failure, but preserves it on adapter-triggered cancellation", async () => { + const failed = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.batch([ + { jsonrpc: "2.0", id: 101, method: "session/request_permission", params: { sessionId: "s1", toolCall: call } }, + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call_update", toolCallId: call.toolCallId, status: "failed" } } }, + { jsonrpc: "2.0", id: frame.id, result: { stopReason: "cancelled" } }, + ]); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(failed.events.some(event => event.type === "tool_call_start")).toBe(false); + expect(errorCode(failed)).toBe("agy_acp_cancelled"); + + const cancelledAfterPermission = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.batch([ + { jsonrpc: "2.0", id: 102, method: "session/request_permission", params: { sessionId: "s1", toolCall: call } }, + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call_update", toolCallId: call.toolCallId, status: "cancelled" } } }, + { jsonrpc: "2.0", id: frame.id, result: { stopReason: "cancelled" } }, + ]); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(cancelledAfterPermission.events.filter(event => event.type === "tool_call_start")).toHaveLength(1); + expect(terminal(cancelledAfterPermission)).toMatchObject([{ type: "done", stopReason: "tool_use" }]); + }); + + test("bounds per-image and aggregate encoded image bytes before sending session/prompt", async () => { + const oversizedSingle = parsed(); + oversizedSingle.context.messages = [{ + role: "user", + timestamp: 0, + content: [{ type: "image", imageUrl: "data:image/png;base64," + "A".repeat(MAX_ACP_IMAGE_ENCODED_BYTES + 4) }], + }]; + const singleResult = await run(script(undefined, { image: true }), { parsed: oversizedSingle }); + expect(errorCode(singleResult)).toBe("unsupported_input_modality"); + expect(methods(singleResult)).not.toContain("session/prompt"); + + const halfOverAggregate = Math.floor(MAX_ACP_TOTAL_IMAGE_ENCODED_BYTES / 2) + 4; + expect(halfOverAggregate).toBeLessThanOrEqual(MAX_ACP_IMAGE_ENCODED_BYTES); + const oversizedTotal = parsed(); + oversizedTotal.context.messages = [{ + role: "user", + timestamp: 0, + content: [ + { type: "image", imageUrl: "data:image/png;base64," + "A".repeat(halfOverAggregate) }, + { type: "image", imageUrl: "data:image/png;base64," + "B".repeat(halfOverAggregate) }, + ], + }]; + const totalResult = await run(script(undefined, { image: true }), { parsed: oversizedTotal }); + expect(errorCode(totalResult)).toBe("unsupported_input_modality"); + expect(methods(totalResult)).not.toContain("session/prompt"); + + for (const badUrl of [ + "data:image/png;base64," + "\\".repeat(128), + `data:image/${"a".repeat(100)};base64,AQ==`, + ]) { + const invalid = parsed(); + invalid.context.messages = [{ role: "user", timestamp: 0, content: [{ type: "image", imageUrl: badUrl }] }]; + const res = await run(script(undefined, { image: true }), { parsed: invalid }); + expect(errorCode(res)).toBe("unsupported_input_modality"); + expect(methods(res)).not.toContain("session/prompt"); + } + }); + + test("ignores a new tool call after a deferred prompt reply when the first pending call fails in the same batch", async () => { + const secondCall = { ...call, toolCallId: "local-2" }; + const result = await run(script((frame, api) => { + if (frame.method !== "session/prompt") return; + api.batch([ + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call", ...call } } }, + { jsonrpc: "2.0", id: frame.id, result: { stopReason: "end_turn" } }, + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call_update", toolCallId: call.toolCallId, status: "failed" } } }, + { jsonrpc: "2.0", method: "session/update", params: { sessionId: "s1", update: { sessionUpdate: "tool_call", ...secondCall } } }, + ]); + return true; + }), { parsed: withTool(), deps: { createWorkspace: () => createTurnWorkspace(tmpdir() + "/test-home") } }); + expect(result.events.some(event => event.type === "tool_call_start")).toBe(false); + expect(terminal(result)).toMatchObject([{ type: "done" }]); + }); +}); From 76be5671340e540e165585a7431d096a46d0cdd8 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:50:02 +0900 Subject: [PATCH 22/64] fix(codebuddy): refuse DeepSeek native tool-call markup printed as text (#9194) * fix(codebuddy): refuse DeepSeek native tool-call markup printed as text (#8447) * fix(codebuddy): close scaffold-guard fences only on a matching CommonMark closing line * docs(codebuddy): describe the DeepSeek native tool markup in the scaffold contract (#8447) * fix(codebuddy): accept indented closing fences and hold split fence openers in the scaffold guard * fix(codebuddy): reject backtick fence openers whose info string contains a backtick * docs(codebuddy): state that only column-zero markers outside a fence trigger the scaffold refusal * fix(codebuddy): track streamed fence runs incrementally without buffering Co-authored-by: utsxvrai --------- Co-authored-by: utsxvrai --- .../content/docs/es/guides/api-key-catalog.md | 2 +- .../content/docs/guides/api-key-catalog.md | 2 +- src/adapters/codebuddy/scaffold-guard.ts | 190 ++++++++++++++---- structure/providers/chat-compat.md | 2 +- tests/providers/codebuddy-adapter.test.ts | 165 +++++++++++++++ 5 files changed, 317 insertions(+), 44 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index 0870ae87e80..8e8d21d43e7 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -301,7 +301,7 @@ OpenCodex proporciona soporte oficial para adaptadores para el código CodeBuddy - CN: [Llaves CodeBuddy CN API](https://copilot.tencent.com/profile/keys) - **Aislamiento de la región:** `codebuddy` y `codebuddy-cn` utilizan puntos finales canónicos separados (`https://www.codebuddy.ai` y `https://www.codebuddy.cn`) y entornos infantiles aislados (`CODEBUDDY_INTERNET_ENVIRONMENT=public` vs `internal`). Las credenciales son estrictamente regionales y nunca se intercambian entre entornos. La anulación de la URL base canónica falla cerrada. - **Modelo Discovery:** el proxy solicita la configuración del producto CodeBuddy (`GET {baseUrl}/v3/config`) con la clave configurada como el encabezado `X-API-Key`, y la lista en esa respuesta es la lista autorizada de modelos descubiertos: es la configuración de la cuenta propia de la clave, por lo que se demuestra que pertenece a la clave: una clave diferente o incorrecta responde al sobre anónimo sin lista en lugar de los modelos de otra cuenta. La lista autenticada es la misma lista de las impresiones CLI para `--model` (la línea "Actualmente compatible" de un inicio de sesión CLI), puede diferir del manifiesto estático incluido con el CLI, y los selectores predeterminados del proveedor (`default` para CN, `default-model` para Global) nunca aparecen en él, pero permanecen llamables: el catálogo los retiene durante el descubrimiento en vivo y en cada ruta alternativa. Al iniciar/sincronizar, el proxy vincula la lista almacenada en caché a una huella digital irreversible de la clave configurada, por lo que un conmutador de clave nunca observa una lista almacenada en caché para la clave anterior, y se degrada a la caché obsoleta de proveedor/huella digital, luego a la semilla estática en `src/providers/codebuddy-models.ts`, cuando la clave no se autentica o la solicitud falla. Los registros de fallos de detección contienen solo una categoría y un estado HTTP, sin el mensaje de la puerta de enlace o una excepción de transporte sin procesar. La solicitud de descubrimiento con credenciales no sigue a las redirecciones; una respuesta 3xx degrada la lista sin reenviar la clave a otro origen. -- **Propiedad de la herramienta y el puente de herramientas:** El CLI siempre se genera con `--tools ""` y `--strict-mcp-config`, por lo que no tiene herramientas incorporadas o configuradas por el usuario. Cuando una solicitud lleva un catálogo de herramientas Codex, el proveedor arma un puente MCP de captura solamente: el catálogo validado y la configuración MCP se escriben en un dir temp privado, el CLI se lanza con `--mcp-config` y una lista `--allowedTools` exacta, y el marco `system/init` debe informar exactamente ese servidor de puente como conectado o el giro falla cerrado. El puente anuncia las herramientas Codex y captura las llamadas propuestas, pero nunca ejecuta nada: un lote de llamadas a herramientas completado se devuelve como `function_call` elementos (nombres asignados a los nombres de cable de la solicitud, como máximo 16 llamadas por mensaje de asistente), el árbol de procesos se termina en `message_stop`, y el cliente externo Codex solo realiza aprobación, sandboxing y ejecución. Los bloques de uso de herramientas paralelos se almacenan en memoria intermedia y se devuelven como llamadas completas incluso cuando sus fragmentos se entrelazan o CodeBuddy reutiliza un índice de bloque de contenido. Un bloque que se deja abierto en el extremo de giro, un reemplazo del mismo índice antes de completar JSON argumentos, o un fragmento de argumento que no se puede atribuir a un bloque abierto falla el giro en lugar de reenviar una llamada parcial o vacía. Los resultados de la herramienta vuelven como entrada de la siguiente solicitud, y la conversación continúa. Las solicitudes sin herramientas mantienen la forma de texto y razonamiento sin formato. Si el CLI escribe una línea de control DSML `calls` no citada seguida de una línea de control `functions.*` invocada en texto o razonamiento, el OpenCodex rechaza el turno en lugar de reenviar el andamio o interpretarlo como una llamada ejecutable. DSML discutido o citado en prosa, código en línea, código cercado o ejemplos de fuente sigue siendo texto de respuesta ordinario. +- **Propiedad de la herramienta y el puente de herramientas:** El CLI siempre se genera con `--tools ""` y `--strict-mcp-config`, por lo que no tiene herramientas incorporadas o configuradas por el usuario. Cuando una solicitud lleva un catálogo de herramientas Codex, el proveedor arma un puente MCP de captura solamente: el catálogo validado y la configuración MCP se escriben en un dir temp privado, el CLI se lanza con `--mcp-config` y una lista `--allowedTools` exacta, y el marco `system/init` debe informar exactamente ese servidor de puente como conectado o el giro falla cerrado. El puente anuncia las herramientas Codex y captura las llamadas propuestas, pero nunca ejecuta nada: un lote de llamadas a herramientas completado se devuelve como `function_call` elementos (nombres asignados a los nombres de cable de la solicitud, como máximo 16 llamadas por mensaje de asistente), el árbol de procesos se termina en `message_stop`, y el cliente externo Codex solo realiza aprobación, sandboxing y ejecución. Los bloques de uso de herramientas paralelos se almacenan en memoria intermedia y se devuelven como llamadas completas incluso cuando sus fragmentos se entrelazan o CodeBuddy reutiliza un índice de bloque de contenido. Un bloque que se deja abierto en el extremo de giro, un reemplazo del mismo índice antes de completar JSON argumentos, o un fragmento de argumento que no se puede atribuir a un bloque abierto falla el giro en lugar de reenviar una llamada parcial o vacía. Los resultados de la herramienta vuelven como entrada de la siguiente solicitud, y la conversación continúa. Las solicitudes sin herramientas mantienen la forma de texto y razonamiento sin formato. Si el CLI escribe una línea de control `calls` no citada seguida de una línea de control de invocación con nombre en texto o razonamiento, ya sea en DSML (`<||DSML|| calls>` / `<||DSML|| invoke name="…">`) o en el marcado nativo de DeepSeek (`<|tool▁calls|>` / `<|tool▁invoke name="…">`), OpenCodex rechaza el turno en lugar de reenviar el andamio o interpretarlo como una llamada ejecutable. El marcado impreso nunca llega al puente de herramientas. Solo coinciden los marcadores que empiezan en la columna cero fuera de un bloque de código cercado, así que un ejemplo de cualquiera de las dos gramáticas sigue siendo texto de respuesta ordinario cuando se escribe en línea, citado, con sangría o dentro de un bloque de código cercado (la propia cerca puede tener hasta tres espacios de sangría). Un ejemplo de las dos líneas sin sangría ni cerca se rechaza aunque la prosa lo presente. - **Aplicación de elección de herramienta:** Cuando una solicitud especifica `tool_choice: "required"` o selecciona una herramienta con nombre específico, el puente espera una llamada de herramienta del modelo. Si el CLI completa el turno con texto sin formato en lugar de capturar una llamada de herramienta, el OpenCodex falla al cerrarse con un error 502 `tool_call_required` en lugar de devolver una finalización de texto no válida. - **Estado de gobierno:** Si el enrutamiento de esta superficie de automatización del proveedor detrás de un proxy para un agente de terceros satisface los términos de uso aceptable de CodeBuddy es una pregunta abierta marcada para la revisión de seguridad del mantenedor (consulte la nota de gobierno en la entrada del registro del proveedor). Trate a este proveedor como pendiente de esa revisión, y tenga en cuenta el límite de propiedad del puente de herramientas: el CLI anidado anuncia herramientas pero nunca las ejecuta, y la aprobación, el sandboxing y la ejecución permanecen con el cliente externo Codex. - **Derechos y facturación:** El proveedor utiliza la misma cuenta CodeBuddy/superficie de autenticación CLI documentada por el proveedor. La disponibilidad y la facturación de los créditos gratuitos, promocionales, de prueba o de suscripción siguen estando determinadas por el derecho de cuenta de CodeBuddy del usuario. diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 714d4dc8b20..3479e5bde6c 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -756,7 +756,7 @@ OpenCodex provides official adapter support for Tencent Cloud's CodeBuddy Code C - **Region Isolation:** `codebuddy` and `codebuddy-cn` use separate canonical endpoints (`https://www.codebuddy.ai` and `https://www.codebuddy.cn`) and isolated child environments (`CODEBUDDY_INTERNET_ENVIRONMENT=public` vs `internal`). Credentials are strictly region-scoped and never exchanged across environments. Overriding the canonical base URL fails closed. - **Model Discovery:** the proxy requests the CodeBuddy product configuration (`GET {baseUrl}/v3/config`) with the configured key as the `X-API-Key` header, and the roster in that answer is the authoritative roster of discovered models: it is the key's own account configuration, so it is proven to belong to the key — a different or wrong key answers the anonymous envelope with no roster instead of another account's models. The authenticated roster is the same list the CLI prints for `--model` (the "Currently supported" line of a signed-in CLI), can differ from the static manifest bundled with the CLI, and the vendor default selectors (`default` for CN, `default-model` for Global) never appear in it but remain callable: the catalog retains them during live discovery and on every fallback path. On start/sync the proxy binds the cached roster to an irreversible fingerprint of the configured key, so a key switch never observes a roster cached for the previous key, and degrades to the stale provider/key-fingerprint-scoped cache, then to the static seed in `src/providers/codebuddy-models.ts`, when the key does not authenticate or the request fails. Discovery failure logs contain only a category and HTTP status, without the gateway's message or a raw transport exception. The credentialed discovery request does not follow redirects; a 3xx response degrades the roster without forwarding the key to another origin. -- **Tool Ownership and the Tool Bridge:** The CLI is always spawned with `--tools ""` and `--strict-mcp-config`, so it has no built-in or user-configured tools of its own. When a request carries a Codex tool catalog, the provider arms a capture-only MCP bridge: the validated catalog and MCP config are written to a private temp dir, the CLI is launched with `--mcp-config` and an exact `--allowedTools` list, and the `system/init` frame must report exactly that bridge server as connected or the turn fails closed. The bridge advertises the Codex tools and captures proposed calls but never executes anything: a completed tool-call batch is returned as `function_call` items (names mapped back to the request's wire names, at most 16 calls per assistant message), the process tree is terminated at `message_stop`, and the external Codex client alone performs approval, sandboxing, and execution. Parallel tool-use blocks are buffered and returned as complete calls even when their fragments interleave or CodeBuddy reuses a content-block index. A block left open at turn end, a same-index replacement before complete JSON arguments, or an argument fragment that cannot be attributed to an open block fails the turn instead of forwarding a partial or empty call. Tool results come back as the next request's input, and the conversation continues. Requests without tools keep the plain text-and-reasoning shape. If the CLI writes an unquoted DSML `calls` control line followed by a `functions.*` invoke control line into text or reasoning, OpenCodex refuses the turn instead of forwarding the scaffold or interpreting it as an executable call. DSML discussed or quoted in prose, inline code, fenced code, or source examples remains ordinary answer text. +- **Tool Ownership and the Tool Bridge:** The CLI is always spawned with `--tools ""` and `--strict-mcp-config`, so it has no built-in or user-configured tools of its own. When a request carries a Codex tool catalog, the provider arms a capture-only MCP bridge: the validated catalog and MCP config are written to a private temp dir, the CLI is launched with `--mcp-config` and an exact `--allowedTools` list, and the `system/init` frame must report exactly that bridge server as connected or the turn fails closed. The bridge advertises the Codex tools and captures proposed calls but never executes anything: a completed tool-call batch is returned as `function_call` items (names mapped back to the request's wire names, at most 16 calls per assistant message), the process tree is terminated at `message_stop`, and the external Codex client alone performs approval, sandboxing, and execution. Parallel tool-use blocks are buffered and returned as complete calls even when their fragments interleave or CodeBuddy reuses a content-block index. A block left open at turn end, a same-index replacement before complete JSON arguments, or an argument fragment that cannot be attributed to an open block fails the turn instead of forwarding a partial or empty call. Tool results come back as the next request's input, and the conversation continues. Requests without tools keep the plain text-and-reasoning shape. If the CLI writes an unquoted `calls` control line followed by a named invoke control line into text or reasoning, in either DSML (`<||DSML|| calls>` / `<||DSML|| invoke name="…">`) or DeepSeek's native markup (`<|tool▁calls|>` / `<|tool▁invoke name="…">`), OpenCodex refuses the turn instead of forwarding the scaffold or interpreting it as an executable call. Printed markup never reaches the tool bridge. Only markers that start at column zero outside a fenced code block match, so an example of either grammar stays ordinary answer text when it is written inline, quoted, indented, or placed in a fenced code block (the fence itself may be indented up to three spaces). An unindented, unfenced example of the two lines is refused even when prose introduces it. - **Tool Choice Enforcement:** When a request specifies `tool_choice: "required"` or selects a specific named tool, the bridge expects a tool call from the model. If the CLI completes the turn with plain text instead of capturing a tool call, OpenCodex fails closed with a 502 `tool_call_required` error rather than returning an invalid text completion. - **Governance Status:** Whether routing this vendor automation surface behind a proxy for a third-party agent satisfies CodeBuddy's acceptable-use terms is an open question flagged for maintainer security review (see the governance note in the provider registry entry). Treat this provider as pending that review, and keep the tool bridge's ownership boundary in mind: the nested CLI advertises tools but never executes them, and approval, sandboxing, and execution remain with the external Codex client. - **Entitlements and Billing:** The provider uses the same vendor-documented CodeBuddy account/CLI authentication surface. Availability and billing of free, promotional, trial, or subscription credits remain determined by the user's CodeBuddy account entitlement. diff --git a/src/adapters/codebuddy/scaffold-guard.ts b/src/adapters/codebuddy/scaffold-guard.ts index 6f913233e1e..e62c4d651bd 100644 --- a/src/adapters/codebuddy/scaffold-guard.ts +++ b/src/adapters/codebuddy/scaffold-guard.ts @@ -3,12 +3,21 @@ import type { AdapterEvent } from "../../types"; /** Error code for a CodeBuddy turn whose output contains vendor agent scaffolding. */ export const CODEBUDDY_SCAFFOLD_ERROR_CODE = "vendor_scaffold_detected"; -// The observed control protocol uses FULLWIDTH VERTICAL LINE (U+FF5C). Detection stays +// The observed control protocols use FULLWIDTH VERTICAL LINE (U+FF5C). Detection stays // deliberately narrower than the marker spelling: a calls control line must be followed by an // invoke line with a non-empty tool name. That distinguishes an agent scaffold from prose quoting or // discussing one tag. -const DSML_CALLS_LINE = "<||dsml|| calls>"; -const DSML_INVOKE_PREFIX = "<||dsml|| invoke name=\""; +interface ScaffoldGrammar { + callsLine: string; + invokePrefix: string; +} + +const SCAFFOLD_GRAMMARS: readonly ScaffoldGrammar[] = [ + { callsLine: "<||dsml|| calls>", invokePrefix: "<||dsml|| invoke name=\"" }, + // DeepSeek's native tool markup (LOWER ONE EIGHTH BLOCK U+2581 joins the words), printed as + // text when the CLI runs with no tool catalog (#8447). + { callsLine: "<|tool▁calls|>", invokePrefix: "<|tool▁invoke name=\"" }, +]; export interface CodeBuddyScaffoldFilterResult { /** Bytes released from a suffix withheld by an earlier event on this channel. */ @@ -20,11 +29,32 @@ export interface CodeBuddyScaffoldFilterResult { fail: boolean; } +/** + * An open fenced code block (CommonMark): it closes only on a line whose fence run uses the same + * character, is at least as long as the opener, and is followed by nothing but spaces or tabs. + * `closing` tracks a candidate closing line whose remainder has not been seen yet: `run` while the + * fence run may still grow, `space` once trailing whitespace started. A backtick opener's info + * string may not contain a backtick (` ```a``` ` is an inline code span, not a fence). + */ +interface FenceState { + char: "`" | "~"; + length: number; + closing: "run" | "space" | null; + /** A backtick opener whose info string is still being read; a backtick in it voids the fence. */ + opening: boolean; +} + +interface FenceRunState { + char: "`" | "~"; + length: number; +} + interface ScanResult { safe: string; held: string; fail: boolean; - fence: "`" | "~" | null; + fence: FenceState | null; + fenceRun: FenceRunState | null; lineStart: boolean; } @@ -52,58 +82,134 @@ function prefixAtEnd(text: string, at: number, expected: string): boolean { return true; } +/** + * Classify a column-zero position against every known control grammar: a complete + * calls-plus-named-invoke sequence fails the turn, and a suffix that may still become one is held. + */ +function matchControlSequence(text: string, index: number): "fail" | "hold" | null { + let hold = false; + for (const { callsLine, invokePrefix } of SCAFFOLD_GRAMMARS) { + if (startsWithFolded(text, index, callsLine)) { + const afterCalls = index + callsLine.length; + let invokeAt = -1; + if (text[afterCalls] === "\n") invokeAt = afterCalls + 1; + else if (text[afterCalls] === "\r" && text[afterCalls + 1] === "\n") invokeAt = afterCalls + 2; + else if (afterCalls === text.length || (text[afterCalls] === "\r" && afterCalls + 1 === text.length)) { + hold = true; + continue; + } + + if (invokeAt >= 0) { + const invokeNameStart = text[invokeAt + invokePrefix.length]; + if (startsWithFolded(text, invokeAt, invokePrefix) && invokeNameStart && !/[\s"]/.test(invokeNameStart)) { + return "fail"; + } + if (invokeAt === text.length || prefixAtEnd(text, invokeAt, invokePrefix)) hold = true; + } + } else if (prefixAtEnd(text, index, callsLine)) { + hold = true; + } + } + return hold ? "hold" : null; +} + /** * Scan complete bytes and retain only a bounded suffix that can still become a control sequence. * * Control tags are recognized only at column zero and outside fenced Markdown. Inline code, * quoted strings, blockquotes, indented source, and prose all add syntax before the tag and are - * therefore forwarded unchanged. A calls line alone is harmless; refusal requires the observed - * two-line calls-plus-named-invoke grammar. + * therefore forwarded unchanged. A calls line alone is harmless; refusal requires one of the + * observed two-line calls-plus-named-invoke grammars. */ function scan( text: string, - initialFence: "`" | "~" | null, + initialFence: FenceState | null, + initialFenceRun: FenceRunState | null, initialLineStart: boolean, ): ScanResult { - let fence = initialFence; + let fence = initialFence && { ...initialFence }; + let fenceRun = initialFenceRun && { ...initialFenceRun }; let lineStart = initialLineStart; let index = 0; while (index < text.length) { - if (lineStart) { - const fenceMarkers = fence ? [fence.repeat(3)] : ["```", "~~~"]; - const completeFence = fenceMarkers.find(marker => text.startsWith(marker, index)); - if (completeFence) { - fence = fence ? null : (completeFence[0] as "`" | "~"); - index += completeFence.length; - lineStart = false; + if (fenceRun) { + const char = text[index]!; + if (char === fenceRun.char) { + fenceRun.length += 1; + index += 1; + continue; + } + const run = fenceRun; + fenceRun = null; + if (!fence && run.length >= 3) { + fence = { char: run.char, length: run.length, closing: null, opening: run.char === "`" }; + continue; + } + if (fence && run.char === fence.char && run.length >= fence.length) { + fence.closing = "run"; + continue; + } + } else if (fence?.opening) { + const char = text[index]!; + if (char === "`") fence = null; + else if (char === "\n" || char === "\r") fence.opening = false; + } else if (fence?.closing) { + const char = text[index]!; + if (fence.closing === "run" && char === fence.char) { + index += 1; continue; } - if (fenceMarkers.some(marker => prefixAtEnd(text, index, marker))) { - return { safe: text.slice(0, index), held: text.slice(index), fail: false, fence, lineStart }; + if (char === " " || char === "\t") { + fence.closing = "space"; + index += 1; + continue; + } + // A line end confirms the close; any other text makes the line ordinary fenced content. + if (char === "\n" || char === "\r") fence = null; + else fence.closing = null; + } else if (lineStart) { + // A fence line may be indented by up to three spaces; control markers stay column-zero only. + let runStart = index; + while (runStart < text.length && runStart - index < 3 && text[runStart] === " ") runStart += 1; + if (runStart === text.length) { + return { safe: text.slice(0, index), held: text.slice(index), fail: false, fence, fenceRun, lineStart }; + } + const runChar = text[runStart]; + if (runChar === "`" || runChar === "~") { + let runEnd = runStart + 1; + while (runEnd < text.length && text[runEnd] === runChar) runEnd += 1; + const runLength = runEnd - runStart; + // Track a chunk-ending fence run incrementally instead of holding its bytes in pending, + // keeping buffering O(1) and avoiding cross-channel stalls on long backtick/tilde runs. + if (runEnd === text.length && (!fence || (runChar === fence.char && runLength < fence.length))) { + fenceRun = { char: runChar, length: runLength }; + index = runEnd; + lineStart = false; + continue; + } + if (!fence && runLength >= 3) { + fence = { char: runChar, length: runLength, closing: null, opening: runChar === "`" }; + index = runEnd; + lineStart = false; + continue; + } + if (fence && runChar === fence.char && runLength >= fence.length) { + fence.closing = "run"; + index = runEnd; + lineStart = false; + continue; + } + index = runEnd; + lineStart = false; + continue; } if (!fence) { - if (startsWithFolded(text, index, DSML_CALLS_LINE)) { - const afterCalls = index + DSML_CALLS_LINE.length; - let invokeAt = -1; - if (text[afterCalls] === "\n") invokeAt = afterCalls + 1; - else if (text[afterCalls] === "\r" && text[afterCalls + 1] === "\n") invokeAt = afterCalls + 2; - else if (afterCalls === text.length || (text[afterCalls] === "\r" && afterCalls + 1 === text.length)) { - return { safe: text.slice(0, index), held: text.slice(index), fail: false, fence, lineStart }; - } - - if (invokeAt >= 0) { - const invokeNameStart = text[invokeAt + DSML_INVOKE_PREFIX.length]; - if (startsWithFolded(text, invokeAt, DSML_INVOKE_PREFIX) && invokeNameStart && !/[\s"]/.test(invokeNameStart)) { - return { safe: text.slice(0, index), held: "", fail: true, fence, lineStart }; - } - if (invokeAt === text.length || prefixAtEnd(text, invokeAt, DSML_INVOKE_PREFIX)) { - return { safe: text.slice(0, index), held: text.slice(index), fail: false, fence, lineStart }; - } - } - } else if (prefixAtEnd(text, index, DSML_CALLS_LINE)) { - return { safe: text.slice(0, index), held: text.slice(index), fail: false, fence, lineStart }; + const verdict = matchControlSequence(text, index); + if (verdict === "fail") return { safe: text.slice(0, index), held: "", fail: true, fence, fenceRun, lineStart }; + if (verdict === "hold") { + return { safe: text.slice(0, index), held: text.slice(index), fail: false, fence, fenceRun, lineStart }; } } } @@ -113,14 +219,15 @@ function scan( lineStart = char === "\n"; } - return { safe: text, held: "", fail: false, fence, lineStart }; + return { safe: text, held: "", fail: false, fence, fenceRun, lineStart }; } -/** Streaming DSML control-sequence filter for one text or reasoning channel. */ +/** Streaming vendor control-sequence filter for one text or reasoning channel. */ export class CodeBuddyScaffoldFilter { private pending = ""; private failed = false; - private fence: "`" | "~" | null = null; + private fence: FenceState | null = null; + private fenceRun: FenceRunState | null = null; private lineStart = true; /** True while an earlier event owns an unresolved marker or fence prefix. */ @@ -142,9 +249,10 @@ export class CodeBuddyScaffoldFilter { } const priorPending = this.pending; - const result = scan(priorPending + chunk, this.fence, this.lineStart); + const result = scan(priorPending + chunk, this.fence, this.fenceRun, this.lineStart); this.pending = result.held; this.fence = result.fence; + this.fenceRun = result.fenceRun; this.lineStart = result.lineStart; this.failed = result.fail; diff --git a/structure/providers/chat-compat.md b/structure/providers/chat-compat.md index 171a89a95d3..d132ac8bb24 100644 --- a/structure/providers/chat-compat.md +++ b/structure/providers/chat-compat.md @@ -562,7 +562,7 @@ transport or URL fetch is added, and no client filename, payload, URL or metadat charges supported audio by decoded size at the conservative 256-bytes-per-token proxy, not an upstream token formula. The shared coding-agent projection in `src/adapters/coding-agent/` carries supported tool-result images as real image blocks in conversation order, history before current. Current tool-result prose retains `[image attached below]` and `[image omitted: unsupported reference]`. Qoder alone opts into omission markers for single-user input and historical user/tool-result prose through `src/adapters/qoder/image-input.ts`; CodeBuddy retains its previous bytes (historical `[image]` and single-user unsupported-reference omission), and Claude keeps its stable replay builder. Vendor tool execution stays disabled. -CodeBuddy refuses an unquoted, line-oriented full-width-bar DSML `calls` container followed by a named bare or namespaced invoke control line in either output channel; it preserves preceding answer text, never promotes vendor prose into execution authority, and leaves discussed or quoted literals and code examples untouched. Qoder Global continues forwarding supported images without a per-model vision allowlist. CN retains its sidecar classification. Its raw-image route admits only one canonical base64 PNG of at most 1 MiB decoded in one non-developer user message, on `DeepSeek-Flash` or `Qwen3.8-Flash`; developer images, URL references, other media types/models, multiple images, tool-result images and image-bearing multi-turn replay return a fixed non-retryable 400 `unsupported_input_modality` before CLI discovery/spawn. Before CLI discovery, admission bounds encoded length, validates base64 length/padding and round-trip decoding, then checks the PNG signature and basic IHDR fields (13-byte first chunk, positive dimensions no larger than 8192 per edge or 16 million pixels, legal depth/colour pair, compression/filter/interlace). It does not decompress pixels or validate all chunks/CRCs. Invalid or oversized images receive the same fixed error event; text-only CN turns remain unrestricted by this gate. +CodeBuddy refuses an unquoted, line-oriented full-width-bar `calls` container followed on the next line by a named bare or namespaced invoke control line in either output channel, in either observed grammar: DSML (`<||DSML|| calls>` / `<||DSML|| invoke name="…">`) or DeepSeek's native markup (`<|tool▁calls|>` / `<|tool▁invoke name="…">`, #8447). It preserves preceding answer text, never promotes vendor prose into execution authority, and leaves inline, quoted, indented or fenced literals untouched (only column-zero markers outside a fence match, even when prose introduces them); a fenced example ends only at a CommonMark closing fence (indented at most three spaces, same character, at least the opener's length, nothing but trailing whitespace). Qoder Global continues forwarding supported images without a per-model vision allowlist. CN retains its sidecar classification. Its raw-image route admits only one canonical base64 PNG of at most 1 MiB decoded in one non-developer user message, on `DeepSeek-Flash` or `Qwen3.8-Flash`; developer images, URL references, other media types/models, multiple images, tool-result images and image-bearing multi-turn replay return a fixed non-retryable 400 `unsupported_input_modality` before CLI discovery/spawn. Before CLI discovery, admission bounds encoded length, validates base64 length/padding and round-trip decoding, then checks the PNG signature and basic IHDR fields (13-byte first chunk, positive dimensions no larger than 8192 per edge or 16 million pixels, legal depth/colour pair, compression/filter/interlace). It does not decompress pixels or validate all chunks/CRCs. Invalid or oversized images receive the same fixed error event; text-only CN turns remain unrestricted by this gate. Issue #7516 reports live verification on Windows 11 x64 with `qoderclicn 1.1.70` for those two models and a single PNG, through both `--attachment` and inline `--input-format stream-json --output-format stream-json` stdin. OpenCodex uses only stdin; attachment flags are not added. The 1 MiB decoded ceiling is local resource policy, not a vendor maximum: the reported 96×96 PNG has a 36 KiB RGBA raster; larger upstream inputs remain unverified. This is reported evidence, not a fresh live test or a guarantee for other CLI versions; operators must use the verified version (no runtime version probe is added). Injected CLI tests prove serialization, omission markers, refusals and cancellation, not upstream image understanding. Global still replays historical images with `--no-session-persistence`, whose text/image association remains unverified across turns. The scaffold/replay output guards ([ADR-7517](../clients/qoder.md#qoder-assistant-text-replay-guard)) and selector ownership ([ADR-7512](../clients/qoder.md#qoder-settings-ownership)) remain independent. Canonical Responses identity sanitation and narrowly scoped pre-output combo recovery follow [request-local target compatibility](../runtime.md#request-local-target-compatibility); other adapter contracts remain unchanged. diff --git a/tests/providers/codebuddy-adapter.test.ts b/tests/providers/codebuddy-adapter.test.ts index 9132a4b652f..0b0edb01f07 100644 --- a/tests/providers/codebuddy-adapter.test.ts +++ b/tests/providers/codebuddy-adapter.test.ts @@ -326,6 +326,171 @@ describe("codebuddy runTurn streams a headless turn", () => { expect(events).toEqual([expect.objectContaining({ type: "error", code: "vendor_scaffold_detected" })]); }); + test("refuses DeepSeek native tool-call markup printed as text (#8447)", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + + guarded({ + type: "text_delta", + text: "Reading it.\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n" + + "<|tool▁parameter name=\"file_path\" string=\"true\">/tmp/private-body", + }); + + expect(events).toEqual([ + { type: "text_delta", text: "Reading it.\n" }, + expect.objectContaining({ type: "error", code: "vendor_scaffold_detected", retryable: false }), + ]); + expect(JSON.stringify(events)).not.toContain("private-body"); + }); + + test("holds DeepSeek native markup split across deltas until the invoke name arrives", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + + guarded({ type: "text_delta", text: "Safe prefix.\n<|tool▁" }); + guarded({ type: "text_delta", text: "calls|>\r\n<|tool▁invoke name=\"" }); + expect(events).toEqual([{ type: "text_delta", text: "Safe prefix.\n" }]); + guarded({ type: "text_delta", text: "Read\">private-body" }); + + expect(events.at(-1)).toEqual(expect.objectContaining({ type: "error", code: "vendor_scaffold_detected" })); + expect(JSON.stringify(events)).not.toContain("private-body"); + }); + + test("delivers discussed, quoted and fenced DeepSeek markup unchanged", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + const answer = "The tag <|tool▁calls|> opens a native call block.\n" + + "<|tool▁calls|>\nfollowed by prose, not an invoke line.\n" + + "> <|tool▁calls|>\n> <|tool▁invoke name=\"Read\">\n" + + "```text\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n```\n" + + "<|tool▁calls|>\n<|tool▁invoke name=\"\">"; + + guarded({ type: "text_delta", text: answer }); + guarded({ type: "done", stopReason: "stop" }); + + expect(events).toEqual([ + { type: "text_delta", text: answer }, + { type: "done", stopReason: "stop" }, + ]); + }); + + test("keeps a longer fence open across an inner shorter fence line", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + const answer = "````md\n```\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n```\n````\n"; + + guarded({ type: "text_delta", text: answer }); + guarded({ type: "done", stopReason: "stop" }); + + expect(events).toEqual([ + { type: "text_delta", text: answer }, + { type: "done", stopReason: "stop" }, + ]); + }); + + test("does not close a fence on a fence-like line with trailing text", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + const answer = "```text\n```not a close\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n```\n"; + + guarded({ type: "text_delta", text: answer }); + guarded({ type: "done", stopReason: "stop" }); + + expect(events).toEqual([ + { type: "text_delta", text: answer }, + { type: "done", stopReason: "stop" }, + ]); + }); + + test("refuses markup after a long fence closes on a matching line split across deltas", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + + guarded({ type: "text_delta", text: "````\n```\n``" }); + guarded({ type: "text_delta", text: "`` \n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">private-body" }); + + expect(events.at(-1)).toEqual(expect.objectContaining({ type: "error", code: "vendor_scaffold_detected" })); + expect(JSON.stringify(events)).not.toContain("private-body"); + }); + + test("refuses markup after a closing fence indented by up to three spaces", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + + guarded({ type: "text_delta", text: "````\ncode\n " }); + guarded({ type: "text_delta", text: " ````\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">private-body" }); + + expect(events.at(-1)).toEqual(expect.objectContaining({ type: "error", code: "vendor_scaffold_detected" })); + expect(JSON.stringify(events)).not.toContain("private-body"); + }); + + test.each([ + ["DSML", "<||DSML|| calls>\n<||DSML|| invoke name=\"exec\">"], + ["DeepSeek native", "<|tool▁calls|>\n<|tool▁invoke name=\"Read\">"], + ])("refuses %s markup after an inline code span that looks like a fence opener", (_name, markup) => { + for (const deltas of [[` \`\`\`example\`\`\`\n${markup}private-body`], [" ```exam", `ple\`\`\`\n${markup}private-body`]]) { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + + for (const text of deltas) guarded({ type: "text_delta", text }); + + expect(events.at(-1)).toEqual(expect.objectContaining({ type: "error", code: "vendor_scaffold_detected" })); + expect(JSON.stringify(events)).not.toContain("private-body"); + } + }); + + test("keeps a backtick fence with a valid info string open", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + const answer = " ```md title=\"x\"\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n```\n" + + "~~~md `x`\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n~~~\n"; + + guarded({ type: "text_delta", text: answer }); + guarded({ type: "done", stopReason: "stop" }); + + expect(events).toEqual([ + { type: "text_delta", text: answer }, + { type: "done", stopReason: "stop" }, + ]); + }); + + test("keeps a fence open when its opener is split across deltas", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + const first = "```"; + const second = "`md\n```\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n````\n"; + + guarded({ type: "text_delta", text: first }); + guarded({ type: "text_delta", text: second }); + guarded({ type: "done", stopReason: "stop" }); + + expect(events.some(event => event.type === "error")).toBe(false); + expect(events.map(event => event.type === "text_delta" ? event.text : "").join("")).toBe(first + second); + }); + + test("releases streamed fence runs incrementally without buffering or stalling the other channel", () => { + const events: AdapterEvent[] = []; + const guarded = guardCodeBuddyScaffolding(event => events.push(event)); + + guarded({ type: "text_delta", text: "``" }); + guarded({ type: "thinking_delta", thinking: "checking" }); + guarded({ type: "text_delta", text: "``" }); + expect(events).toEqual([ + { type: "text_delta", text: "``" }, + { type: "thinking_delta", thinking: "checking" }, + { type: "text_delta", text: "``" }, + ]); + + guarded({ type: "text_delta", text: "md\n```\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">\n" }); + guarded({ type: "text_delta", text: "``" }); + guarded({ type: "thinking_delta", thinking: "closing" }); + expect(events.at(-1)).toEqual({ type: "thinking_delta", thinking: "closing" }); + + guarded({ type: "text_delta", text: "``\n<|tool▁calls|>\n<|tool▁invoke name=\"Read\">private-body" }); + expect(events.at(-1)).toEqual(expect.objectContaining({ type: "error", code: "vendor_scaffold_detected" })); + expect(JSON.stringify(events)).not.toContain("private-body"); + }); + test("holds a bare invoke prefix split across deltas until its name arrives", () => { const events: AdapterEvent[] = []; const guarded = guardCodeBuddyScaffolding(event => events.push(event)); From 400bc826860494849895cd708d3a92ae805bb2b0 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:51:22 +0900 Subject: [PATCH 23/64] fix(service): do not bake Claude Desktop's picker egress proxy into the service definition (#9190) * fix(service): do not bake Claude Desktop's picker egress proxy into the service definition The picker profile points Claude Desktop's `egressProxyUrl` at this install's credential-less picker CONNECT proxy, and Desktop exports it as HTTP(S)_PROXY to every process it spawns. Running `ocx service install|repair|restart` from a Claude Desktop Code session then baked that URL into the launcher, because `resolvedProxyEnv` only recognized the credentialed Claude Code intercept URL. The service tunneled every provider request back into itself and failed with TLS / 502 errors. Read the applied picker profile (read-only, via inspectDesktopPickerProfile) and drop an outbound proxy variable that names its egress URL. Without an applied picker profile nothing extra is dropped, and NO_PROXY is untouched. Co-Authored-By: Claude Opus 5.5 * fix(service): normalize picker proxy URL match and document runtime contract Co-authored-by: Yushi Chen <282529358+scy7796@users.noreply.github.com> --------- Co-authored-by: Yushi Chen <282529358+scy7796@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- src/claude/desktop-picker-profile.ts | 2 + src/service/definition.ts | 52 ++++++++++++++++++++++- structure/runtime.md | 2 +- tests/service/service-proxy-env.test.ts | 56 +++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 2 deletions(-) diff --git a/src/claude/desktop-picker-profile.ts b/src/claude/desktop-picker-profile.ts index 0165ec436ea..6b1037a36e5 100644 --- a/src/claude/desktop-picker-profile.ts +++ b/src/claude/desktop-picker-profile.ts @@ -102,6 +102,8 @@ function pickerEntry(metadata: Desktop3pMetadata): Desktop3pMetadataEntry | unde if (entries.length > 1) throw new Error("duplicate_picker_entries"); const entry = entries[0]; if (entry && !SAFE_DESKTOP_PROFILE_ID.test(entry.id)) throw new Error("unsafe_picker_id"); + // A row sharing the picker's id would make a foreign profile file read as ours. + if (entry && metadata.entries.filter(other => other.id === entry.id).length > 1) throw new Error("shared_picker_id"); return entry; } diff --git a/src/service/definition.ts b/src/service/definition.ts index 5978da1ced4..c6b65eb3f35 100644 --- a/src/service/definition.ts +++ b/src/service/definition.ts @@ -10,6 +10,7 @@ import { basename, join } from "node:path"; import { getConfigDir, loadConfig } from "../config"; import { readClaudeInterceptProxyToken } from "../claude/intercept/proxy-auth"; +import { inspectDesktopPickerProfile } from "../claude/desktop-picker-profile"; import { serviceApiTokenFilePath } from "../lib/service-secrets"; import { PROXY_ENV_KEYS } from "../lib/proxy-env"; @@ -125,16 +126,65 @@ export function resolvedProxyEnv( ownClaudeInterceptProxy?: string | null, ): { name: string; value: string }[] { const token = ownClaudeInterceptProxy === undefined ? readClaudeInterceptProxyToken(getConfigDir()) : null; + const picker = ownClaudeInterceptProxy === undefined ? ownDesktopPickerProxy() : null; const resolved: { name: string; value: string }[] = []; for (const key of PROXY_ENV_KEYS) { + const outbound = key !== "NO_PROXY"; const value = [env[key]?.trim(), env[key.toLowerCase()]?.trim()].find(v => v && ( - ownClaudeInterceptProxy === undefined ? !isOwnedClaudeInterceptProxy(v, token) : v !== ownClaudeInterceptProxy + ownClaudeInterceptProxy === undefined + ? !isOwnedClaudeInterceptProxy(v, token) && !(outbound && isOwnedDesktopPickerProxy(v, picker)) + : v !== ownClaudeInterceptProxy )); if (value) resolved.push({ name: key, value }); } return resolved; } +interface PickerProxyEndpoint { + protocol: string; + hostname: string; + port: string; +} + +function parsePickerProxyEndpoint(value: string): PickerProxyEndpoint | null { + const trimmed = value.trim(); + if (!trimmed || trimmed.includes("@") || /[?#]/.test(trimmed)) return null; + if (/\/\/+$/.test(trimmed)) return null; + let url: URL; + try { url = new URL(trimmed); } catch { return null; } + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + if (url.username || url.password || url.search || url.hash) return null; + if (url.pathname !== "" && url.pathname !== "/") return null; + const port = url.port || (url.protocol === "http:" ? "80" : "443"); + if (!/^\d{1,5}$/.test(port) || Number(port) <= 0 || Number(port) > 65535) return null; + return { protocol: url.protocol, hostname: url.hostname.toLowerCase(), port }; +} + +function isOwnedDesktopPickerProxy(value: string, picker: PickerProxyEndpoint | null): boolean { + if (!picker) return false; + const candidate = parsePickerProxyEndpoint(value); + return candidate !== null + && candidate.protocol === picker.protocol + && candidate.hostname === picker.hostname + && candidate.port === picker.port; +} + +/** + * The egress URL of this install's applied Claude Desktop picker profile, read without writing. + * That profile points Desktop at the credential-less picker CONNECT proxy, and Desktop exports + * it as HTTP(S)_PROXY to everything it spawns, so a `service install`/`repair`/`restart` run + * from a Desktop Code session would otherwise bake it and the service would tunnel every + * provider request back into itself. + */ +function ownDesktopPickerProxy(): PickerProxyEndpoint | null { + try { + const profile = inspectDesktopPickerProfile(); + return profile.kind === "applied" ? parsePickerProxyEndpoint(profile.proxyUrl) : null; + } catch { + return null; + } +} + /** * Match this installation's credential and exact URL components without creating a token. * An inherited URL can still use an old bound port after the persisted config changes. diff --git a/structure/runtime.md b/structure/runtime.md index 77179eb66f4..c189a29392e 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -237,7 +237,7 @@ under `/claude-intercept/` with a 0600 key; never installed into Claude Code reaches the pair through an authenticated `HTTPS_PROXY` URL plus `NODE_EXTRA_CA_CERTS` in its settings env (`src/claude/intercept/settings.ts`), so no `ANTHROPIC_BASE_URL` rewrite is involved and the client still believes it talks to Anthropic. The proxy splices `CONNECT api.anthropic.com:443` onto the TLS -listener, relays every other CONNECT target blind, and refuses unauthenticated clients, plain proxied HTTP (a 405 whose body names the NO_PROXY fix), and loopback targets. Because it can never serve loopback, the same env carries a `NO_PROXY` loopback bypass (`127.0.0.1,localhost,::1,0.0.0.0`); without it Claude Code sent local HTTP MCP traffic to the proxy and every such server failed (#6936). Apply appends only the missing entries to a user value and leaves a covering value (including `*`) alone; an owned block without the bypass classifies stale so the startup migrate repairs it, and a non-string value other than null is refused as `foreign_env` rather than rewritten. Because the key is shared, apply records `{ hadKey, previous, written }` in `/opencodex-no-proxy.json` (`src/claude/intercept/settings-no-proxy.ts`, no token), and removal restores `previous` only while NO_PROXY still equals `written`, preserving anything else. Restoration needs that receipt: one that could not be written leaves none, and removal then keeps the appended entries (the harmless direction); a removal whose settings write fails before committing tries to put the receipt back. The receipt lives exactly as long as its ownership episode: an apply from an absent block and every removal invalidate it first and fail closed (`unreadable`) when they cannot, and rollback restores it with the captured value. The per-install proxy token is stored owner-only under `/claude-intercept/` (0600 plus a real per-user NTFS ACL on Windows, via `src/lib/windows-secret-acl.ts`, and re-pinned on every read-through `ensure`), and the settings file carrying it is written through the same hardened atomic writer. After a successful CONNECT bind, startup runs `migrateClaudeInterceptSettings` (`src/claude/intercept/settings.ts`), which rewrites an owned env that no longer matches — e.g. a pre-auth URL left by an upgrade — while never creating an absent env or touching a foreign one, so a service restart cannot strand clients on 407s. Migration uses the bound handle's port; a failed bind leaves settings bytes unchanged. `StartServerDeps.startClaudeInterceptProxy` forwards the runtime binder seam through `src/server/index/optional-listeners.ts`, letting tests bind real proxies on port 0 without probe-and-release races while production retains stable ports. Status/inspection reads the token without minting it; only apply and intercept startup create it. Every process Claude Code starts inherits this env, so `resolvedProxyEnv` (`src/service/definition.ts`) skips only an HTTP URL with this installation's validated token, the exact opencodex username and 127.0.0.1 host, and a valid port (1–65535), independently of the current configured port when it bakes a service definition: a service installed from such a shell never sends its own outbound traffic back through its intercept listener, while other loopback proxies (including authenticated ones) are still baked. +listener, relays every other CONNECT target blind, and refuses unauthenticated clients, plain proxied HTTP (a 405 whose body names the NO_PROXY fix), and loopback targets. Because it can never serve loopback, the same env carries a `NO_PROXY` loopback bypass (`127.0.0.1,localhost,::1,0.0.0.0`); without it Claude Code sent local HTTP MCP traffic to the proxy and every such server failed (#6936). Apply appends only the missing entries to a user value and leaves a covering value (including `*`) alone; an owned block without the bypass classifies stale so the startup migrate repairs it, and a non-string value other than null is refused as `foreign_env` rather than rewritten. Because the key is shared, apply records `{ hadKey, previous, written }` in `/opencodex-no-proxy.json` (`src/claude/intercept/settings-no-proxy.ts`, no token), and removal restores `previous` only while NO_PROXY still equals `written`, preserving anything else. Restoration needs that receipt: one that could not be written leaves none, and removal then keeps the appended entries (the harmless direction); a removal whose settings write fails before committing tries to put the receipt back. The receipt lives exactly as long as its ownership episode: an apply from an absent block and every removal invalidate it first and fail closed (`unreadable`) when they cannot, and rollback restores it with the captured value. The per-install proxy token is stored owner-only under `/claude-intercept/` (0600 plus a real per-user NTFS ACL on Windows, via `src/lib/windows-secret-acl.ts`, and re-pinned on every read-through `ensure`), and the settings file carrying it is written through the same hardened atomic writer. After a successful CONNECT bind, startup runs `migrateClaudeInterceptSettings` (`src/claude/intercept/settings.ts`), which rewrites an owned env that no longer matches — e.g. a pre-auth URL left by an upgrade — while never creating an absent env or touching a foreign one, so a service restart cannot strand clients on 407s. Migration uses the bound handle's port; a failed bind leaves settings bytes unchanged. `StartServerDeps.startClaudeInterceptProxy` forwards the runtime binder seam through `src/server/index/optional-listeners.ts`, letting tests bind real proxies on port 0 without probe-and-release races while production retains stable ports. Status/inspection reads the token without minting it; only apply and intercept startup create it. Every process Claude Code starts inherits this env, so `resolvedProxyEnv` (`src/service/definition.ts`) skips an HTTP URL with this installation's validated token, the exact opencodex username and 127.0.0.1 host, and a valid port (1–65535), independently of the current configured port when it bakes a service definition: a service installed from such a shell never sends its own outbound traffic back through its intercept listener, while other loopback proxies (including authenticated ones) are still baked. For outbound proxy keys (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, never `NO_PROXY`), it also skips a credential-free, pathless/queryless/fragmentless URL whose normalized scheme, host, and port match this installation's currently applied Claude Desktop picker profile (`inspectDesktopPickerProfile` in `src/claude/desktop-picker-profile.ts`, which rejects duplicate or shared picker IDs), so a service installed or repaired from a Claude Desktop Code session never bakes the picker egress proxy into its own outbound environment. The TLS listener rewrites `POST /v1/messages` and `POST /v1/messages/count_tokens` to a loopback origin and dispatches them under the `claude-intercept` ingress; other paths relay to the configured upstream. One relayed path is extended: for the standalone CLI's picker catalog, the listener's `cliCatalog` hook (`src/claude/intercept/cli-catalog.ts`) merges opencodex rows into `GET /api/organizations//model_selector/cc` (or `/api/model_selector/cc`), touching only the `cc` surface and leaving Desktop's `ccd`/`code` surfaces to picker mode, and into the fallback `additional_model_options` of `GET /api/claude_cli/bootstrap`. Eligibility: the `cc` catalog is rewritten only for a CLI-classified `User-Agent` with `claudeCode.cliFirstParty` on, because Claude Code caches it on disk for every process and a Desktop-spawned process must not seed rows a plain `claude` cannot route; the bootstrap request carries no entrypoint and follows CLI intent alone. Rows come from `buildCliPickerModels` (`src/claude/intercept/picker-models.ts`), which uses Desktop 3P registry aliases because the CLI offers only Claude-shaped ids (an `ocx-claude-*` row renders "Update Claude Code"), and advertises only an alias the registry decodes back to the same route. `src/claude/intercept/cli-picker.ts` supplies them lazily on the first eligible request, persists the snapshot at `/claude-intercept/cli-picker-models.json`, re-checks each persisted row against the live registry (its alias must still decode to its recorded route; a cold registry after a restart is awaited first, and a snapshot whose rows still do not decode, for example after a provider change, is rebuilt within the same bound), and bounds a cold build at 2.5 s while awaiting the shared registry build in `src/claude/desktop-3p-startup.ts` that startup also uses (a failed or empty on-demand build is not retried for 30 s). Both CLI catalogs obey the shared [picker rewrite bounds](clients/claude-desktop.md#picker-catalog-rewrite-bounds), preflighting row growth before copying and keeping the final JSON within 16 MiB. The rewrite fails open: a provider error, non-2xx status, unparsable body, or no added row relays the upstream bytes unchanged; a body over the 16 MiB cap is cut off while streaming and answered 502 rather than buffered. Claude Code trusts its cached `/cache/model-catalog/*-cc.json` for about an hour, so `writeSettings` in `src/claude/intercept/settings.ts` and every successful `reconcileClaudeFirstPartySettings` drop those files (leaving Desktop's `*-ccd.json`); running sessions keep their list until restarted. The pair is on by default on a hub (`claudeCode.intercept.enabled`); its proxy port defaults to public port + 100 (`claudeCode.intercept.port`). The lifecycle records bind failure, and stop joins both sockets. Its serialized `ensure()` joins pending startup, reuses the live config and dispatch wrapper, and can start a previously unbound pair. `stop()` refuses future ensure calls and awaits an in-flight start. Local management applies and `ocx claude intercept start` (`POST /api/claude-intercept/start`) use this seam through `src/server/index/optional-listeners.ts`; hub-management ingress and data-plane credentials cannot start interception. Status reports `interceptReason` (with `interceptFailurePort` for a CONNECT bind failure) and optional `pickerReason` (with `pickerFailurePort` when the Desktop picker relay port is occupied), distinguishing disabled routing, client role, ephemeral public ports, occupied CONNECT ports and other failures. A changed configured port never rebinds a running pair: apply reports `port_mismatch` with both ports. With an ephemeral public port (`startServer(0)`), an explicit intercept port is required. The lifecycle makes a best-effort legacy picker-key cleanup attempt before checking client role, disabled routing/interception, or an ephemeral public port. Each new unbound lifecycle `ensure()` attempt retries cleanup; management requests rejected before that seam do not invoke it. Cleanup failures do not change the eligibility result or block startup. Direct `startClaudeIntercept` callers retain the same cleanup defense. Mock-only regression coverage lives in `tests/claude-integration/claude-intercept-cleanup.test.ts`. This ingress honours first-party model bindings (`claudeCode.intercept.modelMap`); see [Claude Desktop](clients/claude-desktop.md#first-party-model-bindings). Picker mode and the primitive's optional `allowedTargets` restriction are described under [Desktop egress proxy](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy). The macOS and Windows picker reuses an exportable signing identity protected by the OS credential store across normal restarts, without a plaintext key in the config directory. Restore verifies the constrained CA and current OS trust without installing trust; explicit picker `on` or `trust` completes the missing trust step, including the Windows confirmation when needed. Windows trust subprocesses are terminated on timeout or output-read failure; those failures remain distinguishable. Legacy migration cleanup may still require consent, and native macOS keychain unlock or application-access prompts are separate. Windows and Linux defer picker startup until picker intent or an applied profile requires recovery. The main intercept pair and best-effort legacy-key cleanup remain available. diff --git a/tests/service/service-proxy-env.test.ts b/tests/service/service-proxy-env.test.ts index b1ba2701163..825f113a1a8 100644 --- a/tests/service/service-proxy-env.test.ts +++ b/tests/service/service-proxy-env.test.ts @@ -10,19 +10,34 @@ import { removeTreeWithRetry } from "../helpers/remove-tree"; const token = "a".repeat(43); let home: string; let previousHome: string | undefined; +let previousLibrary: string | undefined; beforeEach(() => { previousHome = process.env.OPENCODEX_HOME; + previousLibrary = process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR; home = mkdtempSync(join(tmpdir(), "service-proxy-env-")); process.env.OPENCODEX_HOME = home; + process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR = join(home, "desktop-library"); }); afterEach(() => { if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + if (previousLibrary === undefined) delete process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR; + else process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR = previousLibrary; removeTreeWithRetry(home); }); +function storePickerProfile(egressProxyUrl: string, applied = true): void { + const library = join(home, "desktop-library"); + mkdirSync(library, { recursive: true }); + writeFileSync(join(library, "picker.json"), `${JSON.stringify({ egressProxyUrl })}\n`); + writeFileSync(join(library, "_meta.json"), JSON.stringify({ + appliedId: applied ? "picker" : "personal", + entries: [{ id: "picker", name: "opencodex-picker" }, { id: "personal", name: "Personal" }], + })); +} + function storeToken(value = token): void { mkdirSync(join(home, "claude-intercept"), { mode: 0o700 }); writeFileSync(claudeInterceptProxyTokenPath(home), `${value}\n`, { mode: 0o600 }); @@ -76,6 +91,47 @@ describe("service proxy environment ownership", () => { } }); + test("excludes the egress URL of the applied Desktop picker profile from outbound keys only", () => { + const picker = "http://127.0.0.1:13101"; + storePickerProfile(picker); + expect(resolvedProxyEnv({ HTTPS_PROXY: picker, HTTP_PROXY: `${picker}/`, ALL_PROXY: picker })).toEqual([]); + expect(resolvedProxyEnv({ HTTPS_PROXY: "HTTP://127.0.0.1:13101", HTTP_PROXY: "HTTP://127.0.0.1:13101/" })).toEqual([]); + expect(resolvedProxyEnv({ HTTPS_PROXY: picker, https_proxy: "http://127.0.0.1:7897" })) + .toEqual([{ name: "HTTPS_PROXY", value: "http://127.0.0.1:7897" }]); + expect(resolvedProxyEnv({ NO_PROXY: picker })).toEqual([{ name: "NO_PROXY", value: picker }]); + for (const value of [ + "http://127.0.0.1:10201", + "http://127.0.0.1:13100", + "http://localhost:13101", + "https://127.0.0.1:13101", + "http://user:pass@127.0.0.1:13101", + "http://127.0.0.1:13101/path", + "http://127.0.0.1:13101//", + "http://127.0.0.1:13101?query=1", + "http://127.0.0.1:13101#fragment", + ]) { + expect(resolvedProxyEnv({ HTTPS_PROXY: value })).toEqual([{ name: "HTTPS_PROXY", value }]); + } + expect(existsSync(join(home, "config.json"))).toBe(false); + }); + + test("keeps a loopback proxy when no picker profile is applied", () => { + const value = "http://127.0.0.1:10201"; + expect(resolvedProxyEnv({ HTTPS_PROXY: value })).toEqual([{ name: "HTTPS_PROXY", value }]); + storePickerProfile(value, false); + expect(resolvedProxyEnv({ HTTPS_PROXY: value })).toEqual([{ name: "HTTPS_PROXY", value }]); + }); + + test("keeps the proxy when a foreign row shares the picker's id", () => { + const value = "http://127.0.0.1:12450"; + storePickerProfile(value); + writeFileSync(join(home, "desktop-library", "_meta.json"), JSON.stringify({ + appliedId: "picker", + entries: [{ id: "picker", name: "Personal" }, { id: "picker", name: "opencodex-picker" }], + })); + expect(resolvedProxyEnv({ HTTPS_PROXY: value })).toEqual([{ name: "HTTPS_PROXY", value }]); + }); + test("an absent or unusable stored token cannot claim a proxy or create a credential", () => { const value = claudeInterceptProxyUrl(10200, token); expect(resolvedProxyEnv({ HTTPS_PROXY: value })).toEqual([{ name: "HTTPS_PROXY", value }]); From 12eeebd1d924af5573d039bfb3436c093f6c892b Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:52:24 +0900 Subject: [PATCH 24/64] fix(integrations): patch Kimi's config.toml in place instead of rewriting it (#9196) * fix(integrations): patch Kimi's config.toml in place instead of rewriting it * fix(integrations): keep trailing blank lines and commented headers in Kimi's config.toml * fix(integrations): preserve comments, line endings, and separators in Kimi TOML patcher * fix(integrations): track absent EOF newline provenance and keep trailing blank lines in place * fix(integrations): fingerprint EOF provenance for Kimi TOML disable Co-authored-by: Fred Amartey <43480311+FredAmartey@users.noreply.github.com> --------- Co-authored-by: Fred Amartey <43480311+FredAmartey@users.noreply.github.com> --- .../content/docs/es/guides/integrations.md | 4 +- .../content/docs/fr/guides/integrations.md | 12 +- .../src/content/docs/guides/integrations.md | 12 +- .../content/docs/ja/guides/integrations.md | 4 +- .../content/docs/ko/guides/integrations.md | 4 +- .../content/docs/ru/guides/integrations.md | 12 +- .../content/docs/tr/guides/integrations.md | 17 +- .../content/docs/zh-cn/guides/integrations.md | 4 +- .../content/docs/zh-tw/guides/integrations.md | 4 +- src/integrations/mutation-plan.ts | 2 +- src/integrations/ownership.ts | 16 +- src/integrations/registry.ts | 3 + src/integrations/state.ts | 7 +- src/integrations/target.ts | 4 + src/integrations/toml-source.ts | 298 ++++++++++++++++++ src/integrations/writer.ts | 23 ++ structure/clients/integrations.md | 2 +- tests/clients/integrations-state.test.ts | 18 +- tests/clients/integrations-writer.test.ts | 175 ++++++++++ 19 files changed, 578 insertions(+), 43 deletions(-) create mode 100644 src/integrations/toml-source.ts diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index 8823ada7e33..a1c9f5d179c 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -234,7 +234,7 @@ Cada escritura exitosa toma una instantánea de su archivo *primero*, por lo que - Se mantienen 10 copias de seguridad por cliente. Más allá de eso, los archivos de instantáneas más antiguos se eliminan y sus filas de historia leen **La copia de seguridad expiró**. Desactivar elimina únicamente las entradas que opencodex registró como propias. Si el archivo se ha modificado después, el resultado depende de si esas entradas siguen intactas y del formato del archivo. En las configuraciones JSON estricto (OpenCode y Pi), una edición **junto a** nuestro bloque, como añadir un servidor MCP o un proveedor propio, se muestra como **Actualización necesaria**: al actualizar, se conservan esas entradas, aunque puede normalizarse el formato. La excepción son los valores que JSON no puede reescribir con exactitud: un número no finito como `1e999`, uno que se redondearía al reescribirlo (un entero muy grande o un número tan pequeño que se convertiría en cero), `-0`, una clave repetida en un objeto o un anidamiento de más de 1000 niveles. En esos casos, el interruptor se bloquea para evitar cambios o pérdidas silenciosas. -**OMP, DSH y Hermes** también conservan las ediciones ajenas al bloque: sus escritores modifican únicamente los rangos de proveedor que administran, byte a byte, sin reescribir el resto del archivo. En los demás formatos que admiten comentarios (OpenClaw, Kimi Code, gjc, MiniMax Code y Raycast: JSON5 o TOML reescritos como documentos completos, o YAML genérico sin preservación del original), o si se han editado las propias entradas administradas, el interruptor se bloquea y la desactivación se rechaza. El bloque administrado permanece en el archivo; opencodex no intenta adivinar qué cambios pertenecen al usuario. +**OMP, DSH, Hermes y Kimi Code** también conservan las ediciones ajenas al bloque: sus escritores modifican únicamente los rangos de proveedor que administran, byte a byte, sin reescribir el resto del archivo. En los demás formatos que admiten comentarios (OpenClaw, gjc, MiniMax Code y Raycast: JSON5 reescrito como documento completo, o YAML genérico sin preservación del original), o si se han editado las propias entradas administradas, el interruptor se bloquea y la desactivación se rechaza. El bloque administrado permanece en el archivo; opencodex no intenta adivinar qué cambios pertenecen al usuario. Esa cerradura ya no es un callejón sin salida. Un cliente en conflicto muestra **Sustituir** al lado de su interruptor, tanto en la tarjeta de visión general como en la propia página del cliente. Reemplaza lo que contiene nuestra configuración con el bloque opencodex que escribiría, y pregunta primero: el diálogo nombra el archivo, dice lo que se pierde y señala la instantánea que permite deshacer el reemplazo. El switch en sí permanece bloqueado, porque el switch no puede saber qué ediciones pretende mantener, solo usted puede decirlo. Nada más está relajado: un archivo que no podemos analizar, o uno cuya estructura no podemos razonar, todavía se niega. @@ -301,7 +301,7 @@ Si una ruta administrada generada no puede representarse de forma segura, ese cl Realice una copia de seguridad de la configuración del cliente usted mismo, luego elimine las entradas innecesarias o reduzca la lista de modelos exportados antes de volver a intentar. **Sustituir** no pasa el límite. Si la configuración debe permanecer más grande, adminístrela manualmente en lugar de usar el interruptor Conectar. -**El formato generalmente no se conserva.** La aplicación analiza una configuración y la vuelve a escribir, por lo que JSON, JSON5 y TOML pueden reformatearse y los comentarios en JSON5 o TOML se pierden. OMP, DSH y Hermes son las excepciones: OMP y Hermes parche sólo `providers.opencodex`. DSH corrige solo `[id=llm-pi-ai].config.providers.opencodex` en el parche de perfil de escritorio, o `llm-pi-ai.providers.opencodex` en `settings.yaml` cuando no hay perfil de escritorio. Sus redactores de YAML conservan comentarios de proveedores no relacionados y formatean byte por byte. Si ese rango de fuente exacto no se puede identificar de manera segura, la operación se niega. Para otros clientes, utilice Restaurar cuando necesite los bytes de archivo anteriores: la instantánea es una copia literal. +**El formato generalmente no se conserva.** La aplicación analiza una configuración y la vuelve a escribir, por lo que JSON y JSON5 pueden reformatearse y los comentarios en JSON5 se pierden. OMP, DSH, Hermes y Kimi Code son las excepciones: OMP y Hermes parche sólo `providers.opencodex`. DSH corrige solo `[id=llm-pi-ai].config.providers.opencodex` en el parche de perfil de escritorio, o `llm-pi-ai.providers.opencodex` en `settings.yaml` cuando no hay perfil de escritorio. Sus redactores de YAML conservan comentarios de proveedores no relacionados y formatean byte por byte. Si ese rango de fuente exacto no se puede identificar de manera segura, la operación se niega. El escritor de Kimi Code reemplaza solo sus propias tablas `[providers.opencodex]` y `[models."opencodex/…"]` en `config.toml`, conserva los comentarios y las tablas `[[hooks]]`, y se niega si esas tablas están escritas de otra forma. Para otros clientes, utilice Restaurar cuando necesite los bytes de archivo anteriores: la instantánea es una copia literal. **Si un valor no puede ser reescrito fielmente, el interruptor se niega.** El viaje de ida y vuelta cubre los tipos de valor que estos formatos usan en la práctica, y donde no lo hace - un archivo TOML usando `inf` o `nan`, por ejemplo, que el analizador sintáctico disponible para nosotros no puede leer con precisión - aplicando paradas y lo dice en lugar de escribir un valor cambiado y llamarlo éxito. Verá el archivo con nombre y nada en el disco se habrá movido. La edición de ese archivo a mano todavía funciona; es solo nuestra reescritura automática la que disminuye. diff --git a/docs-site/src/content/docs/fr/guides/integrations.md b/docs-site/src/content/docs/fr/guides/integrations.md index da6e5c90a73..d1c37253cd4 100644 --- a/docs-site/src/content/docs/fr/guides/integrations.md +++ b/docs-site/src/content/docs/fr/guides/integrations.md @@ -129,10 +129,10 @@ l'actualisation fusionne les changements autour de vos entrées et les conserve, comme `1e999`, un nombre qu'une réécriture arrondirait (un très grand entier ou une valeur si petite qu'elle deviendrait zéro), `-0`, une même clé écrite deux fois dans un objet ou une imbrication de plus de 1000 niveaux. Dans ces cas, le commutateur est verrouillé afin que rien ne soit modifié ou supprimé silencieusement. -**OMP, DSH et Hermes** ne sont pas affectés non plus par les modifications voisines, mais pour une autre raison : leurs outils -d'écriture ne modifient, octet par octet, que leur propre plage `providers.opencodex` ; le reste du fichier +**OMP, DSH, Hermes et Kimi Code** ne sont pas affectés non plus par les modifications voisines, mais pour une autre raison : leurs outils +d'écriture ne modifient, octet par octet, que leurs propres plages gérées ; le reste du fichier n'est jamais réécrit. Pour les autres formats susceptibles de contenir des commentaires (OpenClaw, -Kimi Code, gjc, MiniMax Code et Raycast — documents YAML, JSON5 et TOML réécrits en entier), ou lorsque les propres entrées +gjc, MiniMax Code et Raycast — documents YAML et JSON5 réécrits en entier), ou lorsque les propres entrées d'opencodex ont été modifiées, le commutateur se verrouille et la désactivation est refusée plutôt que de deviner quelles modifications vous appartiennent. @@ -162,9 +162,9 @@ remplace depuis la page de ce profil. ## À quoi s'attendre, en toute transparence **Le formatage n'est généralement pas préservé.** L'application analyse une configuration avant de la -réécrire ; JSON, JSON5 et TOML peuvent donc être reformatés, et les commentaires JSON5 ou TOML sont perdus. -OMP et DSH font exception : leurs outils d’écriture YAML ne modifient que le fragment géré. Pour OMP, il s’agit de `providers.opencodex` ; pour DSH, de `[id=llm-pi-ai].config.providers.opencodex` dans le patch Desktop, ou de `llm-pi-ai.providers.opencodex` dans `settings.yaml` uniquement si le profil Desktop est absent. Ils préservent octet par octet les commentaires et le formatage des fournisseurs sans rapport. Si la plage source exacte ne peut pas être identifiée de manière -sûre, l'opération est refusée. Pour les autres clients, utilisez **Restaurer** lorsque vous avez besoin des +réécrire ; JSON et JSON5 peuvent donc être reformatés, et les commentaires JSON5 sont perdus. +OMP, DSH, Hermes et Kimi Code font exception. Les outils d’écriture YAML d’OMP, de Hermes et de DSH ne modifient que le fragment géré. Pour OMP et Hermes, il s’agit de `providers.opencodex` ; pour DSH, de `[id=llm-pi-ai].config.providers.opencodex` dans le patch Desktop, ou de `llm-pi-ai.providers.opencodex` dans `settings.yaml` uniquement si le profil Desktop est absent. Ils préservent octet par octet les commentaires et le formatage des fournisseurs sans rapport. Si la plage source exacte ne peut pas être identifiée de manière +sûre, l'opération est refusée. L'outil d'écriture de Kimi Code ne remplace que ses propres tables `[providers.opencodex]` et `[models."opencodex/…"]` dans `config.toml`, conserve les commentaires et les tables `[[hooks]]`, et refuse si ces tables sont écrites autrement. Pour les autres clients, utilisez **Restaurer** lorsque vous avez besoin des octets précédents du fichier : l'instantané en est une copie exacte. **Si une valeur ne peut pas être réécrite fidèlement, le commutateur refuse l'opération.** L'aller-retour diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index ee2ab5c3b83..fed917bedfe 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -394,10 +394,10 @@ normalized. The exception is something JSON cannot rewrite exactly — a non-fin number like `1e999`, a number a rewrite would round (a very large integer, or one so small it collapses to zero), `-0`, the same key written twice in one object, or nesting deeper than 1000 levels — which locks the switch instead, so nothing is silently changed or dropped. -**OMP, DSH and Hermes** are unaffected by sibling edits too, for a different reason: their writers +**OMP, DSH, Hermes and Kimi Code** are unaffected by sibling edits too, for a different reason: their writers patch only their own managed provider ranges byte-wise, so the rest of the file is never rewritten. For the remaining formats that can carry comments -(OpenClaw, Kimi Code, gjc, MiniMax Code, Raycast — JSON5 and TOML +(OpenClaw, gjc, MiniMax Code, Raycast — JSON5 written as whole documents, or generic YAML without source preservation), or whenever our own entries were edited, the switch locks and disable refuses rather than guessing which edits were yours. @@ -508,12 +508,14 @@ exported model list before retrying. **Replace** does not bypass the limit. If t configuration must stay larger, manage it manually instead of using the Connect switch. **Formatting is generally not preserved.** Applying parses a config and writes it back -out, so JSON, JSON5 and TOML may be reformatted and comments in JSON5 or TOML are lost. -OMP, DSH and Hermes are the exceptions: OMP and Hermes patch only `providers.opencodex`. +out, so JSON and JSON5 may be reformatted and comments in JSON5 are lost. +OMP, DSH, Hermes and Kimi Code are the exceptions: OMP and Hermes patch only `providers.opencodex`. DSH patches only `[id=llm-pi-ai].config.providers.opencodex` in the Desktop profile patch, or `llm-pi-ai.providers.opencodex` in `settings.yaml` when there is no Desktop profile. Their YAML writers preserve unrelated provider comments and formatting byte-for-byte. If that exact -source range cannot be identified safely, the operation refuses instead. For other clients, use +source range cannot be identified safely, the operation refuses instead. Kimi Code's writer replaces +only its own `[providers.opencodex]` and `[models."opencodex/…"]` tables in `config.toml`, keeping +comments and `[[hooks]]` tables, and refuses when those tables are written another way. For other clients, use Restore when you need the previous file bytes: the snapshot is a verbatim copy. **If a value cannot be rewritten faithfully, the switch refuses instead.** The round diff --git a/docs-site/src/content/docs/ja/guides/integrations.md b/docs-site/src/content/docs/ja/guides/integrations.md index adb148640db..11193fa1cee 100644 --- a/docs-site/src/content/docs/ja/guides/integrations.md +++ b/docs-site/src/content/docs/ja/guides/integrations.md @@ -88,7 +88,7 @@ opencodex は自身の環境からこれらの値を読みます。ゲートウ - 古い操作、または操作後にファイルが変わった場合は **Restore this point…** が表示されます。変更をまたいで復元する場合は、新しい編集を置き換える前に再確認し、その編集もバックアップするため復元自体も取り消せます。 - クライアントごとにバックアップを 10 件保持します。それを超えると最古のスナップショットファイルが削除され、履歴行には **Backup expired** と表示されます。 -Disable は opencodex が自身のものとして記録した項目だけを削除します。書き込み後にファイルが変更された場合の動作は、管理対象項目が無傷かどうかとファイル形式によって異なります。厳密な JSON 設定(OpenCode、Pi)では、管理対象ブロックの*隣*に MCP サーバーや独自プロバイダーを追加すると **Update needed** と表示されます。更新時はそれらの項目を維持しながらマージしますが、書式は正規化されることがあります。例外は JSON が正確に書き直せない値です。`1e999` のような非有限数、書き直しで丸められる数(非常に大きな整数やゼロに潰れるほど小さい数)、`-0`、同一オブジェクト内で重複するキー、1000 階層を超える入れ子はスイッチをロックし、値が黙って変更・欠落するのを防ぎます。**OMP、DSH、Hermes** は別の理由で隣接する編集の影響を受けません。各書き込み処理が管理対象プロバイダーの範囲だけをバイト単位で変更し、ファイルの残りを書き直さないためです。コメントを含められる残りの形式(OpenClaw、Kimi Code、gjc、MiniMax Code、Raycast。文書全体を書き込む JSON5 と TOML、またはソース保持のない一般的な YAML)、あるいは管理対象項目自体が編集された場合は、どの編集を残したいか推測せず、スイッチをロックして Disable を拒否します。 +Disable は opencodex が自身のものとして記録した項目だけを削除します。書き込み後にファイルが変更された場合の動作は、管理対象項目が無傷かどうかとファイル形式によって異なります。厳密な JSON 設定(OpenCode、Pi)では、管理対象ブロックの*隣*に MCP サーバーや独自プロバイダーを追加すると **Update needed** と表示されます。更新時はそれらの項目を維持しながらマージしますが、書式は正規化されることがあります。例外は JSON が正確に書き直せない値です。`1e999` のような非有限数、書き直しで丸められる数(非常に大きな整数やゼロに潰れるほど小さい数)、`-0`、同一オブジェクト内で重複するキー、1000 階層を超える入れ子はスイッチをロックし、値が黙って変更・欠落するのを防ぎます。**OMP、DSH、Hermes、Kimi Code** は別の理由で隣接する編集の影響を受けません。各書き込み処理が管理対象プロバイダーの範囲だけをバイト単位で変更し、ファイルの残りを書き直さないためです。コメントを含められる残りの形式(OpenClaw、gjc、MiniMax Code、Raycast。文書全体を書き込む JSON5、またはソース保持のない一般的な YAML)、あるいは管理対象項目自体が編集された場合は、どの編集を残したいか推測せず、スイッチをロックして Disable を拒否します。 ロックされても操作不能ではありません。競合したクライアントには、概要カードとクライアントページの両方で、スイッチの横に **Replace** が表示されます。管理対象設定が置かれている内容を opencodex のブロックで置き換える操作で、先に確認を求めます。ダイアログにはファイル名、失われる内容、元に戻すためのスナップショットが示されます。スイッチ自体はロックされたままです。どの編集を維持するか判断できるのは利用者だけだからです。それ以外の制約は緩めません。解析できないファイルや、構造を安全に判断できないファイルは引き続き拒否されます。 @@ -106,7 +106,7 @@ Aside も選択したプロファイル 1 件ずつ同じプレビューと確 ## 実際に起こること -**通常、書式は保持されません。** 適用時には設定を解析して書き戻すため、JSON、JSON5、TOML は再整形され、JSON5 や TOML のコメントが失われることがあります。OMP、DSH、Hermes は例外です。YAML の書き込み処理は管理対象の範囲だけを変更します。OMP と Hermes では `providers.opencodex`、DSH では Desktop パッチの `[id=llm-pi-ai].config.providers.opencodex` が対象です。Desktop プロファイルがない場合に限り、DSH は `settings.yaml` の `llm-pi-ai.providers.opencodex` を使います。無関係なプロバイダーのコメントと書式はバイト単位で保持します。 その正確な範囲を安全に識別できなければ、操作を拒否します。他のクライアントで以前のファイル内容が必要な場合は Restore を使ってください。スナップショットはバイト単位のコピーです。 +**通常、書式は保持されません。** 適用時には設定を解析して書き戻すため、JSON と JSON5 は再整形され、JSON5 のコメントが失われることがあります。OMP、DSH、Hermes、Kimi Code は例外です。YAML の書き込み処理は管理対象の範囲だけを変更します。OMP と Hermes では `providers.opencodex`、DSH では Desktop パッチの `[id=llm-pi-ai].config.providers.opencodex` が対象です。Desktop プロファイルがない場合に限り、DSH は `settings.yaml` の `llm-pi-ai.providers.opencodex` を使います。無関係なプロバイダーのコメントと書式はバイト単位で保持します。 その正確な範囲を安全に識別できなければ、操作を拒否します。Kimi Code の書き込み処理は `config.toml` 内の自身の `[providers.opencodex]` と `[models."opencodex/…"]` テーブルだけを置き換え、コメントと `[[hooks]]` テーブルを保持します。これらのテーブルが別の形で書かれている場合は拒否します。他のクライアントで以前のファイル内容が必要な場合は Restore を使ってください。スナップショットはバイト単位のコピーです。 **値を忠実に書き直せない場合も、スイッチは拒否します。** 通常使う値の種類は往復処理に対応していますが、たとえば利用可能なパーサーが正確に読み直せない `inf` や `nan` を使う TOML ファイルでは、変更された値を書いて成功とみなさず、適用を停止して理由を示します。ファイル名が表示され、ディスク上の内容は変わりません。手動編集は引き続き可能で、自動書き換えだけが拒否されます。 diff --git a/docs-site/src/content/docs/ko/guides/integrations.md b/docs-site/src/content/docs/ko/guides/integrations.md index 98d6082bd5e..6749c7e9d43 100644 --- a/docs-site/src/content/docs/ko/guides/integrations.md +++ b/docs-site/src/content/docs/ko/guides/integrations.md @@ -90,7 +90,7 @@ CLI의 `ocx integration client enable|disable --client `는 대시보드 토 - **Restore this point…**는 오래된 작업이나 작업 이후 파일이 바뀌었을 때 표시됩니다. 이후 변경을 넘어서 복원하려면 최신 편집을 교체하기 전에 다시 확인합니다. 그 편집도 백업하므로 복원 작업 자체를 되돌릴 수 있습니다. - 클라이언트마다 백업 열 개를 보관합니다. 이를 넘으면 가장 오래된 스냅샷 파일을 제거하고 해당 기록 행에 **Backup expired**를 표시합니다. -Disable은 opencodex가 소유한다고 기록한 항목만 제거합니다. 이후 파일이 바뀌었다면 opencodex 항목이 온전한지와 파일 형식에 따라 동작이 달라집니다. 엄격한 JSON 설정(OpenCode, Pi)에서는 블록 **옆에** MCP 서버나 자체 프로바이더를 추가하면 **Update needed**가 표시됩니다. 새로 고칠 때 사용자 항목을 유지하며 병합하지만 형식이 정규화될 수 있습니다. 예외는 JSON이 정확히 다시 쓸 수 없는 값입니다. `1e999` 같은 유한하지 않은 수, 다시 쓰면 반올림되는 수(아주 큰 정수나 0으로 사라질 만큼 작은 수), `-0`, 같은 객체에 중복된 키, 1000단계보다 깊은 중첩이 있으면 내용을 조용히 바꾸거나 버리지 않도록 스위치를 잠급니다. **OMP, DSH and Hermes**도 주변 편집의 영향을 받지 않습니다. 이들의 기록기는 소유한 프로바이더 범위만 바이트 단위로 수정해 나머지 파일을 다시 쓰지 않기 때문입니다. 주석을 담을 수 있는 나머지 형식(OpenClaw, Kimi Code, gjc, MiniMax Code, Raycast: 문서 전체를 기록하는 JSON5와 TOML 또는 원본 보존 기능이 없는 일반 YAML)이나 opencodex 항목 자체가 수정된 경우에는 어떤 편집이 사용자 것인지 추측하지 않고 스위치를 잠그고 Disable을 거부합니다. +Disable은 opencodex가 소유한다고 기록한 항목만 제거합니다. 이후 파일이 바뀌었다면 opencodex 항목이 온전한지와 파일 형식에 따라 동작이 달라집니다. 엄격한 JSON 설정(OpenCode, Pi)에서는 블록 **옆에** MCP 서버나 자체 프로바이더를 추가하면 **Update needed**가 표시됩니다. 새로 고칠 때 사용자 항목을 유지하며 병합하지만 형식이 정규화될 수 있습니다. 예외는 JSON이 정확히 다시 쓸 수 없는 값입니다. `1e999` 같은 유한하지 않은 수, 다시 쓰면 반올림되는 수(아주 큰 정수나 0으로 사라질 만큼 작은 수), `-0`, 같은 객체에 중복된 키, 1000단계보다 깊은 중첩이 있으면 내용을 조용히 바꾸거나 버리지 않도록 스위치를 잠급니다. **OMP, DSH, Hermes, Kimi Code**도 주변 편집의 영향을 받지 않습니다. 이들의 기록기는 소유한 프로바이더 범위만 바이트 단위로 수정해 나머지 파일을 다시 쓰지 않기 때문입니다. 주석을 담을 수 있는 나머지 형식(OpenClaw, gjc, MiniMax Code, Raycast: 문서 전체를 기록하는 JSON5 또는 원본 보존 기능이 없는 일반 YAML)이나 opencodex 항목 자체가 수정된 경우에는 어떤 편집이 사용자 것인지 추측하지 않고 스위치를 잠그고 Disable을 거부합니다. 잠겨도 해결 방법이 있습니다. 충돌한 클라이언트는 개요 카드와 클라이언트 페이지의 스위치 옆에 **Replace**를 표시합니다. opencodex 설정을 담은 부분을 새 블록으로 교체하기 전에 확인을 요청합니다. 대화 상자에 파일 이름, 잃게 될 내용, 되돌릴 수 있게 해 주는 스냅샷이 나옵니다. 스위치는 어떤 편집을 유지할지 판단할 수 없으므로 잠긴 채로 둡니다. 그 결정은 사용자가 해야 합니다. 그 밖의 거부 조건은 완화하지 않습니다. 파싱할 수 없거나 구조를 판단할 수 없는 파일은 여전히 거부합니다. @@ -114,7 +114,7 @@ Aside는 선택한 프로필 하나에 같은 미리 보기와 확인 흐름을 ## 실제로 예상해야 할 동작 -**형식은 대체로 보존되지 않습니다.** 적용 과정에서 설정을 파싱하고 다시 기록하므로 JSON, JSON5, TOML의 형식이 달라질 수 있고 JSON5나 TOML의 주석은 사라집니다. OMP, DSH, Hermes는 예외입니다. YAML 기록기는 관리하는 부분만 수정합니다. OMP와 Hermes는 `providers.opencodex`를, DSH는 Desktop 패치의 `[id=llm-pi-ai].config.providers.opencodex`를 수정합니다. Desktop 프로필이 없을 때만 DSH는 `settings.yaml`의 `llm-pi-ai.providers.opencodex`를 사용합니다. 다른 프로바이더의 주석과 형식은 바이트 단위로 보존합니다. 정확한 원본 범위를 안전하게 찾을 수 없으면 작업을 거부합니다. 다른 클라이언트에서 이전 파일 바이트가 필요하면 Restore를 사용하세요. 스냅샷은 원본 그대로의 사본입니다. +**형식은 대체로 보존되지 않습니다.** 적용 과정에서 설정을 파싱하고 다시 기록하므로 JSON과 JSON5의 형식이 달라질 수 있고 JSON5의 주석은 사라집니다. OMP, DSH, Hermes, Kimi Code는 예외입니다. YAML 기록기는 관리하는 부분만 수정합니다. OMP와 Hermes는 `providers.opencodex`를, DSH는 Desktop 패치의 `[id=llm-pi-ai].config.providers.opencodex`를 수정합니다. Desktop 프로필이 없을 때만 DSH는 `settings.yaml`의 `llm-pi-ai.providers.opencodex`를 사용합니다. 다른 프로바이더의 주석과 형식은 바이트 단위로 보존합니다. 정확한 원본 범위를 안전하게 찾을 수 없으면 작업을 거부합니다. Kimi Code 기록기는 `config.toml`에서 자신의 `[providers.opencodex]`와 `[models."opencodex/…"]` 테이블만 교체해 주석과 `[[hooks]]` 테이블을 보존하며, 이 테이블이 다른 방식으로 작성되어 있으면 거부합니다. 다른 클라이언트에서 이전 파일 바이트가 필요하면 Restore를 사용하세요. 스냅샷은 원본 그대로의 사본입니다. **값을 충실히 다시 쓸 수 없다면 스위치가 거부합니다.** 왕복 변환은 이 형식에서 실제로 쓰는 값 종류를 지원합니다. 예를 들어 사용 가능한 파서가 정확히 다시 읽을 수 없는 `inf` 또는 `nan`을 사용한 TOML 파일은 변경된 값을 성공으로 간주해 기록하지 않고 적용을 멈추며 이유를 알립니다. 파일 이름이 표시되고 디스크는 바뀌지 않습니다. 파일을 직접 편집하는 것은 계속 가능하며 자동 재작성만 거부합니다. diff --git a/docs-site/src/content/docs/ru/guides/integrations.md b/docs-site/src/content/docs/ru/guides/integrations.md index 412b1acbd86..1aaae5573f2 100644 --- a/docs-site/src/content/docs/ru/guides/integrations.md +++ b/docs-site/src/content/docs/ru/guides/integrations.md @@ -240,11 +240,11 @@ opencodex применяет настройку, остановка возвра настолько малое, что станет нулём), `-0`, одинаковый ключ дважды в одном объекте либо вложенность глубже 1000 уровней. В этих случаях переключатель блокируется, чтобы ничего не изменилось или не потерялось незаметно. -**OMP, DSH и Hermes** тоже не затрагивают соседние правки, но по другой +**OMP, DSH, Hermes и Kimi Code** тоже не затрагивают соседние правки, но по другой причине: их средства записи меняют побайтно только собственные управляемые диапазоны провайдера и не переписывают остальную часть файла. Для остальных -форматов с комментариями (OpenClaw, Kimi Code, gjc, MiniMax Code, Raycast — -JSON5 и TOML при записи всего документа либо обычный YAML без сохранения +форматов с комментариями (OpenClaw, gjc, MiniMax Code, Raycast — +JSON5 при записи всего документа либо обычный YAML без сохранения исходника), а также при изменении наших собственных записей, переключатель блокируется и отключение отказывается угадывать, какие правки ваши. @@ -285,10 +285,10 @@ Apply, Replace, Disable и Restore теперь начинаются с пред ## Чего ожидать на практике **Форматирование обычно не сохраняется.** При применении конфигурация -разбирается и записывается заново. Поэтому JSON, JSON5 и TOML могут получить -другое форматирование, а комментарии JSON5 и TOML будут утрачены. Исключения — OMP, DSH и Hermes: их средства записи YAML меняют только управляемый фрагмент. Для OMP и Hermes это `providers.opencodex`; для DSH — `[id=llm-pi-ai].config.providers.opencodex` в патче Desktop или, только при отсутствии профиля Desktop, `llm-pi-ai.providers.opencodex` в `settings.yaml`. Комментарии и форматирование остальных провайдеров сохраняются побайтно. Если +разбирается и записывается заново. Поэтому JSON и JSON5 могут получить +другое форматирование, а комментарии JSON5 будут утрачены. Исключения — OMP, DSH, Hermes и Kimi Code: их средства записи YAML меняют только управляемый фрагмент. Для OMP и Hermes это `providers.opencodex`; для DSH — `[id=llm-pi-ai].config.providers.opencodex` в патче Desktop или, только при отсутствии профиля Desktop, `llm-pi-ai.providers.opencodex` в `settings.yaml`. Комментарии и форматирование остальных провайдеров сохраняются побайтно. Если точный диапазон исходного файла нельзя безопасно определить, операция -отказывается от записи. Для остальных клиентов используйте Restore, когда +отказывается от записи. Средство записи Kimi Code заменяет в `config.toml` только собственные таблицы `[providers.opencodex]` и `[models."opencodex/…"]`, сохраняя комментарии и таблицы `[[hooks]]`, и отказывает, если эти таблицы записаны иначе. Для остальных клиентов используйте Restore, когда нужны прежние байты файла: снимок представляет собой точную копию. **Если значение нельзя точно перезаписать, переключатель отказывается от diff --git a/docs-site/src/content/docs/tr/guides/integrations.md b/docs-site/src/content/docs/tr/guides/integrations.md index e86f65260d4..1968143d512 100644 --- a/docs-site/src/content/docs/tr/guides/integrations.md +++ b/docs-site/src/content/docs/tr/guides/integrations.md @@ -159,11 +159,11 @@ normalleştirilebilir. İstisna, JSON'un birebir yeniden yazamayacağı şeylerd büyük bir tam sayı ya da sıfıra çökecek kadar küçük bir sayı), `-0`, aynı nesnede iki kez yazılmış bir anahtar veya 1000 seviyeden derin iç içe geçme — bu durumda anahtar kilitlenir, böylece -hiçbir şey sessizce değiştirilmez veya düşürülmez. **OMP** de yanındaki -düzenlemelerden etkilenmez, ama başka bir nedenle: writer'ı yalnızca kendi -`providers.opencodex` aralığını bayt bayt yamalar, dosyanın geri kalanı hiçbir -zaman yeniden yazılmaz. Yorum taşıyabilen diğer biçimlerde (Hermes, OpenClaw, -Kimi Code, gjc, MiniMax Code, Raycast — bütün belge olarak yazılan YAML, JSON5 ve TOML) veya +hiçbir şey sessizce değiştirilmez veya düşürülmez. **OMP**, **DSH**, **Hermes** ve **Kimi Code** de yanındaki +düzenlemelerden etkilenmez, ama başka bir nedenle: writer'ları yalnızca kendi +yönetilen aralıklarını bayt bayt yamalar, dosyanın geri kalanı hiçbir +zaman yeniden yazılmaz. Yorum taşıyabilen diğer biçimlerde (OpenClaw, +gjc, MiniMax Code, Raycast — bütün belge olarak yazılan YAML ve JSON5) veya kendi girdilerimiz düzenlenmişse, anahtar kilitlenir ve hangi düzenlemelerin size ait olduğunu tahmin etmek yerine devre dışı bırakmayı reddeder. @@ -193,14 +193,15 @@ sayfasında değiştirilir. ## Dürüstçe ne beklenmeli? **Biçimlendirme genellikle korunmaz.** Uygulama işlemi bir yapılandırmayı -ayrıştırır ve geri yazar, bu nedenle JSON, JSON5 ve TOML yeniden -biçimlendirilebilir ve JSON5 veya TOML içindeki yorumlar kaybolur. OMP ve DSH -istisnadır: OMP YAML yazıcısı yalnızca `providers.opencodex` bölümünü yamalar. +ayrıştırır ve geri yazar, bu nedenle JSON ve JSON5 yeniden +biçimlendirilebilir ve JSON5 içindeki yorumlar kaybolur. OMP, DSH, Hermes ve Kimi Code +istisnadır: OMP ve Hermes YAML yazıcıları yalnızca `providers.opencodex` bölümünü yamalar. DSH yazıcısı, Desktop profili varsa `$DSH_HOME/profiles/desktop/cordis.patch.yml` içindeki `[id=llm-pi-ai].config.providers.opencodex` satırını, profil yoksa `$DSH_HOME/settings.yaml` içindeki `llm-pi-ai.providers.opencodex` bölümünü yamalar; ilgisiz sağlayıcı yorumlarını ve biçimlendirmesini bayt bayt korur. Bu tam kaynak aralığı güvenli bir şekilde tanımlanamazsa işlem bunun yerine reddeder. +Kimi Code yazıcısı `config.toml` içinde yalnızca kendi `[providers.opencodex]` ve `[models."opencodex/…"]` tablolarını değiştirir, yorumları ve `[[hooks]]` tablolarını korur; bu tablolar başka bir biçimde yazılmışsa reddeder. Diğer istemciler için önceki dosya baytlarına ihtiyacınız olduğunda Geri Yükle'yi kullanın: anlık görüntü birebir bir kopyadır. diff --git a/docs-site/src/content/docs/zh-cn/guides/integrations.md b/docs-site/src/content/docs/zh-cn/guides/integrations.md index d997c5ed929..6e90f24535e 100644 --- a/docs-site/src/content/docs/zh-cn/guides/integrations.md +++ b/docs-site/src/content/docs/zh-cn/guides/integrations.md @@ -88,7 +88,7 @@ opencodex 从自己的环境读取这些变量。如果网关使用配置文件 - 较旧的操作,或操作后文件已发生变化时,会显示 **Restore this point…**。跨越此类变更恢复时,会在替换较新编辑内容前再次确认,并先备份这些编辑内容,因此恢复操作本身也可撤销。 - 每个客户端保留十份备份。超过后会删除最旧的快照文件,对应的历史记录显示 **Backup expired**。 -Disable 只移除 opencodex 记录为自己管理的条目。如果文件在写入后发生变化,结果取决于我们的条目是否仍完整以及文件格式。对于严格 JSON 配置(OpenCode、Pi),在配置块**旁边**编辑,例如添加 MCP 服务器或自己的提供商,会显示 **Update needed**:刷新时会绕过并保留这些条目,但格式可能被规范化。有些 JSON 内容无法精确保留:如 `1e999` 这样的非有限数值、重写时会舍入的数字(超大整数或会变成零的极小数字)、`-0`、同一对象中的重复键,或超过 1000 层的嵌套。遇到这些内容时,开关会锁定,以免静默更改或丢弃数据。**OMP、DSH 和 Hermes** 也不受相邻编辑影响,但原因不同:其写入器只按字节修补自身管理的提供商片段,不重写文件其余部分。对于其他可能带注释的格式(OpenClaw、Kimi Code、gjc、MiniMax Code、Raycast——整份写入的 JSON5 和 TOML,或不保留源码的通用 YAML),以及我们管理的条目被编辑时,开关会锁定,Disable 会拒绝执行,而不是猜测哪些编辑来自你。 +Disable 只移除 opencodex 记录为自己管理的条目。如果文件在写入后发生变化,结果取决于我们的条目是否仍完整以及文件格式。对于严格 JSON 配置(OpenCode、Pi),在配置块**旁边**编辑,例如添加 MCP 服务器或自己的提供商,会显示 **Update needed**:刷新时会绕过并保留这些条目,但格式可能被规范化。有些 JSON 内容无法精确保留:如 `1e999` 这样的非有限数值、重写时会舍入的数字(超大整数或会变成零的极小数字)、`-0`、同一对象中的重复键,或超过 1000 层的嵌套。遇到这些内容时,开关会锁定,以免静默更改或丢弃数据。**OMP、DSH、Hermes 和 Kimi Code** 也不受相邻编辑影响,但原因不同:其写入器只按字节修补自身管理的提供商片段,不重写文件其余部分。对于其他可能带注释的格式(OpenClaw、gjc、MiniMax Code、Raycast——整份写入的 JSON5,或不保留源码的通用 YAML),以及我们管理的条目被编辑时,开关会锁定,Disable 会拒绝执行,而不是猜测哪些编辑来自你。 锁定状态并非无解。有冲突的客户端会在概览卡片和自身页面的开关旁显示 **Replace**。它会将占据我们设置位置的内容替换为 opencodex 将写入的配置块,并事先询问:对话框会显示文件名、说明会丢失什么,并指向可用于撤销的快照。开关本身仍锁定,因为它无法知道你希望保留哪些编辑;只有你能决定。其他限制没有放宽:无法解析或无法可靠理解结构的文件仍会拒绝处理。 @@ -106,7 +106,7 @@ Aside 对单个选中配置文件采用相同的预览和确认流程。**Sync a ## 实际效果与限制 -**通常不会保留格式。** 应用操作会解析配置并重新写出,因此 JSON、JSON5 和 TOML 的排版可能变化,JSON5 或 TOML 中的注释也会丢失。OMP、DSH 和 Hermes 是例外:OMP 和 Hermes 的 YAML 写入器只修补 `providers.opencodex`。DSH 在 Desktop profile 存在时修补 `$DSH_HOME/profiles/desktop/cordis.patch.yml` 中的 `[id=llm-pi-ai].config.providers.opencodex` 行;仅在没有该 profile 时,才修补 `$DSH_HOME/settings.yaml` 中的 `llm-pi-ai.providers.opencodex`。这些写入器逐字节保留无关提供商的注释和格式。如果无法安全确定准确的源码范围,操作会拒绝执行。对于其他客户端,如需先前文件的原始字节,请使用 Restore;快照是逐字节副本。 +**通常不会保留格式。** 应用操作会解析配置并重新写出,因此 JSON 和 JSON5 的排版可能变化,JSON5 中的注释也会丢失。OMP、DSH、Hermes 和 Kimi Code 是例外:OMP 和 Hermes 的 YAML 写入器只修补 `providers.opencodex`。DSH 在 Desktop profile 存在时修补 `$DSH_HOME/profiles/desktop/cordis.patch.yml` 中的 `[id=llm-pi-ai].config.providers.opencodex` 行;仅在没有该 profile 时,才修补 `$DSH_HOME/settings.yaml` 中的 `llm-pi-ai.providers.opencodex`。这些写入器逐字节保留无关提供商的注释和格式。如果无法安全确定准确的源码范围,操作会拒绝执行。Kimi Code 的写入器只替换 `config.toml` 中自己的 `[providers.opencodex]` 和 `[models."opencodex/…"]` 表,保留注释和 `[[hooks]]` 表;如果这些表以其他方式写入,则拒绝执行。对于其他客户端,如需先前文件的原始字节,请使用 Restore;快照是逐字节副本。 **如果无法忠实重写某个值,开关也会拒绝执行。** 往返转换覆盖这些格式实际使用的值类型;无法覆盖时,例如 TOML 使用 `inf` 或 `nan` 而当前解析器无法准确读回,应用操作会停止并说明原因,不会写入改变后的值却声称成功。界面会指出文件名,磁盘内容保持不变。你仍可手动编辑该文件;拒绝的只是自动重写。 diff --git a/docs-site/src/content/docs/zh-tw/guides/integrations.md b/docs-site/src/content/docs/zh-tw/guides/integrations.md index 1a5ce4c70a7..1582906ee9a 100644 --- a/docs-site/src/content/docs/zh-tw/guides/integrations.md +++ b/docs-site/src/content/docs/zh-tw/guides/integrations.md @@ -91,7 +91,7 @@ opencodex 從自己的環境讀取這些變數。如果你的 gateway 以 profil - **Restore this point…** 會出現在較舊的操作上,或當檔案在那次操作之後有變更時。跨過這樣的變更做回復會再詢問一次,才覆蓋你的較新編輯——並且也會備份它們,所以那次的回復本身也可以復原。 - 每個客戶端保留十份備份。超過之後,最舊的快照檔案會被移除,其歷史列顯示為 **Backup expired**。 -停用只移除 opencodex 記錄為自己寫入的條目。如果你的檔案在我們寫入之後有變更,後續行為取決於我們自己的條目是否完好,以及檔案的格式。對於嚴格 JSON 設定檔(OpenCode、Pi),在我們的區塊**旁邊**進行的編輯——例如新增 MCP 伺服器或你自己的 provider——會顯示為**需要更新**:重新整理會在保留你的條目的前提下合併寫入,但格式可能會被正規化。例外情況是 JSON 無法精確重寫的內容——例如 `1e999` 這類非有限數字、重寫會被四捨五入的數字(極大的整數,或小到會塌縮成零的數字)、`-0`、同一個物件裡重複出現的鍵,或巢狀層數超過 1000 層——此時開關會鎖定,確保沒有任何值被悄悄改動或刪除。**OMP、DSH 與 Hermes** 同樣不受旁邊編輯影響,但原因不同:它們的 writer 只逐位元組修補自己管理的 provider 片段,檔案其餘部分從不會被重寫。至於其餘可以包含註解的格式(OpenClaw、Kimi Code、gjc、MiniMax Code、Raycast——以整份文件寫出的 YAML、JSON5 與 TOML),或當我們自己的條目被編輯過時,開關會鎖定,停用會拒絕執行,而不是猜測哪些編輯是你的。 +停用只移除 opencodex 記錄為自己寫入的條目。如果你的檔案在我們寫入之後有變更,後續行為取決於我們自己的條目是否完好,以及檔案的格式。對於嚴格 JSON 設定檔(OpenCode、Pi),在我們的區塊**旁邊**進行的編輯——例如新增 MCP 伺服器或你自己的 provider——會顯示為**需要更新**:重新整理會在保留你的條目的前提下合併寫入,但格式可能會被正規化。例外情況是 JSON 無法精確重寫的內容——例如 `1e999` 這類非有限數字、重寫會被四捨五入的數字(極大的整數,或小到會塌縮成零的數字)、`-0`、同一個物件裡重複出現的鍵,或巢狀層數超過 1000 層——此時開關會鎖定,確保沒有任何值被悄悄改動或刪除。**OMP、DSH、Hermes 與 Kimi Code** 同樣不受旁邊編輯影響,但原因不同:它們的 writer 只逐位元組修補自己管理的 provider 片段,檔案其餘部分從不會被重寫。至於其餘可以包含註解的格式(OpenClaw、gjc、MiniMax Code、Raycast——以整份文件寫出的 YAML 與 JSON5),或當我們自己的條目被編輯過時,開關會鎖定,停用會拒絕執行,而不是猜測哪些編輯是你的。 Hermes 的會話標識升級是上述衝突規則的特例:既有受管設定僅新增 `session_affinity_header: session-id` 時,可透過 **Apply** 接納;其他受管欄位的修改仍會衝突。升級前,背景重新整理也會暫停此整合的模型清單更新。此設定適用於該 provider 的所有模型,需要支援此能力的 Hermes 版本,且不保證快取命中率。詳見[英文升級說明](/guides/integrations/#hermes-session-affinity)。 @@ -113,7 +113,7 @@ Aside 會對一次選取的單一設定檔使用相同的預覽與確認流程 ## 誠實的預期 -**格式通常不會被保留。** 套用會解析設定並重新寫出,所以 JSON、JSON5 與 TOML 可能被重新格式化,JSON5 或 TOML 中的註解會遺失。OMP 與 DSH 是例外:OMP 的 YAML writer 只修補 `providers.opencodex`。DSH 在 Desktop profile 存在時修補 `$DSH_HOME/profiles/desktop/cordis.patch.yml` 中的 `[id=llm-pi-ai].config.providers.opencodex` 列;僅在沒有該 profile 時,才修補 `$DSH_HOME/settings.yaml` 中的 `llm-pi-ai.providers.opencodex`。這些 writer 逐位元組保留無關的 provider 註解與格式。如果無法安全地識別那個確切的來源範圍,操作會拒絕執行。對其他客戶端,當你需要先前的檔案位元組時請使用 Restore:快照是逐字的副本。 +**格式通常不會被保留。** 套用會解析設定並重新寫出,所以 JSON 與 JSON5 可能被重新格式化,JSON5 中的註解會遺失。OMP、DSH、Hermes 與 Kimi Code 是例外:OMP 與 Hermes 的 YAML writer 只修補 `providers.opencodex`。DSH 在 Desktop profile 存在時修補 `$DSH_HOME/profiles/desktop/cordis.patch.yml` 中的 `[id=llm-pi-ai].config.providers.opencodex` 列;僅在沒有該 profile 時,才修補 `$DSH_HOME/settings.yaml` 中的 `llm-pi-ai.providers.opencodex`。這些 writer 逐位元組保留無關的 provider 註解與格式。如果無法安全地識別那個確切的來源範圍,操作會拒絕執行。Kimi Code 的 writer 只取代 `config.toml` 中自己的 `[providers.opencodex]` 與 `[models."opencodex/…"]` 表格,保留註解與 `[[hooks]]` 表格;若這些表格以其他方式寫入,則拒絕執行。對其他客戶端,當你需要先前的檔案位元組時請使用 Restore:快照是逐字的副本。 **如果某個值無法忠實重寫,開關會拒絕執行。** 往返覆蓋這些格式在實務上會用到的值種類;當它做不到時——例如使用 `inf` 或 `nan` 的 TOML 檔案,我們可用的 parser 無法準確讀回——套用會停止並說明,而不是寫入被改動的值然後宣稱成功。你會看到檔案被指名,磁碟上沒有任何東西被移動。手動編輯那個檔案仍然有效;只有我們的自動重寫會拒絕。 diff --git a/src/integrations/mutation-plan.ts b/src/integrations/mutation-plan.ts index faebdb803bf..8b531ad5b29 100644 --- a/src/integrations/mutation-plan.ts +++ b/src/integrations/mutation-plan.ts @@ -1040,7 +1040,7 @@ export function observeIntegration( // ownership here and disable would delete fragments it never wrote. const classified = classifyIntegration({ fileText: before, fileIsRegular: true, parsed, record, contribution, configPath, clientId, - format: effective.format, sourcePreservingYaml: effective.sourcePreservingYaml !== null, + format: effective.format, sourcePreserving: effective.sourcePreservingYaml !== null || effective.sourcePreservingToml, }); if (clientId === "droid" && record && (classified.state === "current" || classified.state === "stale")) { try { assertDroidRecordedSettingsUnambiguous(detectDir, parsed, record); } diff --git a/src/integrations/ownership.ts b/src/integrations/ownership.ts index 512fc389686..6afa80139e4 100644 --- a/src/integrations/ownership.ts +++ b/src/integrations/ownership.ts @@ -99,6 +99,14 @@ export interface OwnershipRecord { * this field existed simply prune nothing, which is the old behavior. */ createdContainers?: readonly string[]; + /** + * Hash of the original file when a source-preserving writer first appended + * to a non-empty file that lacked a trailing newline. Disable strips the + * added EOF newline only when the remaining bytes hash back to that exact + * original content, so an overwrite or later sibling edit never loses its + * own newline. + */ + sourceMissingTrailingNewlineFingerprint?: string; appliedAt: string; opId: string; } @@ -117,8 +125,12 @@ export function isOwnershipRecord(value: unknown): value is OwnershipRecord { && hash(record.fileFingerprint) && hash(record.blockFingerprint) && (record.modelNames === undefined || record.modelNames === "routed" || record.modelNames === "alias") && paths(record.fragmentPaths) && (record.fragmentPaths as unknown[]).length > 0 - && ["semanticBlockFingerprint", "protectedBlockFingerprint", "semanticProtectedBlockFingerprint"] - .every(key => record[key] === undefined || hash(record[key])) + && [ + "semanticBlockFingerprint", + "protectedBlockFingerprint", + "semanticProtectedBlockFingerprint", + "sourceMissingTrailingNewlineFingerprint", + ].every(key => record[key] === undefined || hash(record[key])) && (record.refreshablePaths === undefined || paths(record.refreshablePaths)) && (record.createdContainers === undefined || (Array.isArray(record.createdContainers) && record.createdContainers.every(path => typeof path === "string"))); diff --git a/src/integrations/registry.ts b/src/integrations/registry.ts index 611662c3041..7529bedbebf 100644 --- a/src/integrations/registry.ts +++ b/src/integrations/registry.ts @@ -146,6 +146,8 @@ export interface IntegrationClientSpec { }; /** Patch only this block-map YAML leaf; never re-render the shared file. */ sourcePreservingYaml?: { path: readonly string[] }; + /** Replace only the owned TOML tables; never re-render the shared file (#9152). */ + sourcePreservingToml?: true; /** Coordinate the complete mutation through a sibling config lock. */ writerLock?: { suffix: ".lock" }; /** @@ -342,6 +344,7 @@ export const INTEGRATION_CLIENTS: Record item.path)].some(path => !path.every(isPlainKey))) return null; + if (upsert.some(item => !isPlainRecord(item.value))) return null; + const eol = before.includes("\r\n") ? "\r\n" : "\n"; + const lines = splitLines(before); + const headers = lines.map(line => tableHeaderPath(line.text)); + const owned = new Set([...remove, ...upsert.map(item => item.path)].map(pathKey)); + const prunedHeaders = prunedContainers(before, expected); + const drop = new Set(); + const retained: string[][] = []; + let insertAt: number | undefined; + for (let index = 0; index < headers.length; index += 1) { + const header = headers[index]!; + if (header === null || header === "array") continue; + const key = pathKey(header); + if (header.some((_, depth) => owned.has(pathKey(header.slice(0, depth + 1))))) { + insertAt ??= index; + if (!dropRange(lines, headers, index, true, drop)) return null; + } else if (prunedHeaders.has(key)) { + // A comment the user put on the header line keeps the table, now empty, rather than going + // with it. + if (hasTomlComment(lines[index]!.text)) retained.push(header); + else dropRange(lines, headers, index, false, drop); + } + } + const kept: LineToken[] = []; + let insertKept: number | undefined; + let droppedFirstSeparator = false; + lines.forEach((line, index) => { + if (index === insertAt) { + insertKept = kept.length; + droppedFirstSeparator = index > 0 && drop.has(index - 1) && lines[index - 1]!.text.trim() === ""; + } + if (!drop.has(index)) kept.push({ text: line.text, eol: line.eol }); + }); + const blocks = upsert.map(item => renderTable(item.path, item.value as Record, eol)); + let text: string; + if (blocks.length === 0) { + // Restore an absent EOF newline only when ownership provenance proves the remaining bytes are + // identical to the original newline-less file we appended to. + if (options.restoreAbsentTrailingNewlineFingerprint !== undefined + && insertKept !== undefined && insertKept === kept.length + && kept.length > 0 && kept[kept.length - 1]!.eol !== "") { + const last = kept[kept.length - 1]!; + const originalEol = last.eol; + last.eol = ""; + if (fingerprint(joinLines(kept)) !== options.restoreAbsentTrailingNewlineFingerprint) { + last.eol = originalEol; + } + } + text = joinLines(kept); + } else if (insertKept !== undefined) { + const head = kept.slice(0, insertKept); + const tail = kept.slice(insertKept); + const headText = joinLines(head); + const tailText = joinLines(tail); + let lead = ""; + if (head.length > 0) { + if (head[head.length - 1]!.eol === "") lead = eol; + else if (droppedFirstSeparator) lead = eol; + } + text = `${headText}${lead}${blocks.join(eol)}${tailText}`; + } else { + const body = joinLines(kept); + const separator = body.length === 0 + ? "" + : kept[kept.length - 1]!.eol === "" ? `${eol}${eol}` : eol; + text = `${body}${separator}${blocks.join(eol)}`; + } + try { + const normalizedExpected = withEmptyTables( + withoutImplicitEmptyAncestors(expected, remove, headers), + retained, + ); + return Bun.deepEquals(Bun.TOML.parse(text), normalizedExpected) ? text : null; + } catch { + return null; + } +} + +function splitLines(input: string): LineToken[] { + if (input.length === 0) return []; + const tokens: LineToken[] = []; + let start = 0; + for (let i = 0; i < input.length; i += 1) { + const ch = input[i]; + if (ch === "\r" && input[i + 1] === "\n") { + tokens.push({ text: input.slice(start, i), eol: "\r\n" }); + i += 1; + start = i + 1; + } else if (ch === "\n") { + tokens.push({ text: input.slice(start, i), eol: "\n" }); + start = i + 1; + } + } + if (start < input.length) { + tokens.push({ text: input.slice(start), eol: "" }); + } + return tokens; +} + +function joinLines(lines: readonly LineToken[]): string { + return lines.map(line => line.text + line.eol).join(""); +} + +/** True when a TOML line carries a `#` comment outside single- or double-quoted strings. */ +function hasTomlComment(line: string): boolean { + let inDouble = false; + let inSingle = false; + for (let i = 0; i < line.length; i += 1) { + const ch = line[i]!; + if (inDouble) { + if (ch === "\\") { i += 1; continue; } + if (ch === "\"") inDouble = false; + } else if (inSingle) { + if (ch === "'") inSingle = false; + } else { + if (ch === "\"") inDouble = true; + else if (ch === "'") inSingle = true; + else if (ch === "#") return true; + } + } + return false; +} + +function isPlainRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isPlainKey(segment: string): boolean { + return parseSegment(segment).kind === "key"; +} + +function pathKey(path: readonly string[]): string { + return path.join("\u0000"); +} + +/** The table a `[header]` line opens, "array" for `[[header]]`, or null for any other line. */ +function tableHeaderPath(line: string): string[] | "array" | null { + const trimmed = line.trim(); + if (!trimmed.startsWith("[")) return null; + let parsed: unknown; + try { + parsed = Bun.TOML.parse(trimmed); + } catch { + return null; + } + if (trimmed.startsWith("[[")) return "array"; + const path: string[] = []; + let node = parsed; + while (isPlainRecord(node)) { + const keys = Object.keys(node); + if (keys.length === 0) break; + if (keys.length !== 1) return null; + path.push(keys[0]!); + node = node[keys[0]!]; + } + return path.length > 0 ? path : null; +} + +/** + * Mark a table for removal: its header, the blank line above it, and with `body` its key lines up + * to the next header. Comments and blank lines at the end of the body stay, since they usually + * introduce whatever follows. Returns false if an owned table header or body carries a user + * comment that dropping the range would silently lose. + */ +function dropRange( + lines: readonly LineToken[], + headers: readonly (string[] | "array" | null)[], + start: number, + body: boolean, + drop: Set, +): boolean { + let end = start + 1; + if (body) { + while (end < lines.length && headers[end] === null) end += 1; + while (end > start + 1 && /^\s*(#.*)?$/.test(lines[end - 1]!.text)) end -= 1; + for (let index = start; index < end; index += 1) { + if (hasTomlComment(lines[index]!.text)) return false; + } + } + for (let index = start; index < end; index += 1) drop.add(index); + if (start > 0 && lines[start - 1]!.text.trim() === "" && !drop.has(start - 1)) drop.add(start - 1); + return true; +} + +/** Table paths the file declares that the expected document no longer has. */ +function prunedContainers(before: string, expected: unknown): Set { + const pruned = new Set(); + let current: unknown; + try { + current = Bun.TOML.parse(before); + } catch { + return pruned; + } + const walk = (node: unknown, target: unknown, path: string[]): void => { + if (!isPlainRecord(node)) return; + for (const [key, child] of Object.entries(node)) { + if (!isPlainRecord(child)) continue; + const next = [...path, key]; + const counterpart = isPlainRecord(target) ? target[key] : undefined; + if (counterpart === undefined) pruned.add(pathKey(next)); + walk(child, counterpart, next); + } + }; + walk(current, expected, []); + return pruned; +} + +function withoutImplicitEmptyAncestors( + document: unknown, + removedPaths: readonly (readonly string[])[], + headers: readonly (string[] | "array" | null)[], +): unknown { + if (removedPaths.length === 0 || !isPlainRecord(document)) return document; + const explicitHeaders = new Set(); + for (const header of headers) { + if (header !== null && header !== "array") explicitHeaders.add(pathKey(header)); + } + const ancestors: string[][] = []; + const seen = new Set(); + for (const path of removedPaths) { + for (let depth = path.length - 1; depth >= 1; depth -= 1) { + const ancestor = path.slice(0, depth); + const key = pathKey(ancestor); + if (!seen.has(key) && !explicitHeaders.has(key)) { + seen.add(key); + ancestors.push(ancestor); + } + } + } + if (ancestors.length === 0) return document; + ancestors.sort((a, b) => b.length - a.length); + const copy = structuredClone(document); + for (const ancestor of ancestors) { + let parent: Record = copy; + let reachable = true; + for (let i = 0; i < ancestor.length - 1; i += 1) { + const next = parent[ancestor[i]!]; + if (!isPlainRecord(next)) { reachable = false; break; } + parent = next; + } + if (!reachable) continue; + const leafKey = ancestor[ancestor.length - 1]!; + const target = parent[leafKey]; + if (isPlainRecord(target) && Object.keys(target).length === 0) { + delete parent[leafKey]; + } + } + return copy; +} + +function withEmptyTables(document: unknown, paths: readonly string[][]): unknown { + if (paths.length === 0 || !isPlainRecord(document)) return document; + const copy = structuredClone(document); + for (const path of paths) { + let node: Record = copy; + for (const key of path) { + if (!isPlainRecord(node[key])) node[key] = {}; + node = node[key] as Record; + } + } + return copy; +} + +function renderTable(path: readonly string[], value: Record, eol: string): string { + const header = path.map(quoteTomlKey).join("."); + const rendered = `[${header}]\n${renderToml(value, header)}`; + return eol === "\n" ? rendered : rendered.replace(/\n/g, eol); +} diff --git a/src/integrations/writer.ts b/src/integrations/writer.ts index b1f68317da0..2cfa476b9ed 100644 --- a/src/integrations/writer.ts +++ b/src/integrations/writer.ts @@ -58,6 +58,7 @@ import { sourcePrunableYamlContainers, yamlFragmentUnsupportedStyle, } from "./omp-yaml-source"; +import { patchTomlTablesSource } from "./toml-source"; /** * "comments or formatting" used to be the only refusal this path could report. @@ -228,6 +229,11 @@ function snapshotAbsPath(store: IntegrationStateStore, entry: JournalEntry): str return snapshot.kind === "stored" ? snapshot.path : undefined; } +function tomlRefusalReason(configPath: string, outcome: string): string { + return `${configPath} keeps opencodex's tables in a layout opencodex cannot edit without rewriting the whole file, so ${outcome}. ` + + "Move them back to their own [providers.opencodex] and [models.\"opencodex/…\"] tables, or remove them, and try again."; +} + function sourcePreservingFragmentValue( contribution: ManagedContribution, path: readonly string[], @@ -448,6 +454,10 @@ function applyOrRefreshIntegration( yamlRefusalReason(before, target.sourcePreservingYaml.path, configPath, "it was left alone")); } text = patched; + } else if (target.sourcePreservingToml && before !== null) { + const patched = patchTomlTablesSource(before, base === parsed ? [] : record!.fragmentPaths, contribution.fragments, nextDocument); + if (patched === null) return refuse(clientId, "unsafe", "unsafe", tomlRefusalReason(configPath, "it was left alone")); + text = patched; } else { text = clientId === "cline" ? serializeClineDocument(nextDocument) : serializeDocument(nextDocument, target.format); } @@ -501,6 +511,11 @@ function applyOrRefreshIntegration( snapshot, resultFingerprint: fingerprint(text), resultAbsent: false, priorRecord: record, }; const refreshablePaths = refreshablePathsOf(contribution); + const sourceMissingTrailingNewlineFingerprint = classified.state === "absent" + ? (target.sourcePreservingToml && before !== null && before.length > 0 && !before.endsWith("\n") + ? fingerprint(before) + : undefined) + : record?.sourceMissingTrailingNewlineFingerprint; return commit({ io, store, clientId, configPath, before, nextText: text, state: "current", priorRecord: record, @@ -518,6 +533,8 @@ function applyOrRefreshIntegration( refreshablePaths, } : {}), fragmentPaths: fragmentPathsOf(contribution), createdContainers: created, + ...(sourceMissingTrailingNewlineFingerprint !== undefined + ? { sourceMissingTrailingNewlineFingerprint } : {}), appliedAt: at, opId, }, entry, @@ -627,6 +644,12 @@ export function disableIntegration(input: IntegrationWriteInput): WriteOutcome { yamlRefusalReason(before, target.sourcePreservingYaml.path, configPath, "nothing was removed")); } text = patched; + } else if (target.sourcePreservingToml && before !== null) { + const patched = patchTomlTablesSource(before, record!.fragmentPaths, [], doc, { + restoreAbsentTrailingNewlineFingerprint: record!.sourceMissingTrailingNewlineFingerprint, + }); + if (patched === null) return refuse(clientId, "unsafe", "unsafe", tomlRefusalReason(configPath, "nothing was removed")); + text = patched; } else { text = clientId === "cline" ? serializeClineDocument(doc) : serializeDocument(doc, target.format); } diff --git a/structure/clients/integrations.md b/structure/clients/integrations.md index 35413f0b8b9..28c8e43c6c6 100644 --- a/structure/clients/integrations.md +++ b/structure/clients/integrations.md @@ -194,7 +194,7 @@ provider block in `models.yml`; default presets and proxy routing in `config.yml TOML temporal scalars cannot survive the JSON-cloned merge representation with their types intact. The common parser refuses documents containing them before either status or mutation -proceeds, including nested arrays and inline tables. Quoted date strings remain supported. YAML serializers quote leading-dot numeric strings, including exponent forms, in keys and values to preserve their string types. +proceeds, including nested arrays and inline tables. Quoted date strings remain supported. YAML serializers quote leading-dot numeric strings, including exponent forms, in keys and values to preserve their string types. Kimi Code's `config.toml` is patched in place by `src/integrations/toml-source.ts` (#9152): only the owned `[providers.opencodex]` and `[models."opencodex/…"]` tables are replaced, so comments, `[[array]]` tables and sibling edits survive, and a layout that cannot be patched that way is refused rather than re-rendered. ## Catalog visibility diff --git a/tests/clients/integrations-state.test.ts b/tests/clients/integrations-state.test.ts index c554320ed3f..710c57b556e 100644 --- a/tests/clients/integrations-state.test.ts +++ b/tests/clients/integrations-state.test.ts @@ -718,6 +718,23 @@ describe("ownership is scoped to recorded fragments", () => { expect(result).toEqual({ state: "current" }); }); + test("Kimi patches its TOML tables in place, so a sibling edit is not a conflict (#9152)", () => { + const contribution = { ...ownedContribution, clientId: "kimi" as const }; + const result = classifyIntegration({ + fileText: textWithExtra, + fileIsRegular: true, + parsed: documentWithExtra, + record: { + ...record, + clientId: "kimi", + configPath: "/tmp/kimi-config.toml", + blockFingerprint: fingerprint(canonicalContribution(contribution)), + }, + contribution, + }); + expect(result).toEqual({ state: "current" }); + }); + // Re-serializing a whole document in these formats would drop any comments // the user keeps next to our block, so file-level drift stays a hard // conflict for every one of them — a regression that narrowed the condition @@ -725,7 +742,6 @@ describe("ownership is scoped to recorded fragments", () => { for (const { clientId, configPath } of [ { clientId: "gajae" as const, configPath: "/tmp/gajae-models.yaml" }, { clientId: "openclaw" as const, configPath: "/tmp/openclaw.json5" }, - { clientId: "kimi" as const, configPath: "/tmp/kimi-config.toml" }, ]) { test(`${clientId} (comment-capable) still conflicts on an unrelated source edit`, () => { const contribution = { ...ownedContribution, clientId }; diff --git a/tests/clients/integrations-writer.test.ts b/tests/clients/integrations-writer.test.ts index 53d443f18f9..d464308b506 100644 --- a/tests/clients/integrations-writer.test.ts +++ b/tests/clients/integrations-writer.test.ts @@ -8,6 +8,7 @@ import { buildClientContribution, type ExportModel } from "../../src/clients/con import { refreshOwnedCatalogIntegrations } from "../../src/integrations/catalog-refresh"; import { assertIntegrationWriteOwnership, fileIO, type IntegrationIO } from "../../src/integrations/config-io"; import { canonicalContribution, fingerprint, semanticContribution } from "../../src/integrations/ownership"; +import { serializeDocument } from "../../src/integrations/serialize"; import { protectedContributionFingerprint } from "../../src/integrations/ownership-policy"; import { INTEGRATION_CLIENTS } from "../../src/integrations/registry"; import { createIntegrationStateStore, type IntegrationStateStore } from "../../src/integrations/store"; @@ -996,6 +997,180 @@ describe("disable", () => { }); }); +describe("Kimi source preservation (#9152)", () => { + const original = [ + "# user header", + "default_model = \"kimi-k3\"", + "", + "# >>> other-tool-hooks >>>", + "[[hooks]]", + "event = \"SessionStart\"", + "command = \"echo start\"", + "", + "[[hooks]]", + "event = \"Stop\"", + "command = \"echo stop\"", + "# <<< other-tool-hooks <<<", + "", + ].join("\n"); + + function installKimi(text: string): string { + mkdirSync(join(home, ".kimi-code"), { recursive: true }); + const configPath = join(home, ".kimi-code", "config.toml"); + writeFileSync(configPath, text); + return configPath; + } + + test("apply and disable leave the user's comments and hook tables as written", () => { + const configPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const applied = readFileSync(configPath, "utf8"); + expect(applied.startsWith(original)).toBe(true); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(configPath, "utf8")).toBe(original); + }); + + test("another tool's block added after apply survives refresh and disable", () => { + const configPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const sibling = "# >>> late-tool >>>\n[[hooks]]\nevent = \"UserPromptSubmit\"\n# <<< late-tool <<<\n"; + writeFileSync(configPath, `${readFileSync(configPath, "utf8")}\n${sibling}`); + expect(refreshIntegration(input({ clientId: "kimi", models: MODELS.slice(1) })).ok).toBe(true); + const refreshed = readFileSync(configPath, "utf8"); + expect(refreshed.startsWith(original)).toBe(true); + expect(refreshed.endsWith(sibling)).toBe(true); + expect(refreshed).not.toContain("claude-opus-4-8"); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(configPath, "utf8")).toBe(`${original}\n${sibling}`); + }); + + test("disable cleans up a file the whole-document writer left behind", () => { + const configPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const rerendered = serializeDocument(Bun.TOML.parse(readFileSync(configPath, "utf8")), "toml"); + expect(rerendered).toContain("[providers]\n[providers.opencodex]"); + writeFileSync(configPath, rerendered); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(Bun.TOML.parse(readFileSync(configPath, "utf8"))).toEqual(Bun.TOML.parse(original)); + }); + + test("trailing blank lines in the user's file survive apply and disable", () => { + const padded = `${original}\n\n`; + const configPath = installKimi(padded); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(configPath, "utf8").startsWith(padded)).toBe(true); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(configPath, "utf8")).toBe(padded); + }); + + test("disable keeps a comment the user put on a parent table header", () => { + const configPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const rerendered = serializeDocument(Bun.TOML.parse(readFileSync(configPath, "utf8")), "toml") + .replace("[providers]\n", "[providers] # mine\n"); + writeFileSync(configPath, rerendered); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const after = readFileSync(configPath, "utf8"); + expect(after).toContain("[providers] # mine"); + expect(after).not.toContain("opencodex"); + }); + + test("an overwrite refuses a provider table it cannot replace in place", () => { + const inline = `providers = { opencodex = { type = "openai" } }\n${original}`; + const configPath = installKimi(inline); + const result = overwriteIntegration(input({ clientId: "kimi" })); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.reason).toBe("unsafe"); + expect(readFileSync(configPath, "utf8")).toBe(inline); + }); + + test("refuses refresh or disable when a user added a comment inside a managed table", () => { + const configPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const commented = readFileSync(configPath, "utf8").replace( + "[providers.opencodex]\n", + "[providers.opencodex]\n# keep my note\n", + ); + writeFileSync(configPath, commented); + const refreshed = refreshIntegration(input({ clientId: "kimi", models: MODELS.slice(1) })); + expect(refreshed.ok).toBe(false); + if (!refreshed.ok) expect(refreshed.reason).toBe("unsafe"); + expect(readFileSync(configPath, "utf8")).toBe(commented); + const disabled = disableIntegration(input({ clientId: "kimi" })); + expect(disabled.ok).toBe(false); + if (!disabled.ok) expect(disabled.reason).toBe("unsafe"); + expect(readFileSync(configPath, "utf8")).toBe(commented); + }); + + test("preserves CRLF line endings, absent trailing newline, and surrounding blank lines", () => { + const crlf = original.replace(/\n/g, "\r\n"); + const crlfPath = installKimi(crlf); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + const appliedCrlf = readFileSync(crlfPath, "utf8"); + expect(appliedCrlf.startsWith(crlf)).toBe(true); + expect(appliedCrlf.replace(/\r\n/g, "")).not.toContain("\n"); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(crlfPath, "utf8")).toBe(crlf); + + const noNewline = 'default_model = "kimi-k3"'; + const noNewlinePath = installKimi(noNewline); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(refreshIntegration(input({ clientId: "kimi", models: MODELS.slice(1) })).ok).toBe(true); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(noNewlinePath, "utf8")).toBe(noNewline); + + // Removing the blank separator before the managed block after apply must NOT strip + // the preceding user line's trailing newline on disable when the file originally had one. + const compactPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + writeFileSync(compactPath, readFileSync(compactPath, "utf8").replace(`${original}\n[providers.opencodex]`, `${original}[providers.opencodex]`)); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(compactPath, "utf8")).toBe(original); + + // Trailing blank lines added after the final managed table stay after it on refresh. + const trailingPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + writeFileSync(trailingPath, `${readFileSync(trailingPath, "utf8")}\n\n`); + expect(refreshIntegration(input({ clientId: "kimi", models: MODELS.slice(1) })).ok).toBe(true); + const refreshedTrailing = readFileSync(trailingPath, "utf8"); + expect(refreshedTrailing.startsWith(`${original}\n[providers.opencodex]`)).toBe(true); + expect(refreshedTrailing.endsWith("\n\n\n")).toBe(true); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(trailingPath, "utf8")).toBe(`${original}\n\n`); + + const sibling = "# >>> late-tool >>>\n[[hooks]]\nevent = \"Stop\"\n# <<< late-tool <<<\n"; + const blankPath = installKimi(original); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + writeFileSync(blankPath, `${readFileSync(blankPath, "utf8")}\n\n${sibling}`); + expect(refreshIntegration(input({ clientId: "kimi", models: MODELS.slice(1) })).ok).toBe(true); + expect(readFileSync(blankPath, "utf8").endsWith(`\n\n\n${sibling}`)).toBe(true); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(blankPath, "utf8")).toBe(`${original}\n\n${sibling}`); + + // Overwriting a pre-existing managed table in a newline-less file must not strip the + // preceding user line's newline on disable. + const existingNoEof = 'default_model = "kimi-k3"\n\n[providers.opencodex]\ntype = "old"'; + const overwritePath = installKimi(existingNoEof); + expect(overwriteIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(overwritePath, "utf8")).toBe('default_model = "kimi-k3"\n'); + + // Adding a sibling line before the managed block after an initial append to a newline-less + // file invalidates the EOF provenance, so disable keeps the new sibling's trailing newline. + const editedBeforePath = installKimi(noNewline); + expect(applyIntegration(input({ clientId: "kimi" })).ok).toBe(true); + writeFileSync( + editedBeforePath, + readFileSync(editedBeforePath, "utf8").replace( + `${noNewline}\n\n[providers.opencodex]`, + `${noNewline}\ntheme = "dark"\n\n[providers.opencodex]`, + ), + ); + expect(disableIntegration(input({ clientId: "kimi" })).ok).toBe(true); + expect(readFileSync(editedBeforePath, "utf8")).toBe(`${noNewline}\ntheme = "dark"\n`); + }); +}); + describe("OMP source preservation", () => { test("disables a generated OMP config without leaving its created container", () => { const configPath = installOmp(); From 45db3eeb70fb1c78a251b1572b93c63e83ff609a Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:57:36 +0900 Subject: [PATCH 25/64] fix(codex): keep the main hard-lock refusal when a pool account refuses the model (#9186) * fix(codex): keep the main hard-lock refusal when a pool account refuses the model * docs(codex): note the hard-lock refusal after a pool account declines the model * docs(codex): point the pool-model refusal note at the retry-time rule The client receives the hard-lock refusal's suggested retry time, which is main's reset or an earlier pool recovery (never sooner than one minute), or none when neither is known (mainHardLockRetryAt). Refer to the rule stated just above instead of promising main's reset, in English, Spanish and Turkish. * docs(codex): scope the retry floor and the pool-model refusal note - The one-minute floor applies to a pool account's recovery time only; mainHardLockRetryAt returns the main reset as is. - The main-policy refusal replaces the pool account's model error only when the request could move to another account. An uploaded file, a request held to one account, or no send left for an account move keeps the first account's model error. English, Spanish and Turkish. --------- Co-authored-by: Fred Amartey <43480311+FredAmartey@users.noreply.github.com> --- .../es/reference/codex-retry-diagnostics.md | 4 +- .../docs/reference/codex-retry-diagnostics.md | 11 +- .../tr/reference/codex-retry-diagnostics.md | 10 +- scripts/test-layout/layout.json | 2 +- src/server/responses/core-codex-account.ts | 13 ++ structure/transports/responses-failover.md | 2 + ...in-account-hard-lock-model-refusal.test.ts | 161 ++++++++++++++++++ tests/fixtures/test-layout-expected.json | 2 +- 8 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 tests/codex-integration/main-account-hard-lock-model-refusal.test.ts diff --git a/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md b/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md index 6364ec50c48..e22302e44b1 100644 --- a/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md +++ b/docs-site/src/content/docs/es/reference/codex-retry-diagnostics.md @@ -27,7 +27,9 @@ Una respuesta `upstream_reset_replay_refused` generada por el proxy también usa Una credencial principal bloqueada cierra la solicitud de admisión; no reserva la cuota restante de la cuenta, y un restablecimiento predicho nunca libera el bloque por sí solo. Los umbrales (por defecto `short` 90, `long` 98) son visibles en la carga útil de estado y configurables a través de `codexMainAccountHardLockThresholds`. -Un rechazo de bloqueo duro se informa como `usage_limit_reached`, por lo que Codex termina el turno y marca un objetivo activo como limitado al uso en lugar de esperar días en un reintento. El tiempo de reintento sugerido es el restablecimiento de la cuenta principal o, para una solicitud de que el grupo de cuentas enrutado a la cuenta principal, el primer momento conocido en que se recupera otra cuenta del grupo, lo que ocurra primero (nunca antes de un minuto). Reanudar el objetivo después de ese tiempo; enrutamiento a continuación, recoge una cuenta de estado fresco. +Un rechazo de bloqueo duro se informa como `usage_limit_reached`, por lo que Codex termina el turno y marca un objetivo activo como limitado al uso en lugar de esperar días en un reintento. El tiempo de reintento sugerido es el restablecimiento de la cuenta principal o, para una solicitud de que el grupo de cuentas enrutado a la cuenta principal, el primer momento conocido en que se recupera otra cuenta del grupo, lo que ocurra primero (el momento de otra cuenta del grupo nunca es antes de un minuto; el restablecimiento de la cuenta principal se usa tal cual). Reanudar el objetivo después de ese tiempo; enrutamiento a continuación, recoge una cuenta de estado fresco. + +El mismo rechazo se devuelve cuando otra cuenta del grupo se probó primero, respondió que no admite el modelo solicitado y la solicitud podía pasar a otra cuenta. El cliente ve el límite de la cuenta principal, con el tiempo de reintento sugerido descrito arriba, en lugar del error de modelo de esa cuenta. Una solicitud que lleva un archivo subido, está fijada a una cuenta o no tiene envíos disponibles para cambiar de cuenta sigue recibiendo el error de modelo de esa cuenta, y un rechazo de cuota de la otra cuenta se devuelve como antes. diff --git a/docs-site/src/content/docs/reference/codex-retry-diagnostics.md b/docs-site/src/content/docs/reference/codex-retry-diagnostics.md index ce0887f508a..694049aa78f 100644 --- a/docs-site/src/content/docs/reference/codex-retry-diagnostics.md +++ b/docs-site/src/content/docs/reference/codex-retry-diagnostics.md @@ -56,9 +56,18 @@ A hard-lock refusal is reported as `usage_limit_reached`, so Codex ends the turn and marks an active Goal as usage-limited instead of waiting for days in a retry. The suggested retry time is the main account's reset or, for a request that the account pool routed to the main account, the earliest known time another -pool account recovers, whichever comes first (never sooner than one minute). +pool account recovers, whichever comes first (a pool account's time is never +sooner than one minute away; the main reset is used as is). Resume the Goal after that time; routing then picks an account from fresh state. +The same refusal is returned when another pool account was tried first, answered +that it does not support the requested model, and the request could move to +another account. The client sees the main account's limit, with the suggested +retry time described above, rather than that account's model error. A request +that carries an uploaded file, is held to one account, or has no send left for +an account move still gets that account's model error, and a quota refusal from +the other account is returned as before. + ## Stored-account credit metadata retries An explicitly selected stored account can reach its included usage limit while its last diff --git a/docs-site/src/content/docs/tr/reference/codex-retry-diagnostics.md b/docs-site/src/content/docs/tr/reference/codex-retry-diagnostics.md index 2fcf4c4b1e3..23be4271181 100644 --- a/docs-site/src/content/docs/tr/reference/codex-retry-diagnostics.md +++ b/docs-site/src/content/docs/tr/reference/codex-retry-diagnostics.md @@ -45,9 +45,17 @@ Kesin kilit reddi `usage_limit_reached` olarak bildirilir. Böylece Codex günle yeniden denemede beklemek yerine turu bitirir ve etkin Goal'ı kullanım sınırlı işaretler. Önerilen zaman, ana hesap sıfırlanmasıdır; havuzun ana hesaba yönlendirdiği isteklerde başka havuz hesabının bilinen en erken düzelme zamanı -daha erkense o kullanılır. Süre hiçbir zaman bir dakikadan kısa değildir. +daha erkense o kullanılır. Havuz hesabının zamanı hiçbir zaman bir dakikadan +kısa değildir; ana hesap sıfırlanması olduğu gibi kullanılır. Goal'ı o zamandan sonra sürdürün; yönlendirme güncel durumdan hesap seçer. +Önce başka bir havuz hesabı denenip istenen modeli desteklemediğini söylediğinde +ve istek başka bir hesaba geçebildiğinde de aynı ret döner. İstemci o hesabın +model hatası yerine ana hesabın sınırını ve yukarıda açıklanan önerilen yeniden +deneme zamanını görür. Yüklenmiş dosya taşıyan, tek hesaba bağlı olan ya da hesap +değiştirmek için gönderim hakkı kalmamış bir istek o hesabın model hatasını almaya +devam eder; diğer hesabın kota reddi önceki gibi döner. + ## İlk yeniden bağlanma satırı neden görünmeyebilir? Herkese açık Codex `rust-v0.158.0-alpha.2.1` kaynaklarında normal akış yeniden diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index c9abac57f5c..1c6589a43e6 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1187,7 +1187,7 @@ "loopback-listener-admission.test.ts": "server", "loopback-listener-integration.test.ts": "server", "macos-serial-lanes.test.ts": "ci-workflows", - "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", + "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", "main-account-hard-lock-model-refusal.test.ts": "codex-integration", "main-account-hard-lock-default.test.ts": "codex-integration", "main-account-hard-lock-policy.test.ts": "codex-integration", "main-account-hard-lock-refusal-read.test.ts": "codex-integration", "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration", diff --git a/src/server/responses/core-codex-account.ts b/src/server/responses/core-codex-account.ts index 777f81f6c8b..e9e32f5cafd 100644 --- a/src/server/responses/core-codex-account.ts +++ b/src/server/responses/core-codex-account.ts @@ -69,6 +69,8 @@ import { CodexAuthContextError, CodexAccountCooldownError, CodexMainProfileDrainingError, + CodexMainAccountHardLockError, + CodexMainAccountCreditsOffError, headersForCodexAuthContext, applyCodexAuthContextToProvider, stripCodexRuntimeProviderFields, @@ -837,6 +839,17 @@ export async function retryCodexPoolOnAlternateAccount( releaseCodexAuthContextProbeLease(firstAuthCtx); throw error; } + // The only alternate was main, and main's own policy refused it. The first account declined + // the model, so its 400 is not why this request cannot be served: returning it reports the + // model as unsupported while the login that can serve it is waiting for a reset. Let the + // owner map the policy refusal instead, which names that reset. + if ((error instanceof CodexMainAccountHardLockError || error instanceof CodexMainAccountCreditsOffError) + && await shouldRetryCodexPoolAccountModel400(firstResponse, route.modelId, options.abortSignal, parsed.modelId)) { + accountMovePermit?.release(); + releaseCodexAuthContextProbeLease(firstAuthCtx); + await firstResponse.body?.cancel().catch(() => undefined); + return { kind: "transport", error, authCtx: firstAuthCtx }; + } } // A validated request-owned main bearer is a real alternate when the failed credential was a // stored Pool account. It has no Pool account id to promote or cool, but it can own this one diff --git a/structure/transports/responses-failover.md b/structure/transports/responses-failover.md index e6e66355469..e5bc20c5fb6 100644 --- a/structure/transports/responses-failover.md +++ b/structure/transports/responses-failover.md @@ -555,6 +555,8 @@ Precommit Codex model refusals use bounded account recovery for HTTP `detail` an `error.message` bodies. Only an exact HTTP 400 refusal naming the requested or wire model establishes denial evidence; ordinary malformed requests and committed stream errors do not authorize another send. Account selectors, uploaded files and send budgets retain their existing restrictions. +When the only alternate is a main login refused by its hard lock or credits-off hold, the client +receives that policy refusal with its reset instead of the first account's model 400. OpenCode Go inference POSTs obey the same operator gate; the destination itself does not authorize replay. A granted pre-header replacement that returns transient 5xx has its body cancelled and returns diff --git a/tests/codex-integration/main-account-hard-lock-model-refusal.test.ts b/tests/codex-integration/main-account-hard-lock-model-refusal.test.ts new file mode 100644 index 00000000000..1615098fb7e --- /dev/null +++ b/tests/codex-integration/main-account-hard-lock-model-refusal.test.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { reconcileMainCodexAccountRuntimeState, resetMainCodexAccountIdentityTrackingForTests } from "../../src/codex/account-lifecycle"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearAccountNeedsReauth } from "../../src/codex/account-runtime-state"; +import { captureMainQuotaWriter, clearMainAccountInfoCache, observeMainQuotaCredential, observeMainQuotaIdentity } from "../../src/codex/main-account-cache"; +import { resetCodexModelEntitlementCacheForTests } from "../../src/codex/model-entitlements"; +import { clearAccountQuota, setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { clearCodexUpstreamHealth, clearThreadAccountMap } from "../../src/codex/routing"; +import { handleResponses } from "../../src/server/responses"; +import type { OcxConfig } from "../../src/types"; +import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; +import { drainAndRemoveFixtureRoots } from "../helpers/fixture-teardown"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; + +const MODEL = "gpt-5.5"; +const MAIN_ACCOUNT = "lock-refusal-main"; +const POOL_ID = "lock-refusal-pool"; +const POOL_TOKEN = "fixture-lock-refusal-pool-access"; +const mainToken = fakeChatGptJwt({ + exp: Math.floor(Date.now() / 1000) + 86_400, + "https://api.openai.com/auth": { chatgpt_account_id: MAIN_ACCOUNT }, +}); +const shortResetAt = Math.floor(Date.now() / 1000) + 3_600; +const originalFetch = globalThis.fetch; +let home: string; +let previousHome: string | undefined; +let previousCodexHome: string | undefined; +let releaseSpendHome: (() => void) | undefined; + +beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + previousCodexHome = process.env.CODEX_HOME; + home = mkdtempSync(join(tmpdir(), "ocx-main-lock-model-refusal-")); + process.env.OPENCODEX_HOME = home; + process.env.CODEX_HOME = home; + releaseSpendHome = acquireOwnedSpendHome(); + clearAccountQuota(); + clearMainAccountInfoCache(); + clearCodexUpstreamHealth(); + clearThreadAccountMap(); + clearAccountNeedsReauth(POOL_ID); + resetMainCodexAccountIdentityTrackingForTests(); + resetCodexModelEntitlementCacheForTests(); + observeMainQuotaIdentity(MAIN_ACCOUNT); + observeMainQuotaCredential(mainToken, MAIN_ACCOUNT); + saveCodexAccountCredential(POOL_ID, { + accessToken: POOL_TOKEN, refreshToken: "fixture-lock-refusal-pool-refresh", + expiresAt: Date.now() + 3_600_000, chatgptAccountId: "lock-refusal-pool-account", + }); +}); + +afterEach(async () => { + releaseSpendHome?.(); + releaseSpendHome = undefined; + globalThis.fetch = originalFetch; + clearAccountQuota(); + clearMainAccountInfoCache(); + clearCodexUpstreamHealth(); + clearThreadAccountMap(); + resetMainCodexAccountIdentityTrackingForTests(); + resetCodexModelEntitlementCacheForTests(); + await drainAndRemoveFixtureRoots({ + roots: [{ path: home }], + restoreEnvironment: () => { + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = previousCodexHome; + }, + }); +}); + +function observeMainShortUsage(shortPercent: number): void { + const writer = captureMainQuotaWriter(MAIN_ACCOUNT); + if (!writer) throw new Error("fixture identity was not observed"); + setAccountQuotaFromParsed("__main__", { + shortPercent, shortResetAt, shortWindowSeconds: 18_000, weeklyPercent: 18, + }, undefined, writer); +} + +/** One turn through a pool of the main login and a stored account that cannot serve MODEL. */ +async function dispatch(options: { hardLock?: false; poolRefusal?: Response; storedMain?: true } = {}): Promise<{ response: Response; sends: string[] }> { + const sends: string[] = []; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + if (!String(input).endsWith("/responses")) return new Response(null, { status: 404 }); + const bearer = new Headers(init?.headers).get("authorization"); + sends.push(bearer === `Bearer ${POOL_TOKEN}` ? "pool" : bearer === `Bearer ${mainToken}` ? "main" : "other"); + if (bearer === `Bearer ${POOL_TOKEN}`) { + return options.poolRefusal ?? Response.json({ + detail: `The '${MODEL}' model is not supported when using Codex with a ChatGPT account.`, + }, { status: 400 }); + } + return Response.json({ id: "resp_lock_refusal_fixture", status: "completed", model: MODEL, + output: [{ type: "message", role: "assistant", content: [{ type: "output_text", text: "ok" }] }], + usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 } }); + }) as typeof fetch; + const config = { + defaultProvider: "openai", autoSwitchThreshold: 0, + ...(options.hardLock === false ? { codexMainAccountHardLock: false } : {}), + providers: { openai: { adapter: "openai-responses", authMode: "forward", codexAccountMode: "pool", + baseUrl: "https://chatgpt.com/backend-api/codex", upstreamWebsocket: false } }, + codexAccounts: [{ id: POOL_ID, email: "pool@example.test", isMain: false, plan: "free" }], + } as OcxConfig; + if (options.storedMain) { + writeFileSync(join(home, "auth.json"), JSON.stringify({ + tokens: { access_token: mainToken, refresh_token: "fixture-lock-refusal-main-refresh", account_id: MAIN_ACCOUNT }, + })); + reconcileMainCodexAccountRuntimeState(); + } + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", + headers: { "content-type": "application/json", + ...(options.storedMain ? {} : { authorization: `Bearer ${mainToken}`, "chatgpt-account-id": MAIN_ACCOUNT }) }, + body: JSON.stringify({ model: MODEL, stream: false, input: "hello" }), + }), config, { model: "", provider: "" }, {}); + return { response, sends }; +} + +test.each([ + ["the caller's own", {}], + ["the stored", { storedMain: true }], +] as const)("a pool account's model refusal does not replace the hard-lock refusal for %s main login", async (_owner, options) => { + observeMainShortUsage(91); + const { response, sends } = await dispatch(options); + expect(sends).toEqual(["pool"]); + expect(response.status).toBe(429); + const { error } = await response.json() as { error: Record }; + expect(error).toMatchObject({ type: "usage_limit_reached", resets_at: shortResetAt }); + expect(String(error.message)).toContain("main-account quota policy"); +}); + +test("a main login held at its usage limit with credits off answers the same way", async () => { + observeMainShortUsage(100); + const { response, sends } = await dispatch({ hardLock: false }); + expect(sends).toEqual(["pool"]); + expect(response.status).toBe(429); + const { error } = await response.json() as { error: Record }; + expect(String(error.message)).toContain("spending ChatGPT credits is off"); +}); + +test("a pool account's quota refusal is still returned while main is locked", async () => { + observeMainShortUsage(91); + const { response, sends } = await dispatch({ poolRefusal: Response.json( + { error: { code: "usage_limit_reached", message: "fixture pool quota exhausted" } }, + { status: 429, headers: { "retry-after": "60" } }, + ) }); + expect(sends).toEqual(["pool"]); + expect(response.status).toBe(429); + const { error } = await response.json() as { error: Record }; + expect(error.message).toBe("fixture pool quota exhausted"); +}); + +test("below the lock threshold the caller's main serves the request itself", async () => { + observeMainShortUsage(89); + const { response, sends } = await dispatch(); + expect(sends).toEqual(["main"]); + expect(response.status).toBe(200); +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 17881aa720b..89f9ef44ec6 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1122,7 +1122,7 @@ "loop-reasoning-replay.test.ts": "images", "loop.test.ts": "images", "loopback-companion-client-targets.test.ts": "server", "loopback-listener-admission.test.ts": "server", "local-control-socket.test.ts": "server", "local-control-socket-windows.test.ts": "server", "loopback-listener-integration.test.ts": "server", "macos-serial-lanes.test.ts": "ci-workflows", - "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", + "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", "main-account-hard-lock-model-refusal.test.ts": "codex-integration", "main-account-hard-lock-default.test.ts": "codex-integration", "main-account-hard-lock-policy.test.ts": "codex-integration", "main-account-hard-lock-refusal-read.test.ts": "codex-integration", "main-account-hard-lock-recovery.test.ts": "codex-integration", "main-account-credit-renewal.test.ts": "codex-integration", From d6dbc1d04adf0c3deb7df5bee0ab46630f93a3ca Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 05:59:52 +0900 Subject: [PATCH 26/64] fix(transports): opt-in classical TLS groups for hosts that reset on the 1.4.x ClientHello (#9197) * fix(transports): host-scoped classical TLS groups for PQ-incompatible upstreams Bun 1.4.x offers X25519MLKEM768 in every fetch() ClientHello (~1500 bytes, split across two TCP segments on a 1460-byte MSS path). Some upstream edges - observed on an Azure OpenAI host - intermittently reset those connections during the handshake, which surfaces as synthetic upstream_reset_replay_refused 429s. Bun 1.3.8 sent a ~520-byte classical-only ClientHello and does not trip. Add an opt-in escape hatch mirroring OCX_FRESH_CONNECTION_HOSTS: OCX_TLS_CLASSICAL_GROUPS_HOSTS names hosts whose final HTTPS sends use classical groups only (X25519:P-256:P-384, ~260-byte ClientHello). Matching follows the rewritten wire destination, applies only to https:, preserves existing TLS options including certificate verification, and leaves every other request untouched. Measured on Windows 11 against the affected host: default TLS 10/70 ECONNRESET on Bun 1.4.5 and 12/16 synthetic 429s through a Bun 1.4.4 proxy; with the override 0/70 and 16/16 success including streaming, and 12/12 through a live patched proxy after transition. Certificate verification confirmed with a local self-signed TLS server: untrusted rejected, trusted accepted. Upstream report with the ClientHello captures and version matrix: oven-sh/bun#49346. * fix(socks5): carry request TLS options into the SOCKS5 handshake The classical-groups override (and any caller tls init) was dropped on the built-in SOCKS5 transport: secureSocket hardcoded its tls.connect options. Thread init.tls through so a matching HTTPS send negotiates with the selected groups while certificate verification and unmatched requests stay unchanged. Regression test parses the ClientHello key shares at the SOCKS5 boundary. * fix(socks5): review follow-ups for the TLS curve passthrough Address maintainer review and CodeRabbit findings: only ecdhCurve now crosses the SOCKS5 TLS boundary (the transport keeps its verification and server-name policy, and caller ALPN can no longer reach a transport that speaks HTTP/1.1); the curve regression gains a real control that asserts the pinned runtime default offers the hybrid share, so dropping the passthrough fails the test; the capture fixture propagates pre-ClientHello failures under a bounded deadline instead of hanging; and both new test files are registered in the test-layout manifest and membership fixture. * fix(transports): preserve TLS policies for opted-in hosts * fix(transports): require TLS context proof for wrappers * fix(transports): propagate TLS context transparency through built-in Mistral and xAI wrappers and assert SNI boundary Co-authored-by: x3M3x --------- Co-authored-by: x3M3x Co-authored-by: @{id=98298256; login=x3M3x}.login <98298256+x3M3x@users.noreply.github.com> --- .../docs/es/reference/configuration/server.md | 14 + .../docs/reference/configuration/server.md | 20 ++ scripts/test-layout/layout.json | 4 +- src/lib/socks5-fetch.ts | 27 +- src/lib/tls-context-proof.ts | 16 + src/providers/anthropic-billing-ownership.ts | 2 + src/providers/api-key-response-ownership.ts | 2 + src/providers/mistral-transport.ts | 7 +- src/providers/passive-key-observation.ts | 2 + src/providers/xai-transport.ts | 7 +- src/server/responses/fetch-helpers.ts | 25 +- structure/transports/responses.md | 2 +- tests/fixtures/test-layout-expected.json | 4 +- tests/lib/socks5-tls-curve.test.ts | 187 +++++++++++ tests/responses/classical-tls-hosts.test.ts | 293 ++++++++++++++++++ .../responses-fetch-helpers-boundary.test.ts | 5 + 16 files changed, 606 insertions(+), 11 deletions(-) create mode 100644 src/lib/tls-context-proof.ts create mode 100644 tests/lib/socks5-tls-curve.test.ts create mode 100644 tests/responses/classical-tls-hosts.test.ts diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index bb5ca1dd732..75003aeecbf 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -232,6 +232,20 @@ El valor es una lista separada por comas de nombres de host. El emparejamiento e Un envío coincidente lleva `Connection: close` y se envía con keep-alive deshabilitado. La decisión se toma en contra de la dirección realmente utilizada en el cable, por lo que todavía se aplica cuando un proveedor de transporte reescribe el destino después de la selección de credenciales. La latencia por solicitud aumenta ligeramente para esos hosts, ya que cada solicitud paga un nuevo protocolo TCP y TLS; nombre solo los hosts que lo necesitan. + + +## Compatibilidad TLS para hosts de origen específicos + +Algunas rutas de red ascendentes restablecen las conexiones cuando el protocolo de enlace TLS ofrece un intercambio de claves híbrido poscuántico. Para probar un intercambio de claves solo clásico para los hosts nombrados en las rutas HTTP de Responses y Chat nativo, defina esta variable de entorno antes de iniciar OpenCodex: + +```bash +OCX_TLS_CLASSICAL_GROUPS_HOSTS="api.example.com" ocx start +``` + +El valor es una lista separada por comas de nombres de host. La coincidencia no distingue entre mayúsculas y minúsculas, incluye subdominios e ignora un punto DNS final; omita esquemas, puertos y rutas. La opción afecta solo a las solicitudes HTTPS a los hosts coincidentes y conserva la verificación de certificados. Elimina el grupo híbrido poscuántico para esas conexiones, así que úsela solo para los extremos que necesiten esta solución de compatibilidad. Sin definir o vacía mantiene el comportamiento TLS predeterminado del entorno de ejecución. + +Una solicitud coincidente que use `FetchSession` debe proporcionar su configuración TLS en la propia solicitud. Las solicitudes coincidentes que usan transportes personalizados o perfiles TLS se rechazan porque no se pueden inspeccionar sus ajustes de seguridad. Las demás solicitudes no se ven afectadas. + ## Acceso remoto diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index 430fb67e5cb..b4cadcc5c2c 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -320,6 +320,26 @@ transport rewrites the destination after credential selection. Per-request laten for those hosts, since each request pays a fresh TCP and TLS handshake; name only the hosts that need it. +## TLS compatibility for specific upstream hosts + +Some upstream network paths reset connections when the TLS handshake offers a hybrid +post-quantum key exchange. To try a classical-only key exchange for named hosts on the +Responses and native Chat HTTP paths, set this environment variable before starting OpenCodex: + +```bash +OCX_TLS_CLASSICAL_GROUPS_HOSTS="api.example.com" ocx start +``` + +The value is a comma-separated list of hostnames. Matching is case-insensitive and includes +subdomains, ignoring a trailing DNS root dot; omit schemes, ports and paths. The option affects HTTPS requests to matching hosts +only and preserves certificate verification. It removes the hybrid post-quantum group for +those connections, so use it only for endpoints that need this compatibility workaround. +Unset or empty means the runtime's default TLS behavior. + +A matching request using a `FetchSession` must supply its TLS settings on the request itself. +Matching requests using custom provider transports or TLS profiles are refused because their +connection security settings cannot be safely inspected. Other requests are unaffected. + ## Remote access The default `127.0.0.1` bind is loopback-only. A non-loopback address such as `0.0.0.0` or a tailnet IP requires a data-admission credential for model requests: a configured client key in `config.apiKeys` or a shared data token. Management routes `/api/*` use the independent `OPENCODEX_ADMIN_AUTH_TOKEN` or generated admin token, including on loopback. A data credential does not grant management access; never give the admin token to a model client. diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 1c6589a43e6..3b34de7df37 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -970,7 +970,7 @@ "flash-route-image-modalities.test.ts": "providers", "format-result.test.ts": "web-search", "forward-admission-separation.test.ts": "providers", - "fresh-connection-optout.test.ts": "responses", + "classical-tls-hosts.test.ts": "responses", "fresh-connection-optout.test.ts": "responses", "video-capabilities.test.ts": "videos", "video-image-input.test.ts": "videos", "fulfill-video.test.ts": "videos", "gather-routed-models-single-flight.test.ts": "codex-integration", "gcp-adc.test.ts": "adapters/google", @@ -1731,7 +1731,7 @@ "sidecar-tracker.test.ts": "vision", "skill-ocx.test.ts": "ci-workflows", "slug-codec.test.ts": "codex-integration", - "socks5-fetch.test.ts": "lib", "socks5-tls-lifecycle.test.ts": "lib", + "socks5-fetch.test.ts": "lib", "socks5-tls-curve.test.ts": "lib", "socks5-tls-lifecycle.test.ts": "lib", "socks5-upload-lifecycle.test.ts": "lib", "socks5-reader-lifecycle.test.ts": "lib", "socks5-timeout-cleanup.test.ts": "lib", "spend-ceiling-enforcement.test.ts": "lib", "spend-instrumentation-log.test.ts": "server", diff --git a/src/lib/socks5-fetch.ts b/src/lib/socks5-fetch.ts index 03ce04d0539..3e82ce5d07b 100644 --- a/src/lib/socks5-fetch.ts +++ b/src/lib/socks5-fetch.ts @@ -309,7 +309,22 @@ function requestHeaders(request: Request, target: URL): { text: string; chunked: }; } -async function secureSocket(socket: Socket, target: URL, signal: AbortSignal): Promise { +function hostOptedIntoClassicalTls(hostname: string, hostsEnv = process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS): boolean { + if (!hostsEnv) return false; + const host = hostname.toLowerCase().replace(/\.$/, ""); + for (const entry of hostsEnv.split(",")) { + const target = entry.trim().toLowerCase().replace(/^\.+/, "").replace(/\.$/, ""); + if (target && (host === target || host.endsWith(`.${target}`))) return true; + } + return false; +} + +async function secureSocket( + socket: Socket, + target: URL, + signal: AbortSignal, + ecdhCurve: string | undefined, +): Promise { return new Promise((resolve, reject) => { if (signal.aborted) { socket.destroy(); @@ -320,6 +335,8 @@ async function secureSocket(socket: Socket, target: URL, signal: AbortSignal): P socket, servername: target.hostname, rejectUnauthorized: true, + // shortcut: only the curve override crosses this boundary; the transport owns verification and server name. + ...(ecdhCurve ? { ecdhCurve } : {}), }); let settled = false; // Absolute deadline: a peer sending occasional TLS bytes must not extend the handshake. @@ -691,7 +708,13 @@ export async function socks5Fetch( }; request.signal.addEventListener("abort", onAbort, { once: true }); try { - if (target.protocol === "https:") socket = await secureSocket(tunnel, target, request.signal); + if (target.protocol === "https:") { + const requestedCurve = (init?.tls as { ecdhCurve?: string } | undefined)?.ecdhCurve; + const ecdhCurve = typeof requestedCurve === "string" && requestedCurve && hostOptedIntoClassicalTls(target.hostname) + ? requestedCurve + : undefined; + socket = await secureSocket(tunnel, target, request.signal, ecdhCurve); + } // A positive Bun fetch timeout is the request's socket idle budget. Keep the tunnel's // existing bound for callers that didn't request a positive timeout. const idleMs = init?.timeout; diff --git a/src/lib/tls-context-proof.ts b/src/lib/tls-context-proof.ts new file mode 100644 index 00000000000..314b6020005 --- /dev/null +++ b/src/lib/tls-context-proof.ts @@ -0,0 +1,16 @@ +const TLS_CONTEXT_TRANSPARENT = Symbol.for("opencodex.tls-context.transparent-executor"); + +/** Marks a wrapper that forwards request TLS settings without owning a hidden TLS session. */ +export function markTlsContextTransparentExecutor(executor: F): F { + (executor as unknown as Record)[TLS_CONTEXT_TRANSPARENT] = true; + return executor; +} + +export function isTlsContextTransparentExecutor(executor: unknown): boolean { + return executor === globalThis.fetch || (typeof executor === "function" + && (executor as unknown as Record)[TLS_CONTEXT_TRANSPARENT] === true); +} + +export function inheritTlsContextProof(executor: typeof globalThis.fetch, underlying: typeof globalThis.fetch): void { + if (isTlsContextTransparentExecutor(underlying)) markTlsContextTransparentExecutor(executor); +} diff --git a/src/providers/anthropic-billing-ownership.ts b/src/providers/anthropic-billing-ownership.ts index 892ed67c663..91476d9c1d9 100644 --- a/src/providers/anthropic-billing-ownership.ts +++ b/src/providers/anthropic-billing-ownership.ts @@ -6,6 +6,7 @@ import type { OcxConfig } from "../types"; import { registerProviderResponseProvenance } from "./request-pacing"; import { isEgressTransparentExecutor, markEgressTransparentExecutor } from "../lib/provider-egress"; import { inheritPassiveKeyProof } from "../lib/passive-key-fetch-proof"; +import { inheritTlsContextProof } from "../lib/tls-context-proof"; interface BillingSendOwnership { readonly providerName: string; @@ -47,6 +48,7 @@ export function anthropicBillingPhysicalFetch( return response; }) as typeof globalThis.fetch; inheritPassiveKeyProof(wrapped, physicalFetch); + inheritTlsContextProof(wrapped, physicalFetch); return isEgressTransparentExecutor(physicalFetch) ? markEgressTransparentExecutor(wrapped) : wrapped; } diff --git a/src/providers/api-key-response-ownership.ts b/src/providers/api-key-response-ownership.ts index 250cd998c41..b6807ed2b0c 100644 --- a/src/providers/api-key-response-ownership.ts +++ b/src/providers/api-key-response-ownership.ts @@ -1,6 +1,7 @@ import type { OcxConfig, OcxProviderConfig } from "../types"; import { isEgressTransparentExecutor, markEgressTransparentExecutor } from "../lib/provider-egress"; import { inheritPassiveKeyProof } from "../lib/passive-key-fetch-proof"; +import { inheritTlsContextProof } from "../lib/tls-context-proof"; import { isNonReplayableResponse } from "../lib/upstream-retry"; import { providerApiKeySelectionOwnsFailure } from "./api-key-selection"; import { recordDistributedKeyFailure } from "./key-failover"; @@ -45,6 +46,7 @@ export function distributedKeyPhysicalFetch( return response; }) as typeof globalThis.fetch; inheritPassiveKeyProof(wrapped, physicalFetch); + inheritTlsContextProof(wrapped, physicalFetch); return isEgressTransparentExecutor(physicalFetch) ? markEgressTransparentExecutor(wrapped) : wrapped; } diff --git a/src/providers/mistral-transport.ts b/src/providers/mistral-transport.ts index 18221763268..dead3b39c12 100644 --- a/src/providers/mistral-transport.ts +++ b/src/providers/mistral-transport.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import type { OcxProviderConfig } from "../types"; import { isEgressTransparentExecutor, markEgressTransparentExecutor } from "../lib/provider-egress"; import { isPassiveKeyTransparent, markPassiveKeyTransparent, markPassiveKeyDeferred, PASSIVE_KEY_SEND } from "../lib/passive-key-fetch-proof"; +import { inheritTlsContextProof, markTlsContextTransparentExecutor } from "../lib/tls-context-proof"; import { configuredOutboundFetch } from "../lib/proxy-env"; import { waitOutsideProviderHeaderDeadline } from "../lib/provider-admission-wait"; import { markSameTargetRetryHold, sleepWithAbort } from "../lib/upstream-retry"; @@ -199,7 +200,10 @@ export function resolveMistralTransport( if (!isCanonicalMistralChat(provider) || (provider.fetch && wrapped.has(provider.fetch))) return provider; const baseFetch = provider.fetch ?? markEgressTransparentExecutor(((input, init) => configuredOutboundFetch(input, init)) as typeof globalThis.fetch); - if (!provider.fetch) markPassiveKeyTransparent(baseFetch); + if (!provider.fetch) { + markPassiveKeyTransparent(baseFetch); + markTlsContextTransparentExecutor(baseFetch); + } const attemptFetch = (async (input, init) => { const send = () => { const observe = (init as (RequestInit & { [PASSIVE_KEY_SEND]?: (input: RequestInfo | URL, init: RequestInit) => void }) | undefined)?.[PASSIVE_KEY_SEND]; @@ -244,6 +248,7 @@ export function resolveMistralTransport( return response; }) as typeof globalThis.fetch; if (isEgressTransparentExecutor(baseFetch)) markEgressTransparentExecutor(attemptFetch); + inheritTlsContextProof(attemptFetch, baseFetch); if (isPassiveKeyTransparent(baseFetch)) { markPassiveKeyTransparent(attemptFetch); markPassiveKeyDeferred(attemptFetch); diff --git a/src/providers/passive-key-observation.ts b/src/providers/passive-key-observation.ts index 02e3eabbc90..5df9bdc01e3 100644 --- a/src/providers/passive-key-observation.ts +++ b/src/providers/passive-key-observation.ts @@ -1,6 +1,7 @@ import type { OcxConfig, OcxProviderConfig } from "../types"; import { getConfigDir } from "../config/paths"; import { isEgressTransparentExecutor, markEgressTransparentExecutor } from "../lib/provider-egress"; +import { inheritTlsContextProof } from "../lib/tls-context-proof"; import { isPassiveKeyDeferred, isPassiveKeyTransparent, PASSIVE_KEY_SEND } from "../lib/passive-key-fetch-proof"; import { isKeychainReference, passiveKeychainGeneration, peekResolvedProviderKey, resolveProviderApiKeyPassively } from "./api-key-resolve"; import { passiveKeyLimits, type PassiveKeyProvider } from "./quota/passive-key-limits"; @@ -209,6 +210,7 @@ export function passiveKeyPhysicalFetch( return response; } finally { reservation?.cancel(); } }) as typeof globalThis.fetch; + inheritTlsContextProof(wrapped, physicalFetch); return isEgressTransparentExecutor(physicalFetch) ? markEgressTransparentExecutor(wrapped) : wrapped; } diff --git a/src/providers/xai-transport.ts b/src/providers/xai-transport.ts index d98df79dda5..e81a2ce7aab 100644 --- a/src/providers/xai-transport.ts +++ b/src/providers/xai-transport.ts @@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto"; import type { OcxProviderConfig } from "../types"; import { isEgressTransparentExecutor, markEgressTransparentExecutor } from "../lib/provider-egress"; import { isPassiveKeyTransparent, markPassiveKeyTransparent } from "../lib/passive-key-fetch-proof"; +import { inheritTlsContextProof, markTlsContextTransparentExecutor } from "../lib/tls-context-proof"; import { configuredOutboundFetch } from "../lib/proxy-env"; import { resolveGithubCopilotTransport } from "./github-copilot-transport"; import { resolveMistralTransport } from "./mistral-transport"; @@ -166,13 +167,17 @@ export function resolveProviderTransport( // the configuration named a proxy. const baseFetch = provider.fetch ?? markEgressTransparentExecutor(((input, init) => configuredOutboundFetch(input, init)) as typeof globalThis.fetch); - if (!provider.fetch) markPassiveKeyTransparent(baseFetch); + if (!provider.fetch) { + markPassiveKeyTransparent(baseFetch); + markTlsContextTransparentExecutor(baseFetch); + } const attemptFetch = ((input, init) => baseFetch(input, withGeneratedRequestId(init, requestId, stableHeaders))) as typeof globalThis.fetch; // This wrapper only adds a header and forwards the init, so it carries a request-scoped proxy // option through to whatever it wraps — but only if what it wraps carries it too. A // configured executor owns its own routing and is not assumed to. if (isEgressTransparentExecutor(baseFetch)) markEgressTransparentExecutor(attemptFetch); + inheritTlsContextProof(attemptFetch, baseFetch); if (isPassiveKeyTransparent(baseFetch) && !Object.keys(stableHeaders).some(name => ["authorization", "x-api-key", "api-key"].includes(name.toLowerCase()))) markPassiveKeyTransparent(attemptFetch); return { diff --git a/src/server/responses/fetch-helpers.ts b/src/server/responses/fetch-helpers.ts index f591de22139..73723819a17 100644 --- a/src/server/responses/fetch-helpers.ts +++ b/src/server/responses/fetch-helpers.ts @@ -37,6 +37,7 @@ import { type ProviderEgressBinding, } from "../../lib/provider-egress"; import { redactSecretString } from "../../lib/redact"; +import { inheritTlsContextProof, isTlsContextTransparentExecutor, markTlsContextTransparentExecutor } from "../../lib/tls-context-proof"; import { outboundCredentials } from "../../lib/outbound-credential-registry"; import { compressUpstreamRequestBody, isCanonicalCodexResponsesUrl } from "./request-compression"; import { redeemOutboundTurnState, TURN_STATE_BINDING_INIT, turnStateBinding } from "../turn-state-handles"; @@ -153,10 +154,10 @@ export function wantsFreshConnection( if (!hostsEnv) return false; try { const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; - const host = new URL(rawUrl).hostname.toLowerCase(); + const host = new URL(rawUrl).hostname.toLowerCase().replace(/\.$/, ""); const targets = hostsEnv .split(",") - .map(h => h.trim().toLowerCase().replace(/^\.+/, "")) + .map(h => h.trim().toLowerCase().replace(/^\.+/, "").replace(/\.$/, "")) .filter(Boolean); for (const target of targets) { if (host === target || host.endsWith(`.${target}`)) return true; @@ -239,6 +240,21 @@ export function sendWithConnectionPolicy( // retry and HTTP fallback re-enters here with the caller's original string, so each send derives // its own coded bytes; `headers` is already this send's private copy. const target = input instanceof Request ? input.url : String(input); + const classicalTlsHosts = process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; + const classicalTls = classicalTlsHosts && wantsFreshConnection(input, classicalTlsHosts) + && new URL(target).protocol === "https:"; + const requestTls = (init as BunFetchRequestInit | undefined)?.tls; + if (classicalTls && (init as BunFetchRequestInit | undefined)?.session && !requestTls) { + return Promise.reject(new Error("Cannot apply classical TLS groups to a FetchSession without explicit request TLS settings")); + } + const providerTransport = egress?.provider as { fetch?: unknown; tlsProfile?: unknown } | undefined; + if (classicalTls && ( + !isTlsContextTransparentExecutor(physicalFetch) + || (typeof providerTransport?.fetch === "function" && !isTlsContextTransparentExecutor(providerTransport.fetch)) + || providerTransport?.tlsProfile !== undefined + )) { + return Promise.reject(new Error("Cannot apply classical TLS groups to a custom provider transport")); + } const body = init?.body; const compressed = compressUpstreamRequestBody(target, body, headers); if (compressed) { @@ -254,6 +270,7 @@ export function sendWithConnectionPolicy( headers, redirect: "manual", ...(fresh ? { keepalive: false } : {}), + ...(classicalTls ? { tls: { ...(init as BunFetchRequestInit | undefined)?.tls, ecdhCurve: "X25519:P-256:P-384" } } : {}), ...egressInit, ...(decide || redirectedToLoopback ? { [EGRESS_DECIDED]: true } : {}), ...{ [UPSTREAM_REWRITTEN]: true }, @@ -379,6 +396,7 @@ export function providerFetch( { preconnect: globalThis.fetch.preconnect?.bind(globalThis.fetch) }, ) as typeof globalThis.fetch); markPassiveKeyTransparent(configuredFetch); + markTlsContextTransparentExecutor(configuredFetch); const base = customExecutor ?? configuredFetch; const transport = options.providerName ? providerTlsFetch(options.providerName, provider, base) : base; const preconnect = (...args: Parameters): void => { @@ -400,6 +418,7 @@ export function providerFetch( { preconnect }, ) as typeof globalThis.fetch); inheritPassiveKeyProof(dispatch, transport); + inheritTlsContextProof(dispatch, transport); const httpFetch = Object.assign( async (input: Parameters[0], init?: RequestInit, reacquirePacing?: (provider: OcxProviderConfig, modelId?: string) => Promise, @@ -578,6 +597,8 @@ export function providerFetch( unpacedFetch: markPhysicalSendReceiptExecutor(Object.assign(unpaced, { preconnect }) as typeof globalThis.fetch), }); markEgressTransparentExecutor(paceAware as unknown as typeof globalThis.fetch); + inheritTlsContextProof(paceAware as unknown as typeof globalThis.fetch, transport); + inheritTlsContextProof(paceAware.unpacedFetch, transport); if (customExecutor === undefined && transport === base && !options.dispatchOverride) bindProviderSocketRoute(paceAware, providerName, provider); const { onPhysicalDispatch, dispatchOverride, beforeDispatch, accountAutoPause, ...supportOptions } = options; if (onPhysicalDispatch || dispatchOverride || beforeDispatch || accountAutoPause) { diff --git a/structure/transports/responses.md b/structure/transports/responses.md index a40d2f608cf..4c962ce5340 100644 --- a/structure/transports/responses.md +++ b/structure/transports/responses.md @@ -45,7 +45,7 @@ through their existing upstream-error path without relaying Location. This serve redirect following; providers requiring a redirect must be configured with their final API URL. ### Fetch-helper import boundary -Explicitly opted-in first-party DeepSeek image replay uses `src/server/responses/deepseek-image-files.ts` during credential-bound construction; see the [image byte contract](byte-accounting.md#deepseek-image-replay). Token usage, client compaction and inference dispatch fences are preserved. +Explicitly opted-in first-party DeepSeek image replay uses `src/server/responses/deepseek-image-files.ts` during credential-bound construction; see the [image byte contract](byte-accounting.md#deepseek-image-replay). Token usage, client compaction and inference dispatch fences are preserved. `OCX_TLS_CLASSICAL_GROUPS_HOSTS` opts named hosts and their subdomains into classical TLS groups on the final Responses and native Chat HTTPS send, matching the rewritten destination and ignoring a trailing DNS root dot. Bun fetch preserves other request TLS options; SOCKS5 forwards only `ecdhCurve` for opted-in hosts and keeps its own certificate-verification and server-name policy. A matching send refuses opaque provider transports and a FetchSession without explicit request TLS settings; `src/lib/tls-context-proof.ts` carries TLS transparency through built-in executor wrappers. Unset means the runtime default. `src/server/responses/fetch-helpers.ts` is a transport leaf shared by Responses, compact, and native Chat. Its runtime imports are limited to the Codex WebSocket transport, provider request pacing, and the upstream HTTP-version helper, and core-owned admission-deadline metadata. Provider-local recovery queues share `src/lib/provider-admission-wait.ts`: local waiting retains client cancellation while pausing the upstream header timer, which restarts before dispatch. Server, provider, and WebSocket data types remain type-only edges. Opt-in `codexWsReuseAcrossTurns` (default off) in `src/server/responses/codex-ws-pool.ts` keeps a socket for a provider route, caller, account and thread across turns, waits at most 750ms for a busy socket before dialing another, and leaves `x-codex-turn-state` / `x-codex-turn-metadata` on each frame. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 89f9ef44ec6..9acd75c8a9a 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -959,7 +959,7 @@ "featherless-provider.test.ts": "providers", "fetch-header-timeout.test.ts": "server", "file-size-ratchet.test.ts": "ci-workflows", "fixture-dir-uniqueness.test.ts": "ci-workflows", "import-cycle-ratchet.test.ts": "ci-workflows", "flash-route-image-modalities.test.ts": "providers", "format-result.test.ts": "web-search", - "forward-admission-separation.test.ts": "providers", "fresh-connection-optout.test.ts": "responses", + "forward-admission-separation.test.ts": "providers", "classical-tls-hosts.test.ts": "responses", "fresh-connection-optout.test.ts": "responses", "video-capabilities.test.ts": "videos", "video-image-input.test.ts": "videos", "fulfill-video.test.ts": "videos", "gather-routed-models-single-flight.test.ts": "codex-integration", "gcp-adc.test.ts": "adapters/google", "vertex-adc-verified.test.ts": "adapters/google", "gemini-37-flash-migration.test.ts": "adapters/google", "gemini-4-argon-antigravity.test.ts": "adapters/google", "gemini-4-hydrogen-antigravity.test.ts": "adapters/google", "gemini-progress-history.test.ts": "adapters/google", "antigravity-account-roster.test.ts": "adapters/google", "gemini-inline.test.ts": "images", "gemini-web-search.test.ts": "adapters/google", @@ -1517,7 +1517,7 @@ "sidecar-settings-web-search-gate.test.ts": "vision", "sidecar-settings-web-search-off.test.ts": "vision", "sidecar-settings-web-search-stream.test.ts": "vision", "sidecar-tracker.test.ts": "vision", "skill-ocx.test.ts": "ci-workflows", "slug-codec.test.ts": "codex-integration", - "socks5-fetch.test.ts": "lib", "socks5-tls-lifecycle.test.ts": "lib", + "socks5-fetch.test.ts": "lib", "socks5-tls-curve.test.ts": "lib", "socks5-tls-lifecycle.test.ts": "lib", "socks5-upload-lifecycle.test.ts": "lib", "socks5-reader-lifecycle.test.ts": "lib", "socks5-timeout-cleanup.test.ts": "lib", "spend-ceiling-enforcement.test.ts": "lib", "spend-instrumentation-log.test.ts": "server", "spend-ledger-file-journal.test.ts": "lib", "spend-ledger-lifecycle.test.ts": "server", diff --git a/tests/lib/socks5-tls-curve.test.ts b/tests/lib/socks5-tls-curve.test.ts new file mode 100644 index 00000000000..53cd435987e --- /dev/null +++ b/tests/lib/socks5-tls-curve.test.ts @@ -0,0 +1,187 @@ +import { afterEach, describe, test } from "bun:test"; +import assert from "node:assert/strict"; +import { createServer, type AddressInfo, type Socket } from "node:net"; +import { socks5Fetch } from "../../src/lib/socks5-fetch"; + +const originalClassicalTlsHosts = process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; +afterEach(() => { + if (originalClassicalTlsHosts === undefined) delete process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; + else process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = originalClassicalTlsHosts; +}); + +const HYBRID_GROUP = 0x11ec; // X25519MLKEM768 +const X25519 = 0x1d; + +/** Walk the ClientHello extension list once, returning key-share groups, SNI, and whether ALPN was offered. */ +function parseHello(hello: Buffer): { keyShareGroups: number[]; alpnOffered: boolean; serverName?: string } { + let p = 5 + 4 + 2 + 32; + const u16 = () => { const n = hello.readUInt16BE(p); p += 2; return n; }; + let n = hello[p]!; p += 1 + n; n = u16(); p += n; n = hello[p]!; p += 1 + n; + const end = p + 2 + hello.readUInt16BE(p); p += 2; + const keyShareGroups: number[] = []; + let alpnOffered = false; + let serverName: string | undefined; + while (p + 4 <= end) { + const type = u16(); const len = u16(); const stop = p + len; + if (type === 0 && p + 5 <= stop && hello[p + 2] === 0) { + const nameLen = hello.readUInt16BE(p + 3); + if (p + 5 + nameLen <= stop) serverName = hello.subarray(p + 5, p + 5 + nameLen).toString("ascii"); + } + if (type === 51) { + let q = p + 2; + while (q + 4 <= stop) { keyShareGroups.push(hello.readUInt16BE(q)); q += 4 + hello.readUInt16BE(q + 2); } + } + if (type === 16) alpnOffered = true; + p = stop; + } + return { keyShareGroups, alpnOffered, serverName }; +} + +/** + * SOCKS5 stand-in that completes CONNECT, captures the first ClientHello, then drops the socket. + * A fetch failure before any ClientHello rejects instead of hanging, and a capture deadline + * bounds the wait so the fixture always reaches cleanup. + */ +async function captureClientHello( + init?: RequestInit, + options: { deadlineMs?: number; holdAfterHello?: boolean; controller?: AbortController; target?: string } = {}, +): Promise<{ keyShareGroups: number[]; alpnOffered: boolean; serverName?: string }> { + let resolveHello: (hello: Buffer) => void; + const hello = new Promise(resolve => { resolveHello = resolve; }); + const sockets = new Set(); + let capturedHello = false; + const server = createServer(socket => { + sockets.add(socket); + socket.once("error", () => {}); + let stage: "greeting" | "connect" | "tls" = "greeting"; + let buffer = Buffer.alloc(0); + socket.on("data", chunk => { + buffer = Buffer.concat([buffer, chunk]); + if (stage === "greeting") { + if (buffer.length < 2 || buffer.length < 2 + buffer[1]!) return; + buffer = buffer.subarray(2 + buffer[1]!); + socket.write(Buffer.from([5, 0])); + stage = "connect"; + } + if (stage === "connect") { + if (buffer.length < 5 || buffer.length < 7 + buffer[4]!) return; + buffer = buffer.subarray(7 + buffer[4]!); + socket.write(Buffer.from([5, 0, 0, 1, 127, 0, 0, 1, 0, 80])); + stage = "tls"; + } + if (stage === "tls" && buffer.length >= 5 && buffer.length >= 5 + buffer.readUInt16BE(3)) { + capturedHello = true; + resolveHello(buffer.subarray(0, 5 + buffer.readUInt16BE(3))); + if (!options.holdAfterHello) socket.destroy(); + } + }); + }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + const controller = options.controller ?? new AbortController(); + let deadline: ReturnType | undefined; + try { + const port = (server.address() as AddressInfo).port; + const outcome = socks5Fetch(options.target ?? "https://destination.invalid/", { ...init, signal: controller.signal }, `socks5://127.0.0.1:${port}`) + .then(() => ({ ok: true as const }), error => ({ ok: false as const, error })); + const timedOut = new Promise((_, reject) => { + deadline = setTimeout(() => { + const error = new Error(capturedHello ? "TLS teardown deadline expired" : "ClientHello capture deadline expired"); + reject(error); + controller.abort(error); + }, options.deadlineMs ?? 5_000); + }); + const captured = await Promise.race([ + hello, + outcome.then(result => { + if (result.ok) throw new Error("socks5Fetch succeeded before sending a ClientHello"); + throw result.error; + }), + timedOut, + ]); + const result = await Promise.race([outcome, timedOut]); + assert.equal(result.ok, false, "the stand-in must close the TLS connection after capture"); + return parseHello(captured); + } finally { + clearTimeout(deadline); + controller.abort(); + for (const socket of sockets) socket.destroy(); + await new Promise(resolve => server.close(() => resolve())); + } +} + +describe("socks5Fetch TLS options", () => { + test("preserves failures before ClientHello capture", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "destination.invalid"; + await assert.rejects( + captureClientHello({ tls: { ecdhCurve: "invalid-curve" } } as BunFetchRequestInit), + /curve|group/i, + ); + }); + + test("aborts a stalled fetch even after capturing ClientHello", async () => { + const controller = new AbortController(); + await assert.rejects( + captureClientHello(undefined, { deadlineMs: 1_000, holdAfterHello: true, controller }), + /TLS teardown deadline expired/, + ); + assert.ok(controller.signal.aborted); + assert.match(controller.signal.reason.message, /TLS teardown deadline expired/); + }, 10_000); + + test("the pinned runtime default offers the hybrid share, so the override below is distinguishable", async () => { + delete process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; + const byDefault = await captureClientHello(); + assert.ok(byDefault.keyShareGroups.includes(HYBRID_GROUP), + `control failed: runtime default offered ${byDefault.keyShareGroups.map(g => "0x" + g.toString(16))}; ` + + "if the pinned runtime stops offering the hybrid share, this regression loses its discriminating power"); + }); + + test("caller-supplied init.tls.ecdhCurve is ignored when the host did not opt in", async () => { + delete process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; + const withoutOptIn = await captureClientHello({ tls: { ecdhCurve: "X25519:P-256:P-384" } } as BunFetchRequestInit); + assert.ok(withoutOptIn.keyShareGroups.includes(HYBRID_GROUP), + "an unopted host must keep the runtime default hybrid share even if init.tls.ecdhCurve is supplied"); + + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "other.invalid"; + const mismatchedOptIn = await captureClientHello({ tls: { ecdhCurve: "X25519:P-256:P-384" } } as BunFetchRequestInit); + assert.ok(mismatchedOptIn.keyShareGroups.includes(HYBRID_GROUP), + "a non-matching opt-in list must not forward init.tls.ecdhCurve"); + }); + + test("init.tls.ecdhCurve reaches the SOCKS5 TLS handshake for an opted-in host", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "destination.invalid"; + const overridden = await captureClientHello({ tls: { ecdhCurve: "X25519:P-256:P-384" } } as BunFetchRequestInit); + assert.ok(overridden.keyShareGroups.includes(X25519), "a classical key share must be offered"); + assert.ok(!overridden.keyShareGroups.includes(HYBRID_GROUP), "the hybrid share must not be offered"); + }); + + test("accepts a trailing root dot in the configured and destination hostnames", async () => { + const init = { tls: { ecdhCurve: "X25519:P-256:P-384" } } as BunFetchRequestInit; + for (const [configured, target] of [ + ["destination.invalid", "https://destination.invalid./"], + ["destination.invalid.", "https://destination.invalid/"], + [".DESTINATION.INVALID.", "https://sub.destination.invalid./"], + ]) { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = configured; + const captured = await captureClientHello(init, { target }); + assert.ok(!captured.keyShareGroups.includes(HYBRID_GROUP), "the opted-in host must use classical groups"); + assert.ok(captured.keyShareGroups.includes(X25519)); + } + }); + + test("only ecdhCurve crosses the boundary: caller ALPN and verification options do not reach the handshake", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = ".destination.invalid"; + const captured = await captureClientHello({ + tls: { + ecdhCurve: "X25519:P-256:P-384", + ALPNProtocols: ["h2", "http/1.1"], + rejectUnauthorized: false, + servername: "attacker.invalid", + }, + } as BunFetchRequestInit); + assert.equal(captured.alpnOffered, false, "caller ALPN must not be advertised; this transport speaks HTTP/1.1 only"); + assert.equal(captured.serverName, "destination.invalid", "caller servername must not replace the destination SNI"); + assert.ok(!captured.keyShareGroups.includes(HYBRID_GROUP), "the curve override itself must still apply"); + }); +}); + diff --git a/tests/responses/classical-tls-hosts.test.ts b/tests/responses/classical-tls-hosts.test.ts new file mode 100644 index 00000000000..009c874380e --- /dev/null +++ b/tests/responses/classical-tls-hosts.test.ts @@ -0,0 +1,293 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { providerFetch, sendWithConnectionPolicy, wantsFreshConnection } from "../../src/server/responses/fetch-helpers"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { registerUpstreamRewriter, resetUpstreamRewritersForTests } from "../../src/plugins/upstream-hooks"; +import { markEgressTransparentExecutor } from "../../src/lib/provider-egress"; +import { markTlsContextTransparentExecutor } from "../../src/lib/tls-context-proof"; +import { markPassiveKeyTransparent } from "../../src/lib/passive-key-fetch-proof"; +import { anthropicBillingPhysicalFetch } from "../../src/providers/anthropic-billing-ownership"; +import { distributedKeyPhysicalFetch } from "../../src/providers/api-key-response-ownership"; +import { passiveKeyPhysicalFetch } from "../../src/providers/passive-key-observation"; +import { resolveProviderTransport } from "../../src/providers/xai-transport"; + +const originalHosts = process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; +const builtinBinding = { providerName: "fixture", provider: {} }; +const builtinFetch = (executor: typeof fetch) => markTlsContextTransparentExecutor(markEgressTransparentExecutor(executor)); +afterEach(() => { + resetUpstreamRewritersForTests(); + if (originalHosts === undefined) delete process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; + else process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = originalHosts; +}); + +describe("host-scoped classical TLS groups", () => { + test("applies the curve override while preserving TLS verification and request properties", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + const input: BunFetchRequestInit = { + method: "POST", body: "{}", headers: { "X-Test": "value" }, + tls: { rejectUnauthorized: true, serverName: "relay.example" }, + }; + await sendWithConnectionPolicy(builtinFetch(fetcher), "https://relay.example/v1/responses", input, builtinBinding); + expect(observed?.tls).toMatchObject({ + rejectUnauthorized: true, serverName: "relay.example", ecdhCurve: "X25519:P-256:P-384", + }); + expect(observed?.method).toBe("POST"); + expect(observed?.body).toBe("{}"); + expect(new Headers(observed?.headers).get("X-Test")).toBe("value"); + expect((input.tls as Record).ecdhCurve).toBeUndefined(); + }); + + test("leaves nonmatching, cleartext and unconfigured requests unchanged", async () => { + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + for (const url of ["https://other.example/v1", "https://notrelay.example/v1", "http://relay.example/v1"]) { + await sendWithConnectionPolicy(fetcher, url); + expect(observed?.tls).toBeUndefined(); + } + delete process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS; + await sendWithConnectionPolicy(fetcher, "https://relay.example/v1"); + expect(observed?.tls).toBeUndefined(); + }); + + test("matches configured subdomains case-insensitively for Request inputs", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = " .EXAMPLE.test , other.invalid "; + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + await sendWithConnectionPolicy(builtinFetch(fetcher), new Request("https://sub.example.test/v1"), undefined, builtinBinding); + expect((observed?.tls as Record)?.ecdhCurve).toBe("X25519:P-256:P-384"); + }); + + test("matches a trailing DNS root dot in either hostname", async () => { + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + for (const [configured, url] of [ + ["relay.example", "https://relay.example./v1"], + ["relay.example.", "https://relay.example/v1"], + [".EXAMPLE.test.", "https://sub.example.test./v1"], + ]) { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = configured; + await sendWithConnectionPolicy(builtinFetch(fetcher), url, undefined, builtinBinding); + expect((observed?.tls as Record)?.ecdhCurve).toBe("X25519:P-256:P-384"); + } + expect(wantsFreshConnection("https://sub.example.test./v1", ".example.test.")).toBe(true); + expect(wantsFreshConnection("https://example.test/v1", ".")).toBe(false); + }); + + test("refuses to discard TLS settings from a FetchSession", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let dispatched = false; + const fetcher = (async () => { dispatched = true; return new Response("ok"); }) as typeof fetch; + const session = new Bun.FetchSession({ tls: { checkServerIdentity: () => new Error("fixture pin") } }); + try { + await expect(sendWithConnectionPolicy(fetcher, "https://relay.example/v1", { session } as BunFetchRequestInit, + { providerName: "fixture", provider: {} })).rejects.toThrow(/FetchSession/); + expect(dispatched).toBe(false); + } finally { session.close(); } + }); + + test("refuses an opaque provider fetch that may own its TLS session", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let dispatched = false; + const fetcher = (async () => { dispatched = true; return new Response("ok"); }) as typeof fetch; + await expect(sendWithConnectionPolicy(fetcher, "https://relay.example/v1", undefined, + { providerName: "fixture", provider: { fetch: fetcher } as never })).rejects.toThrow(/custom.*transport/i); + expect(dispatched).toBe(false); + }); + + test("refuses a bound FetchSession executor without dispatching", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + const session = new Bun.FetchSession({ tls: { checkServerIdentity: () => new Error("fixture pin") } }); + try { + await expect(sendWithConnectionPolicy(session.fetch as typeof fetch, "https://relay.example/v1")) + .rejects.toThrow(/custom.*transport/i); + } finally { session.close(); } + }); + + test("refuses an opaque executor even when a provider binding is supplied", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let dispatched = false; + const opaque = (async () => { dispatched = true; return new Response("ok"); }) as typeof fetch; + await expect(sendWithConnectionPolicy(opaque, "https://relay.example/v1", undefined, builtinBinding)) + .rejects.toThrow(/custom.*transport/i); + expect(dispatched).toBe(false); + }); + + test("proxy transparency alone does not prove that an executor preserves TLS settings", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let dispatched = false; + const session = new Bun.FetchSession({ tls: { checkServerIdentity: () => new Error("fixture pin") } }); + const opaque = markEgressTransparentExecutor((async (input: Parameters[0], init?: RequestInit) => { + dispatched = true; return session.fetch(input, init); + }) as typeof fetch); + try { + await expect(sendWithConnectionPolicy(opaque, "https://relay.example/v1", undefined, builtinBinding)) + .rejects.toThrow(/custom.*transport/i); + const provider = { adapter: "openai-responses", baseUrl: "https://relay.example/v1" } as OcxProviderConfig; + const wrapped = anthropicBillingPhysicalFetch(opaque, "fixture", provider); + await expect(sendWithConnectionPolicy(wrapped, "https://relay.example/v1", undefined, builtinBinding)) + .rejects.toThrow(/custom.*transport/i); + expect(dispatched).toBe(false); + } finally { session.close(); } + }); + + test("built-in credential observation wrappers preserve the TLS proof", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let observed: BunFetchRequestInit | undefined; + const base = builtinFetch((async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; return new Response("ok"); + }) as typeof fetch); + markPassiveKeyTransparent(base); + const provider = { adapter: "openai-responses", baseUrl: "https://relay.example/v1", apiKey: "fixture-key", + _apiKeyAttempt: { distributed: true, reference: "fixture-key" } } as OcxProviderConfig; + const config = { defaultProvider: "fixture", providers: { fixture: provider } } as OcxConfig; + const billing = anthropicBillingPhysicalFetch(base, "fixture", provider); + const distributed = distributedKeyPhysicalFetch(billing, "fixture", provider, "https://relay.example/v1"); + const physical = passiveKeyPhysicalFetch(distributed, config, "fixture", provider); + expect(billing).not.toBe(base); + expect(distributed).not.toBe(billing); + expect(physical).not.toBe(distributed); + await sendWithConnectionPolicy(physical, "https://relay.example/v1", undefined, builtinBinding); + expect((observed?.tls as Record)?.ecdhCurve).toBe("X25519:P-256:P-384"); + }); + + test("refuses a provider-owned FetchSession executor only for opted-in hosts", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let dispatched = false; + const session = new Bun.FetchSession({ tls: { checkServerIdentity: () => new Error("fixture pin") } }); + const provider = { adapter: "openai-responses", baseUrl: "https://relay.example/v1", + fetch: (async (input: Parameters[0], init?: RequestInit) => { + dispatched = true; return session.fetch(input, init); + }) as typeof fetch, + } as OcxProviderConfig; + try { + await expect(providerFetch(provider, undefined, { providerName: "fixture" })("https://relay.example/v1")) + .rejects.toThrow(/custom.*transport/i); + expect(dispatched).toBe(false); + const otherProvider = { ...provider, fetch: (async () => { dispatched = true; return new Response("ok"); }) as typeof fetch }; + const other = await providerFetch(otherProvider, undefined, { providerName: "fixture" })("https://other.example/v1"); + expect(other.status).toBe(200); + expect(dispatched).toBe(true); + } finally { session.close(); } + }); + + test("leaves an unmatched FetchSession unchanged", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + const session = new Bun.FetchSession({ tls: { checkServerIdentity: () => new Error("fixture pin") } }); + try { + await sendWithConnectionPolicy(fetcher, "https://other.example/v1", { session } as BunFetchRequestInit); + expect(observed?.session).toBe(session); + expect(observed?.tls).toBeUndefined(); + } finally { session.close(); } + }); + + test("preserves explicit request TLS options when a FetchSession is supplied", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + const pin = () => new Error("fixture pin"); + const session = new Bun.FetchSession(); + try { + await sendWithConnectionPolicy(builtinFetch(fetcher), "https://relay.example/v1", + { session, tls: { checkServerIdentity: pin } } as BunFetchRequestInit, builtinBinding); + expect(observed?.tls?.checkServerIdentity).toBe(pin); + expect((observed?.tls as Record)?.ecdhCurve).toBe("X25519:P-256:P-384"); + } finally { session.close(); } + }); + + test("matches the final rewritten destination instead of the original URL", async () => { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "relay.example"; + let observed: BunFetchRequestInit | undefined; + const fetcher = (async (_input: unknown, init?: RequestInit) => { + observed = init as BunFetchRequestInit; + return new Response("ok"); + }) as typeof fetch; + registerUpstreamRewriter("test-rewrite", target => { target.url = "https://relay.example/v1"; }); + await sendWithConnectionPolicy(builtinFetch(fetcher), "https://other.example/v1", undefined, builtinBinding); + expect((observed?.tls as Record)?.ecdhCurve).toBe("X25519:P-256:P-384"); + resetUpstreamRewritersForTests(); + registerUpstreamRewriter("test-rewrite", target => { target.url = "https://other.example/v1"; }); + await sendWithConnectionPolicy(builtinFetch(fetcher), "https://relay.example/v1", undefined, builtinBinding); + expect(observed?.tls).toBeUndefined(); + }); + + test("preserves TLS transparency through resolved built-in Mistral and xAI transports while rejecting opaque inner executors", async () => { + const originalFetch = globalThis.fetch; + const observed: Array<{ url: string; ecdhCurve?: unknown }> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: BunFetchRequestInit) => { + observed.push({ + url: input instanceof Request ? input.url : String(input), + ecdhCurve: (init?.tls as Record | undefined)?.ecdhCurve, + }); + return new Response("ok"); + }) as typeof fetch; + try { + process.env.OCX_TLS_CLASSICAL_GROUPS_HOSTS = "api.mistral.ai, api.x.ai"; + const mistral = resolveProviderTransport("mistral", { + adapter: "openai-chat", + baseUrl: "https://api.mistral.ai/v1", + apiKey: "test-mistral-key", + models: ["mistral-large-latest"], + } as OcxProviderConfig); + const xai = resolveProviderTransport("xai", { + adapter: "openai-responses", + baseUrl: "https://api.x.ai/v1", + apiKey: "test-xai-key", + models: ["grok-4"], + } as OcxProviderConfig); + + expect((await providerFetch(mistral, undefined, { providerName: "mistral" })("https://api.mistral.ai/v1/chat/completions", { method: "POST", body: "{}" })).status).toBe(200); + expect((await providerFetch(xai, undefined, { providerName: "xai" })("https://api.x.ai/v1/responses", { method: "POST", body: "{}" })).status).toBe(200); + expect(observed).toEqual([ + { url: "https://api.mistral.ai/v1/chat/completions", ecdhCurve: "X25519:P-256:P-384" }, + { url: "https://api.x.ai/v1/responses", ecdhCurve: "X25519:P-256:P-384" }, + ]); + + let opaqueCalled = false; + const opaque = (async () => { opaqueCalled = true; return new Response("ok"); }) as typeof fetch; + const opaqueMistral = resolveProviderTransport("mistral", { + adapter: "openai-chat", + baseUrl: "https://api.mistral.ai/v1", + apiKey: "test-mistral-key", + models: ["mistral-large-latest"], + fetch: opaque, + } as OcxProviderConfig & { fetch: typeof fetch }); + const opaqueXai = resolveProviderTransport("xai", { + adapter: "openai-responses", + baseUrl: "https://api.x.ai/v1", + apiKey: "test-xai-key", + models: ["grok-4"], + fetch: opaque, + } as OcxProviderConfig & { fetch: typeof fetch }); + + await expect(providerFetch(opaqueMistral, undefined, { providerName: "mistral" })("https://api.mistral.ai/v1/chat/completions")) + .rejects.toThrow(/custom.*transport/i); + await expect(providerFetch(opaqueXai, undefined, { providerName: "xai" })("https://api.x.ai/v1/responses")) + .rejects.toThrow(/custom.*transport/i); + expect(opaqueCalled).toBe(false); + } finally { + globalThis.fetch = originalFetch; + } + }); +}); diff --git a/tests/responses/responses-fetch-helpers-boundary.test.ts b/tests/responses/responses-fetch-helpers-boundary.test.ts index 0b720007146..22c61610561 100644 --- a/tests/responses/responses-fetch-helpers-boundary.test.ts +++ b/tests/responses/responses-fetch-helpers-boundary.test.ts @@ -223,6 +223,7 @@ describe("Responses fetch-helper import boundary", () => { "../../lib/provider-tls-profile", "../../lib/proxy-env", "../../lib/redact", + "../../lib/tls-context-proof", "../../lib/upstream-http-version", // Import-free plugin rewrite slot (src/plugins/upstream-hooks.ts). "../../plugins/upstream-hooks", @@ -249,6 +250,10 @@ describe("Responses fetch-helper import boundary", () => { expect(expectRuntimeImportBoundary(readFileSync(resolve(repoRoot, "src/lib/passive-key-fetch-proof.ts"), "utf8"))).toEqual([]); }); + test("the TLS context proof is an import-free runtime leaf", () => { + expect(expectRuntimeImportBoundary(readFileSync(resolve(repoRoot, "src/lib/tls-context-proof.ts"), "utf8"))).toEqual([]); + }); + test("the guard recognizes runtime edges and ignores type-only imports", () => { const scan = runtimeImports([ 'import type { T } from "./types";', From e5ba967098d7b9b2c9ef49c3929d5e7b11da0ab2 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:02:10 +0900 Subject: [PATCH 27/64] fix(retry-after): preserve leap-second HTTP dates (#9195) * fix(retry-after): preserve leap-second HTTP dates * fix(retry-after): restrict leap-second carry to month-end 23:59:60 UTC and sync docs Co-authored-by: AaronZ345 --------- Co-authored-by: zhangyu.34 --- .../src/content/docs/es/guides/claude-code.md | 2 +- .../src/content/docs/guides/claude-code.md | 2 +- src/lib/client-retry-after.ts | 8 ++++++-- structure/data-planes/error-detail.md | 2 +- tests/lib/client-retry-after.test.ts | 20 +++++++++++++++++++ tests/server/client-retry-after-sites.test.ts | 5 +++++ 6 files changed, 34 insertions(+), 5 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/claude-code.md b/docs-site/src/content/docs/es/guides/claude-code.md index 79d3466d82b..1a7a3320118 100644 --- a/docs-site/src/content/docs/es/guides/claude-code.md +++ b/docs-site/src/content/docs/es/guides/claude-code.md @@ -655,7 +655,7 @@ Es una medida de compatibilidad, no una afirmación de que cada backend personal **Detener el mapeo de la razón:** `completed` → `tool_use` (si se llama alguna herramienta) o `end_turn`; `incomplete/max_output_tokens` → `max_tokens` `incomplete/content_filter` → `refusal`. -**Taxonomía de error:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, otros 5xx `api_error`. El encabezado `Retry-After` se envía como segundos enteros (una fecha HTTP se convierte en los segundos restantes), con un máximo de ocho días. +**Taxonomía de error:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, otros 5xx `api_error`. El encabezado `Retry-After` se envía como segundos enteros (una fecha HTTP se convierte en los segundos restantes, trasladando un segundo intercalar de fin de mes `23:59:60` al día UTC siguiente), con un máximo de ocho días. diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index 6fccdf4f2fe..ad615d7016c 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -1260,7 +1260,7 @@ on the schema to reject a malformed argument. **Error taxonomy:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -other 5xx `api_error`. `Retry-After` is sent as whole seconds (an HTTP date becomes the remaining seconds), capped at eight days. +other 5xx `api_error`. `Retry-After` is sent as whole seconds (an HTTP date becomes the remaining seconds, carrying a month-end `23:59:60` leap second into the following UTC day), capped at eight days. ## Prompt caching and token usage diff --git a/src/lib/client-retry-after.ts b/src/lib/client-retry-after.ts index 5a52a9bb023..1700453f934 100644 --- a/src/lib/client-retry-after.ts +++ b/src/lib/client-retry-after.ts @@ -20,8 +20,12 @@ function utcMs(day: string, monthName: string, year: number, hour: string, minut const month = MONTHS.get(monthName.toLowerCase()); const [d, h, m, s] = [Number(day), Number(hour), Number(minute), Number(second)]; if (month === undefined || d < 1 || h > 23 || m > 59 || s > 60) return undefined; - const at = Date.UTC(year, month, d, h, m, s); - return new Date(at).getUTCDate() === d ? at : undefined; + if (s === 60 && (h !== 23 || m !== 59)) return undefined; + // Validate the calendar before carrying a month-end leap second into the following day. + const at = Date.UTC(year, month, d, h, m, Math.min(s, 59)); + if (new Date(at).getUTCDate() !== d) return undefined; + if (s === 60) return new Date(at + 1000).getUTCDate() === 1 ? at + 1000 : undefined; + return at; } /** Milliseconds since the epoch for an RFC 9110 HTTP-date, or undefined. */ diff --git a/structure/data-planes/error-detail.md b/structure/data-planes/error-detail.md index 438972a7b93..a66567e4a9f 100644 --- a/structure/data-planes/error-detail.md +++ b/structure/data-planes/error-detail.md @@ -202,7 +202,7 @@ HTTP and WebSocket. Client `Retry-After` advice is a string this proxy formats: `formatClientRetryAfter` in `src/lib/client-retry-after.ts` turns delay seconds (fractions round up) or an HTTP date in any RFC 9110 -form (IMF-fixdate, RFC 850, asctime, all read as GMT field by field) into +form (IMF-fixdate, RFC 850, asctime, all read as GMT field by field, with a month-end `23:59:60` leap second carried into the following day after calendar validation) into an integer of seconds clamped to 0..691200 (eight days, so a weekly usage-window reset such as a local Codex account cooldown still reaches the client), and yields nothing for any other input. The Ollama surface keeps its own smaller bound (`ollamaRetryAfter`). Every other client boundary uses `formatClientRetryAfter` diff --git a/tests/lib/client-retry-after.test.ts b/tests/lib/client-retry-after.test.ts index db0efd4f7db..d9ae520c1c3 100644 --- a/tests/lib/client-retry-after.test.ts +++ b/tests/lib/client-retry-after.test.ts @@ -34,6 +34,26 @@ describe("formatClientRetryAfter", () => { expect(formatClientRetryAfter("Mon, 30 Nov 2026 00:00:00 GMT", now)).toBe("691200"); }); + test.each([ + "Sat, 31 Dec 2016 23:59:60 GMT", + "Saturday, 31-Dec-16 23:59:60 GMT", + "Sat Dec 31 23:59:60 2016", + ])("carries the leap second into the following UTC day: %s", value => { + const before = Date.parse("2016-12-31T23:59:59Z"); + expect(formatClientRetryAfter(value, before)).toBe("1"); + expect(formatClientRetryAfter(value, before + 1000)).toBe("0"); + }); + + test("leap-second handling still rejects invalid calendar dates, positions, and seconds", () => { + expect(formatClientRetryAfter("Sat, 31 Apr 2016 23:59:60 GMT", now)).toBeUndefined(); + expect(formatClientRetryAfter("Sat, 31 Dec 2016 23:59:61 GMT", now)).toBeUndefined(); + expect(formatClientRetryAfter("Mon, 02 Nov 2026 12:34:60 GMT", now)).toBeUndefined(); + expect(formatClientRetryAfter("Thu, 15 Dec 2016 23:59:60 GMT", now)).toBeUndefined(); + expect(formatClientRetryAfter("Sun, 28 Feb 2016 23:59:60 GMT", now)).toBeUndefined(); + const feb29 = Date.parse("2016-02-29T23:59:59Z"); + expect(formatClientRetryAfter("Mon, 29 Feb 2016 23:59:60 GMT", feb29)).toBe("1"); + }); + test("obsolete RFC 850 and asctime dates are read as GMT", () => { expect(formatClientRetryAfter("Monday, 02-Nov-26 00:00:30 GMT", now)).toBe("30"); expect(formatClientRetryAfter("Sunday, 01-Nov-26 23:00:00 GMT", now)).toBe("0"); diff --git a/tests/server/client-retry-after-sites.test.ts b/tests/server/client-retry-after-sites.test.ts index eed5adf4cea..01b2c7ce067 100644 --- a/tests/server/client-retry-after-sites.test.ts +++ b/tests/server/client-retry-after-sites.test.ts @@ -23,6 +23,11 @@ describe("client Retry-After is regenerated at every boundary", () => { expect(safeResponseHeaders(new Headers({ "retry-after": "must-not-echo" }))["retry-after"]).toBeUndefined(); }); + test("WebSocket response metadata retains zero advice for a past leap second", () => { + const headers = new Headers({ "retry-after": "Sat, 31 Dec 2016 23:59:60 GMT" }); + expect(safeResponseHeaders(headers)["retry-after"]).toBe("0"); + }); + test("fallback refusal", () => { expect(fallbackRefusedResponse(event, { failureStatus: 429, retryAfter: NUMERIC_KEY }).headers.get("retry-after")).toBe("691200"); expect(fallbackRefusedResponse(event, { failureStatus: 429, retryAfter: "30" }).headers.get("retry-after")).toBe("30"); From 977c1856082c5b88b680bc6cfe664a46b26bbd9b Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:08:11 +0900 Subject: [PATCH 28/64] fix(combos): check the stored revision on dashboard Combo saves (#9126) * fix(combos): check the stored revision on dashboard Combo saves GET and successful PUT /api/combos responses include a per-Combo revision. A PUT that sends ifRevision is checked against the stored Combo (and, for a rename, a free destination) under the config mutation lock and is refused with 409 combo_revision_conflict when the Combo changed or was removed since the draft loaded. The dashboard sends its loaded revision, refreshes on a conflict and keeps the draft. Requests without ifRevision, including CLI saves, are unchanged. * fix(combos): adopt the stored combo after a durable revision conflict A conditional save refused because another process edited or removed the combo on disk left the live config stale. The dashboard refresh after the 409 showed the same combo, so every retry conflicted again. The refused save now adopts the stored source and destination combos into the live config, so the refresh shows the edit that blocked the save. * fix(combos): keep adopted combos in the rebase baseline and recover removed drafts Adopting a stored combo after a durable conflict changed only the live row, so a later save treated it as a pending live edit and could overwrite a newer disk edit. adoptPersistedCombos now updates the live config and its rebase baseline together, and the conflict path clears selection and cooldown state and converges the catalog for the adopted ids, as a save does. A dirty dashboard draft whose combo was removed on the server kept sending the old revision for a source that no longer exists. The editor now keeps the conflict notice for a removed combo and its next Save recreates it without ifRevision. * fix(combos): recreate a removed combo only while its id is free Recreating a combo removed on the server sent an unconditional PUT, which could overwrite a combo another writer created under the same id after the refresh. PUT /api/combos now accepts ifAbsent: true, checked against the live and stored config under the mutation lock; an existing combo returns combo_revision_conflict without writing and the stored rows are adopted as for other durable conflicts. The editor now says the combo was removed on the server and labels the action Recreate, which sends ifAbsent. * test(combos): count the conflict-adoption catalog convergence The durable revision conflict now converges the catalog for adopted combos, a third await convergeCodexCatalog() in combo-routes.ts. Update the route convergence inventory to match. * fix(combos): address CodeRabbit findings on dashboard combo saves - Add saves create-only (ifAbsent), so a combo another client saved under the same id is never replaced; the dialog stays open with a duplicate-id error. - A conditional rename onto an id already in the live config returns the combo_revision_conflict 409, matching the stored-config case. - Conflict adoption also adopts live combos whose public model id would otherwise collide with an adopted row, so one disk edit that moves an alias cannot leave two combos advertising the same model. - Korean and Turkish recreate notices say the id must not be in use. --- .../docs/es/reference/management-api.md | 2 + .../content/docs/reference/management-api.md | 2 + gui/src/combo-workspace-data.ts | 8 + gui/src/components/ComboWorkspace.tsx | 10 +- .../combo-workspace-detail-panel.tsx | 20 +- gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/es.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/Combos.tsx | 6 + .../combo-capability-hidden-targets.test.tsx | 89 ++++++ gui/tests/jev-auto-combo.test.tsx | 2 +- scripts/test-layout/layout.json | 2 +- src/cli/combo-result.ts | 2 +- src/cli/combo.ts | 1 + src/config/live-reconcile.ts | 19 ++ src/server/management/combo-routes.ts | 125 +++++++- structure/gui-and-management-api.md | 2 +- .../codex-convergence-contract.test.ts | 5 +- tests/fixtures/test-layout-expected.json | 1 + tests/routing/combo-revision.test.ts | 285 ++++++++++++++++++ 29 files changed, 584 insertions(+), 21 deletions(-) create mode 100644 tests/routing/combo-revision.test.ts diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 9420a98d3c8..b7c3c246240 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -221,6 +221,8 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode, targets }` y modo `"create"` o `"append"` | 400 solicitud inválida; 403 si falta una sesión de panel válida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. La creación requiere `allowMeteredTargets: true` en la solicitud y lo guarda en el combo. La ampliación rechaza ese campo y exige el consentimiento guardado en el combo. Todos los destinos sugeridos se guardan con `metered: true` porque incluso los canales de suscripción pueden cobrar créditos o uso adicional. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | +Cada combo de GET incluye una cadena `revision`. Envíala como `ifRevision` opcional en el nivel superior de PUT para proteger una edición o cambio de nombre; si el origen cambió o fue eliminado, o si el destino del cambio de nombre ya existe, responde HTTP 409 con el código `combo_revision_conflict` sin guardar. Una respuesta PUT correcta incluye la nueva `revision` en `combo`. Si se omite `ifRevision`, el guardado sigue siendo incondicional. Envía en su lugar `ifAbsent: true` para crear un combo solo si no existe ninguno con ese `id`; si ya existe, responde el mismo 409 sin guardar. `ifAbsent` no se puede combinar con `ifRevision` ni con `renameFrom`. + Las tres operaciones de sugerencias (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions` y `POST /api/combo-suggestions/save`) requieren una sesión de panel iniciada mediante el acceso local, una identidad de Tailscale verificada o el emparejamiento. Las credenciales de administrador y las sesiones recordadas reciben un 403. Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 3e4cdd3ce47..4cde47d605e 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -250,6 +250,8 @@ completes. | `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode, targets }` with mode `"create"` or `"append"` | 400 invalid request; 403 without an eligible dashboard session; 409 when consent, exclusions, provider availability, or combo state prevents the save. Create requires `allowMeteredTargets: true` in the request and stores it on the combo. Append rejects that field and requires stored combo consent. All suggested targets are saved with `metered: true` because even subscription channels may bill paid credits or extra usage. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | +Each GET combo includes a `revision` string. Send it as the optional top-level `ifRevision` in PUT to protect an edit or rename; a changed or deleted source, or a rename destination that already exists, returns HTTP 409 with code `combo_revision_conflict` without writing. Successful PUT responses include the new `revision` in `combo`. Omitting `ifRevision` keeps unconditional saves. Send `ifAbsent: true` instead to create a combo only when no combo with that `id` exists; an existing one returns the same 409 without writing. `ifAbsent` cannot be combined with `ifRevision` or `renameFrom`. + All three suggestion operations (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions`, and `POST /api/combo-suggestions/save`) require a dashboard session issued through local bootstrap, verified Tailscale identity, or pairing. Admin credentials and remembered sessions receive a 403. See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. diff --git a/gui/src/combo-workspace-data.ts b/gui/src/combo-workspace-data.ts index 2e6ddf4d35d..00793e51b4e 100644 --- a/gui/src/combo-workspace-data.ts +++ b/gui/src/combo-workspace-data.ts @@ -151,6 +151,7 @@ function normalizeReasoningEffortMode(value: unknown): "strict" | "adaptive" { export interface ComboItem { id: string; + revision?: string; /** Wire id shown to clients, e.g. combo/free */ model: string; /** Optional public model name replacing the default combo/ slug; null = default. */ @@ -312,6 +313,7 @@ export function parseComboList(payload: unknown): ComboItem[] { const sessionPin = r.sessionPin === null ? null : normalizeJevSessionPin(r.sessionPin); out.push({ id, + ...(typeof r.revision === "string" ? { revision: r.revision } : {}), model: typeof r.model === "string" && r.model.trim() ? r.model.trim() : comboPublicModelId(id, normalizeAlias(r.alias)), @@ -538,9 +540,13 @@ export function toPutBody( * value the CLI or API changed in the meantime. */ stored?: ComboItem | null; + /** Create only: the server refuses when a combo with this id exists. */ + ifAbsent?: true; } = {}, ): { id: string; + ifRevision?: string; + ifAbsent?: true; renameFrom?: string; visionSidecarTargets?: Array<{ provider: string; model: string }>; combo: { @@ -572,6 +578,8 @@ export function toPutBody( [`${target.provider.trim()}/${target.model.trim()}`, target.metered])); return { id: item.id.trim(), + ...(stored?.revision !== undefined ? { ifRevision: stored.revision } : {}), + ...(options.ifAbsent ? { ifAbsent: true as const } : {}), ...(options.renameFrom ? { renameFrom: options.renameFrom } : {}), ...(options.visionSidecarTargets?.length ? { visionSidecarTargets: options.visionSidecarTargets } : {}), combo: { diff --git a/gui/src/components/ComboWorkspace.tsx b/gui/src/components/ComboWorkspace.tsx index 9736cb96d93..bb5191285e9 100644 --- a/gui/src/components/ComboWorkspace.tsx +++ b/gui/src/components/ComboWorkspace.tsx @@ -89,11 +89,12 @@ export default function ComboWorkspace({ () => combos.flatMap((combo) => combo.alias ? [combo.alias] : []), [combos], ); - const activeId = selectedId && combos.some((c) => c.id === selectedId) ? selectedId : null; - const selected = combos.find((c) => c.id === activeId) ?? null; + const [lastSelected, setLastSelected] = useState(null); + const [detailDirty, setDetailDirty] = useState(false); + const activeId = selectedId && (combos.some((c) => c.id === selectedId) || (detailDirty && lastSelected?.id === selectedId)) ? selectedId : null; + const selected = combos.find((c) => c.id === activeId) ?? (detailDirty && lastSelected?.id === activeId ? lastSelected : null); const baseline = selected && localBaseline?.source === selected ? localBaseline.item : selected; - const [detailDirty, setDetailDirty] = useState(false); const mainRef = useRef(null); const railRef = useRef(null); const previousSelection = useRef(null); @@ -284,7 +285,8 @@ export default function ComboWorkspace({ }} onRequestRemove={() => setRemoveId(baseline.id)} onSave={onSave} - onDirtyChange={setDetailDirty} + onDirtyChange={(dirty) => { setDetailDirty(dirty); if (dirty) setLastSelected(selected); }} + storedRemoved={!combos.some((c) => c.id === baseline.id)} /> ) : creatingFirstCombo ? ( void; onSaved: (item: ComboItem) => void; onRequestRemove?: () => void; + /** `isCreate` saves create-only: the server refuses an id that is already taken. */ onSave: (item: ComboItem, isCreate: boolean, renameFrom?: string, stored?: ComboItem | null) => Promise<{ ok: boolean; error?: string; item?: ComboItem }>; onDirtyChange: (dirty: boolean) => void; + /** The server no longer has this combo while the draft is kept; Recreate creates it from the draft only if the id is still free. */ + storedRemoved?: boolean; }) { const t = useT(); const [tab, setTab] = useState("config"); @@ -111,7 +115,7 @@ export function DetailPanel({ const [conflicts, setConflicts] = useState([]); const dirty = !draftEquals(draft, baseline); const allTargetsExhausted = comboQuotaState(draft.targets, providerQuotaStates, providerMap) === "exhausted"; - const baselineSyncKey = JSON.stringify([baseline.id, baseline.alias, baseline.nativeAlias, baseline.displayName, baseline.strategy, baseline.stickyLimit, baseline.defaultEffort, baseline.imageInput, baseline.reasoningEffortMode, baseline.decisionProvider, baseline.decisionModel, baseline.decisionTimeoutMs, baseline.sessionPin === undefined, baseline.sessionPin, Boolean(baseline.allowMeteredTargets), Boolean(baseline.quotaOnlyFallback), Boolean(baseline.preserveFallbackModel), baseline.targets.map(t => [t.provider, t.model, t.weight, t.reasoningEfforts, t.modelProfile, Boolean(t.metered)])]); + const baselineSyncKey = JSON.stringify([baseline.revision, baseline.id, baseline.alias, baseline.nativeAlias, baseline.displayName, baseline.strategy, baseline.stickyLimit, baseline.defaultEffort, baseline.imageInput, baseline.reasoningEffortMode, baseline.decisionProvider, baseline.decisionModel, baseline.decisionTimeoutMs, baseline.sessionPin === undefined, baseline.sessionPin, Boolean(baseline.allowMeteredTargets), Boolean(baseline.quotaOnlyFallback), Boolean(baseline.preserveFallbackModel), baseline.targets.map(t => [t.provider, t.model, t.weight, t.reasoningEfforts, t.modelProfile, Boolean(t.metered)])]); const effortMap = useMemo(() => { const map = new Map(); for (const model of capabilityModels) { @@ -145,7 +149,7 @@ export function DetailPanel({ draftRef.current = result.merged; setDraft(result.merged); setConflicts(current => [...new Set([...current, ...result.conflicts])]); - setMsg(null); + setMsg(current => current?.text === t("pws.draftConflict") ? current : null); onDirtyChange(!draftEquals(result.merged, baseline)); }, 0); return () => window.clearTimeout(timer); @@ -153,6 +157,11 @@ export function DetailPanel({ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional: key captures baseline payload }, [baselineSyncKey]); + // A removed combo has no revision to check against: say so, and offer Recreate instead of Save. + useEffect(() => { + if (storedRemoved) setMsg({ ok: false, text: t("cws.removedOnServer") }); + }, [storedRemoved, t]); + const copyModel = async () => { try { await navigator.clipboard.writeText(baseline.model); @@ -203,9 +212,10 @@ export function DetailPanel({ // The server keeps these only for JEV, so the saved baseline must not carry stale ones. ...(workingDraft.strategy === "jev" ? {} : { decisionProvider: null, decisionModel: null, decisionTimeoutMs: null, sessionPin: undefined }), }; - const renameFrom = !isCreate && trimmedId !== baseline.id ? baseline.id : undefined; + const recreate = !isCreate && storedRemoved; + const renameFrom = !isCreate && !recreate && trimmedId !== baseline.id ? baseline.id : undefined; try { - const res = await onSave(item, isCreate, renameFrom, isCreate ? null : draftBaseline.current); + const res = await onSave(item, isCreate || recreate, renameFrom, isCreate || recreate ? null : draftBaseline.current); if (!res.ok) { setMsg({ ok: false, text: res.error || t("cws.saveFailed") }); return; @@ -251,7 +261,7 @@ export function DetailPanel({ )} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index d9d089f3a5c..c4c92b03f90 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -3453,6 +3453,8 @@ export const de: Record = { "cws.saved": "Combo gespeichert.", "cws.created": "{model} erstellt.", "cws.removed": "combo/{id} entfernt.", + "cws.removedOnServer": "Diese Combo wurde während der Bearbeitung auf diesem Server entfernt. Ihr Entwurf bleibt erhalten: „Neu erstellen“ speichert ihn als neue Combo, sofern die ID noch frei ist, oder gehen Sie zurück, um ihn zu verwerfen.", + "cws.recreate": "Neu erstellen", "cws.renamed": "{from} wurde in {to} umbenannt.", "cws.add": "Combo hinzufügen", "cws.addTitle": "Combo hinzufügen", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 8c3461e70c9..ad30686aacb 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -3567,6 +3567,8 @@ export const en = { "cws.saved": "Combo saved.", "cws.created": "Created {model}.", "cws.removed": "Removed combo/{id}.", + "cws.removedOnServer": "This combo was removed on this server while you were editing. Your draft is kept: Recreate saves it as a new combo if the id is still free, or go back to discard it.", + "cws.recreate": "Recreate", "cws.renamed": "Renamed {from} to {to}.", "cws.add": "Add combo", "cws.addTitle": "Add combo", diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index 7540e81cee6..6696579ed97 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -3542,6 +3542,8 @@ export const es = { "cws.saved": "Combo guardado.", "cws.created": "Creado {model}.", "cws.removed": "Eliminado combo/{id}.", + "cws.removedOnServer": "Este combo se eliminó en este servidor mientras editabas. Tu borrador se conserva: Volver a crear lo guarda como un combo nuevo si el id sigue libre, o vuelve atrás para descartarlo.", + "cws.recreate": "Volver a crear", "cws.renamed": "Se cambió el nombre de {from} a {to}.", "cws.add": "Añadir combo", "cws.addTitle": "Añadir combo", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index e8570934b4c..2a41fbbf287 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -3480,6 +3480,8 @@ export const fr: Record = { "cws.saved": "Combinaison enregistrée.", "cws.created": "{model} créé.", "cws.removed": "combo/{id} supprimé.", + "cws.removedOnServer": "Cette combinaison a été supprimée sur ce serveur pendant votre modification. Votre brouillon est conservé : Recréer l’enregistre comme nouvelle combinaison si l’identifiant est toujours libre, ou revenez en arrière pour l’abandonner.", + "cws.recreate": "Recréer", "cws.renamed": "{from} renommé en {to}.", "cws.add": "Ajouter une combinaison", "cws.addTitle": "Ajouter une combinaison", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index bf4c1474fea..52f8b740809 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -3578,6 +3578,8 @@ export const ja: Record = { "cws.saved": "コンボを保存しました。", "cws.created": "{model} を作成しました。", "cws.removed": "combo/{id} を削除しました。", + "cws.removedOnServer": "編集中にこのコンボはこのサーバーで削除されました。下書きは保持されています。ID がまだ空いていれば「再作成」で新しいコンボとして保存できます。破棄する場合は戻ってください。", + "cws.recreate": "再作成", "cws.add": "コンボを追加", "cws.addTitle": "コンボを追加", "cws.addSubtitle": "プロバイダー全体にファンアウトする仮想モデルを作成します。クライアントは combo/ をリクエストします。", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index c94e1215ac8..c21aa47f439 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -3500,6 +3500,8 @@ export const ko: Record = { "cws.saved": "콤보를 저장했습니다.", "cws.created": "{model}을(를) 만들었습니다.", "cws.removed": "combo/{id}을(를) 삭제했습니다.", + "cws.removedOnServer": "편집하는 동안 이 서버에서 이 콤보가 삭제됐습니다. 초안은 그대로 보관되어 있습니다. ID가 아직 사용 중이 아니면 다시 만들기로 새 콤보로 저장할 수 있고, 버리려면 뒤로 가세요.", + "cws.recreate": "다시 만들기", "cws.renamed": "{from}을(를) {to}(으)로 이름을 변경했습니다.", "cws.add": "콤보 추가", "cws.addTitle": "콤보 추가", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 08b15af504d..a0b77f2e3fd 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -3523,6 +3523,8 @@ export const pt: Record = { "cws.saved": "Combo salvo.", "cws.created": "{model} criado.", "cws.removed": "combo/{id} removido.", + "cws.removedOnServer": "Este combo foi removido neste servidor enquanto você editava. O rascunho foi mantido: Recriar o salva como um novo combo se o id ainda estiver livre, ou volte para descartá-lo.", + "cws.recreate": "Recriar", "cws.renamed": "{from} renomeado para {to}.", "cws.add": "Adicionar combo", "cws.addTitle": "Adicionar combo", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 350ceebfbd0..6f8cfd5d666 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -3669,6 +3669,8 @@ export const ru: Record = { "cws.saved": "Комбо сохранено.", "cws.created": "Создано: {model}.", "cws.removed": "Удалено: combo/{id}.", + "cws.removedOnServer": "Это комбо удалено на этом сервере во время редактирования. Черновик сохранён: «Создать заново» сохранит его как новое комбо, если идентификатор ещё свободен, или вернитесь назад, чтобы отменить его.", + "cws.recreate": "Создать заново", "cws.renamed": "Переименовано: {from} → {to}.", "cws.add": "Добавить комбо", "cws.addTitle": "Добавить комбо", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 68b19964691..8006d9885a9 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -3503,6 +3503,8 @@ export const tr: Record = { "cws.saved": "Kombo kaydedildi.", "cws.created": "{model} oluşturuldu.", "cws.removed": "combo/{id} kaldırıldı.", + "cws.removedOnServer": "Siz düzenlerken bu kombo bu sunucuda kaldırıldı. Taslağınız korunuyor: Kimlik hâlâ kullanılmıyorsa Yeniden oluştur onu yeni bir kombo olarak kaydeder; atmak için geri dönün.", + "cws.recreate": "Yeniden oluştur", "cws.renamed": "{from}, {to} olarak yeniden adlandırıldı.", "cws.add": "Kombo ekle", "cws.addTitle": "Kombo ekle", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index f9c03af2f02..09273732f7e 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -3491,6 +3491,8 @@ export const vi: Record = { "cws.saved": "Đã lưu combo.", "cws.created": "Đã tạo {model}.", "cws.removed": "Đã xóa combo/{id}.", + "cws.removedOnServer": "Combo này đã bị xóa trên máy chủ này trong khi bạn chỉnh sửa. Bản nháp của bạn được giữ lại: Tạo lại sẽ lưu nó thành combo mới nếu id vẫn còn trống, hoặc quay lại để bỏ bản nháp.", + "cws.recreate": "Tạo lại", "cws.renamed": "Đã đổi tên {from} thành {to}.", "cws.add": "Thêm combo", "cws.addTitle": "Thêm combo", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 68daf854591..43330ac7ac4 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2648,6 +2648,8 @@ export const zhTW: Record = { "cws.saved": "組合已儲存。", "cws.created": "已建立 {model}。", "cws.removed": "已刪除 combo/{id}。", + "cws.removedOnServer": "編輯期間此組合已在此伺服器上被刪除。草稿已保留:若 ID 仍未被使用,「重新建立」會將其儲存為新組合;或返回以捨棄草稿。", + "cws.recreate": "重新建立", "cws.renamed": "已將 {from} 重新命名為 {to}。", "cws.add": "新增組合", "cws.addTitle": "新增組合", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 2d0fcae1db2..7c84d8fdd86 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -3473,6 +3473,8 @@ export const zh: Record = { "cws.saved": "组合已保存。", "cws.created": "已创建 {model}。", "cws.removed": "已删除 combo/{id}。", + "cws.removedOnServer": "编辑期间此组合已在此服务器上被删除。草稿已保留:如果 ID 仍未被占用,“重新创建”会将其保存为新组合;或返回以放弃草稿。", + "cws.recreate": "重新创建", "cws.renamed": "已将 {from} 重命名为 {to}。", "cws.add": "添加组合", "cws.addTitle": "添加组合", diff --git a/gui/src/pages/Combos.tsx b/gui/src/pages/Combos.tsx index 73c1a4a24bc..11c63d56661 100644 --- a/gui/src/pages/Combos.tsx +++ b/gui/src/pages/Combos.tsx @@ -372,6 +372,8 @@ export default function Combos({ headers: { "content-type": "application/json" }, body: JSON.stringify(toPutBody(item, { ...(renameFrom ? { renameFrom } : {}), + // A create never replaces a combo another client saved under the same id meanwhile. + ...(isCreate ? { ifAbsent: true as const } : {}), stored, // Enabling images declares text-only members for the Vision Sidecar so the // operator never has to hand-edit provider config for a multimodal combo. @@ -384,6 +386,10 @@ export default function Combos({ ? await res.json() as unknown : await res.json().catch(() => null) as unknown; const serverError = responseError(data); + if (res.status === 409 && data && typeof data === "object" && "code" in data && data.code === "combo_revision_conflict") { + resource.refresh(); + return { ok: false as const, error: t(isCreate ? "cws.err.duplicateId" : "pws.draftConflict") }; + } if (!res.ok || serverError || !responseSucceeded(data)) { const err = serverError || t("cws.saveFailed"); notify(err, false); diff --git a/gui/tests/combo-capability-hidden-targets.test.tsx b/gui/tests/combo-capability-hidden-targets.test.tsx index 9bd46c2ad3f..9fd9f00dd4f 100644 --- a/gui/tests/combo-capability-hidden-targets.test.tsx +++ b/gui/tests/combo-capability-hidden-targets.test.tsx @@ -262,6 +262,95 @@ test("editing can select and save a hidden model without changing its visibility expect(hiddenImage.disabled).toBe(true); }); +test("revision conflict reloads and keeps the dashboard draft", async () => { + const visible = { ...hiddenImage, id: "visible", disabled: false }; + mockCatalog([hiddenImage, visible], [target(visible)], { revision: "old" }); + const fetchCatalog = globalThis.fetch; + let writes = 0; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + writes++; + expect(JSON.parse(String(init.body)).ifRevision).toBe("old"); + return Response.json({ code: "combo_revision_conflict" }, { status: 409 }); + } + if (writes && new URL(String(input)).pathname === "/api/combos") return Response.json({ combos: [combo([target(visible)], { revision: "new" })] }); + return fetchCatalog(input, init); + }) as typeof fetch; + await mount(); + await openDetail(); + await chooseOption(selectTrigger(container, MODEL), "hidden"); + await act(async () => { container.querySelector("#cwi-edit-save")!.click(); }); + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 0)); }); + expect(writes).toBe(1); + expect(selectValue(selectTrigger(container, MODEL))).toBe("hidden"); + expect(container.textContent).toContain("The saved settings changed on this server while you were editing"); +}); + +test("a combo removed on the server keeps the draft and Recreate creates it only if the id is free", async () => { + const visible = { ...hiddenImage, id: "visible", disabled: false }; + mockCatalog([hiddenImage, visible], [target(visible)], { revision: "old" }); + const fetchCatalog = globalThis.fetch; + const bodies: Array> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + const body = JSON.parse(String(init.body)) as Record; + bodies.push(body); + if (bodies.length === 1) return Response.json({ code: "combo_revision_conflict" }, { status: 409 }); + return Response.json({ success: true, id: body.id, model: "combo/" + String(body.id), combo: { ...(body.combo as object), revision: "recreated" } }); + } + if (bodies.length === 1 && new URL(String(input)).pathname === "/api/combos") return Response.json({ combos: [] }); + return fetchCatalog(input, init); + }) as typeof fetch; + await mount(); + await openDetail(); + await chooseOption(selectTrigger(container, MODEL), "hidden"); + await act(async () => { container.querySelector("#cwi-edit-save")!.click(); }); + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 0)); }); + expect(bodies[0]!.ifRevision).toBe("old"); + expect(selectValue(selectTrigger(container, MODEL))).toBe("hidden"); + expect(container.textContent).toContain("This combo was removed on this server while you were editing"); + expect(container.querySelector("#cwi-edit-save")?.textContent).toBe("Recreate"); + await act(async () => { container.querySelector("#cwi-edit-save")!.click(); }); + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 0)); }); + expect(bodies).toHaveLength(2); + expect(bodies[1]).not.toHaveProperty("ifRevision"); + expect(bodies[1]).not.toHaveProperty("renameFrom"); + expect(bodies[1]!.ifAbsent).toBe(true); + expect((bodies[1]!.combo as { targets: Array<{ model: string }> }).targets.map(t => t.model)).toEqual(["hidden"]); +}); + +test("Add creates only if the id is free and keeps the dialog when another client took it", async () => { + const visible = { ...hiddenImage, id: "visible", disabled: false }; + mockCatalog([hiddenImage, visible], [target(visible)]); + const fetchCatalog = globalThis.fetch; + const bodies: Array> = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT") { + bodies.push(JSON.parse(String(init.body)) as Record); + return Response.json({ code: "combo_revision_conflict" }, { status: 409 }); + } + return fetchCatalog(input, init); + }) as typeof fetch; + await mount(); + await act(async () => { container.querySelector('button[aria-label="Add combo"]')!.click(); }); + const dialog = container.querySelector("dialog")!; + const idInput = dialog.querySelector("#cwi-new-id")!; + await act(async () => { + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(idInput, "fresh"); + idInput.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + }); + await chooseProvider("vision", dialog); + await chooseOption(selectTrigger(dialog, MODEL), "visible"); + const create = [...dialog.querySelectorAll(".cwi-modal-actions button")].find(button => button.textContent === "Create combo")!; + await act(async () => { create.click(); }); + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 0)); }); + expect(bodies).toHaveLength(1); + expect(bodies[0]).toMatchObject({ id: "fresh", ifAbsent: true }); + expect(bodies[0]).not.toHaveProperty("ifRevision"); + expect(container.querySelector("dialog")).not.toBeNull(); + expect(container.querySelector("dialog")!.textContent).toContain("A combo with this id already exists."); +}); + test("JEV decision model suggestions include hidden models but exclude the JEV combo itself", async () => { mockCatalog([hiddenImage], [target(hiddenImage)], { strategy: "jev", decisionModel: "vision/hidden" }); await mount(); diff --git a/gui/tests/jev-auto-combo.test.tsx b/gui/tests/jev-auto-combo.test.tsx index e427b06c383..552dfadc025 100644 --- a/gui/tests/jev-auto-combo.test.tsx +++ b/gui/tests/jev-auto-combo.test.tsx @@ -474,5 +474,5 @@ test("configured JEV deep-link opens the shared editable Combo modal and submits { provider: "openai", model: "gpt-5.6-sol" }, { provider: "anthropic", model: "claude-sonnet-5" }, ], - })]); + }, { ifAbsent: true })]); }); diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 3b34de7df37..49371cea65b 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -750,7 +750,7 @@ "combo-reset-window-model-scope.test.ts": "codex-integration", "combo-child-headers.test.ts": "routing", "combo-last-resort.test.ts": "codex-integration", - "combo-management-api.test.ts": "routing", + "combo-management-api.test.ts": "routing", "combo-revision.test.ts": "routing", "combo-vision-enrollment.test.ts": "routing", "combo-stream-preflight.test.ts": "routing", "combo-workspace-data.test.ts": "gui", diff --git a/src/cli/combo-result.ts b/src/cli/combo-result.ts index c04369cc11c..309a638fac0 100644 --- a/src/cli/combo-result.ts +++ b/src/cli/combo-result.ts @@ -10,7 +10,7 @@ const ENUMS: Readonly> = { imageInput: ["auto", "disabled"], cooldownWaitPolicy: ["before-last-resort"], capabilityPolicy: ["intersection", "union"], onUnservable: ["degrade", "reject"], }; -const STRINGS = new Set(["alias", "displayName", "description", "decisionProvider", "decisionModel"]); +const STRINGS = new Set(["alias", "displayName", "description", "decisionProvider", "decisionModel", "revision"]); const RANGES: Readonly> = { stickyLimit: [1, 100], cooldownMs: [1, 600_000], waitForCooldownMs: [0, 600_000], decisionTimeoutMs: [1_000, 120_000], diff --git a/src/cli/combo.ts b/src/cli/combo.ts index 59addf90cbb..dc2c8653728 100644 --- a/src/cli/combo.ts +++ b/src/cli/combo.ts @@ -213,6 +213,7 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise { } delete combo.id; delete combo.model; + delete combo.revision; if (replacingTargets) combo.targets = additional.targets ?? parsedTargets; combo.strategy = strategy; if (stickyLimit !== undefined) combo.stickyLimit = stickyLimit; diff --git a/src/config/live-reconcile.ts b/src/config/live-reconcile.ts index 8b29ca79440..5c856f96101 100644 --- a/src/config/live-reconcile.ts +++ b/src/config/live-reconcile.ts @@ -130,6 +130,25 @@ export function adoptPersistedAdvisor(config: OcxConfig, persisted: OcxConfig["a if (baseline) clearConfigTopLevelDeletionIntent(baseline, ["advisor"]); } +/** + * Adopt stored combos into the live config and its rebase baseline together. Changing only the + * live rows would make a later save treat them as pending live edits and overwrite a newer disk edit. + */ +export function adoptPersistedCombos( + config: OcxConfig, + persisted: Readonly[string]>>, + ids: Iterable, +): void { + const baseline = liveConfigBaseline.get(config); + for (const id of ids) { + const stored = Object.hasOwn(persisted, id) ? persisted[id] : undefined; + for (const target of baseline ? [config, baseline] : [config]) { + if (stored !== undefined) (target.combos ??= {})[id] = structuredClone(stored); + else if (target.combos) delete target.combos[id]; + } + } +} + /** Adopt the committed telemetry consent subtree without advancing unrelated pending live intent. */ export function adoptPersistedTelemetry(config: OcxConfig, persisted: OcxConfig["telemetry"]): void { if (persisted === undefined) delete config.telemetry; diff --git a/src/server/management/combo-routes.ts b/src/server/management/combo-routes.ts index d5538c6896a..266288baa6a 100644 --- a/src/server/management/combo-routes.ts +++ b/src/server/management/combo-routes.ts @@ -1,4 +1,4 @@ -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { readFileSync } from "node:fs"; import type { CatalogModel } from "../../codex/catalog"; import { catalogModelSlug, invalidateCodexModelsCache, nativeModelRows, uniqueCatalogModelsForPublicList } from "../../codex/catalog"; @@ -56,6 +56,8 @@ import { mergeModelCapabilities, modelCapabilitiesConfigError } from "../../conf import { modelRecordValue } from "../../reasoning-effort"; import { commitProviderPatch } from "./provider-patch-transaction"; import { ConfigWritePublishedError } from "../../config/persist-unlocked"; +import { readConfigFileSnapshot } from "../../config/diagnostics"; +import { adoptPersistedCombos } from "../../config/live-reconcile"; import { customRowInputModalities, isVisionSidecarConsumer, @@ -142,6 +144,63 @@ interface VisionSidecarTarget { model: string; } +function comboRevision(combo: OcxComboConfig): string { + const canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) + : isPlainRecord(value) ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value; + return createHash("sha256").update(JSON.stringify(canonical(combo))).digest("hex"); +} + +/** `stored` carries the persisted combos when the durable check refused the save. */ +class ComboRevisionConflict extends Error { + constructor(readonly stored?: Readonly>) { super("combo revision conflict"); } +} + +/** + * Nothing reloads the live config when another process edits the file, so the + * dashboard's refresh after a durable conflict would read the same stale combo and + * every retry would conflict again. Adopt the stored source and destination combos; + * the next rebasing save would have adopted these unedited disk values anyway. + * One disk edit can move a public model id (alias) between combos, so a live row that + * would share an adopted row's public id is adopted too when its stored value differs; + * otherwise two combos would advertise the same model and routing would pick the first. + * Returns the ids whose live combo changed. + */ +function adoptStoredCombos(config: OcxConfig, stored: Readonly>, ids: readonly string[]): string[] { + const differs = (comboId: string): boolean => { + const durable = Object.hasOwn(stored, comboId) ? stored[comboId] : undefined; + const live = config.combos?.[comboId]; + if (durable === undefined) return live !== undefined; + return live === undefined || comboRevision(live) !== comboRevision(durable); + }; + const publicId = (comboId: string, combo: OcxComboConfig): string => + (typeof combo.alias === "string" ? combo.alias.trim() : "") || `combo/${comboId}`; + const adopt = new Set([...new Set(ids)].filter(differs)); + for (let grew = adopt.size > 0; grew;) { + grew = false; + const prospective: Record = { ...config.combos }; + for (const comboId of adopt) { + if (Object.hasOwn(stored, comboId)) prospective[comboId] = stored[comboId]!; + else delete prospective[comboId]; + } + const owners = new Map(); + for (const [comboId, combo] of Object.entries(prospective)) { + const key = publicId(comboId, combo); + owners.set(key, [...(owners.get(key) ?? []), comboId]); + } + for (const sharing of owners.values()) { + if (sharing.length < 2 || !sharing.some(comboId => adopt.has(comboId))) continue; + for (const comboId of sharing) { + if (adopt.has(comboId) || !differs(comboId)) continue; + adopt.add(comboId); + grew = true; + } + } + } + const changed = [...adopt]; + if (changed.length > 0) adoptPersistedCombos(config, stored, changed); + return changed; +} + /** * Request-only PUT field: combo members to declare text-only so the Vision Sidecar * covers them when the combo accepts images. Every entry must be an exact target of @@ -218,6 +277,7 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise { + const current = config.combos?.[sourceId]; + if (body.ifRevision !== undefined && (!current || comboRevision(current) !== body.ifRevision)) throw new ComboRevisionConflict(); + if (ifAbsent && current) throw new ComboRevisionConflict(); + if ((body.ifRevision !== undefined || ifAbsent) && !deps.saveConfigPreservingClaudeCode) { + const persisted = readConfigFileSnapshot({ passive: true }).diagnostics; + if (persisted.source !== "file") throw new Error("config unavailable"); + const storedCombos = persisted.config.combos ?? {}; + if (ifAbsent) { + if (Object.hasOwn(storedCombos, id)) throw new ComboRevisionConflict(storedCombos); + } else { + const durable = storedCombos[sourceId]; + if (!durable || comboRevision(durable) !== body.ifRevision) throw new ComboRevisionConflict(storedCombos); + // A conditional rename also needs the destination to be free in the stored config. + if (renameFrom && Object.hasOwn(storedCombos, id)) throw new ComboRevisionConflict(storedCombos); + } + } config.combos = nextCombos; if (migratedModels.size > 0) { const migrateReference = (model: string): string => migratedModels.get(model) ?? model; @@ -593,6 +690,21 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise 0) { + // Same follow-up as a save: runtime state and the catalog track the adopted rows. + notifyLiveConfigObservers(config); + reconcileLiveStateStores(); + for (const adoptedId of adopted) { + clearComboSelectionState(adoptedId); + clearComboTargetCooldowns(adoptedId); + } + await convergeCodexCatalog(); + } + return jsonResponse({ error: "combo revision conflict", code: "combo_revision_conflict" }, 409); + } if (!(error instanceof ConfigWritePublishedError)) { return jsonResponse({ error: "combo could not be saved" }, 500); } @@ -600,6 +712,7 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise { @@ -650,7 +651,7 @@ test("the route inventory retains every convergence path after separating subage expect(counts).toEqual({ "provider-routes.ts": 8, "model-routes.ts": 16, - "combo-routes.ts": 2, + "combo-routes.ts": 3, "agent-settings-routes.ts": 1, "subagent-model-routes.ts": 1, }); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 9acd75c8a9a..f8f3c026d83 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -820,6 +820,7 @@ "combo-permanent-failure-cooldown.test.ts": "codex-integration", "combo-reset-window-model-scope.test.ts": "codex-integration", "combo-child-headers.test.ts": "routing", "combo-last-resort.test.ts": "codex-integration", "combo-management-api.test.ts": "routing", + "combo-revision.test.ts": "routing", "combo-vision-enrollment.test.ts": "routing", "combo-stream-preflight.test.ts": "routing", "combo-workspace-data.test.ts": "gui", "combo-selection-keepalive.test.ts": "routing", "server-combo-selection-keepalive.test.ts": "server", diff --git a/tests/routing/combo-revision.test.ts b/tests/routing/combo-revision.test.ts new file mode 100644 index 00000000000..df5f837294c --- /dev/null +++ b/tests/routing/combo-revision.test.ts @@ -0,0 +1,285 @@ +import { expect, test } from "bun:test"; +import { handleManagementAPI } from "../../src/server/management-api"; +import type { OcxConfig } from "../../src/types"; +import { catalogConvergenceFactory } from "../helpers/catalog-convergence"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { armClaudeCodeBaseline, getConfigPath, saveConfig } from "../../src/config"; + +test("combo revisions reject stale saves and allow matching and unconditional saves", async () => { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + } }; + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { + createManagementConvergeCodex: catalogConvergenceFactory(), saveConfigPreservingClaudeCode: () => {}, + }))!; + }; + const m = { provider: "fixture", model: "m", metered: true }; + const n = { provider: "fixture", model: "n" }; + expect((await call("PUT", { id: "c", combo: { strategy: "failover", targets: [m, n] } })).status).toBe(200); + const draft = ((await (await call("GET")).json()).combos as any[])[0]; + expect((await call("PUT", { id: "c", combo: { strategy: "failover", targets: [n] } })).status).toBe(200); + const before = structuredClone(config.combos); + const stale = await call("PUT", { id: "c", ifRevision: draft.revision ?? "missing-revision", combo: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }, n] } }); + expect(stale.status).toBe(409); + expect(await stale.json()).toMatchObject({ code: "combo_revision_conflict" }); + expect(config.combos).toEqual(before); + expect(typeof draft.revision).toBe("string"); + const current = ((await (await call("GET")).json()).combos as any[])[0]; + const matching = await call("PUT", { id: "c", ifRevision: current.revision, combo: { strategy: "failover", targets: [n, m] } }); + expect(matching.status).toBe(200); + const result = await matching.json(); + expect(result.combo.revision).toBeString(); + expect(result.combo.revision).not.toBe(current.revision); + expect((await call("PUT", { id: "c", combo: { strategy: "failover", targets: [n] } })).status).toBe(200); + const latest = ((await (await call("GET")).json()).combos as any[])[0]; + const renamed = await call("PUT", { id: "renamed", renameFrom: "c", ifRevision: latest.revision, combo: { strategy: "failover", targets: [n] } }); + expect(renamed.status).toBe(200); + expect((await call("PUT", { id: "another", renameFrom: "c", ifRevision: latest.revision, combo: { strategy: "failover", targets: [n] } })).status).toBe(409); + expect((await call("PUT", { id: "c", ifRevision: latest.revision, combo: { strategy: "failover", targets: [n] } })).status).toBe(409); +}); + +for (const change of ["changed", "deleted", "unchanged"] as const) { + test(`conditional save checks a combo ${change} on disk`, async () => { + const home = mkdtempSync(join(tmpdir(), "combo-revision-")); + const oldHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + try { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + }, combos: { c: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] } } }; + saveConfig(config); + armClaudeCodeBaseline(config); + let convergences = 0; + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { createManagementConvergeCodex: catalogConvergenceFactory(() => { convergences++; }) }))!; + }; + const draft = ((await (await call("GET")).json()).combos as any[])[0]; + const disk = structuredClone(config); + if (change === "deleted") delete disk.combos!.c; + else if (change === "changed") disk.combos!.c!.targets = [{ provider: "fixture", model: "n" }]; + saveConfig(disk); + const before = readFileSync(getConfigPath(), "utf8"); + const liveBefore = structuredClone(config); + convergences = 0; + const response = await call("PUT", { id: "c", ifRevision: draft.revision, combo: { strategy: "failover", targets: [{ provider: "fixture", model: "n" }] } }); + if (change === "unchanged") { + expect(response.status).toBe(200); + expect((await response.json()).combo.revision).not.toBe(draft.revision); + expect(readFileSync(getConfigPath(), "utf8")).not.toBe(before); + return; + } + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code: "combo_revision_conflict" }); + expect(readFileSync(getConfigPath(), "utf8")).toBe(before); + // Adopting a changed or removed combo converges the catalog like a save would. + expect(convergences).toBe(1); + // The refused save adopts the stored combo, so the dashboard's refresh sees what blocked it. + expect({ ...config, combos: undefined }).toEqual({ ...liveBefore, combos: undefined }); + expect(config.combos?.c).toEqual(disk.combos?.c); + const refreshed = ((await (await call("GET")).json()).combos as any[]).find(combo => combo.id === "c"); + if (change === "deleted") { + expect(refreshed).toBeUndefined(); + return; + } + expect(refreshed.targets.map((target: { model: string }) => target.model)).toEqual(["n"]); + expect(refreshed.revision).not.toBe(draft.revision); + const retried = await call("PUT", { id: "c", ifRevision: refreshed.revision, combo: { strategy: "round-robin", targets: [{ provider: "fixture", model: "n" }] } }); + expect(retried.status).toBe(200); + expect(JSON.parse(readFileSync(getConfigPath(), "utf8")).combos.c.strategy).toBe("round-robin"); + } finally { + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = oldHome; + rmSync(home, { recursive: true, force: true }); + } + }); +} + +test("a PUT returns its own committed combo when another PUT finishes during convergence", async () => { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + } }; + let interleave: (() => Promise) | undefined; + const call = async (body: unknown) => { + const req = new Request("http://localhost/api/combos", { method: "PUT", headers: { host: "localhost", "content-type": "application/json" }, body: JSON.stringify(body) }); + return (await handleManagementAPI(req, new URL(req.url), config, { + createManagementConvergeCodex: catalogConvergenceFactory(async () => { const run = interleave; interleave = undefined; await run?.(); }), + saveConfigPreservingClaudeCode: () => {}, + }))!; + }; + let second: any; + interleave = async () => { second = await (await call({ id: "c", combo: { strategy: "failover", targets: [{ provider: "fixture", model: "n" }] } })).json(); }; + const first = await (await call({ id: "c", combo: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] } })).json(); + expect(first.combo.targets[0].model).toBe("m"); + expect(second.combo.targets[0].model).toBe("n"); + expect(first.combo.revision).not.toBe(second.combo.revision); +}); +test("a conditional rename refuses a destination that exists only in the stored config", async () => { + const home = mkdtempSync(join(tmpdir(), "combo-destination-")); + const oldHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + try { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + }, combos: { c: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] } } }; + saveConfig(config); + armClaudeCodeBaseline(config); + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { createManagementConvergeCodex: catalogConvergenceFactory() }))!; + }; + const draft = ((await (await call("GET")).json()).combos as any[])[0]; + const disk = structuredClone(config); + disk.combos!.other = { strategy: "failover", targets: [{ provider: "fixture", model: "n" }] }; + saveConfig(disk); + const before = readFileSync(getConfigPath(), "utf8"); + const response = await call("PUT", { id: "other", renameFrom: "c", ifRevision: draft.revision, combo: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] } }); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ code: "combo_revision_conflict" }); + expect(readFileSync(getConfigPath(), "utf8")).toBe(before); + const listed = ((await (await call("GET")).json()).combos as any[]).map(combo => combo.id).sort(); + expect(listed).toEqual(["c", "other"]); + } finally { + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = oldHome; + rmSync(home, { recursive: true, force: true }); + } +}); + +test("an adopted stored combo does not override a later disk edit on an unrelated save", async () => { + const home = mkdtempSync(join(tmpdir(), "combo-adopt-baseline-")); + const oldHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + try { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + }, combos: { c: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] } } }; + saveConfig(config); + armClaudeCodeBaseline(config); + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { createManagementConvergeCodex: catalogConvergenceFactory() }))!; + }; + const draft = ((await (await call("GET")).json()).combos as any[])[0]; + const diskB = structuredClone(config); + diskB.combos!.c!.targets = [{ provider: "fixture", model: "n" }]; + saveConfig(diskB); + expect((await call("PUT", { id: "c", ifRevision: draft.revision, combo: { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] } })).status).toBe(409); + const diskC = JSON.parse(readFileSync(getConfigPath(), "utf8")); + diskC.combos.c.strategy = "round-robin"; + diskC.combos.c.targets = [{ provider: "fixture", model: "m" }, { provider: "fixture", model: "n" }]; + saveConfig(diskC); + expect((await call("PUT", { id: "d", combo: { strategy: "failover", targets: [{ provider: "fixture", model: "n" }] } })).status).toBe(200); + const stored = JSON.parse(readFileSync(getConfigPath(), "utf8")).combos; + expect(stored.c.strategy).toBe("round-robin"); + expect(stored.c.targets.map((target: { model: string }) => target.model)).toEqual(["m", "n"]); + expect(Object.keys(stored).sort()).toEqual(["c", "d"]); + } finally { + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = oldHome; + rmSync(home, { recursive: true, force: true }); + } +}); + +test("a create-only save refuses a combo that exists in the live or stored config", async () => { + const home = mkdtempSync(join(tmpdir(), "combo-if-absent-")); + const oldHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + try { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + } }; + saveConfig(config); + armClaudeCodeBaseline(config); + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { createManagementConvergeCodex: catalogConvergenceFactory() }))!; + }; + const m = { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] }; + const n = { strategy: "failover", targets: [{ provider: "fixture", model: "n" }] }; + expect((await call("PUT", { id: "c", ifAbsent: true, combo: m })).status).toBe(200); + const live = await call("PUT", { id: "c", ifAbsent: true, combo: n }); + expect(live.status).toBe(409); + expect(await live.json()).toMatchObject({ code: "combo_revision_conflict" }); + expect(JSON.parse(readFileSync(getConfigPath(), "utf8")).combos.c.targets[0].model).toBe("m"); + const disk = JSON.parse(readFileSync(getConfigPath(), "utf8")); + disk.combos.e = n; + saveConfig(disk); + const before = readFileSync(getConfigPath(), "utf8"); + expect((await call("PUT", { id: "e", ifAbsent: true, combo: m })).status).toBe(409); + expect(readFileSync(getConfigPath(), "utf8")).toBe(before); + const listed = ((await (await call("GET")).json()).combos as any[]).find(combo => combo.id === "e"); + expect(listed.targets.map((target: { model: string }) => target.model)).toEqual(["n"]); + expect((await call("PUT", { id: "f", ifAbsent: false, combo: m })).status).toBe(400); + expect((await call("PUT", { id: "f", renameFrom: "c", ifAbsent: true, combo: m })).status).toBe(400); + } finally { + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = oldHome; + rmSync(home, { recursive: true, force: true }); + } +}); + +test("a conditional rename onto a live combo is a revision conflict, an unconditional one stays a 400", async () => { + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + } }; + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { + createManagementConvergeCodex: catalogConvergenceFactory(), saveConfigPreservingClaudeCode: () => {}, + }))!; + }; + const m = { strategy: "failover", targets: [{ provider: "fixture", model: "m" }] }; + expect((await call("PUT", { id: "c", combo: m })).status).toBe(200); + expect((await call("PUT", { id: "d", combo: m })).status).toBe(200); + const source = ((await (await call("GET")).json()).combos as any[]).find(combo => combo.id === "c"); + const conditional = await call("PUT", { id: "d", renameFrom: "c", ifRevision: source.revision, combo: m }); + expect(conditional.status).toBe(409); + expect(await conditional.json()).toMatchObject({ code: "combo_revision_conflict" }); + const unconditional = await call("PUT", { id: "d", renameFrom: "c", combo: m }); + expect(unconditional.status).toBe(400); + expect(Object.keys(config.combos ?? {}).sort()).toEqual(["c", "d"]); +}); + +test("adopting a stored combo also adopts the combo whose alias the same disk edit moved", async () => { + const home = mkdtempSync(join(tmpdir(), "combo-adopt-alias-")); + const oldHome = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + try { + const target = [{ provider: "fixture", model: "m" }]; + const config: OcxConfig = { port: 10100, defaultProvider: "fixture", providers: { + fixture: { adapter: "openai-chat", baseUrl: "https://fixture.example/v1", apiKey: "fixture", models: ["m", "n"], liveModels: false }, + }, combos: { + c: { strategy: "failover", alias: "alpha", targets: target }, + d: { strategy: "failover", alias: "beta", targets: target }, + e: { strategy: "failover", alias: "delta", targets: target }, + } }; + saveConfig(config); + armClaudeCodeBaseline(config); + const call = async (method: string, body?: unknown) => { + const req = new Request("http://localhost/api/combos", { method, headers: { host: "localhost", "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + return (await handleManagementAPI(req, new URL(req.url), config, { createManagementConvergeCodex: catalogConvergenceFactory() }))!; + }; + const draft = ((await (await call("GET")).json()).combos as any[]).find(combo => combo.id === "c"); + const disk = structuredClone(config); + disk.combos!.c!.alias = "beta"; + disk.combos!.d!.alias = "gamma"; + disk.combos!.e!.strategy = "round-robin"; + saveConfig(disk); + const response = await call("PUT", { id: "c", ifRevision: draft.revision, combo: { strategy: "failover", alias: "alpha", targets: target } }); + expect(response.status).toBe(409); + const listed = (await (await call("GET")).json()).combos as any[]; + const models = Object.fromEntries(listed.map(combo => [combo.id, combo.model])); + expect(models).toEqual({ c: "beta", d: "gamma", e: "delta" }); + // A row the alias swap did not touch keeps its live value. + expect(config.combos?.e?.strategy).toBe("failover"); + } finally { + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = oldHome; + rmSync(home, { recursive: true, force: true }); + } +}); From f170198f68260e4f23fec4dd219c85df7f5b2a52 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Sat, 28 Nov 2026 06:08:19 +0900 Subject: [PATCH 29/64] fix(connections): bound Claude settings reads during status and preview (#9130) * fix(claude): use bounded regular files for connection status and previews * Cover the descriptor identity check when following a settings symlink * fix(connections): report unknown for unpinned Desktop row when settings are unreadable * fix(connections): omit false firstPartySettingsUnreadable from observation --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- src/claude/connection-projection.ts | 21 ++++++-- src/claude/desktop-first-party.ts | 9 +++- src/claude/first-party-preview.ts | 15 ++++-- src/claude/intercept/settings-no-proxy.ts | 17 +++++-- src/claude/intercept/settings.ts | 22 ++++++--- src/lib/bounded-file-read.ts | 26 +++++++--- structure/clients/connections.md | 12 +++-- .../claude-first-party-preview.test.ts | 9 ++++ tests/lib/bounded-file-read.test.ts | 30 ++++++++++++ tests/server/connection-status-routes.test.ts | 49 ++++++++++++++++++- 10 files changed, 179 insertions(+), 31 deletions(-) diff --git a/src/claude/connection-projection.ts b/src/claude/connection-projection.ts index 1d23955dc93..088e792e292 100644 --- a/src/claude/connection-projection.ts +++ b/src/claude/connection-projection.ts @@ -13,11 +13,11 @@ import { displayPath } from "../lib/display-path"; import type { OcxConfig } from "../types"; import { registeredClaudeConfigDirs } from "./auth-detect"; import { inspectDesktop3pConfigLibrary } from "./desktop-3p"; -import { inspectDesktopFirstParty, observeClaudeDesktopMode, resolveClaudeDesktopMode } from "./desktop-first-party"; +import { inspectDesktopFirstParty, isClaudeDesktopMode, observeClaudeDesktopMode, resolveClaudeDesktopMode } from "./desktop-first-party"; import { previewClaudeFirstPartySettings } from "./first-party-preview"; import { firstPartyDesired, firstPartyProxyStatus } from "./first-party-settings"; import { claudeInterceptEnabled } from "./intercept/runtime"; -import { claudeSettingsFileState } from "./intercept/settings"; +import { claudeSettingsFileState, MAX_STATUS_SETTINGS_BYTES } from "./intercept/settings"; export interface ClaudeConnectionInput { live: OcxConfig; @@ -31,7 +31,8 @@ export interface ClaudeConnectionInput { function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "default" | "extra", ordinal?: number): ConnectionView { const { live } = input; - const options = { claudeConfigDir: dir, ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; + const options = { claudeConfigDir: dir, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES, + ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; const settingsPath = join(dir, "settings.json"); const fileState = claudeSettingsFileState(dir); if (fileState === "unsafe") { @@ -84,7 +85,8 @@ function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "defau function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView { const { live } = input; - const options = input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}; + const options = { settingsReadLimit: MAX_STATUS_SETTINGS_BYTES, + ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; const wanted = claudeDesktopIntegrationEnabled(live); const observation = observeClaudeDesktopMode(live, options); const mode = resolveClaudeDesktopMode(live, observation); @@ -96,8 +98,17 @@ function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView { case "foreign": observed = "foreign"; break; case "broken": case "unsafe": observed = "unknown"; break; case "standard": case "no_owned_state": { + const unresolvedFirstParty = !isClaudeDesktopMode(live.claudeCode?.desktopMode) + && !live.claudeCode?.desktopProfile?.appliedFingerprint + && live.claudeCode?.cliFirstParty !== true + && observation.firstPartySettingsUnreadable === true; + if (unresolvedFirstParty) { + observed = "unknown"; + break; + } const settings = mode === "first-party" ? inspectDesktopFirstParty(live, options).settings : null; - observed = settings && (settings.kind === "applied" || settings.kind === "stale") ? "proxy" : "native"; + observed = settings?.kind === "unreadable" ? "unknown" + : settings?.kind === "applied" || settings?.kind === "stale" ? "proxy" : "native"; break; } default: { diff --git a/src/claude/desktop-first-party.ts b/src/claude/desktop-first-party.ts index 88f1106f25c..fda5ceed773 100644 --- a/src/claude/desktop-first-party.ts +++ b/src/claude/desktop-first-party.ts @@ -55,6 +55,8 @@ export interface ClaudeDesktopModeObservation { ownedGatewaySelected?: boolean; /** Claude Code's settings carry first-party env that opencodex wrote (applied or stale). */ ownedFirstPartySettings?: boolean; + /** Claude Code's settings could not be read, so first-party mode could not be ruled out. */ + firstPartySettingsUnreadable?: boolean; } /** @@ -152,6 +154,8 @@ export interface DesktopFirstPartyInspection { export interface DesktopFirstPartyOptions { opencodexConfigDir?: string; claudeConfigDir?: string; + /** Read-only projections cap settings bytes and validate the opened descriptor. */ + settingsReadLimit?: number; } /** Prepare rollback before replacing a gateway, without changing settings. */ @@ -176,7 +180,8 @@ export function inspectDesktopFirstParty( // so an owned env can never match the empty credential — it classifies stale, and a real // apply is what refreshes it. const target = firstPartyTarget(config, opencodexConfigDir, readClaudeInterceptProxyToken(opencodexConfigDir) ?? ""); - const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir); + const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir, + { maxBytes: options.settingsReadLimit }); return { interceptEnabled: claudeInterceptEnabled(config), proxyPort: target.proxyPort, @@ -206,8 +211,10 @@ export function observeClaudeDesktopMode( const kind = inspectDesktopFirstParty(config, options).settings.kind; observed.ownedFirstPartySettings = config.claudeCode?.cliFirstParty === true ? false : kind === "applied" || kind === "stale"; + if (kind === "unreadable") observed.firstPartySettingsUnreadable = true; } catch { // no-excuse-ok: catch -- unreadable settings are no first-party evidence. observed.ownedFirstPartySettings = false; + observed.firstPartySettingsUnreadable = true; } return observed; } diff --git a/src/claude/first-party-preview.ts b/src/claude/first-party-preview.ts index 607d242f8a3..0eb05a85e31 100644 --- a/src/claude/first-party-preview.ts +++ b/src/claude/first-party-preview.ts @@ -23,7 +23,7 @@ import { claudeFirstPartyTransition } from "./first-party-transition"; import { claudeInterceptCaCertPath } from "./intercept/local-ca"; import { readClaudeInterceptProxyToken } from "./intercept/proxy-auth"; import { claudeInterceptEnabled } from "./intercept/runtime"; -import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, readClaudeSettingsEnv } from "./intercept/settings"; +import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, MAX_STATUS_SETTINGS_BYTES, readClaudeSettingsEnv } from "./intercept/settings"; import { mergeClaudeInterceptNoProxy, noProxyMergeable, readNoProxyReceipt } from "./intercept/settings-no-proxy"; export type SettingsChangeKind = "add" | "update" | "remove"; @@ -60,6 +60,8 @@ export interface FirstPartyPreviewInput { } const MANAGED_KEYS = ["HTTPS_PROXY", "NODE_EXTRA_CA_CERTS"] as const; +// A receipt stores both the old and written NO_PROXY strings, plus its JSON fields. +const MAX_PREVIEW_RECEIPT_BYTES = 2 * MAX_STATUS_SETTINGS_BYTES + 1024; function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange { return { file: "settings.json", key: `env.${key}`, change: kind }; @@ -67,7 +69,7 @@ function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): FirstPartyPreview { const { live, persisted, enabled } = input; - const options = input.options ?? {}; + const options = { ...input.options, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES }; const dir = options.claudeConfigDir ?? claudeConfigDir(); const path = join(dir, "settings.json"); const refuse = (reason: FirstPartyPreviewRefusal): FirstPartyPreview => ({ ok: false, enabled, reason, path }); @@ -90,7 +92,7 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): const reconciled: OcxConfig = { ...live, claudeCode: nextBlock }; const desired = firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, options)); - const read = readClaudeSettingsEnv(dir); + const read = readClaudeSettingsEnv(dir, { maxBytes: MAX_STATUS_SETTINGS_BYTES }); if (read.kind === "unreadable") return refuse("unreadable"); const env = read.kind === "env" ? read.env : {}; @@ -101,7 +103,12 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): if (typeof ca !== "string" || ca.trim() !== ownedCa) return accept([]); const changes = [change("NODE_EXTRA_CA_CERTS", "remove")]; if (isClaudeInterceptProxyUrl(env.HTTPS_PROXY)) changes.push(change("HTTPS_PROXY", "remove")); - const receipt = readNoProxyReceipt(dir); + let receipt; + try { + receipt = readNoProxyReceipt(dir, MAX_PREVIEW_RECEIPT_BYTES); + } catch { // no-excuse-ok: catch -- a bounded read failure leaves the restoration undetermined. + return refuse("unreadable"); + } if (receipt && env.NO_PROXY === receipt.written) { const restored = receipt.hadKey ? receipt.previous : undefined; if (restored === undefined) changes.push(change("NO_PROXY", "remove")); diff --git a/src/claude/intercept/settings-no-proxy.ts b/src/claude/intercept/settings-no-proxy.ts index d82210c38f2..9d88267172a 100644 --- a/src/claude/intercept/settings-no-proxy.ts +++ b/src/claude/intercept/settings-no-proxy.ts @@ -1,6 +1,7 @@ import { readFileSync, unlinkSync } from "node:fs"; import { join } from "node:path"; import { atomicWriteFile } from "../../config/atomic-write"; +import { readBoundedRegularFileSync } from "../../lib/bounded-file-read"; import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard"; /** @@ -98,11 +99,21 @@ export function setNoProxyReceiptIoForTests(io: Partial): () => void } /** The receipt, or null when it is missing or malformed (both mean: no provenance). */ -export function readNoProxyReceipt(configDir: string): NoProxyReceipt | null { +export function readNoProxyReceipt(configDir: string, maxBytes?: number): NoProxyReceipt | null { + const path = noProxyReceiptPath(configDir); + let raw: string; + try { + raw = maxBytes === undefined ? readFileSync(path, "utf8") + : readBoundedRegularFileSync(path, maxBytes, { followFinalSymlink: true }).toString("utf8"); + } catch (error) { + // The preview cannot predict a restoration from a receipt it could not safely read. + if (maxBytes !== undefined && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + return null; + } let parsed: unknown; try { - parsed = JSON.parse(readFileSync(noProxyReceiptPath(configDir), "utf8")); - } catch { // no-excuse-ok: catch -- a missing or corrupt receipt is the no-provenance state. + parsed = JSON.parse(raw); + } catch { // no-excuse-ok: catch -- a corrupt receipt is the no-provenance state. return null; } if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; diff --git a/src/claude/intercept/settings.ts b/src/claude/intercept/settings.ts index 0b44b6e091d..a32b84c206e 100644 --- a/src/claude/intercept/settings.ts +++ b/src/claude/intercept/settings.ts @@ -1,6 +1,7 @@ import { mkdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join } from "node:path"; import { atomicWriteFile } from "../../config/atomic-write"; +import { readBoundedRegularFileSync } from "../../lib/bounded-file-read"; import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard"; import { claudeConfigDir } from "../auth-detect"; import { invalidateClaudeCodeServedCatalog } from "./cli-catalog"; @@ -70,15 +71,20 @@ export type ClaudeInterceptSettingsState = | { kind: "unreadable"; path: string }; type SettingsDoc = Record & { env?: Record }; +interface SettingsReadOptions { maxBytes?: number } function settingsPath(configDir: string): string { return join(configDir, "settings.json"); } -function readSettings(path: string): { doc: SettingsDoc } | { error: "missing" | "unreadable" } { +function readSettings( + path: string, + options: SettingsReadOptions = {}, +): { doc: SettingsDoc } | { error: "missing" | "unreadable" } { let raw: string; try { - raw = readFileSync(path, "utf8"); + raw = options.maxBytes === undefined ? readFileSync(path, "utf8") + : readBoundedRegularFileSync(path, options.maxBytes, { followFinalSymlink: true }).toString("utf8"); } catch (error) { // no-excuse-ok: catch -- an absent settings file is the fresh-install state. return { error: (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable" }; } @@ -100,7 +106,7 @@ export type ClaudeSettingsEnvRead = | { kind: "unreadable" } | { kind: "env"; env: Readonly> }; -const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; +export const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; /** * Read-only status guard for a settings.json a status GET is about to read: `unsafe` for a @@ -118,8 +124,11 @@ export function claudeSettingsFileState(configDir = claudeConfigDir()): "missing } /** Read-only: the settings.json env block the writers below start from. Never writes. */ -export function readClaudeSettingsEnv(configDir = claudeConfigDir()): ClaudeSettingsEnvRead { - const read = readSettings(settingsPath(configDir)); +export function readClaudeSettingsEnv( + configDir = claudeConfigDir(), + options: SettingsReadOptions = {}, +): ClaudeSettingsEnvRead { + const read = readSettings(settingsPath(configDir), options); if ("error" in read) return { kind: read.error }; return { kind: "env", env: { ...envRecord(read.doc) } }; } @@ -142,9 +151,10 @@ function setOrDelete(env: Record, key: string, value: unknown): export function inspectClaudeInterceptSettings( expected: ClaudeInterceptEnv, configDir = claudeConfigDir(), + options: SettingsReadOptions = {}, ): ClaudeInterceptSettingsState { const path = settingsPath(configDir); - const read = readSettings(path); + const read = readSettings(path, options); if ("error" in read) return read.error === "missing" ? { kind: "absent" } : { kind: "unreadable", path }; const env = envRecord(read.doc); const proxy = env.HTTPS_PROXY; diff --git a/src/lib/bounded-file-read.ts b/src/lib/bounded-file-read.ts index f37045d0b2c..31543b81530 100644 --- a/src/lib/bounded-file-read.ts +++ b/src/lib/bounded-file-read.ts @@ -1,18 +1,30 @@ -import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs"; +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, statSync } from "node:fs"; import { sameFileIdentity } from "./file-identity"; const MAX_BOUNDED_READ_BYTES = 64 * 1024 * 1024; const READ_CHUNK_BYTES = 64 * 1024; -export function readBoundedRegularFileSync(path: string, limit: number): Buffer { +export interface BoundedRegularFileReadOptions { + /** Follow the final symlink while still requiring its opened target to be bounded regular data. */ + followFinalSymlink?: boolean; +} + +export function readBoundedRegularFileSync( + path: string, + limit: number, + options: BoundedRegularFileReadOptions = {}, +): Buffer { if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_BOUNDED_READ_BYTES) { throw new RangeError("invalid bounded file read limit"); } const windows = process.platform === "win32"; - const flags = constants.O_RDONLY | (windows ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW); - const entryBefore = windows ? lstatSync(path, { bigint: true }) : undefined; - if (entryBefore && (entryBefore.isSymbolicLink() || !entryBefore.isFile())) { + const followFinalSymlink = options.followFinalSymlink === true; + const posixFlags = constants.O_NONBLOCK | (followFinalSymlink ? 0 : constants.O_NOFOLLOW); + const flags = constants.O_RDONLY | (windows ? 0 : posixFlags); + const inspectEntry = followFinalSymlink ? statSync : lstatSync; + const entryBefore = windows || followFinalSymlink ? inspectEntry(path, { bigint: true }) : undefined; + if (entryBefore && !entryBefore.isFile()) { throw new Error("not a regular file"); } const fd = openSync(path, flags); @@ -40,8 +52,8 @@ export function readBoundedRegularFileSync(path: string, limit: number): Buffer if (length > limit) throw new Error("file exceeds byte limit"); if (entryBefore) { - const entryAfter = lstatSync(path, { bigint: true }); - if (entryAfter.isSymbolicLink() || !entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) { + const entryAfter = inspectEntry(path, { bigint: true }); + if (!entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) { throw new Error("file entry changed while reading"); } } diff --git a/structure/clients/connections.md b/structure/clients/connections.md index 5cde8d43e37..f2f2f09b954 100644 --- a/structure/clients/connections.md +++ b/structure/clients/connections.md @@ -59,10 +59,14 @@ prefix becomes `~`, a drive letter stays, and only the fixed directory and file and Claude use are shown; any other segment (a user name, account id or token used as a folder name) becomes `…`, and an extra home is identified by `homeOrdinal` instead of its path. No setting value, token or email is returned; an unexpected failure answers a fixed `connections_failed` body. Reads are -bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), a `settings.json` that is not a -regular file of at most 1 MiB is never opened (`claudeSettingsFileState`; the row reads `unknown` and -the preview refuses `unreadable`), and the Codex profile goes through the same bounded reader as -config.toml. The Codex +bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), and status/preview settings reads +validate and size-cap the opened descriptor at 1 MiB, with nonblocking opens on POSIX, then parse only +those bounded bytes. A final symlink remains compatible with Claude Code when its opened target is a +regular file; a FIFO, device, directory, oversized file or unsafe replacement reads `unknown` in the +row and makes the preview refuse `unreadable`. The switch-off preview applies the same descriptor +checks to the optional NO_PROXY receipt, allowing space for both stored values and its JSON fields. +The Codex profile goes through the same bounded reader +as config.toml. The Codex toggle envelopes in `native-integration-routes.ts` carry `connections: "/api/connections"`. CLI verb: owed. The route registry declares it `deferred-verb` with owner "proxy catch-up 020 diff --git a/tests/claude-integration/claude-first-party-preview.test.ts b/tests/claude-integration/claude-first-party-preview.test.ts index 9b55c2cf4e3..0a103551251 100644 --- a/tests/claude-integration/claude-first-party-preview.test.ts +++ b/tests/claude-integration/claude-first-party-preview.test.ts @@ -151,6 +151,15 @@ describe("enabling CLI first-party", () => { }); describe("turning CLI first-party off", () => { + test("a missing receipt is optional and an oversized receipt makes the preview unreadable", () => { + writeEnv({ NODE_EXTRA_CA_CERTS: claudeInterceptCaCertPath(root) }); + const config = cfg({ cli: true, desktopMode: "gateway" }); + const input = { live: config, persisted: config, enabled: false, options: options() }; + expect(previewClaudeFirstPartySettings(input).ok).toBe(true); + writeFileSync(join(claudeHome, "opencodex-no-proxy.json"), "{}".padEnd(2 * 1024 * 1024 + 1025)); + expect(previewClaudeFirstPartySettings(input)).toMatchObject({ ok: false, reason: "unreadable" }); + }); + test("a CLI-only env is removed, restoring NO_PROXY from its receipt", () => { expect(realSwitch(cfg({ desktopMode: "gateway" }), cfg({ desktopMode: "gateway" }), true).ok).toBe(true); const on = cfg({ cli: true, desktopMode: "gateway" }); diff --git a/tests/lib/bounded-file-read.test.ts b/tests/lib/bounded-file-read.test.ts index 6d1706f87bb..eac7fd4e3e1 100644 --- a/tests/lib/bounded-file-read.test.ts +++ b/tests/lib/bounded-file-read.test.ts @@ -117,6 +117,36 @@ describe("readBoundedRegularFileSync", () => { expect(() => readBoundedRegularFileSync(link, 64)).toThrow(); }); + test.skipIf(!canCreateFileSymlink())("follows a final symlink only when requested", () => { + const path = join(root, "target.json"); + writeFileSync(path, "fixture"); + const link = join(root, "linked.json"); + symlinkSync(path, link, "file"); + expect(readBoundedRegularFileSync(link, 64, { followFinalSymlink: true }).toString("utf8")) + .toBe("fixture"); + }); + + test("the symlink-following reader closes a descriptor whose identity differs from the pre-open stat", () => { + const path = join(root, "settings.json"); + writeFileSync(path, "{}"); + // Change only the metadata returned by the first stat. The fixture and its descriptor stay real. + const before = fs.statSync(path, { bigint: true }); + before.ino += 1n; + const stat = spyOn(fs, "statSync").mockReturnValueOnce(before); + const open = spyOn(fs, "openSync"); + const close = spyOn(fs, "closeSync"); + try { + expect(() => readBoundedRegularFileSync(path, 64, { followFinalSymlink: true })) + .toThrow("file entry changed while opening"); + expect(open).toHaveBeenCalledTimes(1); + expect(close.mock.calls).toEqual([[open.mock.results[0]!.value]]); + } finally { + close.mockRestore(); + open.mockRestore(); + stat.mockRestore(); + } + }); + test.skipIf(process.platform === "win32")("rejects a FIFO without blocking", () => { const fifo = join(root, "input.pipe"); const created = spawnSync("mkfifo", [fifo], { timeout: 2_000 }); diff --git a/tests/server/connection-status-routes.test.ts b/tests/server/connection-status-routes.test.ts index a5fc13c12be..371de153d18 100644 --- a/tests/server/connection-status-routes.test.ts +++ b/tests/server/connection-status-routes.test.ts @@ -7,7 +7,8 @@ */ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import * as fs from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { handleManagementAPI } from "../../src/server/management-api"; @@ -313,12 +314,58 @@ describe("security bounds", () => { expect(row).toMatchObject({ observed: "unknown", owner: "unknown", driftReasons: [] }); }); + test("the connection and preview routes inspect ordinary settings through bounded file descriptors", async () => { + const extra = join(root, "extra-read"); + const settings = [claudeHome, extra].map(dir => { + mkdirSync(dir, { recursive: true }); + const path = join(dir, "settings.json"); + writeFileSync(path, "{}"); + return path; + }); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const opens = spyOn(fs, "openSync"); + const reads = spyOn(fs, "readFileSync"); + try { + const views = await connections(config); + expect(views.find(row => row.homeSource === "extra")?.observed).toBe("native"); + for (const path of settings) expect(opens.mock.calls.some(([file]) => file === path)).toBe(true); + opens.mockClear(); + const preview = await dispatch(config, "/api/claude-code/first-party/preview?enabled=false"); + expect(preview!.status).toBe(200); + expect(opens.mock.calls.some(([file]) => file === settings[0])).toBe(true); + expect(reads.mock.calls.some(([file]) => settings.some(path => path === file))).toBe(false); + } finally { + reads.mockRestore(); + opens.mockRestore(); + } + }); + + test.skipIf(process.platform === "win32")("a symlinked regular settings.json keeps Claude-compatible routing", async () => { + const extra = join(root, "linked-home"); + const target = join(root, "linked-settings.json"); + mkdirSync(extra, { recursive: true }); + writeFileSync(target, JSON.stringify({ env: { + HTTPS_PROXY: "http://proxy.corp:8080", NODE_EXTRA_CA_CERTS: "/corp/ca.pem", + } })); + symlinkSync(target, join(extra, "settings.json")); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const row = (await connections(config)).find(view => view.homeSource === "extra")!; + expect(row).toMatchObject({ observed: "foreign", owner: "external", driftReasons: [] }); + }); + test("an oversized default settings.json makes the preview refuse instead of reading it", async () => { mkdirSync(claudeHome, { recursive: true }); writeFileSync(join(claudeHome, "settings.json"), `{"pad":"${"x".repeat(1024 * 1024 + 16)}"}`); const response = await dispatch(baseConfig(), "/api/claude-code/first-party/preview?enabled=true"); expect(response!.status).toBe(500); expect(await response!.json()).toMatchObject({ code: "unreadable" }); + mkdirSync(join(root, "library"), { recursive: true }); + const pinnedViews = await connections(baseConfig({ claudeCode: { desktopMode: "first-party" } })); + expect(pinnedViews.find(row => row.client === "claude-desktop")).toMatchObject({ observed: "unknown", owner: "unknown" }); + const unpinnedViews = await connections(baseConfig()); + expect(unpinnedViews.find(row => row.client === "claude-desktop")).toMatchObject({ observed: "unknown", owner: "unknown", driftReasons: [] }); + const pinnedGatewayViews = await connections(baseConfig({ claudeCode: { desktopMode: "gateway" } })); + expect(pinnedGatewayViews.find(row => row.client === "claude-desktop")).toMatchObject({ observed: "native", owner: "none" }); }); test("registered homes are capped", async () => { From ab9e517780209a38495e90663517cf12eaf5fcec Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:14:22 +0900 Subject: [PATCH 30/64] fix(link): show local-update guidance instead of Update for Windows npm Children (#9181) * fix(link): show local-update guidance for Windows npm Children The Home recorded a Windows npm Child's plan as an orchestrated update, so the dashboard enabled Update even though the update runner always refuses Windows apply (windows-apply). Clicking it started a job that ran a pinned sync first, and in the reported case failed there. Observe now records a Windows plan whose route is orchestrated as owner-action windows-apply; the probe keeps the plan's own route for the runner. The Home row shows "Remote updates aren't supported for this Windows device. Update OpenCodex directly on the Windows computer." in all 12 locales and offers no Update. A Windows Child's own refusal of an update request gives the same guidance instead of pointing at the Home. Closes #9172 * fix(link): keep long owner-action guidance readable in its badge The Windows guidance is a full sentence the badge truncates. StateBadge takes an optional title, and owner-action badges set it to their full text. * fix(link): apply Windows local-update guidance to cached observations An observation recorded before this change kept its orchestrated route, so an existing Windows npm Child stayed eligible for Update until it was checked again. The status projection now applies the same rule with the link record's platform. The guidance badge wraps instead of truncating, so it is readable without a pointer hover, and the disabled Update button's title gives the owner-action guidance instead of "Up to date". * fix(link): record the observed platform and withhold unknown cached routes A link record may have no remotePlatform, so the status projection could not tell a cached orchestrated Windows observation from a POSIX one. Plan observations now record the platform they ran on. The projection uses the link record's platform, else the observation's; a cached orchestrated route with neither is shown as owner-action recheck-required ("Check this Child again to see how it can be updated", 12 locales) until a fresh check records the platform. * docs(remote-link): say a cached Child without a recorded platform needs a Check Addresses the CodeRabbit note on the Spanish guide; the English guide gets the same sentence. --- .../src/content/docs/es/guides/remote-link.md | 2 +- .../src/content/docs/guides/remote-link.md | 2 +- gui/src/components/v2-startup/primitives.tsx | 8 +++-- gui/src/i18n/de.ts | 2 ++ gui/src/i18n/en.ts | 2 ++ gui/src/i18n/es.ts | 2 ++ gui/src/i18n/fr.ts | 2 ++ gui/src/i18n/ja.ts | 2 ++ gui/src/i18n/ko.ts | 2 ++ gui/src/i18n/pt.ts | 2 ++ gui/src/i18n/ru.ts | 2 ++ gui/src/i18n/tr.ts | 2 ++ gui/src/i18n/vi.ts | 2 ++ gui/src/i18n/zh-TW.ts | 2 ++ gui/src/i18n/zh.ts | 2 ++ gui/src/pages/RemoteLinkChildActions.tsx | 13 +++++++-- gui/tests/remote-link-child-ops.test.tsx | 20 +++++++++++++ src/link/child-observations.ts | 3 ++ src/link/child-observe.ts | 23 +++++++++++---- src/link/management-routes.ts | 19 ++++++++++-- .../management/link-child-ops-routes.ts | 9 ++++-- structure/remote-link.md | 2 +- tests/clients/link-child-observe.test.ts | 14 +++++++-- tests/server/link-child-ops-routes.test.ts | 29 ++++++++++++++++++- tests/server/link-management-relay.test.ts | 11 ++++++- 25 files changed, 156 insertions(+), 23 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/remote-link.md b/docs-site/src/content/docs/es/guides/remote-link.md index 262fbd27daf..c31adbeda18 100644 --- a/docs-site/src/content/docs/es/guides/remote-link.md +++ b/docs-site/src/content/docs/es/guides/remote-link.md @@ -415,7 +415,7 @@ En un Home, cada fila de Remote Link lleva lo último que el Home aprendió sobr - `Catalog current` o `Catalog out of date`. `Codex restart needed ()` y `Codex not running` solo aparecen cuando el Child informa de su estado de Codex, que añade una versión posterior; todavía ningún Child publicado lo envía, así que hoy esas dos insignias no aparecen. - la última operación, como `Last : ` con su razón en monoespaciada, y la que se está ejecutando mientras un trabajo ocupa el enlace. -Cuando el Home no puede actualizar ese Child por sí mismo, la fila dice qué hacer en su lugar: use Check for Updates en OpenCodex Desktop allí, actualice a mano, mediante `mise`, o deje que GOAT lo haga. Una razón desconocida se imprime como un token en lugar de una frase supuesta. +Cuando el Home no puede actualizar ese Child por sí mismo, la fila dice qué hacer en su lugar: use Check for Updates en OpenCodex Desktop allí, actualice a mano, mediante `mise`, o deje que GOAT lo haga. Un Child de Windows instalado con un gestor de paquetes no se puede actualizar desde el Home: su fila no ofrece **Update** e indica que actualice OpenCodex directamente en el equipo Windows, y el panel del propio Child da la misma indicación cuando busca actualizaciones allí. Si el Home no registró la plataforma de un Child que comprobó por última vez antes de este cambio, su fila tampoco ofrece **Update** y pide comprobar de nuevo ese Child; **Check** u `ocx link check` actualiza la fila. Una razón desconocida se imprime como un token en lugar de una frase supuesta. Las cuatro acciones inician el mismo trabajo que la CLI, así que necesitan las mismas versiones en el Child: diff --git a/docs-site/src/content/docs/guides/remote-link.md b/docs-site/src/content/docs/guides/remote-link.md index 528413b813c..6587e6c580e 100644 --- a/docs-site/src/content/docs/guides/remote-link.md +++ b/docs-site/src/content/docs/guides/remote-link.md @@ -351,7 +351,7 @@ On a Home, every Remote Link row carries what the Home last learned about that C - `Catalog current` or `Catalog out of date`. `Codex restart needed ()` and `Codex not running` appear only once the Child reports its Codex state, which a later release adds; no released Child sends it yet, so those two badges do not appear today. - the last operation, as `Last : ` with its reason in monospace, and the running one while a job holds the link. -When the Home cannot update that Child itself, the row says what to do instead: use Check for Updates in OpenCodex Desktop there, update by hand, through `mise`, or let GOAT do it. An unknown reason prints as a token rather than a guessed sentence. +When the Home cannot update that Child itself, the row says what to do instead: use Check for Updates in OpenCodex Desktop there, update by hand, through `mise`, or let GOAT do it. A Windows Child installed with a package manager cannot be updated from the Home: its row offers no **Update** and says to update OpenCodex directly on the Windows computer, and the Child's own dashboard gives the same guidance when you check for updates there. If the Home has not recorded the platform of a Child it last checked before this behavior shipped, its row offers no **Update** either and asks you to check that Child again; **Check** or `ocx link check` refreshes the row. An unknown reason prints as a token rather than a guessed sentence. The four actions start the same job as the CLI, so they need the same versions on the Child: diff --git a/gui/src/components/v2-startup/primitives.tsx b/gui/src/components/v2-startup/primitives.tsx index 6e9fdf8cc62..e82170cfd03 100644 --- a/gui/src/components/v2-startup/primitives.tsx +++ b/gui/src/components/v2-startup/primitives.tsx @@ -22,15 +22,17 @@ const BADGE_TONE: Record = { }; /** A state word in a soft pill with a dot (`integrations-6` status words). */ -export function StateBadge({ tone, children, className }: { tone: Tone; children: ReactNode; className?: string }) { +/** `wrap` lets a sentence-long badge break across lines instead of truncating, so every pointer and keyboard user can read it. */ +export function StateBadge({ tone, children, className, wrap = false }: { tone: Tone; children: ReactNode; className?: string; wrap?: boolean }) { return ( ); } diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index c4c92b03f90..aab905c6079 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4531,6 +4531,8 @@ export const de: Record = { "remoteLink.child.ownerAction.mise-managed": "mise verwaltet OpenCodex auf diesem Child; über mise aktualisieren", "remoteLink.child.ownerAction.source-checkout": "Dieser Child läuft aus einem Quellcode-Checkout; von Hand aktualisieren", "remoteLink.child.ownerAction.installer-unknown": "Die Installationsart dieses Child ist unbekannt; dort aktualisieren", + "remoteLink.child.ownerAction.windows-apply": "Remote-Updates werden für dieses Windows-Gerät nicht unterstützt. Aktualisieren Sie OpenCodex direkt auf dem Windows-Computer.", + "remoteLink.child.ownerAction.recheck-required": "Prüfen Sie dieses Child erneut, um zu sehen, wie es aktualisiert werden kann", "remoteLink.child.check": "Prüfen", "remoteLink.child.checkAll": "Alle prüfen", "remoteLink.child.syncNow": "Jetzt synchronisieren", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index ad30686aacb..11c72bb338c 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -4565,6 +4565,8 @@ export const en = { "remoteLink.child.ownerAction.mise-managed": "mise manages OpenCodex on this Child; update it through mise", "remoteLink.child.ownerAction.source-checkout": "This Child runs from a source checkout; update it by hand", "remoteLink.child.ownerAction.installer-unknown": "This Child's install method is unknown; update it there", + "remoteLink.child.ownerAction.windows-apply": "Remote updates aren’t supported for this Windows device. Update OpenCodex directly on the Windows computer.", + "remoteLink.child.ownerAction.recheck-required": "Check this Child again to see how it can be updated", "remoteLink.child.check": "Check", "remoteLink.child.checkAll": "Check all", "remoteLink.child.syncNow": "Sync now", diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index 6696579ed97..ba689534df6 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -4526,6 +4526,8 @@ export const es = { "remoteLink.child.ownerAction.mise-managed": "mise gestiona OpenCodex en este Child. Actualízalo con mise.", "remoteLink.child.ownerAction.source-checkout": "Este Child se ejecuta desde una copia del código fuente. Actualízalo manualmente.", "remoteLink.child.ownerAction.installer-unknown": "Se desconoce el método de instalación de este Child. Actualízalo desde el propio equipo.", + "remoteLink.child.ownerAction.windows-apply": "Las actualizaciones remotas no son compatibles con este dispositivo Windows. Actualiza OpenCodex directamente en el equipo Windows.", + "remoteLink.child.ownerAction.recheck-required": "Comprueba de nuevo este Child para ver cómo se puede actualizar", "remoteLink.child.check": "Comprobar", "remoteLink.child.checkAll": "Comprobar todos", "remoteLink.child.syncNow": "Sincronizar ahora", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 2a41fbbf287..47298c6d010 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4520,6 +4520,8 @@ export const fr: Record = { "remoteLink.child.ownerAction.mise-managed": "mise gère OpenCodex sur cet Enfant ; mettez-le à jour via mise", "remoteLink.child.ownerAction.source-checkout": "Cet Enfant s’exécute depuis une copie du code source ; mettez-le à jour à la main", "remoteLink.child.ownerAction.installer-unknown": "La méthode d’installation de cet Enfant est inconnue ; mettez-le à jour sur place", + "remoteLink.child.ownerAction.windows-apply": "Les mises à jour à distance ne sont pas prises en charge pour cet appareil Windows. Mettez à jour OpenCodex directement sur l’ordinateur Windows.", + "remoteLink.child.ownerAction.recheck-required": "Vérifiez à nouveau cet Enfant pour savoir comment le mettre à jour", "remoteLink.child.check": "Vérifier", "remoteLink.child.checkAll": "Tout vérifier", "remoteLink.child.syncNow": "Synchroniser maintenant", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 52f8b740809..39789d3a51b 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4553,6 +4553,8 @@ export const ja: Record = { "remoteLink.child.ownerAction.mise-managed": "この Child の OpenCodex は mise が管理しています。mise で更新してください", "remoteLink.child.ownerAction.source-checkout": "この Child はソースチェックアウトから実行されています。手動で更新してください", "remoteLink.child.ownerAction.installer-unknown": "この Child のインストール方法は不明です。そこで更新してください", + "remoteLink.child.ownerAction.windows-apply": "この Windows デバイスではリモート更新に対応していません。Windows コンピューター上で OpenCodex を直接更新してください。", + "remoteLink.child.ownerAction.recheck-required": "更新方法を確認するには、この Child をもう一度チェックしてください", "remoteLink.child.check": "確認", "remoteLink.child.checkAll": "すべて確認", "remoteLink.child.syncNow": "今すぐ同期", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index c21aa47f439..2b045cad0a9 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4553,6 +4553,8 @@ export const ko: Record = { "remoteLink.child.ownerAction.mise-managed": "이 Child의 OpenCodex는 mise가 관리합니다. mise로 업데이트하세요", "remoteLink.child.ownerAction.source-checkout": "이 Child는 소스 체크아웃에서 실행됩니다. 직접 업데이트하세요", "remoteLink.child.ownerAction.installer-unknown": "이 Child의 설치 방식을 알 수 없습니다. 그곳에서 업데이트하세요", + "remoteLink.child.ownerAction.windows-apply": "이 Windows 기기에서는 원격 업데이트를 지원하지 않습니다. Windows 컴퓨터에서 OpenCodex를 직접 업데이트하세요.", + "remoteLink.child.ownerAction.recheck-required": "업데이트 방법을 확인하려면 이 Child를 다시 확인하세요", "remoteLink.child.check": "확인", "remoteLink.child.checkAll": "모두 확인", "remoteLink.child.syncNow": "지금 동기화", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index a0b77f2e3fd..f34d0c11335 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4526,6 +4526,8 @@ export const pt: Record = { "remoteLink.child.ownerAction.mise-managed": "O mise gerencia o OpenCodex neste Child; atualize pelo mise", "remoteLink.child.ownerAction.source-checkout": "Este Child roda a partir de uma cópia do código-fonte; atualize manualmente", "remoteLink.child.ownerAction.installer-unknown": "O método de instalação deste Child é desconhecido; atualize lá", + "remoteLink.child.ownerAction.windows-apply": "Atualizações remotas não são compatíveis com este dispositivo Windows. Atualize o OpenCodex diretamente no computador Windows.", + "remoteLink.child.ownerAction.recheck-required": "Verifique este Child novamente para ver como ele pode ser atualizado", "remoteLink.child.check": "Verificar", "remoteLink.child.checkAll": "Verificar todos", "remoteLink.child.syncNow": "Sincronizar agora", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 6f8cfd5d666..ef4a2340bcb 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4554,6 +4554,8 @@ export const ru: Record = { "remoteLink.child.ownerAction.mise-managed": "OpenCodex на этом Child управляется mise; обновите через mise", "remoteLink.child.ownerAction.source-checkout": "Этот Child запущен из копии исходного кода; обновите вручную", "remoteLink.child.ownerAction.installer-unknown": "Способ установки этого Child неизвестен; обновите его там", + "remoteLink.child.ownerAction.windows-apply": "Удалённые обновления для этого устройства Windows не поддерживаются. Обновите OpenCodex непосредственно на компьютере с Windows.", + "remoteLink.child.ownerAction.recheck-required": "Проверьте этот Child ещё раз, чтобы узнать, как его обновить", "remoteLink.child.check": "Проверить", "remoteLink.child.checkAll": "Проверить все", "remoteLink.child.syncNow": "Синхронизировать сейчас", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 8006d9885a9..2b696b9accb 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4554,6 +4554,8 @@ export const tr: Record = { "remoteLink.child.ownerAction.mise-managed": "Bu Child üzerindeki OpenCodex’i mise yönetiyor; mise ile güncelleyin", "remoteLink.child.ownerAction.source-checkout": "Bu Child bir kaynak kodu kopyasından çalışıyor; elle güncelleyin", "remoteLink.child.ownerAction.installer-unknown": "Bu Child’ın kurulum yöntemi bilinmiyor; orada güncelleyin", + "remoteLink.child.ownerAction.windows-apply": "Bu Windows cihazı için uzaktan güncelleme desteklenmiyor. OpenCodex’i doğrudan Windows bilgisayarında güncelleyin.", + "remoteLink.child.ownerAction.recheck-required": "Nasıl güncellenebileceğini görmek için bu Child’ı yeniden denetleyin", "remoteLink.child.check": "Denetle", "remoteLink.child.checkAll": "Tümünü denetle", "remoteLink.child.syncNow": "Şimdi eşitle", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 09273732f7e..693ed649511 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4523,6 +4523,8 @@ export const vi: Record = { "remoteLink.child.ownerAction.mise-managed": "mise quản lý OpenCodex trên máy con này; hãy cập nhật qua mise", "remoteLink.child.ownerAction.source-checkout": "Máy con này chạy từ bản sao mã nguồn; hãy cập nhật thủ công", "remoteLink.child.ownerAction.installer-unknown": "Không rõ cách cài đặt của máy con này; hãy cập nhật tại đó", + "remoteLink.child.ownerAction.windows-apply": "Thiết bị Windows này không hỗ trợ cập nhật từ xa. Hãy cập nhật OpenCodex trực tiếp trên máy tính Windows.", + "remoteLink.child.ownerAction.recheck-required": "Hãy kiểm tra lại máy con này để biết cách cập nhật", "remoteLink.child.check": "Kiểm tra", "remoteLink.child.checkAll": "Kiểm tra tất cả", "remoteLink.child.syncNow": "Đồng bộ ngay", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 43330ac7ac4..61172373e43 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4517,6 +4517,8 @@ export const zhTW: Record = { "remoteLink.child.ownerAction.mise-managed": "此子裝置的 OpenCodex 由 mise 管理;請透過 mise 更新", "remoteLink.child.ownerAction.source-checkout": "此子裝置從原始碼檢出執行;請手動更新", "remoteLink.child.ownerAction.installer-unknown": "此子裝置的安裝方式不明;請在該裝置上更新", + "remoteLink.child.ownerAction.windows-apply": "此 Windows 裝置不支援遠端更新。請直接在該 Windows 電腦上更新 OpenCodex。", + "remoteLink.child.ownerAction.recheck-required": "請再次檢查此子裝置,以確認更新方式", "remoteLink.child.check": "檢查", "remoteLink.child.checkAll": "全部檢查", "remoteLink.child.syncNow": "立即同步", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 7c84d8fdd86..8b8cdc5315b 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4552,6 +4552,8 @@ export const zh: Record = { "remoteLink.child.ownerAction.mise-managed": "此子设备的 OpenCodex 由 mise 管理;请通过 mise 更新", "remoteLink.child.ownerAction.source-checkout": "此子设备从源码检出运行;请手动更新", "remoteLink.child.ownerAction.installer-unknown": "此子设备的安装方式未知;请在该设备上更新", + "remoteLink.child.ownerAction.windows-apply": "此 Windows 设备不支持远程更新。请直接在该 Windows 电脑上更新 OpenCodex。", + "remoteLink.child.ownerAction.recheck-required": "请再次检查此子设备,以确认更新方式", "remoteLink.child.check": "检查", "remoteLink.child.checkAll": "全部检查", "remoteLink.child.syncNow": "立即同步", diff --git a/gui/src/pages/RemoteLinkChildActions.tsx b/gui/src/pages/RemoteLinkChildActions.tsx index d702b5d93a3..8ed4b61e485 100644 --- a/gui/src/pages/RemoteLinkChildActions.tsx +++ b/gui/src/pages/RemoteLinkChildActions.tsx @@ -40,7 +40,7 @@ const ACTIVE_KEY: Record = { update: "remoteLink.job.active.update", }; -/** The eight owner-action reasons 020 emits; any other token prints as code instead of a guessed sentence. */ +/** The owner-action reasons the Home records; any other token prints as code instead of a guessed sentence. */ const OWNER_ACTION_KEYS: Record = { "legacy-ocx": "remoteLink.child.ownerAction.legacy-ocx", "desktop-app-owned": "remoteLink.child.ownerAction.desktop-app-owned", @@ -50,6 +50,10 @@ const OWNER_ACTION_KEYS: Record = { "mise-managed": "remoteLink.child.ownerAction.mise-managed", "source-checkout": "remoteLink.child.ownerAction.source-checkout", "installer-unknown": "remoteLink.child.ownerAction.installer-unknown", + // #9172: the Home never applies an orchestrated update on Windows; the Child updates locally. + "windows-apply": "remoteLink.child.ownerAction.windows-apply", + // A route cached before the Home recorded the Child's platform; a fresh check decides it. + "recheck-required": "remoteLink.child.ownerAction.recheck-required", }; const JOB_STATE_KEYS: Record = { @@ -115,7 +119,8 @@ export function ChildRowBadges({ row }: { row: ChildOpsRowView }): ReactElement {row.catalog.state === "current" && {t("remoteLink.child.catalog.current")}} {codexRestartNeeded(row) && {t("remoteLink.child.codex.restartNeeded", { count: row.codex?.staleCount ?? 0 })}} {row.codex?.appServers === "not_running" && {t("remoteLink.child.codex.notRunning")}} - {ownerKey && {t(ownerKey)}} + {/* Owner guidance can be a full sentence: let it wrap rather than truncate. */} + {ownerKey && {t(ownerKey)}} {owner && !ownerKey && {owner}} {row.activeJob && {t(ACTIVE_KEY[row.activeJob.op])}} {row.lastOperation && ( @@ -221,13 +226,15 @@ export function ChildRowActions(props: { apiBase: string; link: LinkRowWire; dis const single = (op: ChildOp, restart?: "app-server" | "codex") => void run({ op, linkIds: [props.link.id], ...(restart ? { restart } : {}) }); const canUpdate = updateAvailable(row!); + // A Child the Home cannot update says why, instead of claiming it is up to date. + const ownerReason = row!.update.route === "owner-action" && row!.update.reason ? OWNER_ACTION_KEYS[row!.update.reason] : undefined; return ( + title={canUpdate ? undefined : ownerReason ? t(ownerReason) : t("remoteLink.child.upToDate")}>{t("remoteLink.child.update")} { setRestarting(false); props.onDialog(false); }} onConfirm={scope => { setRestarting(false); props.onDialog(false); single("restart-codex", scope); }} /> diff --git a/gui/tests/remote-link-child-ops.test.tsx b/gui/tests/remote-link-child-ops.test.tsx index 006aff47add..ef8690c5f4d 100644 --- a/gui/tests/remote-link-child-ops.test.tsx +++ b/gui/tests/remote-link-child-ops.test.tsx @@ -841,3 +841,23 @@ test("a reload merges only the fields the operator changed onto the server's ans await click(button(host, "Save")); expect(calls.filter(call => call.method === "PUT").at(-1)?.body).toEqual({ catalogFanout: "manual" }); }); + +test("a Windows npm Child behind Home shows local-update guidance and no Update action (#9172)", async () => { + installFetch(() => response(status([ + row("lnk_0000000000000011", "box-win", childBlock({ update: { route: "owner-action", reason: "windows-apply", observedAt: "2026-11-12T00:00:00.000Z" } })), + ]))); + const host = await mount(); + const badges = host.querySelector(".remote-link-child-badges")!; + expect(badges.textContent).toContain("Behind Home (2.35.0)"); + expect(badges.textContent).not.toContain("Update available"); + expect(badges.textContent).toContain("Remote updates aren’t supported for this Windows device. Update OpenCodex directly on the Windows computer."); + // The sentence wraps instead of truncating, so it is readable without hovering. + const guidance = [...badges.querySelectorAll(".startup-badge")].find(badge => badge.textContent?.startsWith("Remote updates"))!; + expect(guidance.className).toContain("whitespace-normal"); + expect(guidance.querySelector(".truncate")).toBeNull(); + const firstRow = host.querySelectorAll(".remote-link-row")[0]!; + const update = [...firstRow.querySelectorAll("button")].find(item => item.textContent === "Update"); + expect((update as HTMLButtonElement).disabled).toBe(true); + expect(update!.getAttribute("title")).toBe("Remote updates aren’t supported for this Windows device. Update OpenCodex directly on the Windows computer."); + expect(button(host, "Update all").disabled).toBe(true); +}); diff --git a/src/link/child-observations.ts b/src/link/child-observations.ts index 6bcb95bc136..b0b9504bca2 100644 --- a/src/link/child-observations.ts +++ b/src/link/child-observations.ts @@ -41,6 +41,8 @@ export interface ChildObservation { /** An update whose result is unknown. A record carrying desktopRequestId is cleared only by the Desktop route's * status reconciliation or by expiry, never by a sync. */ pendingUpdateRecovery: { target: string; since: string; until: string; desktopRequestId?: string } | null; + /** The platform the plan probe ran on (#9172). Absent on observations recorded before it or not taken from a plan. */ + platform?: "posix" | "windows"; } /** Fields an operation or the Home owns; a fresh observe never overwrites them. Missing in an older file ⇒ null. */ export const CARRIED_OBSERVATION_FIELDS = ["catalogPulledAt", "catalogPulledEtag", "catalogSyncedEtag", "lastOperation", @@ -107,6 +109,7 @@ function observation(value: unknown): ChildObservation { autoUpdateAttempts: nullable(value.autoUpdateAttempts, attempts), updateInFlight: nullable(value.updateInFlight, item => typeof item === "boolean" ? item : drop()), pendingUpdateRecovery: nullable(value.pendingUpdateRecovery, recovery), + ...(value.platform === "posix" || value.platform === "windows" ? { platform: value.platform } : {}), }; } function homeCatalog(value: unknown): ChildObservationsFile["homeCatalog"] { diff --git a/src/link/child-observe.ts b/src/link/child-observe.ts index 5d63e67ee8f..1bbd53f549d 100644 --- a/src/link/child-observe.ts +++ b/src/link/child-observe.ts @@ -1,5 +1,5 @@ import { classifyUpdatePlanProbe, remoteUpdatePlanArgv, type SshResult } from "./child-gated-ocx"; -import type { PlanClassification } from "./child-update-contract"; +import type { PlanClassification, UpdateRoute } from "./child-update-contract"; import type { ChildObservation } from "./child-observations"; import type { LinkPeerEntry } from "./peer-report"; import type { inspectRemoteChildRuntime } from "./remote-plant"; @@ -31,7 +31,7 @@ export interface ObserveOutcome { } type ObservedFields = Pick; + | "targetVersion" | "updateInFlight"> & Pick, "platform">; function observation(fields: ObservedFields, now: Date): ChildObservation { return { @@ -41,6 +41,17 @@ function observation(fields: ObservedFields, now: Date): ChildObservation { }; } +/** + * The Home never applies an orchestrated update on Windows (runUpdateItem refuses windows-apply, D20), so the dashboard + * must not offer one (#9172): a Windows Child with that route is told to update locally. Applied when observing and + * again when projecting status, so an observation cached before this rule existed reads the same way. When neither the + * link record nor the observation names the platform, a cached orchestrated route may be a Windows Child: it is + * withheld until a fresh check records the platform (`recheck-required`). + */ +export function windowsLocalUpdateRoute(platform: "posix" | "windows" | null | undefined, updateRoute: UpdateRoute, updateReason: string | null): { updateRoute: UpdateRoute; updateReason: string | null } { + if (updateRoute !== "orchestrated" || platform === "posix") return { updateRoute, updateReason }; + return { updateRoute: "owner-action", updateReason: platform === "windows" ? "windows-apply" : "recheck-required" }; +} const strictVersion = (value: string | null | undefined): string | null => typeof value === "string" && parseStrictSemver(value) ? value : null; const peerVersion = (deps: ObserveDeps, record: LinkRecord): string | null => strictVersion(deps.peer(record.id).observed?.version); const outcome = (state: ObserveOutcome["state"], reason: string | null, value: ChildObservation | null = null): ObserveOutcome => @@ -91,11 +102,13 @@ export async function observeChild(record: LinkRecord, deps: ObserveDeps): Promi switch (verdict.kind) { case "plan": { const { classification } = verdict; + // The probe keeps the plan's own route for the runner; the observation the dashboard reads gets the local route. + const route = windowsLocalUpdateRoute(platform, classification.updateRoute, classification.updateReason); return { state: "succeeded", reason: null, probe: { classification, childNowMs: verdict.childNowMs, startedAt, platform }, observation: observation({ source: "plan", installedVersion: strictVersion(classification.installedVersion), - installKind: classification.installKind, runtimeOwner: classification.runtimeOwner, updateRoute: classification.updateRoute, - updateReason: classification.updateReason, targetVersion: strictVersion(classification.targetVersion), - updateInFlight: classification.updateInFlight }, deps.now()) }; + installKind: classification.installKind, runtimeOwner: classification.runtimeOwner, + updateRoute: route.updateRoute, updateReason: route.updateReason, targetVersion: strictVersion(classification.targetVersion), + updateInFlight: classification.updateInFlight, platform }, deps.now()) }; } case "ephemeral": return ephemeral(deps.now()); case "legacy": { diff --git a/src/link/management-routes.ts b/src/link/management-routes.ts index c2b859f0a8c..8be649dcb25 100644 --- a/src/link/management-routes.ts +++ b/src/link/management-routes.ts @@ -86,8 +86,21 @@ export function isLinkManagementPath(pathname: string): boolean { * The one refusal every management surface on a link Child uses: the dashboard relay, the CLI, * and the Child's listener. It names the Home and the link and never suggests a relay transport. * `homePhrase` is "Home " or "its Home" when the Child does not know the Home's name. + * A Windows Child cannot be updated from its Home (the Home refuses `windows-apply`), so an update + * request there gets local-update guidance instead of a pointer to the Home (#9172). */ -export function linkChildManagementRefusal(homePhrase: string, linkId: string, operation = "This management command"): string { - return `This machine is a Remote Link Child managed by ${homePhrase} (link ${linkId}). ` - + `${operation} runs on the Home, not on this Child: use the Home's dashboard or run the command there. No request was sent.`; +export function linkChildManagementRefusal( + homePhrase: string, + linkId: string, + operation = "This management command", + platform: NodeJS.Platform = process.platform, +): string { + const child = `This machine is a Remote Link Child managed by ${homePhrase} (link ${linkId}). `; + if (platform === "win32" && /^[A-Z]+ \/api\/update(?:\/|$)/.test(operation)) { + return `${child}${WINDOWS_CHILD_LOCAL_UPDATE} No request was sent.`; + } + return `${child}${operation} runs on the Home, not on this Child: use the Home's dashboard or run the command there. No request was sent.`; } + +/** The Home's dashboard shows the same guidance for a Windows Child (owner-action reason `windows-apply`). */ +export const WINDOWS_CHILD_LOCAL_UPDATE = "Remote updates aren't supported for this Windows device. Update OpenCodex directly on the Windows computer."; diff --git a/src/server/management/link-child-ops-routes.ts b/src/server/management/link-child-ops-routes.ts index 0f9a602a442..8c784b7e8f9 100644 --- a/src/server/management/link-child-ops-routes.ts +++ b/src/server/management/link-child-ops-routes.ts @@ -1,7 +1,7 @@ import { DEFAULT_IDLE_AFTER_MS, isLinkIdle } from "../../link/child-activity"; import { readChildPolicy, updateChildPolicy, validPolicyPatch } from "../../link/child-policy"; import { createCatalogRevisionMonitor, type CatalogRevisionMonitor } from "../../link/child-catalog-freshness"; -import { observeChild } from "../../link/child-observe"; +import { observeChild, windowsLocalUpdateRoute } from "../../link/child-observe"; import { patchChildObservation, readChildObservations, updateChildObservations } from "../../link/child-observations"; import { sharedChildOpsEngine, type ChildOpsEngine, type SubmitRefusal, type SubmitResult } from "../../link/child-ops-engine"; import { CHILD_OPS, CHILD_OPS_MAX_LINK_IDS, type ChildOp, type ChildOpsEnv, type ChildRestart } from "../../link/child-ops-types"; @@ -136,11 +136,16 @@ export function attachLinkChildOpsForState(dto: LinkStatusDto, state: LinkRouteS const revision = (state.catalogRevision ??= catalogRevisionForRoutes()).current(); const observations = readChildObservations(); const known = new Set(store.links.map(link => link.id)); + const platforms = new Map(store.links.map(link => [link.id, link.remotePlatform])); return attachLinkChildOps(dto, { // The policy threshold governs every idle decision (050 reconciliation item 5). homeVersion: packageVersion("0.0.0"), now, idleAfterMs: readChildPolicy().policy.idleAfterMs, revision, peerVersion: linkId => state.listener.peerObservation?.(linkId).observed?.version ?? null, - observation: linkId => known.has(linkId) ? observations.children[linkId] ?? null : null, + observation: linkId => { + const cached = known.has(linkId) ? observations.children[linkId] ?? null : null; + // #9172: an observation recorded before Windows was told to update locally reads the same as a new one. + return cached ? { ...cached, ...windowsLocalUpdateRoute(platforms.get(linkId) ?? cached.platform, cached.updateRoute, cached.updateReason) } : null; + }, activity: linkId => state.listener.linkActivity?.(linkId, now) ?? null, catalogPull: linkId => state.listener.catalogPull?.(linkId) ?? null, // The shared engine: a job the wp5 scheduler started shows on a status read that never submitted one. diff --git a/structure/remote-link.md b/structure/remote-link.md index 64b89f05e9d..b70a7efccc0 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -103,7 +103,7 @@ Applying a link probes the host key into a temporary file, waits for the operato Child operations run as jobs. `src/server/management/link-child-ops-routes.ts` serves `POST /api/link/children/operations` (body exactly `{op, linkIds, restart?}` with `op` one of `observe`, `sync`, `restart-codex`, `update`; `linkIds` is `"all"` or 1 to 64 distinct link ids; `restart` is `app-server` or `codex`, refused on `observe`, defaulting to `app-server` for `restart-codex`, and any request that carries a restart must name its links, so `"all"` with a restart is `400 invalid_body`; `202 {job}`, `400 invalid_body` for any other op or key including `trigger`, `404 link_not_found`, `409 link_not_home_initiated` for a single Child-initiated link outside `observe`, `409 link_operation_in_progress`, `409 no_eligible_links` only when links.json has no link, `409 runtime_role_client` on a Child) and `GET /api/link/children/jobs/{jobId}` (`ljob_` plus 16 hex; `400 invalid_job_id`, `404 job_not_found`). The route always submits `trigger: "manual"`; only the in-process scheduler can submit `auto`. `handleLinkRoutes` delegates every `/api/link/children/` path before its reconnect and DELETE matchers, so `DELETE /api/link/children/x` answers 404 and never removes a link, and `DELETE /api/link/{id}` answers `409 link_operation_in_progress` while a job holds that link; otherwise removal reserves the link in the engine (`reserve`) before its first teardown await and releases it when it ends, so a job submitted during the removal gets 409 for that link alone or a `busy` item, and no job reaches a Child the removal is disconnecting. Both routes take the same principals as probe and apply; the local-control socket still admits only `GET /api/link/status`, so on a non-loopback Home the CLI verbs exit 1 because these operations are not available there (the dashboard has no controls for them). `src/link/child-ops-engine.ts` keeps the `ocx.link.child-job/1` jobs (types in `src/link/child-ops-types.ts`) in one engine per Home process (`sharedChildOpsEngine`; the routes cache it on `LinkRouteState.childOps` and status reads its `activeJob`): one lock per link (a held link makes a single-link request 409 and a multi-link item `busy`, which leaves that link's `lastOperation` to its holder), three items at a time across every job of which at most one is an update (a waiting update does not hold up the items behind it), Child-initiated items of `sync`, `restart-codex` and `update` ended `unsupported`/`child-initiated` at admission, the record re-read before SSH (`refused`/`link-removed` when it vanished), finished jobs kept one hour and at most 32 on each job's own clock, no timer. Each submit carries a `ChildOpsEnv` (store, SSH runner, wire state, activity, Home version, observe, a cache writer that never throws, the Home catalog etag). Items carry closed reason tokens and Home-written hints, never remote text. -`src/link/child-ops-runners.ts` holds the runners. The sync-then-restart sequence both the runners and `ocx sync --restart-children` use is `src/link/sync-then-restart.ts`. `observe` is `src/link/child-observe.ts`: client-initiated and `ocx-child` links answer without SSH; otherwise one gated `update --plan` (60 s, 64 KiB) classifies the Child, and on an npm or pnpm Child served through its census pair the script also reports whether a Node answers `--version` within 10 s (`ocx-fanout:launcher:available|unavailable`). `sync` sends the pinned `sync --expect-link` (gate 2.93.0, 180 s) and, when the sync reports synced, records the catalog etag read before it as `catalogSyncedEtag`; with a restart it reads the link's activity after that sync and sends the restart as a second pinned sync carrying `--restart-app-server-only` or `--restart-codex`, withheld (`restart.outcome: "skipped"`, reason `restart-skipped:link-active`) while a relayed request is in flight or the activity is unknown. A second sync refused before an ocx was selected, or skipped by the Child, reports `not-run`; one that may have run but failed or timed out ends `uncertain`/`restart-result-unknown`. `restart-codex` is that path with the restart as its purpose: a busy link sends nothing (`busy`), Windows is refused without SSH (`windows-restart`), `ocx-child` reports `unsupported` (the record's `childKind` or the `selected-kind` marker). `update` sends an identity pinned sync first, then a fresh observe (Windows Children too, because `desktop-request` is decided before the `windows-apply` refusal), then the gated apply `update --yes --json --version --expect-plan --not-after ` (gate 2.97.0, bounded by `min(mutationBoundMs, 900 s) + 120 s`, an SSH spawn failure ending `failed`/`ssh-spawn-failed` with nothing to recover, not sent with under 15 s of the window left), through ` /bin/ocx.mjs` with `OCX_UPDATE_ORCHESTRATED_CHILD` unset only when the plan's installer is npm or pnpm (a missing Node exits 121 `child-node-unavailable`, owner action `launcher-node-missing`), and a pinned sync after every outcome that may have stopped the Child's proxy (success, failure, roll-back); the target is always the Home's version, exit 11 records `suppressedTarget` and a manual update clears it, an uncertain apply records `pendingUpdateRecovery` for an hour and is never re-sent. The Windows gated builder builds only `update --plan`. A legacy key admission, which is how a Child older than 2.69 reaches the Home, counts as activity only from its response headers, so a non-streaming request from such a Child is invisible to the restart guard while it runs. An item that ran writes its observation fields and then `lastOperation` to `child-observations.json`. `src/cli/link-child-ops.ts` (`runLinkCheck`, `runLinkChildOp`, the tolerant `validateChildJob`) polls every 2 s with a per-op item budget (observe 120 s, sync and restart-codex 420 s, update 2 100 s) that does not run while an item is queued, under a 3-hour cap, and exits 0, 6 for a partial result (including a success with a reason or a restart that did not go out), 1 for a failure, an uncertain item or an unknown item state, 4 for an unknown link or (with its own message) a Home without the route or, for a non-observe op, one that answers `400 invalid_body`, 5 for a conflict. `ocx link update` needs `--yes`, as does any restart of scope `codex` and `restart-codex` itself. Coverage: `tests/server/link-child-ops-routes.test.ts`, `tests/clients/link-child-observe.test.ts`, `tests/clients/link-child-ops-engine.test.ts`, `tests/clients/link-child-ops-runners.test.ts`, `tests/clients/link-child-update-launcher.test.ts`, `tests/cli/cli-link-check.test.ts`, `tests/cli/cli-link-child-ops.test.ts`. +`src/link/child-ops-runners.ts` holds the runners. The sync-then-restart sequence both the runners and `ocx sync --restart-children` use is `src/link/sync-then-restart.ts`. `observe` is `src/link/child-observe.ts`: client-initiated and `ocx-child` links answer without SSH; otherwise one gated `update --plan` (60 s, 64 KiB) classifies the Child, and on an npm or pnpm Child served through its census pair the script also reports whether a Node answers `--version` within 10 s (`ocx-fanout:launcher:available|unavailable`). A Windows plan whose route is `orchestrated` is recorded as `owner-action` with reason `windows-apply` (#9172): the probe keeps the plan's route for the update runner, but the cached observation the dashboard reads says the Home cannot apply it, so the Home row offers no Update and shows local-update guidance. `attachLinkChildOpsForState` applies the same rule (`windowsLocalUpdateRoute`) with the link record's `remotePlatform`, or else the `platform` a plan observation now records, when it projects status, so an observation cached before the rule existed reads the same way. A cached `orchestrated` route whose platform neither names is withheld as `owner-action` `recheck-required` until a fresh check records the platform. A Windows Child's own refusal of an update request (`linkChildManagementRefusal` in `src/link/management-routes.ts`) gives the same guidance instead of pointing at the Home. `sync` sends the pinned `sync --expect-link` (gate 2.93.0, 180 s) and, when the sync reports synced, records the catalog etag read before it as `catalogSyncedEtag`; with a restart it reads the link's activity after that sync and sends the restart as a second pinned sync carrying `--restart-app-server-only` or `--restart-codex`, withheld (`restart.outcome: "skipped"`, reason `restart-skipped:link-active`) while a relayed request is in flight or the activity is unknown. A second sync refused before an ocx was selected, or skipped by the Child, reports `not-run`; one that may have run but failed or timed out ends `uncertain`/`restart-result-unknown`. `restart-codex` is that path with the restart as its purpose: a busy link sends nothing (`busy`), Windows is refused without SSH (`windows-restart`), `ocx-child` reports `unsupported` (the record's `childKind` or the `selected-kind` marker). `update` sends an identity pinned sync first, then a fresh observe (Windows Children too, because `desktop-request` is decided before the `windows-apply` refusal), then the gated apply `update --yes --json --version --expect-plan --not-after ` (gate 2.97.0, bounded by `min(mutationBoundMs, 900 s) + 120 s`, an SSH spawn failure ending `failed`/`ssh-spawn-failed` with nothing to recover, not sent with under 15 s of the window left), through ` /bin/ocx.mjs` with `OCX_UPDATE_ORCHESTRATED_CHILD` unset only when the plan's installer is npm or pnpm (a missing Node exits 121 `child-node-unavailable`, owner action `launcher-node-missing`), and a pinned sync after every outcome that may have stopped the Child's proxy (success, failure, roll-back); the target is always the Home's version, exit 11 records `suppressedTarget` and a manual update clears it, an uncertain apply records `pendingUpdateRecovery` for an hour and is never re-sent. The Windows gated builder builds only `update --plan`. A legacy key admission, which is how a Child older than 2.69 reaches the Home, counts as activity only from its response headers, so a non-streaming request from such a Child is invisible to the restart guard while it runs. An item that ran writes its observation fields and then `lastOperation` to `child-observations.json`. `src/cli/link-child-ops.ts` (`runLinkCheck`, `runLinkChildOp`, the tolerant `validateChildJob`) polls every 2 s with a per-op item budget (observe 120 s, sync and restart-codex 420 s, update 2 100 s) that does not run while an item is queued, under a 3-hour cap, and exits 0, 6 for a partial result (including a success with a reason or a restart that did not go out), 1 for a failure, an uncertain item or an unknown item state, 4 for an unknown link or (with its own message) a Home without the route or, for a non-observe op, one that answers `400 invalid_body`, 5 for a conflict. `ocx link update` needs `--yes`, as does any restart of scope `codex` and `restart-codex` itself. Coverage: `tests/server/link-child-ops-routes.test.ts`, `tests/clients/link-child-observe.test.ts`, `tests/clients/link-child-ops-engine.test.ts`, `tests/clients/link-child-ops-runners.test.ts`, `tests/clients/link-child-update-launcher.test.ts`, `tests/cli/cli-link-check.test.ts`, `tests/cli/cli-link-child-ops.test.ts`. Automatic catalog fan-out (050) is the one timer in Child operations. `src/link/child-ops-host.ts` builds the engine env without a request and starts `src/link/child-ops-scheduler.ts`; `src/server/index/optional-listeners.ts` imports it, with the routes module that owns the shared catalog monitor (`catalogRevisionForRoutes`, which `src/link` cannot import), only dynamically and only while the link listener owns its socket, stops it when the last link closes the listener and in `stop()` before the supervisor teardown, and a generation counter keeps a late import from starting it (INV-LINK-CHILD-OPS-01). The scheduler registers the data-free `setCatalogAutoRefreshLinkFanout` slot in `src/codex/catalog-auto-refresh.ts` (a changed tick) and polls the monitor every 5 minutes (dashboard and management edits), waits a 60 s quiet period capped at 5 minutes from the first change, then submits `trigger: "auto"` `sync` jobs for each connected Home-initiated link that holds no job, is not backed off, and whose `catalogSyncedEtag` differs from the current etag (a fetch never counts as delivered). A busy link qualifies only when its parity `appliedCodexSettingsDigest` already equals the Home's and its `runtimeStartedAt` is not before `lastApplyAt` (`runtimeCurrentDigest`; otherwise the Child's sync restarts its runtime); idle uses the policy `idleAfterMs` everywhere, including the POST env and the status rows. Idle links get `restart: "app-server"` only under `app-server-when-idle`, and `runSyncItem` withholds that restart unless the link is still idle when the item starts and just before the restart; the host's `autoSyncAllowed` re-asks the idle-or-same-digest rule at item start. `createLinkBackoff` (shared with 070) backs failures off from 5 minutes doubling to 6 hours per link and key; `busy` neither grows nor counts; `child-ocx-lacks-expect-link` waits for another reported peer version (a report without one keeps it blocked), or 6 hours when none was known. Each sync group is admitted against the policy read just before it, and none after `stop()`; a quiet timer that fires during a pass reruns it; a Child runtime never evaluates. `src/link/child-policy.ts` keeps `/link/child-policy.json` (`ocx.link.child-policy/1`: `catalogFanout` auto, `childCodexRestart` never, `updates` auto-when-idle, `idleAfterMs` 600000 within 60000–3600000), strict: an absent file is the defaults, a damaged one reads fail-closed (`manual`, `off`, warning `policy-file-invalid`) and is never rewritten on read. `GET/PUT /api/link/children/policy` (same principals as operations; PUT takes a non-empty subset, `400 invalid_body`, `409 runtime_role_client` on a Child, `503 policy_write_failed`) and `ocx link policy` read and change it. wp5 starts no update. Coverage: `tests/clients/link-child-ops-scheduler.test.ts`, `tests/clients/link-child-policy.test.ts`, `tests/server/link-child-policy-routes.test.ts`, `tests/cli/cli-link-policy.test.ts`, `tests/codex-integration/catalog-auto-refresh-link-fanout.test.ts`, `tests/lab/link-child-ops-no-timer.test.ts`, `tests/e2e-style/link-child-catalog-oracle.test.ts`. diff --git a/tests/clients/link-child-observe.test.ts b/tests/clients/link-child-observe.test.ts index aa9fdc5356b..67a9011a63d 100644 --- a/tests/clients/link-child-observe.test.ts +++ b/tests/clients/link-child-observe.test.ts @@ -107,15 +107,25 @@ describe("observeChild", () => { expect(ephemeralVerdict).toMatchObject({ state: "succeeded", observation: { installKind: "ocx-child", updateInFlight: null, runtimeOwner: null, targetVersion: null } }); }); - test("Windows plan without an entry marker is classified with platform windows", async () => { + test("Windows plan without an entry marker is classified with platform windows and recorded as a local update (#9172)", async () => { const spy = spyOn(gated, "classifyUpdatePlanProbe"); try { const outcome = await observeChild(record({ remotePlatform: undefined }), deps(ran(plan(), "ocx-fanout:selected:2.97.0\n"), { platformOf: async () => "windows" }).value); expect(spy.mock.calls[0]?.[1]).toEqual({ homeVersion: "2.100.0", desktopUpdateRequest: false, platform: "windows" }); - expect(outcome).toMatchObject({ state: "succeeded", probe: { platform: "windows" }, observation: { updateRoute: "orchestrated" } }); + // The probe keeps the plan's route for the runner; the observation the dashboard reads says the Home cannot apply it. + expect(outcome).toMatchObject({ state: "succeeded", probe: { platform: "windows", classification: { updateRoute: "orchestrated" } }, + observation: { installKind: "npm", updateRoute: "owner-action", updateReason: "windows-apply", platform: "windows" } }); } finally { spy.mockRestore(); } }); + test("a Windows Desktop request and a POSIX npm plan keep their routes (#9172)", async () => { + const desktop = await observeChild(record({ remotePlatform: "windows" }), deps(ran(plan({ installer: "desktop-app", canApply: false, reason: "desktop-app-owned" })), { + platformOf: async () => "windows", peer: () => peer("2.97.0", ["desktop-update-request/1"]) }).value); + expect(desktop.observation).toMatchObject({ installKind: "desktop-app", updateRoute: "desktop-request", updateReason: "desktop-app-owned" }); + const posix = await observeChild(record(), deps(ran(plan())).value); + expect(posix.observation).toMatchObject({ installKind: "npm", updateRoute: "orchestrated", updateReason: null, platform: "posix" }); + }); + test("a Windows argv over the budget is failed windows-command-too-long with no SSH", async () => { // The longest valid Home version fits since the payload is packed 14 bits per character (#8359), so the // builder's own overflow error is injected to keep the mapping covered. diff --git a/tests/server/link-child-ops-routes.test.ts b/tests/server/link-child-ops-routes.test.ts index 7b9032236a3..97509311bb3 100644 --- a/tests/server/link-child-ops-routes.test.ts +++ b/tests/server/link-child-ops-routes.test.ts @@ -10,7 +10,7 @@ import type { OcxConfig } from "../../src/types"; import type { LinkRecord, LinkStore } from "../../src/link/store"; import type { LinkSupervisor } from "../../src/link/supervisor"; import type { SshRunResult, SshRunner } from "../../src/link/ssh-runner"; -import { readChildObservations } from "../../src/link/child-observations"; +import { emptyChildObservations, patchChildObservation, readChildObservations } from "../../src/link/child-observations"; import { resetSharedChildOpsEngineForTests, sharedChildOpsEngine } from "../../src/link/child-ops-engine"; import { catalogEtag } from "../../src/server/catalog-download"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -267,6 +267,33 @@ describe("link child operations routes", () => { expect(((await invalid!.json()) as { error: { code: string } }).error.code).toBe("invalid_job_id"); }); + test("a Windows observation cached as orchestrated before #9172 reads as a local update; POSIX keeps its route", async () => { + const h = harness({ full: true, links: [link(HUB, { remotePlatform: "windows" }), link(CLIENT)] }); + const file = emptyChildObservations(); + const cached = { source: "plan" as const, installedVersion: "2.95.0", installKind: "npm" as const, updateRoute: "orchestrated" as const, updateReason: null }; + patchChildObservation(file, HUB, cached, new Date(1_762_000_000_000)); + patchChildObservation(file, CLIENT, cached, new Date(1_762_000_000_000)); + writeFileSync(join(temp, "ocx", "link", "child-observations.json"), JSON.stringify(file)); + const body = await (await h.call("/api/link/status?children=1"))!.json() as { links: Array<{ id: string; child: { update: unknown } }> }; + expect(body.links.find(row => row.id === HUB)!.child.update).toMatchObject({ route: "owner-action", reason: "windows-apply" }); + expect(body.links.find(row => row.id === CLIENT)!.child.update).toMatchObject({ route: "orchestrated", reason: null }); + }); + test("without a recorded link platform the observation's platform decides, and an unknown one asks for a fresh check (#9172)", async () => { + const LEGACY = "lnk_00000000000000aa"; + const h = harness({ full: true, links: [link(HUB, { remotePlatform: undefined }), link(CLIENT, { remotePlatform: undefined }), link(LEGACY, { remotePlatform: undefined })] }); + const file = emptyChildObservations(); + const cached = { source: "plan" as const, installedVersion: "2.95.0", installKind: "npm" as const, updateRoute: "orchestrated" as const, updateReason: null }; + patchChildObservation(file, HUB, { ...cached, platform: "windows" }, new Date(1_762_000_000_000)); + patchChildObservation(file, CLIENT, { ...cached, platform: "posix" }, new Date(1_762_000_000_000)); + patchChildObservation(file, LEGACY, cached, new Date(1_762_000_000_000)); + writeFileSync(join(temp, "ocx", "link", "child-observations.json"), JSON.stringify(file)); + const body = await (await h.call("/api/link/status?children=1"))!.json() as { links: Array<{ id: string; child: { update: unknown } }> }; + const update = (id: string) => body.links.find(row => row.id === id)!.child.update; + expect(update(HUB)).toMatchObject({ route: "owner-action", reason: "windows-apply" }); + expect(update(CLIENT)).toMatchObject({ route: "orchestrated", reason: null }); + expect(update(LEGACY)).toMatchObject({ route: "owner-action", reason: "recheck-required" }); + }); + test("?children=1 adds child to Home rows only and nothing without the query", async () => { const h = harness({ full: true }); const plain = await (await h.call("/api/link/status?compatibility=1&diagnostics=1"))!.json() as { links: Array> }; diff --git a/tests/server/link-management-relay.test.ts b/tests/server/link-management-relay.test.ts index da6fbd112d9..1970903de54 100644 --- a/tests/server/link-management-relay.test.ts +++ b/tests/server/link-management-relay.test.ts @@ -18,7 +18,7 @@ import { saveCodexAccountCredential } from "../../src/codex/account-store"; import { linkStorePath } from "../../src/link/paths"; import { writeLinkStore } from "../../src/link/store"; import { parseHomeCodexSettingsDocument } from "../../src/link/codex-settings"; -import { LINK_MANAGEMENT_READ_PATHS } from "../../src/link/management-routes"; +import { LINK_MANAGEMENT_READ_PATHS, linkChildManagementRefusal } from "../../src/link/management-routes"; import { hubRelayDigest, hubRelayEnrollmentProof } from "../../src/remote/hub-management-relay"; import { admitHubRelayRead, HUB_RELAY_IDLE_TTL_MS, issueHubRelayCredential } from "../../src/server/hub-relay-auth"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; @@ -100,6 +100,15 @@ function opensForWrite(args: unknown[]): boolean { return !["r", "rs", "sr"].includes(String(flags)); } +test("a Windows Child's update refusal gives local-update guidance; other refusals and platforms are unchanged (#9172)", () => { + const win = linkChildManagementRefusal("Home home-mac", "lnk_0123456789abcdef", "GET /api/update/check", "win32"); + expect(win).toContain("Remote Link Child managed by Home home-mac (link lnk_0123456789abcdef)"); + expect(win).toContain("Remote updates aren't supported for this Windows device. Update OpenCodex directly on the Windows computer."); + expect(win).toContain("No request was sent."); + expect(win).not.toContain("runs on the Home"); + expect(linkChildManagementRefusal("Home home-mac", "lnk_0123456789abcdef", "GET /api/update/check", "linux")).toContain("runs on the Home, not on this Child"); + expect(linkChildManagementRefusal("Home home-mac", "lnk_0123456789abcdef", "PUT /api/settings", "win32")).toContain("runs on the Home, not on this Child"); +}); test("the passive effect watcher classifies opens by their write capability", () => { const { O_RDONLY, O_NONBLOCK, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC, O_APPEND } = fs.constants; for (const flags of [undefined, "r", "rs", "sr", O_RDONLY, O_RDONLY | O_NONBLOCK]) { From 0eebc45d75f3b123754bce3bb2e456b8b4695b6f Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:21:21 +0900 Subject: [PATCH 31/64] fix(anthropic): keep the checkpoint prefix during routed compaction (#9187) * fix(anthropic): keep the checkpoint prefix during routed compaction After a portable checkpoint, an ordinary routed request carries the continuation note in its system prompt and frames retained requests as history. A remote compaction_trigger summary skipped both, so on the Anthropic route every compaction after the first rewrote the whole cached prompt from the system block on. Remote summaries now get the same historical framing as the ordinary request they extend. The parser still withholds the continuation note from every summary; only the prefix-preserving Anthropic route adds it back at the ordinary request's position, where the appended summary prompt and the summary guard keep the turn a summary. Other routes and client-side summarizer turns keep their exclusions. Refs #7307 Co-Authored-By: Claude Opus 5.5 * docs(anthropic): record the remote summary prefix in a new ADR Keep ADR-7003 historical and record the #7307 contract change as ADR-9174, owned by the decoded checkpoint continuation section. Limit the server reference to decoded checkpoints, and describe the summary guard by what it rejects rather than as a summary-only check. Co-Authored-By: Claude Opus 5.5 * docs(anthropic): state what the summary guard does with truncated turns A truncated summary passes guardCompactionSummary; the response bridges withhold its compaction item and report the turn incomplete (#422). Say so instead of attributing every abnormal ending to the guard. Co-Authored-By: Claude Opus 5.5 * chore(tests): register the checkpoint-prefix test; scope the ADR's framing claim - Register responses-anthropic-compaction-checkpoint-prefix.test.ts in scripts/test-layout/layout-replay.json and tests/fixtures/test-layout-expected.json, beside its #9173 sibling, instead of relying on the regex seeds. - ADR-9174: framing applies where the proxy projects history (adapter context and non-OpenAI-operated outbound bodies); native OpenAI passthrough input is unchanged, matching structure/transports/responses.md. --------- Co-authored-by: Muhammet Alan Co-authored-by: Claude Opus 5.5 --- .../docs/reference/configuration/server.md | 14 +- scripts/test-layout/layout-replay.json | 1 + src/responses/compaction-history-framing.ts | 8 +- src/responses/parser.ts | 1 + src/server/responses/response-effects.ts | 12 +- src/types/request.ts | 6 + ...R-9174-remote-summary-checkpoint-prefix.md | 35 +++++ structure/transports/responses.md | 4 +- tests/fixtures/test-layout-expected.json | 1 + .../compaction-history-framing.test.ts | 13 +- .../compaction-portable-history.test.ts | 11 +- ...ropic-compaction-checkpoint-prefix.test.ts | 134 ++++++++++++++++++ 12 files changed, 226 insertions(+), 14 deletions(-) create mode 100644 structure/decisions/ADR-9174-remote-summary-checkpoint-prefix.md create mode 100644 tests/responses/responses-anthropic-compaction-checkpoint-prefix.test.ts diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index b4cadcc5c2c..1fbda9bc184 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -837,11 +837,15 @@ available for unfinished work within its existing authorization. Later user inpu including pauses, cancellations and changes of scope. A checkpoint grants no new permission. This is enabled by default and needs no setting. Original request text and canonical thread/replay -history are preserved. Native OpenAI Responses passthrough, summarizer turns, context wrappers, -images/files and assistant/tool items are unchanged. The framing applies to plaintext checkpoints -beginning with Codex's summary prefix; decoded OpenCodex checkpoints retain their existing -continuation guidance. Client-side summarizer turns using Codex's standard compaction prompt -also bypass framing. Framing is a prompt instruction, so model behavior can vary. +history are preserved. Native OpenAI Responses passthrough, context wrappers, images/files and +assistant/tool items are unchanged. The framing applies to plaintext checkpoints beginning with +Codex's summary prefix; decoded OpenCodex checkpoints retain their existing continuation guidance. +A routed summary request (Codex `compaction_trigger`) gets the same historical framing as the +ordinary request before it. After a decoded OpenCodex checkpoint, the Anthropic Messages route +also repeats that request's continuation guidance, so the summary keeps the ordinary request's prompt-cache prefix; its +appended summary prompt still tells the model to summarize and not continue. Client-side +summarizer turns using Codex's standard compaction prompt bypass framing. Framing is a prompt +instruction, so model behavior can vary. ## Compaction routing diff --git a/scripts/test-layout/layout-replay.json b/scripts/test-layout/layout-replay.json index 16ec25e5696..a02d8b2614d 100644 --- a/scripts/test-layout/layout-replay.json +++ b/scripts/test-layout/layout-replay.json @@ -3,6 +3,7 @@ "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "responses-anthropic-compaction-prefix.test.ts": "responses", + "responses-anthropic-compaction-checkpoint-prefix.test.ts": "responses", "ws-replay-refusal-attribution.test.ts": "responses", "combo-replay-refusal-attribution.test.ts": "responses", "responses-replay-metadata-principal.test.ts": "responses", diff --git a/src/responses/compaction-history-framing.ts b/src/responses/compaction-history-framing.ts index ab13a9f109f..3c9721f6228 100644 --- a/src/responses/compaction-history-framing.ts +++ b/src/responses/compaction-history-framing.ts @@ -45,7 +45,11 @@ function isCheckpoint(item: unknown): boolean { */ export function frameCompactionHistory(body: T): T { const input = body.input; - if (!Array.isArray(input) || input.some(item => isRecord(item) && item.type === "compaction_trigger")) return body; + if (!Array.isArray(input)) return body; + // A remote compaction_trigger summary gets the same historical framing as the ordinary request + // it extends, so its history keeps that request's prompt-cache prefix (#7307). It gets no + // continuation note here; only a prefix-preserving route adds it (response-effects.ts). + const remoteSummary = input.some(item => isRecord(item) && item.type === "compaction_trigger"); // Codex local compaction appends this user prompt without a compaction_trigger. // Keep that summarizer turn free of generation-only continuation instructions. if (isLocalCompactionCheckpoint(input)) return body; @@ -74,7 +78,7 @@ export function frameCompactionHistory; + /** + * Compaction request after a decoded checkpoint. The parser withholds the continuation note from + * every summary; a prefix-preserving route adds it back where the ordinary request carries it, + * so the summary keeps that request's system prompt (#7307). + */ + _summaryCheckpointNote?: boolean; /** * Completed server-tool exchanges from the Claude client's history, keyed by the block that * followed them (`call:` / `text:`). Same audience as `_anthropicServerTools`. diff --git a/structure/decisions/ADR-9174-remote-summary-checkpoint-prefix.md b/structure/decisions/ADR-9174-remote-summary-checkpoint-prefix.md new file mode 100644 index 00000000000..bffda613082 --- /dev/null +++ b/structure/decisions/ADR-9174-remote-summary-checkpoint-prefix.md @@ -0,0 +1,35 @@ +# ADR-9174: decision recorded under "Decoded checkpoint continuation" + +- Contract owner: [transports/responses.md](../transports/responses.md#decoded-checkpoint-continuation) +- Purpose: stop routed Anthropic summaries from rewriting the whole cached prompt on every + compaction after the first one (#7307). +- Prior constraint: ADR-7003 excludes compaction/summarizer turns from the continuation note, and + #7822 also kept remote `compaction_trigger` summaries out of historical framing. After a portable + checkpoint, the ordinary request carries the note at the end of its system prompt and frames + retained requests as history; the remote summary that extends it carried neither. Anthropic + caches tools, system and messages in that order, so the summary missed the cache from the system + block on. +- Alternatives: keep the exclusion and accept the rewrite on every later compaction; or add the + note to every summary in the parser, which also changes routes that do not preserve the prefix + and gains nothing there. +- Choice: a remote `compaction_trigger` summary gets the historical framing of the ordinary request + it extends wherever the proxy projects history (the parser's adapter context and non-OpenAI-operated + outbound bodies); native OpenAI passthrough input is unchanged by checkpoint framing. The parser + still excludes the note from every summary and sets + `_summaryCheckpointNote` after a decoded checkpoint; only the prefix-preserving Anthropic route + appends `CHECKPOINT_CONTINUATION_NOTE` at the ordinary request's position. Client-side summarizer + turns ending in `COMPACT_PROMPT` keep the ADR-7003 exclusion, and plaintext framing still adds no + note to a remote summary. +- Why the note on that summary is acceptable: the appended summary prompt ("Return only the handoff + summary. Do not call tools or continue the task.") asks for a handoff summary, and the note itself + is conditional. For a summary that is not truncated, the compaction summary guard rejects tool + calls, empty text and explicit non-terminal stop reasons. A truncated summary passes the guard; + the response bridges then withhold its compaction item and report the turn incomplete (#422). + Neither checks that the text is a summary. +- Consequences: from the second compaction on, the Anthropic summary reads the ordinary request's + cached prefix instead of rewriting it. A plaintext `SUMMARY_PREFIX` checkpoint followed by a + remote trigger still differs by the note, which plaintext framing places in `instructions`. +- Evidence boundary: JSON/SSE prefix-equality tests and a non-preserving route control cover the + request construction. One live A/B run (`claude-opus-5-5`, four compactions per arm) showed the + cache read on compactions 2-4 rising from 10,353 tokens to the preceding request's full input, + with summaries of similar structure; that is a small sample, not a quality benchmark. diff --git a/structure/transports/responses.md b/structure/transports/responses.md index 4c962ce5340..b7d7359110b 100644 --- a/structure/transports/responses.md +++ b/structure/transports/responses.md @@ -392,16 +392,16 @@ always become unable to serve. > Decision record: [ADR-0039](../decisions/ADR-0039-responses-http-sse.md) - ## Decoded checkpoint continuation -`src/responses/parser.ts` adds `CHECKPOINT_CONTINUATION_NOTE` from `src/responses/compaction.ts` for decoded `ocx1:`/`ocx2:` checkpoints; `src/adapters/openai-responses/request-strips.ts` does the same while lowering them. For plaintext `SUMMARY_PREFIX` and readable portable checkpoints, `src/responses/compaction-history-framing.ts` frames text-only retained requests before the latest checkpoint as historical context. Plaintext checkpoints append the same note there; portable decoders retain their existing note placement. The parser projects only adapter context; `src/adapters/openai-responses/passthrough.ts` projects only non-OpenAI-operated outbound bodies. Original request text/blocks, canonical raw history, item identities, replay-prefix lengths, checkpoints and later input remain unchanged. Context wrappers, images/files and assistant/tool items are preserved; summarizer turns and opaque native blobs do not activate framing. Native OpenAI passthrough input is unchanged by checkpoint framing; the separate [citation projection](response-citations.md) repairs legacy annotation fields on OpenAI-operated outbound history. +`src/responses/parser.ts` adds `CHECKPOINT_CONTINUATION_NOTE` from `src/responses/compaction.ts` for decoded `ocx1:`/`ocx2:` checkpoints; `src/adapters/openai-responses/request-strips.ts` does the same while lowering them. For plaintext `SUMMARY_PREFIX` and readable portable checkpoints, `src/responses/compaction-history-framing.ts` frames text-only retained requests before the latest checkpoint as historical context. Plaintext checkpoints append the same note there; portable decoders retain their existing note placement. The parser projects only adapter context; `src/adapters/openai-responses/passthrough.ts` projects only non-OpenAI-operated outbound bodies. Original request text/blocks, canonical raw history, item identities, replay-prefix lengths, checkpoints and later input remain unchanged. Context wrappers, images/files and assistant/tool items are preserved; client-side summarizer turns ending in `COMPACT_PROMPT` and opaque native blobs do not activate framing. A remote `compaction_trigger` summary is framed like the ordinary request it extends but gets no note from the parser or the plaintext framing; `src/server/responses/response-effects.ts` appends `CHECKPOINT_CONTINUATION_NOTE` at the ordinary request's position only on the prefix-preserving Anthropic route (parser flag `_summaryCheckpointNote`), where the appended summary prompt steers the turn (#7307). Native OpenAI passthrough input is unchanged by checkpoint framing; the separate [citation projection](response-citations.md) repairs legacy annotation fields on OpenAI-operated outbound history. The note is a prompt contract and grants no authority. Completed requests remain history unless a later user message asks to repeat them. Unfinished work continues only under existing authorization and within its scope, without asking for that authorization again while it still applies. Permission and confirmation gates remain authoritative: a pending decision or required permission must resolve before the dependent action. Checkpoints and delegations, including those from another thread, neither grant authority nor expand scope. Later user messages take priority, including pause, cancellation, replacement and scope changes. The continuation-note and continuation-wire tests establish prompt and wire contracts, including separated `ocx2:` retained reasoning. `tests/responses/compaction-history-framing.test.ts` adds offline A/B projection, original-detail preservation, native passthrough isolation, multi-turn canonical replay/dedup coverage and exclusion of client-side summarizer turns ending in the canonical `COMPACT_PROMPT` (which carry no `compaction_trigger`). `tests/responses/compaction-portable-history.test.ts` covers default JSON/SSE trigger round trips and replacement replay with an external task envelope, plus portable checkpoint families and later user changes. These tests do not establish live model behavior or whether a model actually resumes the correct task. > Decision record: [ADR-7003](../decisions/ADR-7003-decoded-checkpoint-continuation.md) +> Decision record: [ADR-9174](../decisions/ADR-9174-remote-summary-checkpoint-prefix.md) ## Core module ownership diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f8f3c026d83..056a855a7b1 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -86,6 +86,7 @@ "server-combo-stream-send-contract.test.ts": "server", "server-combo-stream-required-tool.test.ts": "server", "combo-required-tool-stream-preflight.test.ts": "routing", "responses-anthropic-compaction-prefix.test.ts": "responses", + "responses-anthropic-compaction-checkpoint-prefix.test.ts": "responses", "service-proxy-env.test.ts": "service", "codex-cli-update-windows-apply.test.ts": "codex-integration", "codex-cli-update-windows-apply-install.test.ts": "codex-integration", "codex-cli-update-windows-apply-outcomes.test.ts": "codex-integration", "codex-cli-update-windows-apply-shared.test.ts": "codex-integration", "codex-cli-update-windows-recovery.test.ts": "codex-integration", diff --git a/tests/responses/compaction-history-framing.test.ts b/tests/responses/compaction-history-framing.test.ts index 82a4b112a73..0033cdcfa0f 100644 --- a/tests/responses/compaction-history-framing.test.ts +++ b/tests/responses/compaction-history-framing.test.ts @@ -86,11 +86,11 @@ describe("plaintext checkpoint historical framing", () => { kept.forEach((item, index) => expect(after.input[index]).toBe(item)); }); - test("no-op controls: no readable checkpoint, opaque state, summarizer, empty candidates", () => { + test("no-op controls: no readable checkpoint, opaque state, local summarizer, empty candidates", () => { for (const input of [ "direct input", [user(completed)], [checkpoint, later], [user(completed), { type: "compaction", encrypted_content: "gAAAA-native" }], - [user(completed), checkpoint, { type: "compaction_trigger" }], + [user(completed), checkpoint, user(COMPACT_PROMPT)], [user(""), checkpoint], [user(completed), { role: "assistant", content: `${SUMMARY_PREFIX}\nnot a checkpoint` }], ]) { @@ -99,6 +99,15 @@ describe("plaintext checkpoint historical framing", () => { } }); + test("a remote compaction_trigger summary is framed like its ordinary request but gets no note (#7307)", () => { + const ordinary = frameCompactionHistory({ instructions: "base", input: [user(completed), checkpoint] }); + const summary = frameCompactionHistory({ instructions: "base", input: [user(completed), checkpoint, { type: "compaction_trigger" }] }); + expect(JSON.stringify(summary.input[0])).toContain(HISTORICAL_REQUEST_START); + expect(summary.input.slice(0, -1)).toEqual(ordinary.input); + expect(ordinary.instructions).toContain(CHECKPOINT_CONTINUATION_NOTE); + expect(summary.instructions).toBe("base"); + }); + test("translated parser changes only context; raw body and continuation positions stay canonical", () => { const body = frozen({ model: "m", input: history() }); const parsed = parseRequest(body); diff --git a/tests/responses/compaction-portable-history.test.ts b/tests/responses/compaction-portable-history.test.ts index 0cfea49d94d..2e54b5684d9 100644 --- a/tests/responses/compaction-portable-history.test.ts +++ b/tests/responses/compaction-portable-history.test.ts @@ -134,12 +134,11 @@ describe("portable checkpoint framing boundaries", () => { expect(framed.input[4]).toBe(later); }); - test("ordinary tool prose, opaque/empty checkpoints and summarizer turns grant no framing", () => { + test("ordinary tool prose, opaque/empty checkpoints and local summarizer turns grant no framing", () => { for (const input of [ [requestA, { type: "function_call_output", call_id: "ordinary", output: summary }], [requestA, { type: "compaction", encrypted_content: "gAAAA-native-opaque" }], [requestA, { type: "compaction", encrypted_content: encodeCompactionSummary("") }], - [requestA, { type: "compaction", encrypted_content: encodeCompactionSummary(summary) }, { type: "compaction_trigger" }], [requestA, { type: "compaction", encrypted_content: encodeCompactionSummary(summary) }, user(COMPACT_PROMPT)], ]) { const body = { input }; @@ -147,6 +146,14 @@ describe("portable checkpoint framing boundaries", () => { } }); + test("a remote compaction_trigger summary frames the retained request like its ordinary turn (#7307)", () => { + const checkpoint = { type: "compaction", encrypted_content: encodeCompactionSummary(summary) }; + const ordinary = frameCompactionHistory({ input: [requestA, checkpoint] }); + const remote = frameCompactionHistory({ input: [requestA, checkpoint, { type: "compaction_trigger" }] }); + expect(JSON.stringify(remote.input[0])).toContain(HISTORICAL_REQUEST_START); + expect(remote.input.slice(0, -1)).toEqual(ordinary.input); + }); + test("OpenAI-operated passthrough retains its existing portable decoder without historical projection", () => { const input = [requestA, { type: "compaction", encrypted_content: encodeCompactionSummary(summary) }]; for (const provider of [ diff --git a/tests/responses/responses-anthropic-compaction-checkpoint-prefix.test.ts b/tests/responses/responses-anthropic-compaction-checkpoint-prefix.test.ts new file mode 100644 index 00000000000..4aec267333a --- /dev/null +++ b/tests/responses/responses-anthropic-compaction-checkpoint-prefix.test.ts @@ -0,0 +1,134 @@ +/** A summary after a checkpoint keeps the ordinary request's cached Anthropic prefix (#7307). */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { CHECKPOINT_CONTINUATION_NOTE, decodeCompactionSummary, encodeCompactionSummary } from "../../src/responses/compaction"; +import { HISTORICAL_REQUEST_START } from "../../src/responses/compaction-history-framing"; +import { handleResponses } from "../../src/server/responses/core"; +import type { OcxConfig } from "../../src/types"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { drainCompactionResponseState, installCompactionRoutingAclFixture, removeCompactionFixture } from "../helpers/compaction-routing-fixtures"; + +type Wire = { tools: unknown[]; system: Array<{ text: string }>; tool_choice?: unknown; messages: unknown[] }; + +const config = (): OcxConfig => ({ defaultProvider: "custom", cacheRetention: "short", providers: { + custom: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "key", apiKey: "synthetic-test-key" }, +} } as OcxConfig); + +const user = (text: string) => ({ type: "message", role: "user", content: [{ type: "input_text", text }] }); +const assistant = (text: string) => ({ type: "message", role: "assistant", content: [{ type: "output_text", text }] }); +// What Codex replays after one routed compaction: the retained request, the proxy-minted +// checkpoint, then the work that followed it. +const history = [ + user("Inspect sample.txt and report whether it is readable."), + { type: "compaction", encrypted_content: encodeCompactionSummary("sample.txt was inspected and is readable. Next: review notes.md.") }, + user("Now review notes.md."), + { type: "function_call", call_id: "read_notes", name: "read", arguments: "{}" }, + { type: "function_call_output", call_id: "read_notes", output: "notes.md: three open items." }, + assistant("notes.md has three open items."), +]; + +function body(input: unknown[], stream: boolean) { + return { model: "custom/claude-sonnet-4-6", stream, store: false, instructions: "stable system", + tools: [{ type: "function", name: "read", description: "Read a file", parameters: { type: "object", properties: {} } }], + tool_choice: "auto", parallel_tool_calls: false, input }; +} + +function upstream(stream: boolean): Response { + if (!stream) return Response.json({ id: "msg-summary", type: "message", role: "assistant", model: "claude-sonnet-4-6", + content: [{ type: "text", text: "handoff summary" }], stop_reason: "end_turn", usage: { input_tokens: 10, output_tokens: 5 } }); + const events = [ + { type: "message_start", message: { id: "msg-summary", type: "message", role: "assistant", model: "claude-sonnet-4-6", content: [], usage: { input_tokens: 10, output_tokens: 0 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "handoff summary" } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 5 } }, + { type: "message_stop" }, + ]; + return new Response(events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""), { + headers: { "content-type": "text/event-stream" }, + }); +} + +// Breakpoints move with the new tail, and a breakpoint turns string content into its single text +// block; Anthropic reads both forms as the same prompt, as consecutive ordinary turns already do. +const content = (messages: unknown[]) => JSON.parse(JSON.stringify(messages, (key, value) => + key === "cache_control" ? undefined + : key === "content" && typeof value === "string" ? [{ type: "text", text: value }] : value)); + +describe("Anthropic compaction after a portable checkpoint", () => { + const originalFetch = globalThis.fetch; + const originalHome = process.env.OPENCODEX_HOME; + let home: string; + let releaseSpendHome: () => void; + installCompactionRoutingAclFixture(); + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-compaction-checkpoint-prefix-")); + process.env.OPENCODEX_HOME = home; + releaseSpendHome = acquireOwnedSpendHome(); + }); + afterEach(async () => { + await drainCompactionResponseState(); + releaseSpendHome(); + await removeCompactionFixture(home); + globalThis.fetch = originalFetch; + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + }); + + const send = (input: unknown[], stream: boolean) => handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body(input, stream)), + }), config(), { model: "", provider: "" }); + + for (const stream of [false, true]) { + test(`the summary request repeats the ordinary request's system and framed history (stream=${stream})`, async () => { + const seen: Wire[] = []; + globalThis.fetch = (async (_input, init) => { + const wire = JSON.parse(String(init?.body)); + seen.push(wire); + return upstream(wire.stream === true); + }) as typeof fetch; + // The ordinary request ends on the tool output; the summary extends it with the reply and the trigger. + await (await send(history.slice(0, -1), stream)).text(); + const text = await (await send([...history, { type: "compaction_trigger" }], stream)).text(); + expect(text).toContain('"type":"compaction"'); + expect(seen).toHaveLength(2); + const [ordinary, summary] = seen as [Wire, Wire]; + // The ordinary turn is framed: the note in system and the retained request wrapped as history. + expect(ordinary.system.map(block => block.text).join("\n")).toContain(CHECKPOINT_CONTINUATION_NOTE); + expect(JSON.stringify(ordinary.messages[0])).toContain(HISTORICAL_REQUEST_START); + expect(summary.tools).toEqual(ordinary.tools); + expect(summary.system).toEqual(ordinary.system); + expect(summary.tool_choice).toEqual(ordinary.tool_choice); + expect(content(summary.messages).slice(0, ordinary.messages.length)).toEqual(content(ordinary.messages)); + // The appended tail still tells the summarizer to summarize and not to continue. + expect(JSON.stringify(summary.messages.at(-1))).toContain("Do not call tools or continue the task."); + const json = stream + ? JSON.parse(text.split("\n").find(line => line.startsWith("data: ") && line.includes('"type":"response.completed"'))!.slice(6)).response + : JSON.parse(text); + expect(decodeCompactionSummary(json.output.at(-1).encrypted_content)).toBe("handoff summary"); + }); + } + + test("a route that does not preserve the prefix keeps the summary free of the continuation note", async () => { + const cfg = config(); + cfg.providers.custom!.modelAdapters = { "claude-sonnet-4-6": "openai-chat" }; + const seen: Array<{ messages: Array<{ role: string; content: unknown }> }> = []; + globalThis.fetch = (async (_input, init) => { + seen.push(JSON.parse(String(init?.body))); + return Response.json({ choices: [{ message: { role: "assistant", content: "handoff summary" }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 5 } }); + }) as typeof fetch; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify(body([...history, { type: "compaction_trigger" }], false)), + }), cfg, { model: "", provider: "" }); + expect((await response.json()).output.at(-1).type).toBe("compaction"); + expect(seen).toHaveLength(1); + const system = seen[0]!.messages.filter(message => message.role === "system" || message.role === "developer"); + expect(JSON.stringify(system)).not.toContain(CHECKPOINT_CONTINUATION_NOTE); + // Historical framing is part of the history projection and applies to every remote summary. + expect(JSON.stringify(seen[0]!.messages)).toContain(HISTORICAL_REQUEST_START); + }); +}); From cca6d5f8df880695dbaf796bb1df1ab1763d391a Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:21:31 +0900 Subject: [PATCH 32/64] fix(combo): advance on the undeclared-tool guard refusal without cooling the target (#9188) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(combo): advance on the undeclared-tool guard's refusal (#9163) A combo child whose model answered with a call to a tool the request never declared was permanently committed: the client-boundary guard suppressed the item and synthesized a terminal undeclared_tool_call after the preflight had already counted the call item as output, so a multi-target combo could never advance to its other targets and every such turn ended. - combo-stream-preflight: with the child's declared wire catalog supplied, an output frame naming an undeclared client tool is read as the refusal the guard will synthesize instead of as committed client output, and the projected terminal joins the hop evidence; anything the client genuinely received (any earlier relayed text delta, or a declared call) still commits the child, and without the catalog option behavior is unchanged. - failover: comboFailureDecision hops and comboFailureCooldownScope returns none on a caller-proven undeclaredToolCallRefusal - the guard's own structured code, never the bare message words, so quoted or reflected occurrences stay terminal. The refusal is deterministic per target but target-local: another model may know the tool or not hallucinate the name. - core-combo: the child presents its current-turn wire catalog (the same boundary its guard authorizes) to the preflight. - tests: combo-undeclared-tool-guard-refusal.test.ts covers the replayable refusal, the committed-text veto, the declared-call pass-through, the no-catalog default and the provenance gate; registered in the combo test layout, and the ratchet baseline records the two grown hosts. * fix(combo): decide the undeclared-tool refusal at the stream's end, gate on the settled route CodeRabbit review fixes on #9164: - combo-stream-preflight: an undeclared call no longer hops at the transport chunk that carries it. A declared call later in the same stream is output the caller could have executed and vetoes the hop, so the refusal is decided only at the stream's decision points (terminal, EOF, byte/chunk caps) — a chunk holding only the undeclared call must not cancel the reader before later chunks are inspected. The projected terminal is built when the frame is seen but only acted on at those decision points; insufficient evidence retains the child exactly as an unknown frame does. - core-combo: the forward-auth gate reads the child's settled route (childRoute.route, filled by request-prepare when the bridge child can land on a route other than the planned one) rather than the planned target route, matching what the production guard authorizes. - tests: two regression tests pin the chunk-boundary behavior — an undeclared call and a later declared call in separate chunks commits the child (accepted), and an undeclared call whose terminal arrives in a later chunk still hops (failed). * fix(combo): exempt a suppressed undeclared call's argument frames from commit CodeRabbit follow-up on #9164: an undeclared output_item.added followed by a response.function_call_arguments.delta (or nameless .done) sharing its item_id set outputCommitted even though the guard trips at the addition and rewrites the stream to its refusal terminal, so the client never received those frames - the combo then kept a target whose turn the guard refuses. The preflight records the offending item's identity when its undeclared addition is recognized, and argument-continuation frames referencing it no longer count as committed output. Text deltas and declared calls keep their commit meaning; deltas for another item are unaffected. * fix(combo): keep a guard-suppressed terminal snapshot uncommitted CodeRabbit on #9164 (outside-diff-range comment on the first review): with requiredToolPrelude enabled, a response.completed/incomplete snapshot whose only output item is the undeclared function call is rewritten by the boundary guard into response.failed, so the client receives nothing from that frame - but the prelude-snapshot commit check still saw the non-empty output array as committed output, stranding the combo on a target the guard refuses. The snapshot check now carries the same undeclaredName/suppressed-continuation gate as the per-frame commit: a snapshot holding only the suppressed call stays uncommitted; declared items the client genuinely received keep their commit meaning. Regression tests: completed snapshot with only the undeclared call refuses (failed); completed snapshot with declared output commits (accepted). * test(combo): make the continuation-exemption test depend on the item identity CodeRabbit on #9164: the accepted-direction test passed even if the new continuation exemption suppressed every argument delta, because the declared addition already set outputCommitted and the callback returned before the delta was judged. The test now emits an undeclared addition (fc_9) followed by a delta for a different item_id, so the accepted result proves the exemption is scoped to the suppressed item's identity. * refactor(combo): keep the undeclared-tool hop under the file-size ratchet The undeclared-tool guard hop (#9163) pushed src/combos/failover.ts to 2020 lines and src/server/responses/core-combo.ts to 2049, and added baseline caps for them (and for combo-stream-preflight.ts, which stays under the threshold). A cap may only move down, so this moves code instead and restores the baseline: - parseRetryAfterMs and its two delay bounds move byte for byte to src/combos/retry-after-delay.ts; failover.ts imports the bounds and re-exports the parser, so every existing import keeps working. - deriveSendBudgetScope moves byte for byte to src/server/responses/combo-send-budget-scope.ts (only core-combo.ts uses it). - The child catalog the preflight reads is built by comboChildDeclaredWireTools in combo-stream-preflight.ts, next to the option type it fills. Same forward-auth gate, same current-turn catalog boundary, same deny-all on an explicit empty catalog. No behaviour change. failover.ts is 1990 lines, core-combo.ts 1975 and combo-stream-preflight.ts 1451. * refactor(combo): read the moved helpers and restore the size baseline Completes the previous commit, which landed only the two new modules: failover.ts now imports the retry-after bounds and re-exports parseRetryAfterMs, core-combo.ts imports deriveSendBudgetScope and builds the preflight catalog through comboChildDeclaredWireTools, and the three caps #9163 added to tests/fixtures/file-size-baseline.json are removed. failover.ts is 1990 lines, core-combo.ts 1975 and combo-stream-preflight.ts 1451, all below the 2000-line threshold without a baseline entry. * fix(combo): take the undeclared-tool hop's provenance from the guard itself The preflight approach judged undeclared calls against a catalog it rebuilt on its own, and read a stream the guard had already rewritten: - On Chat Completions and Anthropic Messages the guard deliberately stands down (the client registry owns deferred tools), but the rebuilt catalog armed on any declared tool. A deferred call then failed a one-target combo with 502 undeclared_tool_call and was dropped and rerouted on two targets. - On Responses the guard rewrites the stream before the combo preflight reads it, so the preflight only ever saw the guard's own response.failed. The marker was never produced, and the healthy target was still cooled. The guard now records its own trip on the attempt's log context (markUndeclaredToolGuardRefusal in its onRefusal), and consumeComboFailure reads that mark after the body read, which also covers a buffered body the guard rewrites lazily. The combo preflight is back to dev: it no longer recomputes a tool catalog. failover.ts keeps the hop-without-cooldown verdict for that provenance. The tests now drive handleResponses, handleChatCompletions and handleClaudeMessages through a two-target combo: on Responses (auto, eager-relay, legacy-tee; stream on and off) a refused undeclared call reaches the second target and does not cool the first; text the client already saw keeps the child committed; and on Chat and Messages a deferred tool call is delivered from the first target, with one target and with two. * fix(combo): grant the no-cooldown hop only to the guard's own refusal The guard marks the attempt when it trips, but a stream can carry an upstream error (a rate limit, say) before the undeclared call. The combo then judges the upstream's error, and the mark alone skipped that target's cooldown, and ahead of the provider-quota and credential checks in comboFailureCooldownScope. Require the consumed failure to carry undeclared_tool_call as well. * test(responses): register the moved combo send-budget scope as a core module combo-send-budget-scope.ts holds deriveSendBudgetScope, moved out of core-combo.ts byte for byte; the responses-core module roster has to list it, or responses-core-modules.test.ts reports an unclaimed owner. * fix(combo): restore the deriveSendBudgetScope re-export from core-combo CodeRabbit round 3: the extracted wrapper used to export deriveSendBudgetScope from this module; the move dropped the named export while keeping only the local import. Re-export from the new module so existing named imports keep their binding. typecheck clean; tests/routing 2586 pass; file-size ratchet 9 pass; structure SSOT passes. * fix(combo): mark the buffered JSON undeclared-tool refusal for the hop CodeRabbit round 4: the buffered application/json refusal branch returned the undeclared_tool_call 502 without markUndeclaredToolGuardRefusal, so consumeComboFailure lost the provenance, the failure kept its cooldown, and a healthy combo target was quarantined. Mirror the SSE refusal path: mark the context and remember the proxy error message before the return. Two regression tests (stream true and false) pin the buffered JSON refusal hop: primary answers non-streaming JSON with an undeclared call, backup output is delivered, primary cooldown stays unset. They fail without the mark. typecheck clean (2,726 files); tests/routing 2,588 pass; file-size ratchet 9 pass; structure SSOT passes. * docs(structure): record the undeclared-tool guard hop in the combo runtime contract structure/runtime.md owns combo classification for src/combos/. Describe the guard's provenance (the mark it records when it trips), that only a consumed undeclared_tool_call failure carrying that mark hops without a cooldown, and what still holds: earlier upstream errors keep their verdict, bare refusal words grant nothing, client-visible output commits the child, and Chat, Messages and forward-auth targets never trip the guard. --------- Co-authored-by: Brad Hallett <53977268+bradhallett@users.noreply.github.com> --- scripts/test-layout/layout-combos.json | 1 + src/combos/failover.ts | 55 ++-- src/combos/retry-after-delay.ts | 33 +++ src/lib/errors.ts | 16 ++ .../responses/combo-send-budget-scope.ts | 28 ++ src/server/responses/core-combo-failure.ts | 9 + src/server/responses/core-combo.ts | 35 +-- src/server/responses/core-options.ts | 2 + src/server/responses/passthrough-delivery.ts | 11 +- structure/runtime.md | 2 +- tests/fixtures/test-layout-expected.json | 1 + tests/helpers/responses-core-source.ts | 2 + ...ombo-undeclared-tool-guard-refusal.test.ts | 256 ++++++++++++++++++ 13 files changed, 389 insertions(+), 62 deletions(-) create mode 100644 src/combos/retry-after-delay.ts create mode 100644 src/server/responses/combo-send-budget-scope.ts create mode 100644 tests/routing/combo-undeclared-tool-guard-refusal.test.ts diff --git a/scripts/test-layout/layout-combos.json b/scripts/test-layout/layout-combos.json index 05c1649e9e7..a1d527871c1 100644 --- a/scripts/test-layout/layout-combos.json +++ b/scripts/test-layout/layout-combos.json @@ -11,6 +11,7 @@ "combo-stream-attempt-timing.test.ts": "responses", "combo-cooldown-persistence.test.ts": "routing", "combo-unoffered-tool-refusal.test.ts": "routing", + "combo-undeclared-tool-guard-refusal.test.ts": "routing", "server-combo-cooldown-recording.test.ts": "server", "server-combo-main-account-cooldown.test.ts": "server", "combo-capability-policy.test.ts": "codex-integration", diff --git a/src/combos/failover.ts b/src/combos/failover.ts index 5eb186317f2..7443cd95302 100644 --- a/src/combos/failover.ts +++ b/src/combos/failover.ts @@ -1,7 +1,6 @@ import { parseResetCooldownMs } from "../codex/routing"; import { CYBER_POLICY_FALLBACK_MESSAGE, TERMINAL_REFUSAL_FALLBACK_MESSAGE, classifyError, isCyberPolicyCode, isCyberPolicyMessage, isRateLimitOrQuotaFailureMessage, isSubscriptionGateMessage, isTerminalRefusalCode, safetyRefusalCodeFromMessage } from "../lib/errors"; import { isHardPolicyOrOriginRefusal } from "../lib/hard-refusal"; -import { parseHttpDate } from "../lib/http-date"; import { isNonReplayableUpstreamCode } from "../lib/upstream-retry"; import { isAnthropicBillingFailure, isAnthropicExtraUsageFailure } from "../providers/anthropic-billing-refusal"; import { hasConflictingReasoningEffortCode } from "../providers/reasoning-metadata"; @@ -11,11 +10,13 @@ import { M365_RESPONSE_LIMIT_MESSAGES } from "../adapters/m365-copilot/response- import type { OcxComboTarget } from "../types"; import { targetKey } from "./types"; import { PersistedCooldownMap } from "./cooldown-store"; +import { MAX_COOLDOWN_MS, MAX_SERVER_DELAY_MS, parseRetryAfterMs } from "./retry-after-delay"; import { registerOptionalShutdownHook } from "../lib/optional-shutdown-hooks"; import { isDefiniteContextOverflow } from "../lib/context-overflow-verdict"; // The verdict lives in a dependency-free leaf so the presentation classifier can share it. export { isDefiniteContextOverflow }; +export { parseRetryAfterMs }; import { captureConfigGeneration, sweepExpiredOnWrite, @@ -32,8 +33,6 @@ interface TargetCooldown { } const DEFAULT_COOLDOWN_MS = 60_000; -const MAX_COOLDOWN_MS = 10 * 60_000; -const MAX_SERVER_DELAY_MS = 24 * 60 * 60_000; /** Short cooldown for request-rate 429s (for example provider code 1302) that omit Retry-After. */ export const COMBO_REQUEST_RATE_COOLDOWN_MS = 5_000; @@ -65,35 +64,6 @@ function cooldownMapKey( return `${comboId}\0${targetKey(target)}`; } -/** Parse a Retry-After delay, optionally retaining an upstream delay up to one day. */ -export function parseRetryAfterMs( - value: string | null | undefined, - now = Date.now(), - options?: { preserveImmediate?: boolean; preserveServerDelay?: boolean }, -): number | undefined { - const text = value?.trim(); - if (!text) return undefined; - // Keep legacy bounded parsing for other callers. Combo cooldowns preserve - // multi-hour upstream delays, but never quarantine a target beyond one day. - const maximum = options?.preserveServerDelay === true - ? MAX_SERVER_DELAY_MS - : MAX_COOLDOWN_MS; - if (/^\d+(?:\.\d+)?$/.test(text)) { - const seconds = Number(text); - if ( - Number.isFinite(seconds) - && (seconds > 0 || (options?.preserveImmediate && seconds === 0)) - ) { - return Math.min(Math.max(Math.ceil(seconds * 1000), 1), maximum); - } - } - const timestamp = parseHttpDate(text, now, { legacy: true }); - if (timestamp === undefined) return undefined; - const delay = timestamp - now; - if (delay > 0) return Math.min(delay, maximum); - return options?.preserveImmediate ? 1 : undefined; -} - export function isComboTargetInCooldown( comboId: string, target: Pick, @@ -1575,6 +1545,8 @@ export function comboFailureCooldownScope( malformedResponseFormat?: boolean; openRouterOpaque400?: boolean; unofferedToolCallRefusal?: boolean; + /** The caller proved this is the undeclared-tool guard's own refusal (#9163). */ + undeclaredToolCallRefusal?: boolean; /** Whole-body moderation verdict from a reader that saw the complete bounded body. */ providerModerationRefusal?: boolean; }, @@ -1603,6 +1575,9 @@ export function comboFailureCooldownScope( || (options?.unofferedToolCallRefusal !== undefined ? options.unofferedToolCallRefusal : isUnofferedToolCallRefusal(status, message, rawCode)) + // The guard-refused child's model invented the call (#9163): the request fit, the target is + // healthy, and only a caller with provenance states this verdict, so it must not cool one. + || options?.undeclaredToolCallRefusal === true ) return "none"; if (isProviderScopedQuotaCap(status, message, rawCode)) return "provider"; // A rejected or unpaid credential is provider-wide evidence: every target that routes @@ -1802,6 +1777,13 @@ export function comboFailureDecision( malformedResponseFormat?: boolean; openRouterOpaque400?: boolean; unofferedToolCallRefusal?: boolean; + /** + * The caller proved this failure is the undeclared-tool guard's own refusal (#9163): the child + * answered with a call to a tool the request never declared, so the guard suppressed the item + * and synthesized the terminal. Target-local model behaviour on a healthy target, exactly as + * `unofferedToolCallRefusal` is for the upstream-400 verdict shape. + */ + undeclaredToolCallRefusal?: boolean; /** Whole-body moderation verdict from a reader that saw the complete bounded body. */ providerModerationRefusal?: boolean; /** Whole-body 413 intake verdict ({@link isProviderIntakeRefusalBody}); false vetoes the hop. */ @@ -1834,6 +1816,8 @@ function decideComboFailure( malformedResponseFormat?: boolean; openRouterOpaque400?: boolean; unofferedToolCallRefusal?: boolean; + /** The caller proved this is the undeclared-tool guard's own refusal (#9163). */ + undeclaredToolCallRefusal?: boolean; /** Whole-body moderation verdict from a reader that saw the complete bounded body. */ providerModerationRefusal?: boolean; /** Whole-body 413 intake verdict ({@link isProviderIntakeRefusalBody}); false vetoes the hop. */ @@ -1956,6 +1940,13 @@ function decideComboFailure( if (options?.unofferedToolCallRefusal !== undefined ? options.unofferedToolCallRefusal : isUnofferedToolCallRefusal(status, message, rawCode)) return "hop"; + // The undeclared-tool guard refused this child after its model answered with a call to a tool + // the request never declared (#9163). Same family as the unoffered-tool verdict above, but the + // refusal is proxy-synthesized at the client boundary, so it never carries the upstream 400 + // shape and only a caller with provenance (the guard's own structured code) reaches this arm: + // the bare words stay terminal for every quoted or reflected occurrence. Deterministic on this + // target, target-local in the combo: another model may know the tool or not hallucinate the name. + if (options?.undeclaredToolCallRefusal === true) return "hop"; if (isAnthropicBillingFailure(status, message, rawCode)) return "hop"; if (isAnthropicExtraUsageFailure(status, message, rawCode)) return "hop"; // Kiro's body validator rejects the request for the identity it was routed under. The account diff --git a/src/combos/retry-after-delay.ts b/src/combos/retry-after-delay.ts new file mode 100644 index 00000000000..6597c02220d --- /dev/null +++ b/src/combos/retry-after-delay.ts @@ -0,0 +1,33 @@ +import { parseHttpDate } from "../lib/http-date"; + +export const MAX_COOLDOWN_MS = 10 * 60_000; +export const MAX_SERVER_DELAY_MS = 24 * 60 * 60_000; + +/** Parse a Retry-After delay, optionally retaining an upstream delay up to one day. */ +export function parseRetryAfterMs( + value: string | null | undefined, + now = Date.now(), + options?: { preserveImmediate?: boolean; preserveServerDelay?: boolean }, +): number | undefined { + const text = value?.trim(); + if (!text) return undefined; + // Keep legacy bounded parsing for other callers. Combo cooldowns preserve + // multi-hour upstream delays, but never quarantine a target beyond one day. + const maximum = options?.preserveServerDelay === true + ? MAX_SERVER_DELAY_MS + : MAX_COOLDOWN_MS; + if (/^\d+(?:\.\d+)?$/.test(text)) { + const seconds = Number(text); + if ( + Number.isFinite(seconds) + && (seconds > 0 || (options?.preserveImmediate && seconds === 0)) + ) { + return Math.min(Math.max(Math.ceil(seconds * 1000), 1), maximum); + } + } + const timestamp = parseHttpDate(text, now, { legacy: true }); + if (timestamp === undefined) return undefined; + const delay = timestamp - now; + if (delay > 0) return Math.min(delay, maximum); + return options?.preserveImmediate ? 1 : undefined; +} diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 0263a383e54..c728538b14d 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -64,6 +64,22 @@ export function isVerifiedModelNotInPlanResponse(response: Response): boolean { return verifiedPlanRefusalResponses.has(response); } +/** + * Request contexts whose undeclared-tool guard refused the turn (#9163). The guard records its + * own trip on the context of the attempt it rewrote, so a combo reads the refusal's provenance + * from the guard rather than from the words: an upstream body that merely repeats the code or + * message never sets it, and a wire on which the guard stands down never trips it. + */ +const undeclaredToolGuardRefusals = new WeakSet(); + +export function markUndeclaredToolGuardRefusal(context: object): void { + undeclaredToolGuardRefusals.add(context); +} + +export function undeclaredToolGuardRefused(context: object | undefined): boolean { + return context !== undefined && undeclaredToolGuardRefusals.has(context); +} + /** True for a verified plan refusal that still carries the canonical code in its 400 body. */ export function isModelNotInPlanRefusal(response: Response, bodyCode: string | null | undefined): boolean { return response.status === 400 && bodyCode === MODEL_NOT_IN_PLAN_CODE && verifiedPlanRefusalResponses.has(response); diff --git a/src/server/responses/combo-send-budget-scope.ts b/src/server/responses/combo-send-budget-scope.ts new file mode 100644 index 00000000000..dcbf8449d5a --- /dev/null +++ b/src/server/responses/combo-send-budget-scope.ts @@ -0,0 +1,28 @@ +import { deriveRequestExecutionBudget } from "../../lib/request-execution-budget"; +import type { RequestExecutionBudget, RequestExecutionBudgetPolicy } from "../../lib/request-execution-budget"; + +/** + * A budget scope that keeps its own recovery ledgers but spends the SAME request-wide counter. + * + * The sharing has to happen inside the factory. Redefining `used` as an accessor onto the parent + * only shared what callers read from the outside: `remainingBaseSends`, the total check and the + * reserve test all consult the factory's own private counter, which an overridden property + * cannot reach. Each derived scope therefore admitted dispatches as though the request had spent + * nothing, and the per-target holdback (`comboTargetSendBudget` in core-combo.ts) -- expressed + * against `maxTotalModelSends` -- had nothing to hold back from. + * + * `deriveRequestExecutionBudget` binds the scope to the parent's real ledger, including pending + * externally-counted bookings and the durable-spend observer, all of which must travel together. + * A pending booking is a send already counted in the total and waiting for its reporter, and the + * observer books by watching that same counter move (#4707) -- so a scope that spent the counter + * without carrying the observer would move it without booking, and this combo's child sends + * would go missing from the spend ledger. The reserve, alternate-target and transition ledgers + * stay per-scope on purpose: a combo target's account failover is its own recovery decision, + * while the request total still bounds every target together. + */ +export function deriveSendBudgetScope( + parent: RequestExecutionBudget, + policy: RequestExecutionBudgetPolicy, +): RequestExecutionBudget { + return deriveRequestExecutionBudget(parent, policy); +} diff --git a/src/server/responses/core-combo-failure.ts b/src/server/responses/core-combo-failure.ts index e8fe1bceac9..03aac10a2e3 100644 --- a/src/server/responses/core-combo-failure.ts +++ b/src/server/responses/core-combo-failure.ts @@ -35,6 +35,8 @@ import { CYBER_POLICY_ERROR_CODE, CYBER_POLICY_FALLBACK_MESSAGE, isModelNotInPlanRefusal, + undeclaredToolGuardRefused, + UNDECLARED_TOOL_CALL_ERROR_CODE, markVerifiedModelNotInPlanResponse, namesModelNotInPlanCode, } from "../../lib/errors"; @@ -448,6 +450,12 @@ export async function consumeComboFailure( if (signal?.aborted) throw error; classificationText = fallback; } + // Read after the body: the passthrough guard rewrites a buffered body lazily, so it may trip + // during the read above. Its own mark on this attempt's context is the provenance (#9163), and + // the failure judged here must be that refusal: an upstream error the stream carried before the + // undeclared call is still the upstream's verdict and keeps its cooldown. + const undeclaredToolCallRefusal = (undeclaredToolGuardRefused(logCtx) + && upstreamCode === UNDECLARED_TOOL_CALL_ERROR_CODE) || undefined; const cyberFailure = isCyberPolicyCode(upstreamCode) || isCyberPolicyMessage(classificationText); const normalizedUpstreamCode = cyberFailure ? CYBER_POLICY_ERROR_CODE : replayRefusal ? UPSTREAM_RESET_REPLAY_REFUSED_CODE : upstreamCode; @@ -503,6 +511,7 @@ export async function consumeComboFailure( response: failureResponse, ...(nonReplayable ? { nonReplayable: true } : {}), ...(verifiedPlanRefusal ? { verifiedPlanRefusal: true } : {}), + ...(undeclaredToolCallRefusal ? { undeclaredToolCallRefusal: true } : {}), classificationText, ...(codexModelRefusal !== undefined ? { codexModelRefusal } : {}), ...(malformedResponseFormat !== undefined ? { malformedResponseFormat } : {}), diff --git a/src/server/responses/core-combo.ts b/src/server/responses/core-combo.ts index cc7cfae4c60..42cb848ac2e 100644 --- a/src/server/responses/core-combo.ts +++ b/src/server/responses/core-combo.ts @@ -30,13 +30,17 @@ import { recordAttemptRequestedEffort } from "../request-log"; import { bindLinkTurnChild, failLinkTurnExpansion, markLinkTurnMissing, observeLinkTurnExpansion } from "../link-turn"; import { CODEX_TEXT_GUARDED_BUDGET_POLICY, - deriveRequestExecutionBudget, isRequestExecutionBudget, } from "../../lib/request-execution-budget"; import type { RequestExecutionBudgetPolicy, RequestExecutionBudget, } from "../../lib/request-execution-budget"; +import { deriveSendBudgetScope } from "./combo-send-budget-scope"; +// The wrapper this PR extracted used to export `deriveSendBudgetScope` from this module; +// the re-export keeps every existing named import of it working while internal calls +// read the extracted implementation (#9163 review: preserve public exports). +export { deriveSendBudgetScope } from "./combo-send-budget-scope"; import type { OcxComboDefaultEffort, OcxConfig, OcxUsage } from "../../types"; import type { RequestLogContext } from "../request-log"; import type { HandleResponsesOptions, ResponsesDispatchers, ConsumedComboFailure } from "./core-options"; @@ -204,33 +208,6 @@ export function comboExecutionBudgetPolicy(declaredTargets: number): RequestExec } -/** - * A budget scope that keeps its own recovery ledgers but spends the SAME request-wide counter. - * - * The sharing has to happen inside the factory. Redefining `used` as an accessor onto the parent - * only shared what callers read from the outside: `remainingBaseSends`, the total check and the - * reserve test all consult the factory's own private counter, which an overridden property - * cannot reach. Each derived scope therefore admitted dispatches as though the request had spent - * nothing, and the per-target holdback below -- expressed against `maxTotalModelSends` -- had - * nothing to hold back from. - * - * `deriveRequestExecutionBudget` binds the scope to the parent's real ledger, including pending - * externally-counted bookings and the durable-spend observer, all of which must travel together. - * A pending booking is a send already counted in the total and waiting for its reporter, and the - * observer books by watching that same counter move (#4707) -- so a scope that spent the counter - * without carrying the observer would move it without booking, and this combo's child sends - * would go missing from the spend ledger. The reserve, alternate-target and transition ledgers - * stay per-scope on purpose: a combo target's account failover is its own recovery decision, - * while the request total still bounds every target together. - */ -export function deriveSendBudgetScope( - parent: RequestExecutionBudget, - policy: RequestExecutionBudgetPolicy, -): RequestExecutionBudget { - return deriveRequestExecutionBudget(parent, policy); -} - - /** * The ladder one combo target may run, expressed as an allowance on the request-wide counter. * @@ -1748,6 +1725,7 @@ export async function executeComboResponses( malformedResponseFormat: failure.malformedResponseFormat, openRouterOpaque400: failure.openRouterOpaque400, unofferedToolCallRefusal: failure.unofferedToolCallRefusal, + undeclaredToolCallRefusal: failure.undeclaredToolCallRefusal, providerModerationRefusal: failure.providerModerationRefusal, providerIntakeRefusal: failure.providerIntakeRefusal, // The adapter the failed leg actually resolved: a configured `kiro` provider can route a @@ -1836,6 +1814,7 @@ export async function executeComboResponses( malformedResponseFormat: failure.malformedResponseFormat, openRouterOpaque400: failure.openRouterOpaque400, unofferedToolCallRefusal: failure.unofferedToolCallRefusal, + undeclaredToolCallRefusal: failure.undeclaredToolCallRefusal, providerModerationRefusal: failure.providerModerationRefusal, }); const failedTargetKey = targetKey(pick.target); diff --git a/src/server/responses/core-options.ts b/src/server/responses/core-options.ts index 443e1e0eb87..76636da501f 100644 --- a/src/server/responses/core-options.ts +++ b/src/server/responses/core-options.ts @@ -79,6 +79,8 @@ export interface ConsumedComboFailure { nonReplayable?: boolean; /** The failed attempt was an adapter-normalized plan refusal; only this grants its combo hop. */ verifiedPlanRefusal?: boolean; + /** The failed attempt is the undeclared-tool guard's own refusal; only this grants its combo hop (#9163). */ + undeclaredToolCallRefusal?: boolean; } diff --git a/src/server/responses/passthrough-delivery.ts b/src/server/responses/passthrough-delivery.ts index e19dd484edf..7063ae75d5c 100644 --- a/src/server/responses/passthrough-delivery.ts +++ b/src/server/responses/passthrough-delivery.ts @@ -5,6 +5,7 @@ import { noteRelaySyntheticTail, noteRequestSentValueGuard } from "../request-lo import { createSentValueGuard } from "../../lib/outbound-credential-registry"; import { carryPolicyCandidateRefusal } from "./policy-request-scope"; import { markProxyError, rememberProxyErrorMessage, carryProxyError } from "../../lib/client-error-body"; +import { markUndeclaredToolGuardRefusal } from "../../lib/errors"; import { releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; import { hasResponseMediaType } from "../../lib/http-response-semantics"; @@ -995,7 +996,10 @@ export async function deliverPassthroughResponse( declaredBareWireToolNames, recoverableBareCustomWireToolNames, { refuseUndeclared: nativeExchange.undeclaredToolGuardActive, - onRefusal: message => rememberProxyErrorMessage(logCtx, message, { status: 502, type: "upstream_error", code: UNDECLARED_TOOL_CALL_ERROR_CODE }) }, + onRefusal: message => { + markUndeclaredToolGuardRefusal(logCtx); + rememberProxyErrorMessage(logCtx, message, { status: 502, type: "upstream_error", code: UNDECLARED_TOOL_CALL_ERROR_CODE }); + } }, ) : undefined, grokUpstreamEchoEnabled @@ -1545,6 +1549,11 @@ export async function deliverPassthroughResponse( } })(); if (undeclared !== undefined) { + // Mirror the SSE refusal path's provenance: the buffered JSON branch never runs the + // block rewrite, so without this mark `consumeComboFailure` cannot grant the hop and + // a healthy combo target would take a cooldown it must not (#9163). + markUndeclaredToolGuardRefusal(logCtx); + rememberProxyErrorMessage(logCtx, undeclaredToolCallMessage(), { status: 502, type: "upstream_error", code: UNDECLARED_TOOL_CALL_ERROR_CODE }); return markProxyError(formatErrorResponse(502, "upstream_error", undeclaredToolCallMessage(), { code: UNDECLARED_TOOL_CALL_ERROR_CODE, })); diff --git a/structure/runtime.md b/structure/runtime.md index c189a29392e..7ab87822a4f 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -500,7 +500,7 @@ The combo may advance to its next eligible unattempted target before output comm A definite context-window overflow is the fourth request-local verdict. A heterogeneous combo mixes windows, so "this turn does not fit THIS model" is not "this turn is impossible", and stopping at the first undersized target burned the ladder on turns a later target could hold. Evidence must come from the innermost provider message: `classifyError` remaps any occurrence of `context window`, `context length`, `maximum context` or `too many tokens` anywhere in the blob, and inheriting that looseness would let a `context_length_exceeded` token sitting in a `code` field beside `Unsupported parameter: user` authorize a replay. `src/lib/context-overflow-verdict.ts` therefore recognizes common context-overflow phrases, including provider wording that a prompt is too long for a model's context window, and bounded wording that the history, conversation, input, prompt, request, turn or messages have reached or passed a model's context window/length/limit, plus a window/length/limit that is full, exhausted, at its limit or has been exceeded. A negator that governs that wording denies the verdict, while a negation in an earlier comma-separated clause does not: a verdict needs its own subject and predicate, and capacity prose about the service stays non-overflow: the verdict's own clause is read with the wide vocabulary (busy, retrying, KV cache, GPU, replica, worker), while a remedy after a semicolon or in the next sentence is read only for plain availability wording (busy, retry, service, queue, throttling), so "full. Remove older messages before retrying" still fails over. The ambiguous state predicates ("full", "exhausted", "at its limit") count only below 500; on a 5xx they keep the target cooldown, as on dev. Negation-aside matching starts at literal words or commas and consumes surrounding whitespace separately, once per bounded 120-character lookbehind; newline and clause boundaries keep their meaning. It unwraps only the exact proxy wrapper, within four envelopes and 16,384 characters, and reads the leaf message from structured error envelopes or string-valued `error` fields. A JSON-shaped body that does not parse fails closed, because `normalizeUpstreamErrorText` caps `classificationText` at 500 characters and a long envelope arrives here as a prefix. The verdict is admitted only for statuses that speak about the request — 400, 413, 422 and 5xx — so a 401/403 body that merely quotes context prose keeps its provider-wide cooldown instead of being rescored as request-shaped. Structured `origin_rejected`, cyber policy and the non-replayable post-send codes are all tested before it. A provider HTTP 413 is a fifth (#9017). Combo targets carry different body and token intake limits (Groq, for example, refuses a turn above the account's tokens-per-minute tier with 413 and `rate_limit_exceeded`), and the provider refused before processing the turn, so `decideComboFailure` hops to the next untried target exactly as it does for a per-target context overflow, and `comboFailureCooldownScope` keeps 413 at `none`. The proxy's own 413s stay terminal because they are identical for every target: `translation_buffer_limit`, `inbound_body_too_large`, `outbound_body_too_large` (read from the structured code or the bounded body) and the exact Ollama late-attribution constant. So does an adapter buffer 413 raised after the request was sent (Microsoft 365 Copilot's answer, reasoning, message and frame buffers in `src/adapters/m365-copilot/response-limits.ts`), because the provider already ran the turn. The hard stops above and any terminal, safety or origin refusal still win, and a generic 410 stays terminal. When the last target also refuses, the client gets that 413 classified as above. This reverses the generic-413 stop recorded in `devlog/_fin/260904_bug_stack_train/040_deferrals.md` (coordinator decision, 2026-11-21). -This is also why the classifier cannot duplicate visible output. Native byte streams reach combo classification only through `preflightComboStreamResponse`, which commits the child on any text, tool call or unknown event (the Responses lifecycle preamble and the Codex WebSocket `codex.rate_limits` / `codex.response.metadata` frames are control, not output) and synthesizes a failure envelope only for a zero-output terminal. A `runTurn` adapter has the equivalent boundary in `preflightAdapterEvents`: when the first meaningful event is an undeclared tool call and no replay-unsafe heartbeat recorded a side effect, `src/server/responses/run-turn-execution.ts` checks it against the exact current request catalog and projects the existing fail-closed refusal as a pre-commit 502 so failover can continue without changing the catalog. Any earlier text, tool call, control boundary, unknown event or replay-unsafe heartbeat commits that child, so a turn whose output the client may have seen or whose side effect may have run is never replayed. +This is also why the classifier cannot duplicate visible output. Native byte streams reach combo classification only through `preflightComboStreamResponse`, which commits the child on any text, tool call or unknown event (the Responses lifecycle preamble and the Codex WebSocket `codex.rate_limits` / `codex.response.metadata` frames are control, not output) and synthesizes a failure envelope only for a zero-output terminal. A `runTurn` adapter has the equivalent boundary in `preflightAdapterEvents`: when the first meaningful event is an undeclared tool call and no replay-unsafe heartbeat recorded a side effect, `src/server/responses/run-turn-execution.ts` checks it against the exact current request catalog and projects the existing fail-closed refusal as a pre-commit 502 so failover can continue without changing the catalog. Any earlier text, tool call, control boundary, unknown event or replay-unsafe heartbeat commits that child, so a turn whose output the client may have seen or whose side effect may have run is never replayed. A passthrough child refused by the undeclared-tool guard is the fifth target-local verdict (#9163). The guard rewrites the client stream before the preflight reads it, so it records its own trip on the attempt's log context: `onRefusal` in `src/server/responses/passthrough-delivery.ts`, and the buffered `application/json` refusal beside it, call `markUndeclaredToolGuardRefusal`. `consumeComboFailure` in `src/server/responses/core-combo-failure.ts` reads that mark after the failed body is read, and only when the consumed failure carries `undeclared_tool_call`. `comboFailureDecision` then hops and `comboFailureCooldownScope` returns `none`: the model invented the call on a healthy target. An upstream error the stream carried before the call keeps its own verdict and cooldown, the bare refusal words in an upstream body never grant the hop, and the preflight's pre-output rule above still applies, so text the client already received commits the child. Chat Completions and Messages ingress, where the guard stands down for client-owned deferred tools, and forward-auth targets never trip it. `tests/routing/combo-undeclared-tool-guard-refusal.test.ts` drives both through two-target combos. Regression coverage: `tests/responses/responses-forward-prompt-envelope.test.ts`, `tests/routing/router-combo-failover-classification.test.ts`, `tests/routing/routing-policy-fallback.test.ts`, `tests/helpers/combo-context-overflow-cases.ts`, and `tests/server/server-combo-failover-e2e.test.ts`. Every combo, routing-profile, subagent and hard-lock hop to another model or provider first passes the [fallback policy](fallback-policy.md#sites). diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 056a855a7b1..afd6f699ada 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -183,6 +183,7 @@ "combo-stream-prelude-guards.test.ts": "routing", "combo-cooldown-persistence.test.ts": "routing", "combo-unoffered-tool-refusal.test.ts": "routing", + "combo-undeclared-tool-guard-refusal.test.ts": "routing", "anthropic-revoked-token.test.ts": "adapters/anthropic", "messages-revoked-token.test.ts": "claude-integration", "anthropic-revoked-token-continuation.test.ts": "adapters/anthropic", diff --git a/tests/helpers/responses-core-source.ts b/tests/helpers/responses-core-source.ts index 02a0a0643e1..f1d60c9e167 100644 --- a/tests/helpers/responses-core-source.ts +++ b/tests/helpers/responses-core-source.ts @@ -40,6 +40,8 @@ export const RESPONSES_CORE_MODULES = [ "core-auth.ts", "core-normalize.ts", "core-combo.ts", + // Reached from core-combo.ts: the per-target send-budget scope moved out of it (#9163). + "combo-send-budget-scope.ts", // Reached from core.ts: the keepalive head a slow streaming combo selection commits (#8326). "combo-selection-keepalive.ts", "deferred-send-reporter.ts", diff --git a/tests/routing/combo-undeclared-tool-guard-refusal.test.ts b/tests/routing/combo-undeclared-tool-guard-refusal.test.ts new file mode 100644 index 00000000000..de5b9d49e94 --- /dev/null +++ b/tests/routing/combo-undeclared-tool-guard-refusal.test.ts @@ -0,0 +1,256 @@ +import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { comboProviderFactory } from "../helpers/combo-provider"; +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { markUndeclaredToolGuardRefusal } from "../../src/lib/errors"; +import { + clearComboSelectionState, + clearComboTargetCooldowns, + comboFailureCooldownScope, + comboFailureDecision, + isComboTargetInCooldown, +} from "../../src/combos"; +import { clearComboRecallForTests } from "../../src/server/responses/combo-session-recall"; +import { consumeComboFailure } from "../../src/server/responses/core-combo-failure"; +import { clearKeyCooldowns } from "../../src/providers/key-failover"; +import { clearCodexUpstreamHealth } from "../../src/codex/routing"; +import { clearRequestLogsForTests, type RequestLogContext } from "../../src/server/request-log"; +import { clearResponseStateForTests, flushResponseState } from "../../src/responses/state"; +import { + UNDECLARED_TOOL_CALL_ERROR_CODE, + undeclaredToolCallMessage, +} from "../../src/server/responses-undeclared-tool-guard"; +import type { OcxConfig } from "../../src/types"; + +const { handleResponses } = await import("../../src/server/responses"); +const { handleChatCompletions } = await import("../../src/server/chat-completions"); +const { handleClaudeMessages } = await import("../../src/server/claude-messages"); + +setDefaultTimeout(30_000); + +const refusalBody = (): string => JSON.stringify({ + error: { message: undeclaredToolCallMessage(), type: "upstream_error", code: UNDECLARED_TOOL_CALL_ERROR_CODE }, +}); +const refusalResponse = (): Response => + new Response(refusalBody(), { status: 502, headers: { "content-type": "application/json" } }); + +describe("undeclared-tool guard refusal classification (#9163)", () => { + test("the guard's provenance grants the hop and no cooldown", () => { + expect(comboFailureDecision(502, undeclaredToolCallMessage(), { + code: UNDECLARED_TOOL_CALL_ERROR_CODE, + undeclaredToolCallRefusal: true, + })).toBe("hop"); + expect(comboFailureCooldownScope(502, undeclaredToolCallMessage(), { + code: UNDECLARED_TOOL_CALL_ERROR_CODE, + undeclaredToolCallRefusal: true, + })).toBe("none"); + }); + + test("the bare refusal words alone stay terminal", () => { + // Reflected prose must never hop (#8563). At 502 a bare status hops on the generic 5xx rule, + // so the provenance gate is asserted at a request-validation status. + expect(comboFailureDecision(400, undeclaredToolCallMessage())).toBe("stop"); + expect(comboFailureDecision(400, undeclaredToolCallMessage(), { code: UNDECLARED_TOOL_CALL_ERROR_CODE })).toBe("stop"); + expect(comboFailureCooldownScope(400, undeclaredToolCallMessage())).toBe("target"); + }); + + test("an unmarked attempt that repeats the code gains nothing", async () => { + const log: RequestLogContext = { model: "combo/test", provider: "combo" }; + const failure = await consumeComboFailure(refusalResponse(), undefined, Date.now(), log); + expect(failure.upstreamCode).toBe(UNDECLARED_TOOL_CALL_ERROR_CODE); + expect(failure.undeclaredToolCallRefusal).toBeUndefined(); + }); + + test("the guard's mark on the attempt's context is the provenance", async () => { + const log: RequestLogContext = { model: "combo/test", provider: "combo" }; + markUndeclaredToolGuardRefusal(log); + const failure = await consumeComboFailure(refusalResponse(), undefined, Date.now(), log); + expect(failure.undeclaredToolCallRefusal).toBe(true); + // Another attempt's context carries nothing. + const other = await consumeComboFailure(refusalResponse(), undefined, Date.now(), { model: "combo/test", provider: "combo" } as RequestLogContext); + expect(other.undeclaredToolCallRefusal).toBeUndefined(); + }); +}); + +let testDir = ""; +let previousHome: string | undefined; +let isolatedHome: IsolatedCodexHome | null = null; +let releaseSpendHome: (() => void) | undefined; +const servers: Array> = []; +const provider = comboProviderFactory(() => undefined); + +const serve = (handler: (request: Request) => Response | Promise) => { + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: handler }); + servers.push(server); + return server; +}; +const baseUrl = (server: ReturnType) => server.url.toString().replace(/\/$/, "") + "/v1"; +const sse = (events: unknown[]) => new Response( + events.map(event => "event: " + (event as { type: string }).type + "\ndata: " + JSON.stringify(event) + "\n\n").join(""), + { headers: { "content-type": "text/event-stream" } }, +); +const success = (text: string, model: string) => ({ + id: "resp-" + model, object: "response", status: "completed", model, + output: [{ id: "msg_b", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] }], + usage: { input_tokens: 2, output_tokens: 1, total_tokens: 3 }, +}); +const call = (id: string, name: string) => ({ type: "function_call", id, call_id: "c_" + id, name, arguments: "" }); +const callOnly = (name: string): unknown[] => [ + { type: "response.created", response: { id: "r1", status: "in_progress" } }, + { type: "response.output_item.added", output_index: 0, item: call("fc_9", name) }, + { type: "response.function_call_arguments.delta", item_id: "fc_9", output_index: 0, delta: "{}" }, + { type: "response.output_item.done", output_index: 0, item: { ...call("fc_9", name), arguments: "{}", status: "completed" } }, + { type: "response.completed", response: { ...success("x", "m1"), output: [{ ...call("fc_9", name), arguments: "{}", status: "completed" }] } }, +]; +const textThenUndeclared: unknown[] = [ + { type: "response.created", response: { id: "r1", status: "in_progress" } }, + { type: "response.output_text.delta", delta: "visible", item_id: "msg_a", output_index: 0, content_index: 0 }, + { type: "response.output_item.added", output_index: 1, item: call("fc_9", "code_runner/bash") }, + { type: "response.completed", response: { ...success("x", "m1"), output: [] } }, +]; + +function comboConfig(firstTarget: unknown[], targets: 1 | 2, hits: string[], streamMode?: string): OcxConfig { + const a = serve(() => { hits.push("a"); return sse(firstTarget); }); + const b = serve(() => { hits.push("b"); return sse([{ type: "response.completed", response: success("BACKUP_OK", "m2") }]); }); + const all = [{ provider: "a", model: "m1" }, { provider: "b", model: "m2" }]; + return { + port: 0, + defaultProvider: "a", + providers: { a: provider("openai-responses", baseUrl(a), "key-a"), b: provider("openai-responses", baseUrl(b), "key-b") }, + combos: { free: { strategy: "failover", targets: all.slice(0, targets) } }, + ...(streamMode ? { streamMode } : {}), + } as OcxConfig; +} +const firstTargetCooled = () => isComboTargetInCooldown("free", { provider: "a", model: "m1" }); + +describe("combo hop on the undeclared-tool guard's refusal (#9163)", () => { + beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + isolatedHome = installIsolatedCodexHome("ocx-undeclared-hop-"); + testDir = mkdtempSync(join(tmpdir(), "ocx-undeclared-hop-")); + process.env.OPENCODEX_HOME = testDir; + releaseSpendHome = acquireOwnedSpendHome(); + clearComboSelectionState(); + clearComboRecallForTests(); + clearComboTargetCooldowns(); + clearKeyCooldowns(); + clearCodexUpstreamHealth(); + clearRequestLogsForTests(); + clearResponseStateForTests(); + }); + + afterEach(async () => { + releaseSpendHome?.(); + for (const server of servers.splice(0)) await server.stop(true); + await flushResponseState(); + clearResponseStateForTests(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + isolatedHome?.restore(); + if (testDir) removeTreeWithRetry(testDir); + clearComboSelectionState(); + clearComboTargetCooldowns(); + }); + + const responsesRequest = (stream: boolean) => new Request("http://localhost/v1/responses", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/free", input: "hi", stream, tools: [{ type: "function", name: "exec", parameters: { type: "object" } }] }), + }); + + for (const streamMode of [undefined, "eager-relay", "legacy-tee"] as const) for (const stream of [true, false]) { + test(`Responses: a refused undeclared call advances without cooling the target (streamMode=${streamMode ?? "auto"}, stream=${stream})`, async () => { + const hits: string[] = []; + const config = comboConfig(callOnly("code_runner/bash"), 2, hits, streamMode); + const response = await handleResponses(responsesRequest(stream), config, { model: "", provider: "" }); + const body = await response.text(); + expect(hits).toEqual(["a", "b"]); + expect(body).toContain("BACKUP_OK"); + expect(body).not.toContain("code_runner/bash"); + // The model invented the call on a healthy target: the hop must not quarantine it. + expect(firstTargetCooled()).toBe(false); + }); + } + + // The buffered application/json refusal branch never runs the SSE block rewrite, so its + // provenance must be marked directly: a primary answering non-streaming JSON with an + // undeclared call still hops without cooling the target (#9163). + for (const stream of [true, false] as const) { + test(`Responses: a buffered JSON undeclared call advances without cooling the target (stream=${stream})`, async () => { + const hits: string[] = []; + const refusedJson = () => new Response(JSON.stringify({ ...success("x", "m1"), output: [{ ...call("fc_9", "code_runner/bash"), arguments: "{}", status: "completed" }] }), { headers: { "content-type": "application/json" } }); + const a = serve(() => { hits.push("a"); return refusedJson(); }); + const b = serve(() => { hits.push("b"); return new Response(JSON.stringify(success("BACKUP_OK", "m2")), { headers: { "content-type": "application/json" } }); }); + const config = { + port: 0, + defaultProvider: "a", + providers: { a: provider("openai-responses", baseUrl(a), "key-a"), b: provider("openai-responses", baseUrl(b), "key-b") }, + combos: { free: { strategy: "failover", targets: [{ provider: "a", model: "m1" }, { provider: "b", model: "m2" }] } }, + } as OcxConfig; + const response = await handleResponses(responsesRequest(stream), config, { model: "", provider: "" }); + const body = await response.text(); + expect(hits).toEqual(["a", "b"]); + expect(body).toContain("BACKUP_OK"); + expect(body).not.toContain("code_runner/bash"); + expect(firstTargetCooled()).toBe(false); + }); + } + + test("Responses: an upstream error before an undeclared call keeps its own cooldown", async () => { + // The guard trips on the later call, but the failure the combo judges is the upstream's own + // rate-limit error: that verdict, not the guard's, decides the cooldown. + const hits: string[] = []; + const config = comboConfig([ + { type: "response.created", response: { id: "r1", status: "in_progress" } }, + { type: "error", error: { type: "rate_limit_error", code: "rate_limit_exceeded", message: "Rate limit reached" } }, + { type: "response.output_item.added", output_index: 0, item: call("fc_9", "code_runner/bash") }, + ], 2, hits); + const response = await handleResponses(responsesRequest(true), config, { model: "", provider: "" }); + const body = await response.text(); + expect(hits).toEqual(["a", "b"]); + expect(body).toContain("BACKUP_OK"); + expect(firstTargetCooled()).toBe(true); + }); + + test("Responses: text the client already received keeps the child committed", async () => { + const hits: string[] = []; + const config = comboConfig(textThenUndeclared, 2, hits); + const response = await handleResponses(responsesRequest(true), config, { model: "", provider: "" }); + const body = await response.text(); + expect(hits).toEqual(["a"]); + expect(body).toContain("visible"); + expect(body).not.toContain("BACKUP_OK"); + }); + + for (const wire of ["chat", "messages"] as const) for (const targets of [1, 2] as const) for (const stream of [true, false]) { + test(`${wire}: a deferred tool the client registry owns is delivered, not refused (targets=${targets}, stream=${stream})`, async () => { + // Chat and Messages clients may defer tools to their own registry, so the guard stands down + // on these wires and the combo must not refuse or reroute the call either. + const hits: string[] = []; + const config = comboConfig(callOnly("deferred_tool"), targets, hits); + const request = wire === "chat" + ? new Request("http://localhost/v1/chat/completions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/free", stream, messages: [{ role: "user", content: "hi" }], tools: [{ type: "function", function: { name: "exec", parameters: { type: "object", properties: {} } } }] }), + }) + : new Request("http://localhost/v1/messages", { + method: "POST", + headers: { "content-type": "application/json", "anthropic-version": "2023-06-01" }, + body: JSON.stringify({ model: "combo/free", stream, max_tokens: 100, messages: [{ role: "user", content: "hi" }], tools: [{ name: "exec", input_schema: { type: "object", properties: {} } }] }), + }); + const log = { model: "", provider: "" } as never; + const response = wire === "chat" ? await handleChatCompletions(request, config, log) : await handleClaudeMessages(request, config, log); + const body = await response.text(); + expect(response.status).toBe(200); + expect(hits).toEqual(["a"]); + expect(body).toContain("deferred_tool"); + expect(body).not.toContain(UNDECLARED_TOOL_CALL_ERROR_CODE); + }); + } +}); + From bee5c226a38233f73103154e34b39d342bcbf094 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:26:47 +0900 Subject: [PATCH 33/64] fix(service): warn on a foreground start when the managed service is not serving (#9198) * fix(service): warn on a foreground start when the managed service is not serving Carries #9006 onto current dev with maintainer review fixes: - Extract foreground advisory eligibility/launch/teardown to src/service/foreground-advisory-process.ts so src/cli/index.ts stays under the 2000-line file-size ratchet (1998 lines). - Use Windows Job Object containment (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + TerminateJobObject) and handle-bound native termination (windowsProcessNative().terminate(pid, ticks)) for both root and read-only CIM snapshotted descendants, eliminating bare-PID taskkill / Stop-Process PID-reuse races. - Add deterministic regression tests for eligibility guards, spaces-in-path launch, Job Object containment, root/descendant PID-reuse races, exited-root stdout close + synchronous exit retry, and unavailable native API fallback. Co-authored-by: lcxhh <59329914+lcxhh521@users.noreply.github.com> * fix(service): use pre-resume Windows Job containment via startWindowsCliChild * fix(service): guard stop after Windows job handle disposal * fix(service): retain Windows job handle ownership when TerminateJobObject fails * fix(service): enable Windows kill-on-job-close and backoff handle settlement * fix(service): arm Windows kill-on-job-close before CreateProcessW * fix(service): retain failed-setup Windows process handle until signaled terminal * fix(service): bind kill-on-close Windows job atomically via PROC_THREAD_ATTRIBUTE_JOB_LIST * test(service): bind stopForegroundAdvisory in syncCleanup/shutdown source-slice fixtures --------- Co-authored-by: lcxhh <59329914+lcxhh521@users.noreply.github.com> --- .../content/docs/reference/cli/lifecycle.md | 4 + scripts/test-layout/layout.json | 2 +- src/cli/index.ts | 6 +- src/codex/windows-cli-child-native.ts | 3 +- src/codex/windows-cli-child.ts | 28 +- src/service.ts | 2 +- src/service/diagnostics.ts | 33 + src/service/foreground-advisory-process.ts | 413 +++++++++ structure/codex-cli-update.md | 7 +- structure/runtime.md | 2 +- tests/fixtures/api-stop-exit-runner.ts | 1 + tests/fixtures/parent-stop-runner.ts | 1 + tests/fixtures/test-layout-expected.json | 2 +- .../foreground-start-service-advisory.test.ts | 834 ++++++++++++++++++ tests/service/shutdown-drain.test.ts | 1 + 15 files changed, 1327 insertions(+), 12 deletions(-) create mode 100644 src/service/foreground-advisory-process.ts create mode 100644 tests/service/foreground-start-service-advisory.test.ts diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index bd49dee32cf..3ce2fab37d6 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -71,6 +71,10 @@ local port where no opencodex has answered for about 20 seconds (an instance tha then died, for example), the proxy re-points Codex at its own port and prints one warning. Codex threads opened in the meantime keep the dead address until you reopen them. +An interactive foreground start may show an advisory about an installed managed service after the +proxy is ready. The check does not block requests; an inconclusive result points to `ocx status`. +The foreground proxy is not supervised, and the advisory never repairs or restarts a service. + `--socks5` (default `127.0.0.1:10808`) saves `config.proxy` as a SOCKS5 URL and routes outbound HTTP(S) through a real SOCKS5 tunnel. `--socks5-off` clears only that saved SOCKS5 proxy; it does not remove an HTTP proxy. The value survives `ocx update` because it lives in config, not in diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 49371cea65b..bffb030fa9d 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1164,7 +1164,7 @@ "lab-public-wire-contract.test.ts": "lab", "lab-read-filter-validation.test.ts": "lab", "lab-read-surfaces.test.ts": "lab", - "launchd-port-fallback.test.ts": "service", "launchd-repair.test.ts": "service", + "launchd-port-fallback.test.ts": "service", "launchd-repair.test.ts": "service", "foreground-start-service-advisory.test.ts": "service", "legacy-shell-compat.test.ts": "responses", "live-call-bindings.test.ts": "server", "live-native-calls.test.ts": "server", "live-service-manager-guard.test.ts": "service", diff --git a/src/cli/index.ts b/src/cli/index.ts index 90fda75454d..9e8a34ec936 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -214,6 +214,7 @@ async function refreshOwnedRaycastCatalog( } } +if (process.argv[2] === "__foreground-service-advisory") process.exit(await (await import("../service/foreground-advisory-process")).runForegroundAdvisoryEntrypoint()); if (process.argv[2] === "__update-orchestrated-identity") process.exit(await (await import("../update/orchestrated-identity-probe-entry")).runIdentityProbe(process.argv.slice(2))); if (process.argv[2] === "start" && process.env.OCX_SERVICE) startServiceLogging(join(getConfigDir(), "service.log")); const updateRestartChild = admitUpdateRestartChild(process.argv.slice(2)); @@ -641,11 +642,13 @@ async function handleStart(options: { block?: boolean } = {}) { let routingHealer: { stop(): void } | undefined; // routing-healer.ts; stopped first in syncCleanup let catalogHealer: { stop(): void } | undefined; + let stopForegroundAdvisory: ((sync?: boolean) => void) | undefined; let cleaned = false; let cleanupSucceeded = true; const syncCleanup = () => { if (cleaned) return cleanupSucceeded; cleaned = true; + stopForegroundAdvisory?.(true); try { catalogHealer?.stop(); } catch { /* best-effort */ } try { routingHealer?.stop(); } catch { /* best-effort */ } try { guardian.stop(); } catch { /* best-effort */ } @@ -702,7 +705,7 @@ async function handleStart(options: { block?: boolean } = {}) { try { syncCleanup(); } catch { /* best-effort */ } process.exit(130); } - shuttingDown = true; + shuttingDown = true; stopForegroundAdvisory?.(); shutdownStartedAt = now; noteExplicitShutdownRequested(); // an automatic package restart must not hand off after this console.log("\n🛑 Shutting down opencodex proxy..."); @@ -797,6 +800,7 @@ async function handleStart(options: { block?: boolean } = {}) { console.error(`⚠️ ${grokSyncFailureMessage(err)}`); } console.log("Client startup work complete."); + stopForegroundAdvisory = (await import("../service/foreground-advisory-process")).maybeStartForegroundAdvisory({ cleaned, shuttingDown, siblingStart, ownerLive: Boolean(owner.live), supervisedServiceChild, restartParentPid: restartParent.restartParentPid, stderrIsTTY: process.stderr?.isTTY }, line => console.warn(line)); if (options.block ?? true) { setInterval(() => {}, 60_000); await new Promise(() => {}); diff --git a/src/codex/windows-cli-child-native.ts b/src/codex/windows-cli-child-native.ts index d2220aa61f7..a0bb2c2fb78 100644 --- a/src/codex/windows-cli-child-native.ts +++ b/src/codex/windows-cli-child-native.ts @@ -4,7 +4,7 @@ import { dlopen, ptr, read, type Library, type Symbols } from "bun:ffi"; export const WIN64_CHILD_ABI = Object.freeze({ securityAttributes: 24, securityDescriptor: 8, inheritHandle: 16, startupInfo: 104, startupInfoEx: 112, startupFlags: 60, stdin: 80, stdout: 88, stderr: 96, attributes: 104, processInformation: 24, process: 0, thread: 8, pid: 16, tid: 20, - overlapped: 32, event: 24, jobAccounting: 48, activeProcesses: 40 }); + overlapped: 32, event: 24, jobAccounting: 48, activeProcesses: 40, jobExtendedLimit: 144, jobLimitFlags: 16 }); const KERNEL = { GetLastError: { args: [], returns: "u32" }, SetLastError: { args: ["u32"], returns: "void" }, @@ -13,6 +13,7 @@ const KERNEL = { GetCurrentProcess: { args: [], returns: "u64" }, CompareStringOrdinal: { args: ["ptr", "i32", "ptr", "i32", "i32"], returns: "i32" }, CreateJobObjectW: { args: ["ptr", "ptr"], returns: "u64" }, + SetInformationJobObject: { args: ["u64", "i32", "ptr", "u32"], returns: "i32" }, AssignProcessToJobObject: { args: ["u64", "u64"], returns: "i32" }, QueryInformationJobObject: { args: ["u64", "i32", "ptr", "u32", "ptr"], returns: "i32" }, TerminateJobObject: { args: ["u64", "u32"], returns: "i32" }, diff --git a/src/codex/windows-cli-child.ts b/src/codex/windows-cli-child.ts index 8c272682774..6b7046bd760 100644 --- a/src/codex/windows-cli-child.ts +++ b/src/codex/windows-cli-child.ts @@ -22,6 +22,8 @@ export interface WindowsCliChildInvocation { /** Private durable recovery identity, selected before native creation. */ readonly recoveryJobName?: string; readonly recoveryProof?: CodexCliUpdateNativeRecoveryProof; + /** Opt-in JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, applied before CreateProcessW. Incompatible with recoveryJobName. */ + readonly killOnJobClose?: boolean; } export interface WindowsCliChildResult { readonly terminal: boolean; @@ -44,6 +46,7 @@ function validate(invocation: WindowsCliChildInvocation): void { || !localAbsolute(invocation.cwd) || !Array.isArray(invocation.args) || invocation.args.some(arg => typeof arg !== "string" || arg.includes("\0")) || !windowsCliChildPolicy(invocation.policy) + || (invocation.killOnJobClose && invocation.recoveryJobName !== undefined) || (invocation.recoveryJobName !== undefined && !/^Global\\ocx-cli-[0-9a-f-]{36}$/.test(invocation.recoveryJobName))) throw new Error("windows_child_invalid_invocation"); } function environmentBlock(env: Readonly, native: WindowsChildNative): Buffer { @@ -183,7 +186,7 @@ export function startWindowsCliChildWithNative(invocation: WindowsCliChildInvoca validate(invocation); const child = new WindowsCliChild(native, invocation.policy), k = native.k; let stdin = 0n, stderr = 0n, thread = 0n, attributes: Buffer | undefined, initialized = false; - let inheritedHandles: Buffer | undefined; + let inheritedHandles: Buffer | undefined, jobList: Buffer | undefined; try { if (invocation.recoveryJobName) { const name = wide(invocation.recoveryJobName), descriptor = native.privateDescriptor(); @@ -195,21 +198,37 @@ export function startWindowsCliChildWithNative(invocation: WindowsCliChildInvoca if (k.GetLastError!() === 183) throw new Error("windows_child_job_exists"); } finally { k.LocalFree!(descriptor); } } else child.job = native.keep(k.CreateJobObjectW!(null, null)); + if (invocation.killOnJobClose) { + const limits = Buffer.alloc(WIN64_CHILD_ABI.jobExtendedLimit); + limits.writeUInt32LE(0x2000, WIN64_CHILD_ABI.jobLimitFlags); // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + if (!k.SetInformationJobObject!(child.job, 9, ptr(limits), limits.length)) throw new Error("job_kill_on_close"); + } child.pipe.open(); const inheritable = securityAttributes(true), nul = wide("NUL"); stdin = native.keep(k.CreateFileW!(ptr(nul), 0x80000000, 3, ptr(inheritable), 3, 0, 0n)); stderr = native.keep(k.CreateFileW!(ptr(nul), 0x40000000, 3, ptr(inheritable), 3, 0, 0n)); const handles = inheritedHandles = Buffer.alloc(24); [stdin, child.pipe.child, stderr].forEach((handle, index) => handles.writeBigUInt64LE(handle, index * 8)); + const attrCount = invocation.killOnJobClose ? 2 : 1; const size = Buffer.alloc(8); - k.InitializeProcThreadAttributeList!(null, 1, 0, ptr(size)); + k.InitializeProcThreadAttributeList!(null, attrCount, 0, ptr(size)); const length = Number(size.readBigUInt64LE()); if (length < 24 || length > 1024 * 1024) throw new Error("attribute_size"); attributes = Buffer.alloc(length); native.borrowedMemory.add(attributes); native.borrowedMemory.add(handles); - if (!k.InitializeProcThreadAttributeList!(ptr(attributes), 1, 0, ptr(size))) throw new Error("attribute_init"); + if (!k.InitializeProcThreadAttributeList!(ptr(attributes), attrCount, 0, ptr(size))) throw new Error("attribute_init"); initialized = true; if (!k.UpdateProcThreadAttribute!(ptr(attributes), 0, 0x20002n, ptr(handles), 24n, null, null)) throw new Error("attribute_handles"); + if (invocation.killOnJobClose) { + jobList = Buffer.alloc(8); + jobList.writeBigUInt64LE(child.job, 0); + native.borrowedMemory.add(jobList); + // PROC_THREAD_ATTRIBUTE_JOB_LIST (0x2000D): atomically assigns the process to child.job + // inside CreateProcessW so no unassigned process can ever exist even if later setup fails. + if (!k.UpdateProcThreadAttribute!(ptr(attributes), 0, 0x2000dn, ptr(jobList), 8n, null, null)) { + throw new Error("attribute_job_list"); + } + } const startup = Buffer.alloc(WIN64_CHILD_ABI.startupInfoEx), info = Buffer.alloc(WIN64_CHILD_ABI.processInformation); startup.writeUInt32LE(startup.length); startup.writeUInt32LE(0x100, 60); [stdin, child.pipe.child, stderr].forEach((handle, index) => startup.writeBigUInt64LE(handle, 80 + index * 8)); @@ -230,7 +249,7 @@ export function startWindowsCliChildWithNative(invocation: WindowsCliChildInvoca if (!k.GetProcessTimes!(child.process, ptr(creation), ptr(exit), ptr(kernel), ptr(user))) throw new Error("process_times"); child.creationTime = creation.readBigUInt64LE().toString(); if (child.creationTime === "0") throw new Error("process_creation_time_unknown"); - if (!k.AssignProcessToJobObject!(child.job, child.process)) throw new Error("job_assignment"); + if (!invocation.killOnJobClose && !k.AssignProcessToJobObject!(child.job, child.process)) throw new Error("job_assignment"); if (invocation.recoveryProof) child.recoveryGuardian = startWindowsCliRecoveryGuardian(native, child.job, invocation.recoveryProof, invocation.cwd); if (Number(k.ResumeThread!(thread)) !== 1) throw new Error("resume_thread"); } catch (error) { @@ -240,6 +259,7 @@ export function startWindowsCliChildWithNative(invocation: WindowsCliChildInvoca if (initialized) k.DeleteProcThreadAttributeList!(ptr(attributes!)); if (attributes) native.borrowedMemory.delete(attributes); if (inheritedHandles) native.borrowedMemory.delete(inheritedHandles); + if (jobList) native.borrowedMemory.delete(jobList); child.pipe.closeChild(); if (stdin) native.close(stdin); if (stderr) native.close(stderr); if (thread) native.close(thread); } diff --git a/src/service.ts b/src/service.ts index da13da0eb5a..654183a1ddb 100644 --- a/src/service.ts +++ b/src/service.ts @@ -33,6 +33,6 @@ export { serviceChildOwnershipDecision, serviceChildStayOutExitCode } from "./se export type { ServiceInstallPreparationDeps, FreshWindowsSchedulerInstallDeps, ServiceStopOutcome, ServiceUninstallOutcome } from "./service/orchestration"; export { proxyStillLiveAfterStop, prepareServiceInstall, installServiceSafely, installFreshWindowsSchedulerSafely, installedServiceRespawnRisk, stopServiceIfInstalledDetailed, stopServiceIfInstalledReport, setUninstallServiceHooksForTests, uninstallServiceDetailed, uninstallServiceIfInstalled, isServiceInstalled, isServiceViable } from "./service/orchestration"; export type { ServiceDiagnostic, WindowsTaskDiagnosticIdentityDeps, WindowsServiceDiagnosticInputs, LaunchdServiceDiagnosticInputs } from "./service/diagnostics"; -export { bakedServicePathsDiagnostic, serviceStartableFromTray, resolveWindowsTaskDiagnosticUserId, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, deriveLaunchdServiceDiagnostic, diagnoseService, serviceStatusSummary, serviceStatusReport } from "./service/diagnostics"; +export { bakedServicePathsDiagnostic, warnForegroundStartService, serviceStartableFromTray, resolveWindowsTaskDiagnosticUserId, deriveWindowsServiceDiagnostic, deriveWindowsServiceDiagnosticForCurrentUser, deriveLaunchdServiceDiagnostic, diagnoseService, serviceStatusSummary, serviceStatusReport } from "./service/diagnostics"; export type { ParsedServiceArgs, ServiceInstallationState, ServiceInstallationProbe, ServiceInstallationProbeHooks, ServiceCommandPlan } from "./service/cli"; export { normalizeServiceSubcommand, probeServiceInstallation, selectServiceSubcommand, planServiceCommand, parseServiceArgs, serviceCommand } from "./service/cli"; diff --git a/src/service/diagnostics.ts b/src/service/diagnostics.ts index d6d822d4c9c..a7d6cdf6f9d 100644 --- a/src/service/diagnostics.ts +++ b/src/service/diagnostics.ts @@ -61,6 +61,8 @@ export interface ServiceDiagnostic { conflict: boolean; backend: ServiceBackend | "launchd" | "systemd" | null; summary: string; + /** Set only by a backend that positively verified a stopped registration. */ + confirmedStopped?: boolean; } /** Windows tray may restart a healthy-but-stopped native service; stale/conflicting installs remain blocked. */ @@ -236,6 +238,7 @@ export function deriveLaunchdServiceDiagnostic(inputs: LaunchdServiceDiagnosticI conflict: false, backend: "launchd", summary, + ...(installed && load.state === "not-loaded" ? { confirmedStopped: true } : {}), }; } @@ -287,6 +290,36 @@ export function diagnoseService(): ServiceDiagnostic { return { supported: false, installed: false, enabled: false, running: false, viable: false, startable: false, stale: false, conflict: false, backend: null, summary: `unsupported on ${process.platform}` }; } +/** + * Only verified stops may suggest repair. Inconclusive backend diagnostics can include + * recovery instructions themselves; never echo that summary in the unknown branch. + */ +export function foregroundStartServiceAdvisoryLines(service: ServiceDiagnostic): readonly string[] { + if (!service.supported || !service.installed || service.running || service.conflict) return []; + if (!service.confirmedStopped) { + return [ + "⚠️ Could not confirm that the managed background service is serving.", + " This foreground proxy does not verify supervision; check 'ocx status' for service details.", + ]; + } + return [ + `⚠️ The managed background service is not loaded (${service.summary}).`, + " This foreground proxy ends with this terminal and nothing restarts it. After stopping it, consider 'ocx service repair' to restore the supervised service.", + ]; +} + +/** Best effort, not asynchronous: a diagnostic or warning failure must not affect the foreground proxy. */ +export function warnForegroundStartService( + probe: () => ServiceDiagnostic, + warn: (line: string) => void, +): void { + try { + for (const line of foregroundStartServiceAdvisoryLines(probe())) warn(line); + } catch { + // Diagnostics are advisory only. + } +} + export interface SystemdServiceDiagnosticInputs { installed: boolean; enabled: boolean; diff --git a/src/service/foreground-advisory-process.ts b/src/service/foreground-advisory-process.ts new file mode 100644 index 00000000000..62fa678c7e4 --- /dev/null +++ b/src/service/foreground-advisory-process.ts @@ -0,0 +1,413 @@ +import { spawn } from "node:child_process"; +import { startWindowsCliChild, type WindowsCliChild } from "../codex/windows-cli-child"; +import { selfLaunchArgv } from "../lib/self-launch-argv"; + +export const FOREGROUND_ADVISORY_ARG = "__foreground-service-advisory"; +const TIMEOUT_MS = 3_000; +const REAP_MS = 1_000; +const POLL_MS = 5; +const SETTLE_POLL_MS = 250; +const MAX_BYTES = 8_192; + +export interface ForegroundAdvisoryEligibility { + cleaned: boolean; + shuttingDown: boolean; + siblingStart: boolean; + ownerLive: boolean; + supervisedServiceChild: boolean; + restartParentPid: number | null; + stderrIsTTY: boolean | undefined; +} + +export interface ContainedWindowsAdvisoryChild { + readonly setupFailure: string | null; + readonly job: bigint; + readonly process: bigint; + readonly pipe: { + readonly eof: boolean; + readonly error: boolean; + pump(onBytes: (chunk: Buffer) => void): void; + dispose(): Promise; + }; + readonly native: { + readonly k: { + TerminateJobObject?: (job: bigint, code: number) => number; + WaitForSingleObject?: (handle: bigint, ms: number) => number; + }; + close(handle: bigint): void; + dispose(): boolean; + }; + observe(): { terminal: boolean; exitCode: number | null; unknown: boolean }; + reapUnstarted(): boolean; +} + +export interface ForegroundAdvisoryDeps { + /** POSIX probe launcher override for tests. */ + launch?: () => ReturnType; + /** + * Windows pre-resume Job-contained launcher override for tests. Defaults to + * `startWindowsCliChild` with `killOnJobClose: true`, which configures + * `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` and `PROC_THREAD_ATTRIBUTE_JOB_LIST` before + * `CreateProcessW` (atomic job assignment at process creation) so no unassigned or + * unprotected process can exist even if setup fails before `ResumeThread`. + */ + launchWindows?: () => ContainedWindowsAdvisoryChild; + timeoutMs?: number; + reapMs?: number; + pollMs?: number; + settlePollMs?: number; + platform?: NodeJS.Platform; +} + +export type StopForegroundAdvisory = (sync?: boolean) => void; + +/** True only for an eligible interactive foreground owner after readiness. */ +export function shouldStartForegroundAdvisory(state: ForegroundAdvisoryEligibility): boolean { + return !state.cleaned + && !state.shuttingDown + && !state.siblingStart + && !state.ownerLive + && !state.supervisedServiceChild + && state.restartParentPid === null + && Boolean(state.stderrIsTTY); +} + +/** Start the background advisory probe only when foreground eligibility holds. */ +export function maybeStartForegroundAdvisory( + state: ForegroundAdvisoryEligibility, + warn: (line: string) => void, + deps?: ForegroundAdvisoryDeps, +): StopForegroundAdvisory | undefined { + if (!shouldStartForegroundAdvisory(state)) return undefined; + return startForegroundAdvisory(warn, deps); +} + +/** Private child entrypoint executed by `startForegroundAdvisory`. */ +export async function runForegroundAdvisoryEntrypoint(): Promise { + const { diagnoseService, foregroundStartServiceAdvisoryLines } = await import("./diagnostics"); + let lines: readonly string[] = []; + try { lines = foregroundStartServiceAdvisoryLines(diagnoseService()); } catch { /* best effort */ } + // Await the write, so an explicit CLI exit cannot truncate the pipe. + await new Promise((resolve, reject) => + process.stdout.write(JSON.stringify(lines), error => error ? reject(error) : resolve()), + ); + return 0; +} + +function publishAdvisoryOutput(raw: string, warn: (line: string) => void): void { + try { + const lines: unknown = JSON.parse(raw); + if (!Array.isArray(lines) || lines.length > 2 || !lines.every(line => typeof line === "string")) return; + for (const line of lines) warn(line); + } catch { /* optional output */ } +} + +function disposeWindowsHandlesAsync(child: ContainedWindowsAdvisoryChild): void { + void child.pipe.dispose().then(() => { + if (child.process) child.native.close(child.process); + if (child.job) child.native.close(child.job); + child.native.dispose(); + }).catch(() => { /* best-effort async handle cleanup */ }); +} + +function isWindowsProcessSignaled(child: ContainedWindowsAdvisoryChild): boolean { + if (!child.process) return true; + try { + return Number(child.native.k.WaitForSingleObject?.(child.process, 0)) === 0; + } catch { + return false; + } +} + +function reapFailedSetupWindowsChild( + child: ContainedWindowsAdvisoryChild, + pollMs: number, + reapMs: number, + settlePollMs: number, +): StopForegroundAdvisory { + if (!child.process) { + disposeWindowsHandlesAsync(child); + return () => { /* setup failed before CreateProcessW; nothing running */ }; + } + + let disposed = false; + let pollTimer: ReturnType | undefined; + const startedAt = performance.now(); + + const clearPoll = () => { + if (pollTimer !== undefined) { + clearTimeout(pollTimer); + pollTimer = undefined; + } + }; + + const finalizeAsync = () => { + if (disposed) return; + disposed = true; + clearPoll(); + disposeWindowsHandlesAsync(child); + }; + + const tryReap = (): boolean => { + if (disposed) return true; + if (isWindowsProcessSignaled(child)) return true; + try { child.reapUnstarted(); } catch { /* retry until process handle signals */ } + if (isWindowsProcessSignaled(child)) return true; + if (child.job) { + try { child.native.k.TerminateJobObject?.(child.job, 1); } catch { /* kernel kill-on-close backs up exit */ } + } + return isWindowsProcessSignaled(child); + }; + + const schedulePoll = (delayMs: number) => { + if (disposed) return; + clearPoll(); + pollTimer = setTimeout(tick, delayMs); + pollTimer.unref(); + }; + + const tick = () => { + pollTimer = undefined; + if (disposed) return; + if (tryReap()) { + finalizeAsync(); + return; + } + schedulePoll(performance.now() - startedAt >= reapMs ? settlePollMs : pollMs); + }; + + // Check WaitForSingleObject first: startWindowsCliChild's catch block already ran reapUnstarted() + // once, and a second TerminateProcess on an already-terminated process can return false. + // Gate handle disposal strictly on WaitForSingleObject(child.process, 0) === 0, retaining the + // original process handle and retrying reapUnstarted() until termination is confirmed. + if (tryReap()) { + finalizeAsync(); + return () => { /* failed-setup process already confirmed terminal and disposed */ }; + } + + schedulePoll(pollMs); + return (sync = false) => { + if (disposed) return; + if (tryReap()) { + if (sync) { + clearPoll(); + disposed = true; + } else { + finalizeAsync(); + } + return; + } + if (sync) { + clearPoll(); + return; + } + if (pollTimer === undefined) schedulePoll(pollMs); + }; +} + +function startWindowsContainedAdvisory( + warn: (line: string) => void, + deps: ForegroundAdvisoryDeps, +): StopForegroundAdvisory { + const timeoutMs = deps.timeoutMs ?? TIMEOUT_MS; + const reapMs = deps.reapMs ?? REAP_MS; + const pollMs = deps.pollMs ?? POLL_MS; + const settlePollMs = deps.settlePollMs ?? SETTLE_POLL_MS; + const expires = performance.now() + timeoutMs; + + let child: ContainedWindowsAdvisoryChild; + try { + child = (deps.launchWindows ?? ((): WindowsCliChild => startWindowsCliChild({ + executable: process.execPath, + args: selfLaunchArgv([FOREGROUND_ADVISORY_ARG]), + cwd: process.cwd(), + env: process.env, + policy: "version", + killOnJobClose: true, + })))(); + } catch { + // Fail closed when kernel Job Object containment is unavailable (e.g. Windows ARM64): + // never launch an uncontained probe or fall back to PID-only termination. + return () => { /* containment unavailable; no probe was started */ }; + } + + if (child.setupFailure || !child.process || !child.job) { + return reapFailedSetupWindowsChild(child, pollMs, reapMs, settlePollMs); + } + + let settled = false; + let terminated = false; + let disposed = false; + let stopAt: number | null = null; + let bytes = 0; + const chunks: Buffer[] = []; + let pollTimer: ReturnType | undefined; + + const clearPoll = () => { + if (pollTimer !== undefined) { + clearTimeout(pollTimer); + pollTimer = undefined; + } + }; + + const finalizeAsync = () => { + if (disposed) return; + disposed = true; + clearPoll(); + disposeWindowsHandlesAsync(child); + }; + + const terminateJob = (): boolean => { + if (disposed || terminated) return true; + let ok = false; + try { ok = Boolean(child.native.k.TerminateJobObject?.(child.job, 1)); } catch { ok = false; } + if (ok) terminated = true; + return ok; + }; + + const schedulePoll = (delayMs = pollMs) => { + if (disposed) return; + clearPoll(); + pollTimer = setTimeout(tick, delayMs); + pollTimer.unref(); + }; + + const stop: StopForegroundAdvisory = (sync = false) => { + if (disposed) return; + settled = true; + const ok = terminateJob(); + if (sync) { + // Synchronous exit path: stop any pending timer. JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + // was armed on child.job before CreateProcessW/ResumeThread, so Windows terminates the + // entire probe tree on parent exit even if TerminateJobObject returned false; retain + // child.job open until process exit when termination was not confirmed. + clearPoll(); + if (ok) disposed = true; + return; + } + stopAt ??= performance.now(); + if (!disposed && pollTimer === undefined) schedulePoll(); + }; + + const tick = () => { + pollTimer = undefined; + if (disposed) return; + try { + child.pipe.pump(chunk => { + if (settled) return; + bytes += chunk.length; + if (bytes > MAX_BYTES) { + stop(false); + return; + } + chunks.push(Buffer.from(chunk)); + }); + } catch { + stop(false); + } + + let observed: { terminal: boolean; exitCode: number | null; unknown: boolean }; + try { + observed = child.observe(); + } catch { + observed = { terminal: false, exitCode: null, unknown: true }; + } + + if (observed.terminal && (settled || child.pipe.eof)) { + const shouldPublish = !settled && observed.exitCode === 0 && performance.now() < expires; + settled = true; + finalizeAsync(); + if (shouldPublish) { + publishAdvisoryOutput(Buffer.concat(chunks).toString("utf8"), warn); + } + return; + } + + if (observed.unknown || child.pipe.error) { + stop(false); + } + + const now = performance.now(); + if (!settled && now >= expires) { + stop(false); + } + if (stopAt !== null) { + // Slow-to-settle job or failed termination: never leak handles by abandoning polling, and + // never close child.job while nonterminal. Retry TerminateJobObject if needed, backing off + // to an unreferenced poll interval after reapMs until the job is observed terminal. + if (!terminated) terminateJob(); + schedulePoll(now - stopAt >= reapMs ? settlePollMs : pollMs); + return; + } + schedulePoll(pollMs); + }; + + schedulePoll(); + return stop; +} + +/** Run an optional OS diagnostic without blocking the listener or keeping the CLI alive. */ +export function startForegroundAdvisory( + warn: (line: string) => void, + deps: ForegroundAdvisoryDeps = {}, +): StopForegroundAdvisory { + const platform = deps.platform ?? process.platform; + if (platform === "win32") { + return startWindowsContainedAdvisory(warn, deps); + } + + const timeoutMs = deps.timeoutMs ?? TIMEOUT_MS; + const expires = performance.now() + timeoutMs; + let child: ReturnType; + try { + child = (deps.launch ?? (() => spawn(process.execPath, selfLaunchArgv([FOREGROUND_ADVISORY_ARG]), { + detached: true, stdio: ["ignore", "pipe", "ignore"], windowsHide: true, + })))(); + } catch { return () => { /* launch failed; nothing to clean up */ }; } + + let settled = false; + let stopped = false; + let bytes = 0; + const chunks: Buffer[] = []; + const stop: StopForegroundAdvisory = () => { + settled = true; + clearTimeout(timer); + if (!stopped) { + stopped = true; + const pid = child.pid; + if (pid && Number.isInteger(pid) && pid > 0) { + // Detached POSIX process group `-pid` is assigned atomically before exec and is never + // reused while any descendant remains alive, so this reaps exited-root descendants too. + try { process.kill(-pid, "SIGKILL"); } catch { + if (child.exitCode === null && child.signalCode === null) { + try { child.kill("SIGKILL"); } catch { /* best effort */ } + } + } + } else if (child.exitCode === null && child.signalCode === null) { + try { child.kill("SIGKILL"); } catch { /* best effort */ } + } + } + child.stdout?.destroy(); + }; + const timer = setTimeout(() => stop(false), timeoutMs); + timer.unref(); + child.once("error", () => stop(false)); + child.stdout?.once("error", () => stop(false)); + child.stdout?.on("data", (chunk: Buffer) => { + bytes += chunk.length; + if (bytes > MAX_BYTES) { stop(false); return; } + if (!settled) chunks.push(chunk); + }); + child.once("close", (code) => { + if (settled) return; + settled = true; + stopped = true; + clearTimeout(timer); + if (code !== 0 || performance.now() >= expires) return; + publishAdvisoryOutput(Buffer.concat(chunks).toString("utf8"), warn); + }); + child.unref(); + // Node's pipe handle has unref(); its public Readable type doesn't expose it. + (child.stdout as (typeof child.stdout & { unref?(): void }))?.unref?.(); + return stop; +} diff --git a/structure/codex-cli-update.md b/structure/codex-cli-update.md index af4ad4c1835..4565393a435 100644 --- a/structure/codex-cli-update.md +++ b/structure/codex-cli-update.md @@ -133,8 +133,11 @@ children. ARM64 is unsupported. It starts only an explicit drive-absolute `.exe` plus argv: `CreateProcessW(CREATE_SUSPENDED)`, assignment to a non-inheritable Job, then `ResumeThread`. Installer/verifier Jobs have a random global name and protected current-user DACL for durable read-only recovery; other Jobs stay unnamed. -An existing named object refuses creation. Normal execution uses original handles; no PID reopen, -shell, breakaway fallback, process-count limit or kill-on-close limit. Assignment/resume failures +An existing named object refuses creation. Update invocations use original handles; no PID reopen, +shell, breakaway fallback, process-count limit or kill-on-close limit (non-update callers such as the +foreground advisory probe may opt into `killOnJobClose: true`, which pairs +`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` with `PROC_THREAD_ATTRIBUTE_JOB_LIST` before `CreateProcessW` +so assignment is atomic with process creation and no unassigned process can exist). Assignment/resume failures reap the original suspended primary before user code; failed termination retains an unknown owner. `STARTUPINFOEXW` and an explicitly rooted attribute buffer whitelist exactly the three owned, inheritable stdio handles with `bInheritHandles=TRUE`. Parent read/event/Job/process/thread handles diff --git a/structure/runtime.md b/structure/runtime.md index 7ab87822a4f..ba5a2a055d1 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -178,7 +178,7 @@ described in [OpenAI quota ownership](providers/openai-tiers.md#public-provider- until shutdown. Standalone shutdown restores native Codex; connected hub clients preserve connection-owned Codex routing, catalog and Grok config across `ocx stop`/`ocx start`. An ordinary runtime rechecks persisted connection ownership in its exit cleanup: a connected Remote Link Child remains subject to the existing native Codex/Grok restoration decisions. Graceful signal shutdown runs that synchronous cleanup after draining and before releasing the listener. After the active-turn drain, `src/server/lifecycle.ts` joins asynchronous teardown receipts registered through `src/lib/optional-shutdown-hooks.ts`. The join uses the time remaining until the drain start plus `shutdownTimeoutMs` and two seconds, including time already spent on earlier teardown. The shared budget in `src/lib/shutdown-budget.ts` reserves the final second of the stop controller's three-second exit grace for finishing teardown and exiting. Each asynchronous hook receives that absolute deadline. A rejected or timed-out receipt reports a shutdown failure, and any registered emergency cleanup for the incomplete hook runs synchronously before listener and startup ownership cleanup. Sibling, recycling and service-managed exit exclusions remain intact; receipt-backed API stop may explicitly defer shared restoration to the stopping client. Only an accepted receipt deferral in `src/server/stop-teardown.ts` latches that process's exit deferral; CLI exit cleanup keeps native Codex and Grok restoration with the parent, while still stopping background owners and removing runtime records. Client start does not re-inject routing: use `ocx sync --restart-codex` to reapply it, or `ocx disconnect` to release connection ownership. A sibling instance beside a live proxy ([Codex home](codex-home.md#codex-home)) syncs and restores nothing, and `ocx stop` of a runtime whose record carries `siblingOfPort` skips the shared teardown. `src/cli/index.ts` resolves same-home ownership, then checks shared client hints through the cross-home owner helper, then reconciles the journal only when no sibling is marked. An indeterminate cross-home result refuses a new start before binding or publication, rather than persisting an unverified sibling topology; the next start performs fresh discovery. Service mode sets `OCX_SERVICE=1`, so managed restarts do not repeatedly restore/reinject; scheduler failure diagnostics follow the [service command contract](ops/service-and-sidecars.md#background-service-command-selection). Explicit service stop and uninstall still restore. Hub client management reads follow the [Hub credential and relay rules](remote-link.md#hub-transport-relay). The serving Hub client owns the lease refresh until stop, restart or recycle. Explicit stop requires connected-client preflight before manager or process mutation when saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health indicates client ownership. Standalone stop uses the ordinary manager, PID fallback and restore path. Without usable HTTP attestation, `src/cli/stop-restore.ts` can authorize the ordinary stop from a matching tracked runtime record in the absence of client or Link evidence. It matches the recorded OS creation identity when present. An older record requires a same-user OpenCodex start process and OS listener ownership on the recorded endpoint. The socket check requires a wildcard listener for a recorded wildcard bind and an exact listener for IPv4 loopback. Linux and macOS also require the live process home and caller home to resolve to existing directories with the same filesystem device and inode. A relative `OPENCODEX_HOME` is resolved against the target process’s working directory and requires a readable absolute cwd. Both paths must still resolve to the originally verified directory at the manager and signal boundaries. On Windows the legacy proof uses the same-user SID, exact start argv and the PID's ownership of the exact recorded listener. Windows x64 reads the SID and creation time from one live process handle, using the existing CIM timestamp format for saved records. The stop rechecks the accepted incarnation and record before acting on a live PID. A live tracked PID with unverified role refuses before manager or process mutation unless it is bound to a matching service registration. An exact runtime endpoint can back an update handover. When a verified standalone stop lacks an exact runtime endpoint, a guessed endpoint can record a teardown obligation and the parent restores after shutdown. Native client signal cleanup, process incarnation checks and the explicit-stop file-route preflight follow the [served-connection and supervisor boundaries](remote-link.md); an unsupervised signal retains the listener and sync fence for a file or native-restoration refusal, while explicit stop refuses before termination for a file cleanup or inherited teardown preflight failure. Native teardown receipts never skip unsupervised file cleanup or its fence. Native signal deferral additionally requires the current exact-runtime explicit-stop marker and a bounded exact-endpoint receipt owned by a live same-user stop invocation; uncertain ownership retains the listener, while a verified current parent can recover coexisting stale exact-endpoint claims. The parent claims its durable receipt before mutating a manager or sending a stop to a live Link Child. For an inherited receipt on a different endpoint, the parent must prove absence and bind the exact receipt snapshot to its claim. The Child requires that snapshot for signal deferral. The parent rechecks endpoint absence after shutdown and before restoration. With an unreadable Linux manager, offline Link cleanup requires `lstat` to report `ENOENT` for the installer unit and every service installation state path. All known endpoints must also be down. Client update stops use full parent restoration because client start cannot discharge standalone handover receipts. `src/service/cli.ts` removes the service token on uninstall only when persisted client state is disconnected and no pending connect marker owns the newly issued key. `src/client/connect.ts` publishes that fingerprint marker before the key, then clears it with the connection commit or rollback under the client lifecycle and config mutation locks. Connected, invalid, or mismatched client state retains an existing token. A valid pending marker retains only its matching fingerprint; an older marker does not own a replacement service key. An absent token is reported as absent; unsafe, malformed, or unreadable markers and lock, state-read, or deletion failures leave cleanup unverified. -`src/cli/tray-proxy.ts` coordinates `ocx restart` and tray restart. A second start requires proof the prior attempt never launched or its child exited, plus confirmed absence under a fresh bounded discovery window; a missing health response alone is insufficient. After an accepted restart, polling continues through uncertain observations until its deadline and requires a new runtime PID on the same port. If the old proxy then disappears, explicit recovery starts it regardless of the Codex autostart preference; a skipped recovery fails rather than reporting success. The Windows tray startup-health probe in `src/tray/windows-tray.ps1` requests termination at its 30-second deadline without waiting on the UI thread. It retains the process through later ticks until actual exit and both redirected readers settle; replacements cannot start while that reference is held. Launch setup failures follow the same cleanup. Tray shutdown alone waits at most 500 ms before disposal. +`src/cli/tray-proxy.ts` coordinates `ocx restart` and tray restart. A second start requires proof the prior attempt never launched or its child exited, plus confirmed absence under a fresh bounded discovery window; a missing health response alone is insufficient. After an accepted restart, polling continues through uncertain observations until its deadline and requires a new runtime PID on the same port. If the old proxy then disappears, explicit recovery starts it regardless of the Codex autostart preference; a skipped recovery fails rather than reporting success. The Windows tray startup-health probe in `src/tray/windows-tray.ps1` requests termination at its 30-second deadline without waiting on the UI thread. It retains the process through later ticks until actual exit and both redirected readers settle; replacements cannot start while that reference is held. Launch setup failures follow the same cleanup. Tray shutdown alone waits at most 500 ms before disposal. The interactive foreground owner start in `src/cli/index.ts` requests a best-effort managed-service advisory only after startup reconciliation and readiness. `src/service/foreground-advisory-process.ts` runs the read-only native diagnostic out of process so a stalled service manager cannot stall the listening proxy. The short deadline, bounded reply and shutdown cancellation do not change readiness or ownership. Unverified stopped state gives status guidance without a repair recommendation; supervised, sibling and restart-child starts do not request the advisory. `ocx restart` also restarts a connected client runtime, which serves the same bound `POST /api/system/restart` from its client listener; the CLI sends that request only while the client's 90-second restart budget still fits before replacement observation ends (`CLIENT_RESTART_REQUEST_MIN_REMAINING_MS`), and reports a supervised client's `409 restart_supervised` as "not performed, runtime kept"; a client whose connection was removed recycles to standalone when its owner is proven (`restartOwnerProven`), except that a manager whose relaunch is not proven (`service-unproven`) still refuses; a bare OCX_SERVICE=1 is refused as `legacy-flag` with advice to re-register the service once (`ocx service repair`), and nothing is stopped on inference (#8545). See [Remote Link](remote-link.md) for the rollback. The Remote Link Child listener checks its startup owner and link against durable client state once per `/readyz`, after readiness probing, and for authenticated machine/link status only on those routes. If they differ, `/readyz` and those status routes answer 503 with `client_state_changed`; the dashboard shows that reason with its recovery guidance. This reports divergence; it does not disconnect the relay or reconstruct a connection. `tests/clients/client-machine-listener.test.ts` covers missing and replaced records. Explicit `ocx disconnect --orphaned-token --yes` in `src/client/orphan-token-recovery.ts` preserves unowned token files only after the start lease, lifecycle lock, liveness proof and config-lock revalidation; Hub, admission-token use and installed or unverified services refuse. Windows closes source handles before rename while private hard links pin identity; a refusal removes a pin only while another name still holds the token, and an extra hard link left by an interrupted run is refused with a message naming the `.identity` pin to remove from the `orphaned-token-*` folder. Missing ownership is never reconstructed. `ocx config import` refuses to replace a connected client record under the config lock. `tests/clients/client-link-connect.test.ts` covers these refusals and local liveness. The package-tree integrity fence for live package replacement follows the [update transaction contract](ops/docs-and-release.md#package-tree-integrity-fence). After client journal reconciliation, `ocx ensure` in `src/cli/dispatch.ts` treats validated connected-client state as a successful no-op without local startup or a remote health probe; invalid or mismatched state still fails, and disconnected state keeps local ensure. `tests/cli/cli-ensure-client-state.test.ts` pins this dispatch contract so the Codex shim does not warn merely because its proxy is delegated to a hub. Startup journal reconciliation, including replacement after restart/drain, follows the [Codex-home recovery contract](codex-home.md#codex-home): already-original recovery is silent, incomplete recovery retains its journal and warns without claiming restoration, and only complete recovery that rewrites or removes an artifact reports a restore; restart admission, drain deadlines and replacement ownership are unchanged. `src/cli/start-owner-fence.ts` holds the ownership mutation lease through recovery for ordinary and supervised starts. After an early negative probe, `start` and `ensure` recheck with `START_OWNERSHIP_LIVENESS` under that lease through `observeProxyLiveness` in `src/server/proxy-liveness.ts`, probing both available loopback families concurrently for every loopback or wildcard spelling classified after the same startup normalization (including `localhost.` and case variants) within the existing per-family retry ceilings and shared deadline. Numeric loopback classification covers the IPv4 127/8 range, equivalent IPv6 loopback spellings and IPv4-mapped loopback literals; it probes the configured address itself plus the other family, retaining the original bind scope and the responding probe address separately. This recovery classification does not change listener admission or bind policy. `probeEndpointLiveness` and `probePortOwner` retain their existing host selection: other specific loopback literals are checked at the requested address without adopting the opposite family. Only definitive absence permits PID deletion and journal reconciliation: no alive or indeterminate PID from either the PID file or runtime record unless fresh readable command-line evidence confirms it is foreign, no answering runtime owner, and only unanimous aggregate connection refusals or clean foreign identities at probed endpoints. Port zero names no existing listener. Timeouts, resets, unreadable/non-200 responses, PID mismatches and exhausted deadlines remain unknown; startup refuses with a fixed message while preserving PID, journal and shared config. One recovery-only exception covers a specific non-loopback literal IP address (a Tailscale or LAN IP, never a hostname, loopback or wildcard), where a connect to this host's own unbound address can time out instead of being refused: when its probe ends "unknown", `canBindAddress` tries an exclusive listen on that raw socket address (IPv6 unbracketed) and port, closes it at once, and only a successful bind turns that endpoint "dead". The proof shares the discovery deadline: it is skipped once the budget is spent, its timeout is capped by the remaining budget, and a proof finishing past the deadline is discarded. Hostnames remain unknown after an inconclusive probe because name resolution may select different addresses for the probe and bind. Any bind error or timeout leaves the endpoint unknown, so startup still refuses; early (non-observer) discovery never binds. `probeEndpointLiveness` has its own narrower bind rule for `ocx resolve` and the other endpoint re-checks (#8318, described with resolve above): only a connect-phase timeout on a local interface address qualifies. `tests/server/proxy-liveness-nonloopback-bind-proof.test.ts` covers hostnames, bound and unbindable IPs, IPv6 and deadline cases. An orphan runtime PID is checked separately from listener ownership: only a definite missing process or a fresh readable foreign command line permits recovery, while an indeterminate process check, unreadable/empty command line, or OpenCodex invocation remains unknown. One exception covers a record naming the PID of the process running the recovery recheck, which in a container is PID 1 on every start (#8552): it is stale, and skipped as a candidate, only when this process has never written `ocx.pid` or `runtime-port.json` itself (`hasPublishedOwnershipRecords` in `src/config/process-state.ts`) and the runtime record names that PID with an `ownerScope` matching this process's (`runtimeOwnerScope` / `sameRuntimeOwnerScope`), which `writeRuntimePort` stamps only on the owner's own record. On Linux the scope needs the same host name plus either the same network namespace within the same boot (a container restarted inside its Kubernetes pod; namespace inode numbers repeat across boots) or the same randomly named writable layer of the overlay mounted at `/` (an `upperdir` in mountinfo with a 64-hex layer id, as Docker's `overlay2` driver and containers/storage use: the same container started again, also across a host reboot; no other container mounts it. Sequence-numbered containerd snapshots and overlay host roots repeat across machines or sandboxes, and a container id is visible to every container joined to that container's network, so none of them is used); elsewhere the PID space is machine-wide and the host name decides, and unreadable Linux evidence yields a per-process value that matches nothing. A replacement pod, a second container with a fixed hostname, or another node matches neither, so their refusal stands, which matters because such an owner can still be serving the same volume from another network namespace. Processes sharing one network namespace (host networking, pod sidecars, WSL distros in one VM) can match, and there the loopback probe still finds a listening owner; an owner that is alive but no longer listening, an owner exit cleanup that removes records by PID only, sandboxes that fake namespace numbers or clone a whole VM (gVisor, restored Firecracker/Kata snapshots), and non-Linux machines with the same host name syncing one home are residuals for a shared state volume. A record without a scope (an older version), a PID file without a runtime record, and a malformed scope keep the refusal; the scope is not part of record validity, so it can never hide a live owner. `tests/server/proxy-liveness-self-pid-record.test.ts` covers these cases and an `exec` handoff that keeps the PID across `ocx start`. The runtime PID is never supplied to destructive callers merely because it appears in the record; a confirmed foreign PID is never signalled. A discovered live owner preserves both records and its runtime/config bind scope in `LiveProxy.hostname`; omitted or blank hostnames become explicit `127.0.0.1` in both early and recovery discovery, so a later config change cannot replace a default loopback bind. Explicit wildcard scope remains intact, and the concrete responding address is separate `probeHostname` metadata. Integration policy uses the bind scope, so loopback discovery of a wildcard listener does not authorize tokenless Grok registration. Grok start and ensure/restart synchronization also recheck current desired-state admission after catalog discovery, immediately before the synchronous writer in `src/grok/sync.ts`; start additionally rejects work after shutdown begins or cleanup runs. This closes the same-process await gap without turning the desired-state and Grok files into a cross-process transaction. Ensure carries `probeHostname` separately through `src/cli/ensure-desired-integrations.ts` and `src/grok/sync.ts` to `src/grok/inject.ts` for the written destination; an explicit secondary loopback listener keeps its own address and port; after lease release, start applies `decideStartWithLiveOwner` and ensure follows its existing live-owner path. Cross-home sibling marking precedes stale PID cleanup and journal recovery. The bind/publication fence remains separate, and supervised recovery checks durable service ownership before liveness or mutation. `tests/cli/cli-start-journal-order.test.ts` covers an early miss; `tests/cli/cli-start-owner-absence.test.ts` covers consecutive misses and dead-owner recovery; `tests/server/proxy-liveness-recovery.test.ts` binds classification and existing budgets; `tests/server/proxy-liveness-bind-scope.test.ts` follows a missed early probe through desired-state reconciliation and the real Grok writer for runtime, orphan and configured-port discovery; `tests/server/proxy-liveness-owner-evidence.test.ts` and `tests/cli/cli-start-owner-evidence.test.ts` cover aggregate children, both listener families, shared deadlines and foreign-PID recovery. diff --git a/tests/fixtures/api-stop-exit-runner.ts b/tests/fixtures/api-stop-exit-runner.ts index 0407a715111..c265f466b02 100644 --- a/tests/fixtures/api-stop-exit-runner.ts +++ b/tests/fixtures/api-stop-exit-runner.ts @@ -59,6 +59,7 @@ const from = source.indexOf(" const syncCleanup = () => {"); const to = source.indexOf("\n let shuttingDown", from); if (from < 0 || to < 0) throw new Error("CLI exit cleanup missing"); const bindings = { + stopForegroundAdvisory: undefined, catalogHealer: null, routingHealer: null, guardian: { stop() {} }, historyGuardian: null, healthSentinel: null, siblingStart: false, isRecyclingForExit, decideStartExitTeardown, preserveConnectedClientRoutingOnExit, stopRestoreWriteGuard, revertSystemEnv() { calls.env++; }, removePid() { calls.pid++; }, removeRuntimePort() { calls.runtime++; }, diff --git a/tests/fixtures/parent-stop-runner.ts b/tests/fixtures/parent-stop-runner.ts index 0142e73eeb9..8650477b142 100644 --- a/tests/fixtures/parent-stop-runner.ts +++ b/tests/fixtures/parent-stop-runner.ts @@ -484,6 +484,7 @@ if (options.exitCleanup) { const restore = await import("../../src/cli/stop-restore"); const dispatch = await import("../../src/cli/dispatch"); const bindings = { + stopForegroundAdvisory: undefined, catalogHealer: null, routingHealer: null, guardian: { stop() {} }, historyGuardian: null, healthSentinel: null, siblingStart: false, isRecyclingForExit: () => false, decideStartExitTeardown: dispatch.decideStartExitTeardown, preserveConnectedClientRoutingOnExit: (teardown: Parameters[0]) => { diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index afd6f699ada..cdd1533bdbf 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1107,7 +1107,7 @@ "lab-public-route-registry.test.ts": "lab", "lab-public-security-regressions.test.ts": "lab", "lab-public-surfaces.test.ts": "lab", "lab-public-wire-contract.test.ts": "lab", "lab-read-filter-validation.test.ts": "lab", "lab-read-surfaces.test.ts": "lab", - "launchd-port-fallback.test.ts": "service", "launchd-repair.test.ts": "service", "legacy-shell-compat.test.ts": "responses", + "launchd-port-fallback.test.ts": "service", "launchd-repair.test.ts": "service", "foreground-start-service-advisory.test.ts": "service", "legacy-shell-compat.test.ts": "responses", "live-call-bindings.test.ts": "server", "live-native-calls.test.ts": "server", "usage-telemetry-profile-contract.test.ts": "usage", "usage-telemetry-profile-sync.test.ts": "usage", "usage-telemetry-profile-collector.test.ts": "usage", "usage-telemetry-profile-lifecycle.test.ts": "usage", "server-telemetry-profile-routes.test.ts": "server", "cli-telemetry-profile.test.ts": "cli", "docs-telemetry-leaderboard.test.ts": "ci-workflows", "live-service-manager-guard.test.ts": "service", diff --git a/tests/service/foreground-start-service-advisory.test.ts b/tests/service/foreground-start-service-advisory.test.ts new file mode 100644 index 00000000000..96a91c3b5d0 --- /dev/null +++ b/tests/service/foreground-start-service-advisory.test.ts @@ -0,0 +1,834 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { once } from "node:events"; +import { read, toArrayBuffer } from "bun:ffi"; +import { startWindowsCliChildWithNative } from "../../src/codex/windows-cli-child"; +import { WIN64_CHILD_ABI, type WindowsChildNative } from "../../src/codex/windows-cli-child-native"; +import { + FOREGROUND_ADVISORY_ARG, + maybeStartForegroundAdvisory, + shouldStartForegroundAdvisory, + startForegroundAdvisory, + type ContainedWindowsAdvisoryChild, + type ForegroundAdvisoryEligibility, +} from "../../src/service/foreground-advisory-process"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { saveConfig } from "../../src/config"; +import { selfLaunchArgv } from "../../src/lib/self-launch-argv"; +import { startServer } from "../../src/server"; +import { installIsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS, removeTreeAfterBackgroundWork } from "../helpers/remove-tree"; +import { repoPath } from "../helpers/repo-root"; +import { describe, expect, test } from "bun:test"; +import { deriveLaunchdServiceDiagnostic, foregroundStartServiceAdvisoryLines, warnForegroundStartService } from "../../src/service/diagnostics"; +import type { ServiceDiagnostic } from "../../src/service/diagnostics"; + +const diagnostic = (overrides: Partial = {}): ServiceDiagnostic => ({ + supported: true, + installed: true, + enabled: false, + running: false, + viable: false, + startable: true, + stale: false, + conflict: false, + backend: "launchd", + summary: "installed, not loaded (launchd; ok)", + confirmedStopped: true, + ...overrides, +}); + +describe("foregroundStartServiceAdvisoryLines", () => { + test("advises when the managed service is installed but not serving", () => { + const lines = foregroundStartServiceAdvisoryLines(diagnostic()); + expect(lines).toHaveLength(2); + expect(lines[0]).toContain("not loaded"); + expect(lines[0]).toContain("installed, not loaded"); + expect(lines[1]).toContain("'ocx service repair'"); + }); + + test("stays silent when the service is serving", () => { + const service = diagnostic({ running: true, enabled: true, viable: true, summary: "installed and loaded (launchd; ok)" }); + expect(foregroundStartServiceAdvisoryLines(service)).toEqual([]); + }); + + test("stays silent when no service is installed", () => { + const service = diagnostic({ installed: false, startable: false, backend: null, summary: "not installed (launchd; ok)" }); + expect(foregroundStartServiceAdvisoryLines(service)).toEqual([]); + }); + + test("stays silent when another manager holds a conflict", () => { + const service = diagnostic({ conflict: true, summary: "conflicting manager (launchd; ok)" }); + expect(foregroundStartServiceAdvisoryLines(service)).toEqual([]); + }); + + test("stays silent on unsupported platforms", () => { + const service = diagnostic({ supported: false, startable: false, summary: "unsupported on freebsd" }); + expect(foregroundStartServiceAdvisoryLines(service)).toEqual([]); + }); + + test("advises on a stale registration that is not serving", () => { + const service = diagnostic({ stale: true, startable: false, summary: "installed, but stale (launchd; baked paths moved)" }); + const lines = foregroundStartServiceAdvisoryLines(service); + expect(lines).toHaveLength(2); + expect(lines[1]).toContain("'ocx service repair'"); + }); + + test("does not treat launchd unknown as stopped, whether or not paths are stale", () => { + for (const stale of [false, true]) { + const result = deriveLaunchdServiceDiagnostic({ + installed: true, stale, load: { state: "unknown" }, diagnostics: "fixture", + }); + const lines = foregroundStartServiceAdvisoryLines(result).join("\n"); + expect(lines).toContain("Could not confirm"); + expect(lines).toContain("ocx status"); + expect(lines.includes("ocx service repair")).toBe(false); + } + }); + + test("derives confirmation from verified launchd not-loaded, not summary text", () => { + const result = deriveLaunchdServiceDiagnostic({ + installed: true, stale: false, load: { state: "not-loaded" }, diagnostics: "fixture", + }); + expect(foregroundStartServiceAdvisoryLines({ ...result, summary: "changed wording" })).toHaveLength(2); + }); + + test("keeps status guidance across unknown and non-launchd backends without copying repair hints", () => { + for (const backend of ["systemd", "native", "scheduler", null] as const) { + const lines = foregroundStartServiceAdvisoryLines(diagnostic({ + backend, confirmedStopped: undefined, summary: "stale assets — run ocx service repair", + })).join("\n"); + expect(lines).toContain("Could not confirm"); + expect(lines).toContain("ocx status"); + expect(lines.includes("ocx service repair")).toBe(false); + } + }); + + test("probe or warning exceptions cannot escape the advisory", () => { + const fail = (): never => { throw new Error("fixture"); }; + expect(() => warnForegroundStartService(fail, fail)).not.toThrow(); + expect(() => warnForegroundStartService(() => diagnostic(), fail)).not.toThrow(); + }); +}); + +test("foreground advisory is wired after readiness initialization and uses the final sibling decision", () => { + const cli = readFileSync(repoPath("src/cli/index.ts"), "utf8"); + const start = cli.slice(cli.indexOf("async function handleStart("), cli.indexOf("function detachedStartEnvironment(")); + const probe = "maybeStartForegroundAdvisory({"; + const probes = start.split(probe); + expect(probes).toHaveLength(2); + const beforeProbe = probes[0]!; + expect(beforeProbe).toContain("await bindAndPublishStartOwnership("); + expect(beforeProbe).toContain("await reconcileClientStartupBeforeReady("); + expect(beforeProbe).toContain('console.log("Client startup work complete.")'); + expect(probes[1]!.slice(0, 240)).toContain("cleaned, shuttingDown, siblingStart, ownerLive: Boolean(owner.live), supervisedServiceChild, restartParentPid: restartParent.restartParentPid, stderrIsTTY: process.stderr?.isTTY"); +}); + +describe("foreground advisory eligibility behavior", () => { + const eligible: ForegroundAdvisoryEligibility = { + cleaned: false, + shuttingDown: false, + siblingStart: false, + ownerLive: false, + supervisedServiceChild: false, + restartParentPid: null, + stderrIsTTY: true, + }; + + test.each([ + ["non-interactive (stderrIsTTY=false)", { stderrIsTTY: false }], + ["non-interactive (stderrIsTTY=undefined)", { stderrIsTTY: undefined }], + ["supervised service child", { supervisedServiceChild: true }], + ["sibling start", { siblingStart: true }], + ["live owner", { ownerLive: true }], + ["restart handoff", { restartParentPid: 4242 }], + ["shutting down", { shuttingDown: true }], + ["already cleaned", { cleaned: true }], + ])("never launches the probe for %s", (_label, override) => { + let launches = 0; + const stop = maybeStartForegroundAdvisory({ ...eligible, ...override }, () => {}, { + launch: () => { + launches += 1; + return fakeProbe("console.log('[]')"); + }, + }); + expect(stop).toBeUndefined(); + expect(launches).toBe(0); + expect(shouldStartForegroundAdvisory({ ...eligible, ...override })).toBe(false); + }); + + test("launches the probe for an eligible interactive foreground owner", async () => { + const warnings: string[] = []; + let child!: ChildProcess; + let launches = 0; + const stop = maybeStartForegroundAdvisory(eligible, line => warnings.push(line), { + launch: () => { + launches += 1; + return (child = fakeProbe('console.log(JSON.stringify(["eligible advisory"]))')); + }, + }); + expect(stop).toBeDefined(); + expect(launches).toBe(1); + try { + await once(child, "close"); + expect(warnings).toEqual(["eligible advisory"]); + } finally { stop?.(); } + }); +}); + +test("private advisory entrypoint launches cleanly from a path containing spaces", async () => { + const dir = mkdtempSync(join(tmpdir(), "ocx advisory spaces ")); + const home = join(dir, "ocx home"); + const entry = join(dir, "cli entry with spaces.ts"); + const cliUrl = pathToFileURL(repoPath("src/cli/index.ts")).href; + writeFileSync(entry, `await import(${JSON.stringify(cliUrl)});\n`, "utf8"); + const argv = selfLaunchArgv([FOREGROUND_ADVISORY_ARG], { isStandaloneExecutable: false, sourceEntrypoint: entry }); + const child = spawn(process.execPath, argv, { + env: { ...process.env, OPENCODEX_HOME: home }, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }); + const chunks: Buffer[] = []; + child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk)); + try { + const [code] = await once(child, "close"); + expect(code).toBe(0); + const parsed: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8")); + expect(Array.isArray(parsed)).toBe(true); + expect((parsed as unknown[]).length).toBeLessThanOrEqual(2); + } finally { + await removeTreeAfterBackgroundWork(dir); + } +}, 15_000); + +describe("Windows pre-resume Job-contained advisory teardown", () => { + async function waitUntilDead(pid: number, timeoutMs = 3_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { process.kill(pid, 0); } catch { return true; } + await Bun.sleep(20); + } + return false; + } + + function safeKillPid(pid: number): void { + if (pid <= 0) return; + try { process.kill(pid, "SIGKILL"); } catch { /* process already exited */ } + } + + function createFakeContainedWindowsChild(options: { + outputChunks?: Buffer[]; + terminal?: boolean; + exitCode?: number | null; + setupFailure?: string | null; + processHandle?: bigint; + processSignaled?: boolean; + onTerminateJob?: (job: bigint, code: number) => boolean | void; + onReapUnstarted?: () => boolean; + } = {}) { + let eof = false; + let terminal = options.terminal ?? false; + let processSignaled = options.processSignaled ?? terminal; + let exitCode = options.exitCode ?? 0; + const queued = [...(options.outputChunks ?? [])]; + const terminatedJobs: Array<{ job: bigint; code: number }> = []; + const closedHandles: bigint[] = []; + let pipeDisposed = 0; + let nativeDisposed = 0; + let reapedUnstarted = 0; + + const child: ContainedWindowsAdvisoryChild = { + setupFailure: options.setupFailure ?? null, + job: 0x100n, + process: options.processHandle ?? 0x200n, + pipe: { + get eof() { return eof; }, + error: false, + pump(onBytes) { + while (queued.length > 0) onBytes(queued.shift()!); + if (terminal) eof = true; + }, + async dispose() { pipeDisposed += 1; }, + }, + native: { + k: { + TerminateJobObject(job, code) { + terminatedJobs.push({ job, code }); + const outcome = options.onTerminateJob?.(job, code); + if (outcome === false) return 0; + terminal = true; + processSignaled = true; + exitCode = code; + eof = true; + return 1; + }, + WaitForSingleObject() { + return processSignaled ? 0 : 258; + }, + }, + close(handle) { closedHandles.push(handle); }, + dispose() { nativeDisposed += 1; return true; }, + }, + observe() { + return { terminal, exitCode: terminal ? exitCode : null, unknown: false }; + }, + reapUnstarted() { + reapedUnstarted += 1; + const ok = options.onReapUnstarted ? options.onReapUnstarted() : true; + if (ok) processSignaled = true; + return ok; + }, + }; + + return { + child, + setTerminal(nextExitCode: number) { terminal = true; processSignaled = true; exitCode = nextExitCode; }, + state: () => ({ terminatedJobs, closedHandles, pipeDisposed, nativeDisposed, reapedUnstarted }), + }; + } + + test("normal Windows completion publishes advisory and releases handles without TerminateJobObject", async () => { + const warnings: string[] = []; + const fake = createFakeContainedWindowsChild({ + outputChunks: [Buffer.from(JSON.stringify(["windows advisory"]))], + terminal: true, + exitCode: 0, + }); + const stop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + pollMs: 5, + launchWindows: () => fake.child, + }); + try { + await Bun.sleep(40); + expect(warnings).toEqual(["windows advisory"]); + // Later CLI shutdown (both async and synchronous exit paths) must not call + // TerminateJobObject with an already-closed job handle that Windows could reuse. + stop(false); + stop(true); + expect(fake.state().terminatedJobs).toEqual([]); + expect(fake.state().pipeDisposed).toBe(1); + expect(fake.state().closedHandles).toEqual([0x200n, 0x100n]); + expect(fake.state().nativeDisposed).toBe(1); + } finally { + stop(true); + } + }); + + test("timeout terminates the Job Object atomically when a descendant outlives the probe root", async () => { + const warnings: string[] = []; + const fake = createFakeContainedWindowsChild({ + outputChunks: [Buffer.from('["too late"]')], + // Root exited, descendant still active inside the Job -> Job accounting stays non-terminal. + terminal: false, + }); + const stop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + timeoutMs: 30, + pollMs: 5, + launchWindows: () => fake.child, + }); + try { + await Bun.sleep(90); + expect(warnings).toEqual([]); + expect(fake.state().terminatedJobs).toEqual([{ job: 0x100n, code: 1 }]); + expect(fake.state().pipeDisposed).toBe(1); + expect(fake.state().closedHandles).toEqual([0x200n, 0x100n]); + expect(fake.state().nativeDisposed).toBe(1); + } finally { + stop(true); + } + }); + + test("synchronous exit cleanup terminates the Windows Job Object immediately without waiting on async timers", () => { + const warnings: string[] = []; + const fake = createFakeContainedWindowsChild({ terminal: false }); + const stop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + timeoutMs: 10_000, + pollMs: 50, + launchWindows: () => fake.child, + }); + stop(true); + expect(fake.state().terminatedJobs).toEqual([{ job: 0x100n, code: 1 }]); + expect(warnings).toEqual([]); + }); + + test("slow-to-settle job and failed TerminateJobObject keep backoff polling until terminal so handles never leak", async () => { + let allowTerminate = false; + const fake = createFakeContainedWindowsChild({ + terminal: false, + onTerminateJob: () => allowTerminate ? undefined : false, + }); + // Override observe so we can simulate a job that takes longer than reapMs to settle even after + // TerminateJobObject succeeds. + let externallyTerminal = false; + const originalObserve = fake.child.observe.bind(fake.child); + const wrappedChild: ContainedWindowsAdvisoryChild = { + ...fake.child, + observe: () => externallyTerminal ? originalObserve() : { terminal: false, exitCode: null, unknown: false }, + }; + + const stop = startForegroundAdvisory(() => {}, { + platform: "win32", + timeoutMs: 15, + reapMs: 25, + pollMs: 5, + settlePollMs: 15, + launchWindows: () => wrappedChild, + }); + try { + // Wait past timeoutMs + reapMs while TerminateJobObject fails: handles stay owned and retry continues. + await Bun.sleep(70); + const attemptsAfterFail = fake.state().terminatedJobs.length; + expect(attemptsAfterFail).toBeGreaterThanOrEqual(2); + expect(fake.state().closedHandles).toEqual([]); + expect(fake.state().pipeDisposed).toBe(0); + + // TerminateJobObject succeeds, but job still takes time past reapMs to become terminal. + allowTerminate = true; + await Bun.sleep(40); + expect(fake.state().terminatedJobs.length).toBeGreaterThanOrEqual(attemptsAfterFail + 1); + expect(fake.state().closedHandles).toEqual([]); + + // Once the slow job finally becomes terminal, backoff polling disposes all handles cleanly. + externallyTerminal = true; + await Bun.sleep(50); + expect(fake.state().pipeDisposed).toBe(1); + expect(fake.state().closedHandles).toEqual([0x200n, 0x100n]); + expect(fake.state().nativeDisposed).toBe(1); + } finally { + stop(true); + } + }); + + test("Windows output overflow terminates the Job Object and suppresses advisory output", async () => { + const warnings: string[] = []; + const fake = createFakeContainedWindowsChild({ + outputChunks: [Buffer.alloc(9_000, 0x20)], + terminal: false, + }); + const stop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + timeoutMs: 10_000, + pollMs: 5, + launchWindows: () => fake.child, + }); + try { + await Bun.sleep(60); + expect(warnings).toEqual([]); + expect(fake.state().terminatedJobs).toEqual([{ job: 0x100n, code: 1 }]); + } finally { + stop(true); + } + }); + + test("Windows arms kill-on-job-close before CreateProcessW and fails closed before any process is created or resumed", async () => { + const warnings: string[] = []; + const unsupportedStop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + launchWindows: () => { throw new Error("windows_child_unsupported_platform"); }, + }); + expect(() => unsupportedStop(true)).not.toThrow(); + + // Setup failure where startWindowsCliChild already terminated the suspended process + // (WaitForSingleObject === 0): a second reapUnstarted() is skipped (even if it would return false), + // and handles are disposed immediately without leaking. + const alreadyReaped = createFakeContainedWindowsChild({ + setupFailure: "job_assignment", + processHandle: 0x200n, + processSignaled: true, + onReapUnstarted: () => false, + }); + const alreadyReapedStop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + launchWindows: () => alreadyReaped.child, + }); + await Bun.sleep(20); + expect(alreadyReaped.state().reapedUnstarted).toBe(0); + expect(alreadyReaped.state().pipeDisposed).toBe(1); + expect(alreadyReaped.state().closedHandles).toEqual([0x200n, 0x100n]); + expect(alreadyReaped.state().nativeDisposed).toBe(1); + alreadyReapedStop(true); + + // Setup failure (ResumeThread failed after CreateProcessW) combined with failed + // TerminateProcess & TerminateJobObject: original process/job handles stay retained while + // unsignaled, backoff polling retries reapUnstarted(), and handles are disposed only once + // WaitForSingleObject === 0. + let allowUnstartedReap = false; + const failedReapSetup = createFakeContainedWindowsChild({ + setupFailure: "resume_thread", + processHandle: 0x200n, + processSignaled: false, + onReapUnstarted: () => allowUnstartedReap, + onTerminateJob: () => allowUnstartedReap ? undefined : false, + }); + const failedReapStop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + pollMs: 5, + reapMs: 20, + settlePollMs: 10, + launchWindows: () => failedReapSetup.child, + }); + try { + await Bun.sleep(45); + const reapRetries = failedReapSetup.state().reapedUnstarted; + expect(reapRetries).toBeGreaterThanOrEqual(2); + expect(failedReapSetup.state().closedHandles).toEqual([]); + expect(failedReapSetup.state().pipeDisposed).toBe(0); + + // Once TerminateProcess finally succeeds and process signals, handles are disposed cleanly + // and later stop() calls never touch the closed handle. + allowUnstartedReap = true; + await Bun.sleep(35); + expect(failedReapSetup.state().reapedUnstarted).toBeGreaterThanOrEqual(reapRetries + 1); + expect(failedReapSetup.state().pipeDisposed).toBe(1); + expect(failedReapSetup.state().closedHandles).toEqual([0x200n, 0x100n]); + expect(failedReapSetup.state().nativeDisposed).toBe(1); + + const reapsAfterDispose = failedReapSetup.state().reapedUnstarted; + failedReapStop(false); + failedReapStop(true); + expect(failedReapSetup.state().reapedUnstarted).toBe(reapsAfterDispose); + } finally { + failedReapStop(true); + } + + const failedStop = alreadyReapedStop; + + // Real startWindowsCliChildWithNative fault injection proving atomic containment: + // (1) SetInformationJobObject(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) runs BEFORE CreateProcessW; + // (2) PROC_THREAD_ATTRIBUTE_JOB_LIST (0x2000D) attaches child.job atomically inside CreateProcessW; + // (3) If either pre-create step fails, CreateProcessW never runs (process === 0n); + // (4) If post-create setup (ResumeThread) AND termination both fail through shutdown -> syncCleanup, + // child.job (already armed with kill-on-close & bound atomically to child.process) stays open + // until parent exit so the Windows kernel reaps the suspended process on exit. + const makeMockNative = (opts: { + setLimitResult: number; + jobListAttrResult?: number; + resumeResult?: number; + terminateProcessResult?: number; + terminateJobResult?: number; + }) => { + const calls: string[] = []; + const observedLimits: Array<{ job: bigint; infoClass: number; flags: number; length: number }> = []; + const observedJobList: Array<{ attr: bigint; job: bigint; size: bigint }> = []; + const attrCounts: number[] = []; + const handles = new Set(); + const borrowedMemory = new Set(); + const closed: bigint[] = []; + let disposed = 0; + let nextHandle = 0x300n; + const native = { + handles, + borrowedMemory, + closeErrors: [] as bigint[], + privateDescriptor: () => 0x50n, + k: { + CreateJobObjectW: () => { calls.push("CreateJobObjectW"); return 0x100n; }, + SetInformationJobObject: (job: bigint, infoClass: number, infoPtr: number, length: number) => { + calls.push("SetInformationJobObject"); + observedLimits.push({ + job, + infoClass, + flags: read.u32(infoPtr as never, WIN64_CHILD_ABI.jobLimitFlags), + length, + }); + return opts.setLimitResult; + }, + CreateNamedPipeW: () => ++nextHandle, + CreateEventW: () => ++nextHandle, + CreateFileW: () => ++nextHandle, + ConnectNamedPipe: () => 1, + LocalFree: () => 0, + InitializeProcThreadAttributeList: (listPtr: number | null, count: number, _flags: number, sizePtr: number) => { + attrCounts.push(count); + if (!listPtr) { + new DataView(toArrayBuffer(sizePtr as never, 0, 8)).setBigUint64(0, 64n, true); + return 0; + } + calls.push(`InitializeProcThreadAttributeList:${count}`); + return 1; + }, + UpdateProcThreadAttribute: (_listPtr: number, _flags: number, attr: bigint, valuePtr: number, size: bigint) => { + calls.push(`UpdateProcThreadAttribute:0x${attr.toString(16)}`); + if (attr === 0x2000dn) { + observedJobList.push({ attr, job: read.u64(valuePtr as never, 0), size }); + return opts.jobListAttrResult ?? 1; + } + return 1; + }, + DeleteProcThreadAttributeList: () => { calls.push("DeleteProcThreadAttributeList"); }, + CompareStringOrdinal: () => 2, + CreateProcessW: (_e: number, _c: number, _pa: unknown, _ta: unknown, _inh: number, _cf: number, _env: number, _cwd: number, _si: number, piPtr: number) => { + calls.push("CreateProcessW"); + const pi = new DataView(toArrayBuffer(piPtr as never, 0, WIN64_CHILD_ABI.processInformation)); + pi.setBigUint64(0, 0x200n, true); // hProcess + pi.setBigUint64(8, 0x201n, true); // hThread + pi.setUint32(16, 4242, true); // dwProcessId + return 1; + }, + GetProcessTimes: (_h: bigint, creationPtr: number) => { + new DataView(toArrayBuffer(creationPtr as never, 0, 8)).setBigUint64(0, 1337000000n, true); + return 1; + }, + AssignProcessToJobObject: () => { calls.push("AssignProcessToJobObject"); return 1; }, + ResumeThread: () => { calls.push("ResumeThread"); return opts.resumeResult ?? 1; }, + TerminateProcess: () => { calls.push("TerminateProcess"); return opts.terminateProcessResult ?? 0; }, + TerminateJobObject: () => { calls.push("TerminateJobObject"); return opts.terminateJobResult ?? 0; }, + WaitForSingleObject: () => 258, + GetLastError: () => 5, + CloseHandle: (handle: bigint) => { closed.push(handle); return 1; }, + }, + keep(value: number | bigint) { + const handle = BigInt(value); + handles.add(handle); + return handle; + }, + close(handle: bigint) { + if (!handles.has(handle)) return; + closed.push(handle); + handles.delete(handle); + }, + dispose() { + if (handles.size || borrowedMemory.size) return false; + disposed += 1; + return true; + }, + }; + return { + native: native as unknown as WindowsChildNative, + calls, + observedLimits, + observedJobList, + attrCounts, + closed, + getDisposed: () => disposed, + }; + }; + + // (1) SetInformationJobObject fails -> no process ever created. + const failLimitMock = makeMockNative({ setLimitResult: 0 }); + const killOnCloseFailChild = startWindowsCliChildWithNative({ + executable: "C:\\Program Files\\bun\\bun.exe", + args: [FOREGROUND_ADVISORY_ARG], + cwd: "C:\\Users\\tester", + env: {}, + policy: "version", + killOnJobClose: true, + }, failLimitMock.native); + expect(killOnCloseFailChild.setupFailure).toBe("job_kill_on_close"); + expect(killOnCloseFailChild.process).toBe(0n); + expect(failLimitMock.calls).toEqual(["CreateJobObjectW", "SetInformationJobObject"]); + expect(failLimitMock.observedLimits).toEqual([{ + job: 0x100n, + infoClass: 9, + flags: 0x2000, + length: WIN64_CHILD_ABI.jobExtendedLimit, + }]); + const abortedLimitStop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + launchWindows: () => killOnCloseFailChild, + }); + abortedLimitStop(false); + abortedLimitStop(true); + await Bun.sleep(20); + expect(failLimitMock.closed).toEqual([0x100n]); + expect(failLimitMock.getDisposed()).toBe(1); + + // (2) PROC_THREAD_ATTRIBUTE_JOB_LIST fails -> no process ever created. + const failJobAttrMock = makeMockNative({ setLimitResult: 1, jobListAttrResult: 0 }); + const jobAttrFailChild = startWindowsCliChildWithNative({ + executable: "C:\\Program Files\\bun\\bun.exe", + args: [FOREGROUND_ADVISORY_ARG], + cwd: "C:\\Users\\tester", + env: {}, + policy: "version", + killOnJobClose: true, + }, failJobAttrMock.native); + expect(jobAttrFailChild.setupFailure).toBe("attribute_job_list"); + expect(jobAttrFailChild.process).toBe(0n); + expect(failJobAttrMock.calls).not.toContain("CreateProcessW"); + expect(failJobAttrMock.observedJobList).toEqual([{ attr: 0x2000dn, job: 0x100n, size: 8n }]); + const abortedAttrStop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + launchWindows: () => jobAttrFailChild, + }); + abortedAttrStop(true); + await Bun.sleep(20); + expect(failJobAttrMock.getDisposed()).toBe(1); + + // (3) Atomic CreateProcessW containment + post-create ResumeThread failure + continuous + // TerminateProcess & TerminateJobObject failures through the entire production exit lifecycle + // (shutdown stop(false) -> single syncCleanup stop(true)): process was already assigned to + // child.job atomically via PROC_THREAD_ATTRIBUTE_JOB_LIST (never AssignProcessToJobObject), + // kill-on-close was armed beforehand, and child.job + child.process remain open until parent + // exit so Windows kernel JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE reaps the suspended process. + const postCreateFailMock = makeMockNative({ + setLimitResult: 1, + jobListAttrResult: 1, + resumeResult: 0, + terminateProcessResult: 0, + terminateJobResult: 0, + }); + const postCreateFailChild = startWindowsCliChildWithNative({ + executable: "C:\\Program Files\\bun\\bun.exe", + args: [FOREGROUND_ADVISORY_ARG], + cwd: "C:\\Users\\tester", + env: {}, + policy: "version", + killOnJobClose: true, + }, postCreateFailMock.native); + expect(postCreateFailChild.setupFailure).toBe("resume_thread"); + expect(postCreateFailChild.process).toBe(0x200n); + expect(postCreateFailMock.calls).not.toContain("AssignProcessToJobObject"); + expect(postCreateFailMock.calls.indexOf("SetInformationJobObject")).toBeLessThan(postCreateFailMock.calls.indexOf("CreateProcessW")); + expect(postCreateFailMock.calls.indexOf("UpdateProcThreadAttribute:0x2000d")).toBeLessThan(postCreateFailMock.calls.indexOf("CreateProcessW")); + expect(postCreateFailMock.observedJobList).toEqual([{ attr: 0x2000dn, job: 0x100n, size: 8n }]); + + const postCreateFailStop = startForegroundAdvisory(line => warnings.push(line), { + platform: "win32", + pollMs: 5, + launchWindows: () => postCreateFailChild, + }); + postCreateFailStop(false); + postCreateFailStop(true); + await Bun.sleep(25); + // Both child.job (with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) and child.process stay open until exit. + expect(postCreateFailMock.native.handles.has(0x100n)).toBe(true); + expect(postCreateFailMock.native.handles.has(0x200n)).toBe(true); + expect(postCreateFailMock.getDisposed()).toBe(0); + expect(postCreateFailMock.calls.filter(call => call === "TerminateProcess").length).toBeGreaterThanOrEqual(3); + expect(postCreateFailMock.calls.filter(call => call === "TerminateJobObject").length).toBeGreaterThanOrEqual(2); + + // Durable recovery jobs remain incompatible with killOnJobClose. + expect(() => startWindowsCliChildWithNative({ + executable: "C:\\Program Files\\bun\\bun.exe", + args: [FOREGROUND_ADVISORY_ARG], + cwd: "C:\\Users\\tester", + env: {}, + policy: "installer", + recoveryJobName: "Global\\ocx-cli-12345678-1234-1234-1234-123456789abc", + killOnJobClose: true, + }, makeMockNative({ setLimitResult: 1 }).native)).toThrow("windows_child_invalid_invocation"); + + expect(warnings).toEqual([]); + failedStop(true); + }); + + test("timeout still terminates a living descendant holding stdout after the probe root exits on POSIX", async () => { + if (process.platform === "win32") return; + const dir = mkdtempSync(join(tmpdir(), "ocx-advisory-exited-root-")); + const descendantPidFile = join(dir, "descendant.pid"); + let child!: ChildProcess; + let descendantPid = 0; + const cancel = startForegroundAdvisory(() => {}, { + timeoutMs: 250, + launch: () => { + const script = [ + 'const { spawn } = require("node:child_process");', + 'const { writeFileSync } = require("node:fs");', + 'const d = spawn(process.execPath, ["-e", "setInterval(() => {}, 60000)"], { stdio: ["ignore", 1, "ignore"], windowsHide: true });', + `writeFileSync(${JSON.stringify(descendantPidFile)}, String(d.pid));`, + 'process.stdout.write("root-exiting\\n", () => process.exit(0));', + ].join(" "); + return (child = fakeProbe(script)); + }, + }); + try { + await once(child, "exit"); + descendantPid = Number(readFileSync(descendantPidFile, "utf8").trim()); + expect(descendantPid).toBeGreaterThan(0); + await once(child, "close"); + expect(await waitUntilDead(descendantPid)).toBe(true); + } finally { + cancel(true); + safeKillPid(descendantPid); + await removeTreeAfterBackgroundWork(dir); + } + }, 15_000); +}); + +function fakeProbe(body: string) { + return spawn(process.execPath, ["-e", body], { + detached: process.platform !== "win32", stdio: ["ignore", "pipe", "ignore"], windowsHide: true, + }); +} + +test("the listening proxy can answer a request while the advisory child is still probing", async () => { + const previousHome = process.env.OPENCODEX_HOME; + const home = mkdtempSync(join(tmpdir(), "ocx-advisory-")); + const codexHome = installIsolatedCodexHome("ocx-advisory-codex-"); + process.env.OPENCODEX_HOME = home; + let server: ReturnType | undefined; + const warnings: string[] = []; + let child: ChildProcess | undefined; + let cancel: (() => void) | undefined; + try { + saveConfig({ + port: 0, + hostname: "127.0.0.1", + defaultProvider: "mock", + providers: { mock: { adapter: "openai-chat", baseUrl: "http://127.0.0.1:9/v1", allowPrivateNetwork: true, liveModels: false, models: ["m"] } }, + clientIntegrations: { codex: false }, + webSearchSidecar: { enabled: false }, + }); + server = startServer(0); + cancel = startForegroundAdvisory(line => warnings.push(line), { + launch: () => (child = fakeProbe("console.log('pending'); for (;;) {}")), + timeoutMs: 4_000, + }); + expect(child).toBeDefined(); + const ready = new AbortController(); + const deadline = setTimeout(() => ready.abort(), 2_000); + try { + await Promise.race([ + once(child!.stdout!, "data", { signal: ready.signal }), + once(child!, "close", { signal: ready.signal }).then(() => { throw new Error("probe exited before starting"); }), + ]); + } finally { + clearTimeout(deadline); + ready.abort(); + } + const response = await fetch(new URL("/healthz", server.url), { signal: AbortSignal.timeout(1_500) }); + expect(response.status).toBe(200); + expect(await response.json()).toHaveProperty("status"); + expect(child!.exitCode).toBeNull(); + expect(child!.signalCode).toBeNull(); + expect(warnings).toEqual([]); + } finally { + const exited = child && child.exitCode === null && child.signalCode === null ? once(child, "close") : undefined; + cancel?.(); + try { await server?.stop(true); await exited; } finally { + codexHome.restore(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + await removeTreeAfterBackgroundWork(home); + } + } +}, BACKGROUND_WORK_TEARDOWN_TIMEOUT_MS); + +test("a completed probe publishes its advisory; a timed-out probe is stopped silently", async () => { + const warnings: string[] = []; + let child!: ChildProcess; + const onWarning = (line: string) => warnings.push(line); + const cancel = startForegroundAdvisory(onWarning, { + launch: () => (child = fakeProbe('console.log(JSON.stringify(["status guidance"]))')), + }); + try { + await once(child, "close"); + expect(warnings).toEqual(["status guidance"]); + } finally { cancel(); } + + const cancelSlow = startForegroundAdvisory(onWarning, { + launch: () => (child = fakeProbe('setTimeout(() => console.log(JSON.stringify(["too late"])), 2000)')), + timeoutMs: 100, + }); + try { + const [code] = await once(child, "close"); + expect(code).not.toBe(0); + expect(warnings).toEqual(["status guidance"]); + } finally { cancelSlow(); } +}); diff --git a/tests/service/shutdown-drain.test.ts b/tests/service/shutdown-drain.test.ts index 9680d962e0f..2205fb88422 100644 --- a/tests/service/shutdown-drain.test.ts +++ b/tests/service/shutdown-drain.test.ts @@ -271,6 +271,7 @@ describe("routing cleanup before listener release", () => { ); const bindings = { server, config: { shutdownTimeoutMs: 0 }, drainAndShutdown, + stopForegroundAdvisory: undefined, syncCleanup: () => { if (!cleaned) { cleaned = true; events.push("native-restore", "grok-strip"); } return restoreSucceeded; From 3a52982378ce05403b1cb60f915b2fad2fe5f8b4 Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:26:58 +0900 Subject: [PATCH 34/64] fix(clients): stop advertising native models the proxy cannot route (#9191) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(clients): stop advertising native models the proxy cannot route A native OpenAI row is only servable while `providers.openai` is enabled: the router answers every bare `gpt-*` selector with `NoEnabledOpenAiProviderError` the moment that provider is disabled, in both Pool and Direct mode. Three client-facing surfaces did not apply that rule, so they offered a picker whose selections could only fail: - `loadExportModels` (`src/server/management/model-rows.ts`) kept native rows unless the individual slug was disabled. Every `/api/client-config` client, every managed integration route and `ocx export` read this roster, so a config with `providers.openai.disabled` exported all native slugs — including the eleven a stock catalog lists — while the router refused each one. - `opencodeCatalogFromProxyRows` and `opencodeLaunchNativeSlugs` (`src/cli/opencode.ts`) filtered natives only for Codex Direct mode, so `ocx opencode` and the launcher's V1/V2 blocks advertised the same dead rows. The rule is one predicate, `isNativeOpenAiProviderEnabled`, which is the router's own admission for a bare native selector: the provider exists and is not disabled, whatever its auth mode. It is deliberately weaker than `shouldIncludeAccountBoundNativeOpenAi` (canonical forward auth is an account-qualified requirement) and deliberately omits `shouldIncludeNativeOpenAi`'s no-enabled-provider bootstrap exception, which keeps the Codex catalog listable rather than promising a servable row. `loadExportModels` and the launcher now both consult it. Direct-mode omission for the launcher is unchanged, and the Pi/DSH rosters keep their own stronger credential rule. Regression coverage: `tests/server/management-model-roster.test.ts` (enabled in both modes, disabled in both modes, absent provider), `tests/providers/opencode-cli.test.ts` (slug selection and proxy-row catalog under a disabled provider), plus the three fixtures that described a config without `providers.openai` while asserting native rows — an unrepresentable state, since a fresh install materializes that provider enabled. Docs: `structure/clients/export-model-names.md` records the admission rule, and the OpenCode guide states when native rows are omitted. * docs(opencode): translate the native-row admission note The English guide gained a paragraph explaining when native OpenAI slug rows are omitted from the picker. `tests/ci-workflows/docs-spanish-localization.test.ts` requires every inline code identifier in the canonical page to appear in the Spanish translation, so the untranslated paragraph failed that gate on `openai` and `gpt-*`. AGENTS.md also requires translated locales not to contradict the English source, so all eight translated guides carry the same statement rather than only the one the gate reads. * docs(structure): place the native-row admission rule as its own section The paragraph had landed inside 'Selector proof', between the alias-candidate sentence and the paragraph that continues it. It is a separate invariant about which rows the export roster may publish, so it now stands on its own after 'Stored connection mode', before the CLI and API boundary. * fix(clients): drop native rows from the managed OpenCode config in Direct mode Codex Direct forwards each caller's own OpenAI bearer, while opencode sends the proxy's admission key, so a native `gpt-*` row can only answer 401 in that mode. The launcher and `ocx export` already omit those rows, and Pi and DSH do the same in their own builders, but the managed integration built its document straight from the export roster and kept them. A managed apply therefore wrote a config listing models that fail when selected. `buildOpencodeClientConfig` now filters native rows when the canonical provider is in Direct mode, so the managed document, the launcher and the CLI export agree about which selectors a Direct-mode client may be offered. The roster itself is unchanged: it still exports native rows for clients that select their own credential. The regression test asserts both config generations in both account modes, including that the synthetic Fast row goes with its native parent. Found by CodeRabbit review on #9042. * fix(clients): drop only bare native rows from the managed OpenCode config in Direct mode The previous filter dropped every row with `native: true` in Codex Direct mode. Account-qualified native rows carry the same flag — `listManagementModelRows` builds `/` rows when `shouldIncludeAccountBoundNativeOpenAi` passes, which it does in Direct mode whenever the canonical provider forwards — so the filter removed rows that actually work. `routeModelInternal` resolves an account-qualified selector to one exact account and stamps `codexAccountMode: "pool"` on the route, so those requests are served from the pool credential rather than the caller's own bearer. Only the bare `gpt-*` form depends on the caller's credential, which is the whole reason Direct mode cannot offer it. `isBareNativeRow` now decides that the way the router does: a row is bare unless its first path segment is a configured `codexAccountNamespaces` key, so a routed row with a slash is not mistaken for an account row either. The new regression test asserts a qualified row survives in both config generations while the bare row is dropped; it fails against the previous filter. Found by CodeRabbit review on #9042. * fix(clients): keep account-qualified native rows across Direct-mode exports Co-authored-by: Yogesh Aggarwal * docs(opencode): distinguish bare gpt-* omission from account-qualified rows in Direct mode * fix(clients): unify Direct-mode bare-native filtering across Pi-family exports and verify credential-routing contract * fix(clients): enforce Direct-mode bare-native filtering across all exported clients and add HTTP admission coverage --------- Co-authored-by: Yogesh Aggarwal --- .../src/content/docs/es/guides/opencode.md | 2 + .../src/content/docs/fr/guides/opencode.md | 2 + docs-site/src/content/docs/guides/opencode.md | 7 + .../src/content/docs/ja/guides/opencode.md | 2 + .../src/content/docs/ko/guides/opencode.md | 2 + .../src/content/docs/ru/guides/opencode.md | 2 + .../src/content/docs/tr/guides/opencode.md | 2 + .../src/content/docs/zh-cn/guides/opencode.md | 2 + .../src/content/docs/zh-tw/guides/opencode.md | 2 + src/cli/opencode.ts | 18 +- src/clients/config-export.ts | 34 ++- src/clients/config-export/agent-clients.ts | 4 +- src/clients/config-export/alias-selectors.ts | 9 +- src/clients/config-export/contracts.ts | 41 +++ src/clients/config-export/dsh.ts | 4 +- src/clients/config-export/omp.ts | 4 +- src/codex/catalog.ts | 2 +- src/codex/catalog/metadata.ts | 18 ++ src/server/management/model-rows.ts | 10 +- structure/clients/export-model-names.md | 45 +++ tests/cli/cli-export-command.test.ts | 13 +- tests/config/client-config-export.test.ts | 269 ++++++++++++++++++ tests/providers/opencode-cli.test.ts | 69 ++++- .../management-client-config-route.test.ts | 10 + tests/server/management-model-roster.test.ts | 53 ++++ 25 files changed, 598 insertions(+), 28 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/opencode.md b/docs-site/src/content/docs/es/guides/opencode.md index f871c0f940a..36afe625331 100644 --- a/docs-site/src/content/docs/es/guides/opencode.md +++ b/docs-site/src/content/docs/es/guides/opencode.md @@ -22,6 +22,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +Las filas `gpt-*` nativas de OpenAI sin prefijo aparecen solo mientras el proveedor canónico `openai` esté activado y no esté en modo Codex Direct; las filas `/gpt-*` calificadas por cuenta que siguen siendo utilizables permanecen en la exportación aunque el modo Codex Direct esté activo. El modo Direct reenvía la credencial de OpenAI de cada invocador, mientras que opencode envía la clave del proxy, y un proveedor `openai` desactivado hace que el proxy rechace todos los selectores `gpt-*` sin prefijo; en ambos estados, el lanzador, la integración administrada y `ocx export` omiten las filas `gpt-*` sin prefijo en lugar de ofrecer un modelo que no puede ejecutarse. + ## Protocolo por modelo diff --git a/docs-site/src/content/docs/fr/guides/opencode.md b/docs-site/src/content/docs/fr/guides/opencode.md index ee5a1dca96f..f0ba5ffd5ff 100644 --- a/docs-site/src/content/docs/fr/guides/opencode.md +++ b/docs-site/src/content/docs/fr/guides/opencode.md @@ -26,6 +26,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +Les lignes natives OpenAI `gpt-*` nues n'apparaissent que tant que le fournisseur canonique `openai` est activé et que le mode Codex Direct est désactivé ; les lignes `/gpt-*` qualifiées par compte et utilisables restent dans l'export lorsque le mode Codex Direct est actif. Le mode Direct transmet la propre clé OpenAI de chaque appelant alors qu'opencode envoie la clé du proxy, et un fournisseur `openai` désactivé fait que le proxy refuse tous les sélecteurs `gpt-*` nus ; dans ces deux états, le lanceur, l'intégration gérée et `ocx export` omettent les lignes `gpt-*` nues plutôt que de proposer un modèle qui ne peut pas s'exécuter. + ## Votre propre configuration n'est jamais modifiée Le lanceur ne copie ni ne réécrit `~/.config/opencode/opencode.json`, diff --git a/docs-site/src/content/docs/guides/opencode.md b/docs-site/src/content/docs/guides/opencode.md index cee6b169344..608c09c78a2 100644 --- a/docs-site/src/content/docs/guides/opencode.md +++ b/docs-site/src/content/docs/guides/opencode.md @@ -28,6 +28,13 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +Bare native OpenAI `gpt-*` rows appear only while the canonical `openai` provider is enabled and not +in Codex Direct mode; usable account-qualified `/gpt-*` rows stay in the export while +Codex Direct mode is on. Direct mode forwards each caller's own OpenAI credential while opencode +sends the proxy's key, and a disabled `openai` provider makes the proxy refuse every bare `gpt-*` +selector; in both states the launcher, the managed integration and `ocx export` leave bare `gpt-*` +rows out rather than offering a model that cannot run. + ## Protocol per model Both blocks send requests to `/v1/responses` by default: V1 through `@ai-sdk/openai`, V2 through diff --git a/docs-site/src/content/docs/ja/guides/opencode.md b/docs-site/src/content/docs/ja/guides/opencode.md index 64c647dcbe8..732bc53aef4 100644 --- a/docs-site/src/content/docs/ja/guides/opencode.md +++ b/docs-site/src/content/docs/ja/guides/opencode.md @@ -20,6 +20,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +前置きのないネイティブ OpenAI の `gpt-*` 行は、正規の `openai` プロバイダーが有効で、かつ Codex Direct モードでない間だけ表示されます。Codex Direct モードが有効な間も、利用可能なアカウント修飾付き `/gpt-*` 行はエクスポートに残ります。Direct モードでは各呼び出し元自身の OpenAI 認証情報を転送しますが、opencode はプロキシのキーを送信します。また、`openai` プロバイダーが無効な場合、プロキシは前置きのない `gpt-*` セレクターをすべて拒否します。どちらの状態でも、ランチャー、管理対象の統合、および `ocx export` は、実行できないモデルを提示する代わりに前置きのない `gpt-*` 行を省略します。 + ## あなた自身の設定は決して変更されません ランチャーは、`~/.config/opencode/opencode.json`、プロジェクト `opencode.json` / `opencode.jsonc`、またはその他のディスク上の構成レイヤーをコピーしたり書き換えたりしません。既存のプロバイダー、エージェント、キーバインド、MCP エントリ、および相対的な `{file:…}` 参照は元のファイルから解決され続けますが、`provider.opencodex` または `providers.opencodex` オーバーライドを検出するためにグローバルまたはプロジェクト設定を読み取ることがあります。 diff --git a/docs-site/src/content/docs/ko/guides/opencode.md b/docs-site/src/content/docs/ko/guides/opencode.md index 2be33661fb6..a04bee14026 100644 --- a/docs-site/src/content/docs/ko/guides/opencode.md +++ b/docs-site/src/content/docs/ko/guides/opencode.md @@ -26,6 +26,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +접두사가 없는 네이티브 OpenAI `gpt-*` 행은 정규 `openai` provider가 활성화되어 있고 Codex Direct 모드가 아닐 때만 나타납니다. Codex Direct 모드가 켜져 있어도 사용 가능한 계정 한정 `/gpt-*` 행은 내보내기에 유지됩니다. Direct 모드에서는 각 호출자의 OpenAI 자격 증명을 전달하지만 opencode는 프록시의 키를 보냅니다. 또한 `openai` provider가 비활성화되면 프록시는 접두사가 없는 모든 `gpt-*` 선택자를 거부합니다. 두 상태 모두에서 런처, 관리형 통합 및 `ocx export`는 실행할 수 없는 모델을 제공하는 대신 접두사가 없는 `gpt-*` 행을 생략합니다. + ## 사용자 구성은 절대 수정되지 않습니다 런처는 `~/.config/opencode/opencode.json`, 프로젝트의 `opencode.json` / diff --git a/docs-site/src/content/docs/ru/guides/opencode.md b/docs-site/src/content/docs/ru/guides/opencode.md index cc62cbe1080..d95223166a4 100644 --- a/docs-site/src/content/docs/ru/guides/opencode.md +++ b/docs-site/src/content/docs/ru/guides/opencode.md @@ -25,6 +25,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +Строки нативных селекторов OpenAI `gpt-*` без префикса появляются только пока канонический провайдер `openai` включён и режим Codex Direct не активен; при включённом режиме Codex Direct пригодные к маршрутизации строки с префиксом аккаунта `/gpt-*` сохраняются в экспорте. В режиме Direct каждый вызывающий передаёт свой собственный ключ OpenAI, а opencode отправляет ключ прокси, а при отключённом провайдере `openai` прокси отвергает все непредварённые селекторы `gpt-*`; в обоих состояниях лончер, управляемая интеграция и `ocx export` не выводят строки `gpt-*` без префикса, а не предлагают модель, которую невозможно запустить. + ## Ваша собственная конфигурация никогда не меняется Лончер не копирует и не переписывает `~/.config/opencode/opencode.json`, diff --git a/docs-site/src/content/docs/tr/guides/opencode.md b/docs-site/src/content/docs/tr/guides/opencode.md index dc76f48d24c..b5bc2d556eb 100644 --- a/docs-site/src/content/docs/tr/guides/opencode.md +++ b/docs-site/src/content/docs/tr/guides/opencode.md @@ -27,6 +27,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # yerel slug'lar öneksiz kalır ``` +Öneksiz yerel OpenAI `gpt-*` satırları yalnızca kanonik `openai` sağlayıcısı etkinken ve Codex Direct modunda değilken görünür; Codex Direct modu açıkken kullanılabilir hesap nitelikli `/gpt-*` satırları dışa aktarımda korunur. Direct modu her çağıranın kendi OpenAI kimlik bilgisini iletirken opencode proxy'nin anahtarını gönderir ve devre dışı bir `openai` sağlayıcısı proxy'nin öneksiz tüm `gpt-*` seçicilerini reddetmesine yol açar; her iki durumda da başlatıcı, yönetilen entegrasyon ve `ocx export` çalıştırılamayan bir model sunmak yerine öneksiz `gpt-*` satırlarını atlar. + ## Kendi yapılandırmanız asla değiştirilmez Başlatıcı `~/.config/opencode/opencode.json`, proje `opencode.json` / diff --git a/docs-site/src/content/docs/zh-cn/guides/opencode.md b/docs-site/src/content/docs/zh-cn/guides/opencode.md index e3ffcffd062..0dfa8ef58f7 100644 --- a/docs-site/src/content/docs/zh-cn/guides/opencode.md +++ b/docs-site/src/content/docs/zh-cn/guides/opencode.md @@ -20,6 +20,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +只有当规范 `openai` provider 已启用且不处于 Codex Direct 模式时,不带前缀的原生 OpenAI `gpt-*` 行才会出现;开启 Codex Direct 模式时,可用的账号限定 `/gpt-*` 行仍会保留在导出结果中。Direct 模式转发每个调用方自己的 OpenAI 凭据,而 opencode 发送的是代理的密钥;`openai` provider 被禁用时,代理会拒绝所有不带前缀的 `gpt-*` 选择器。在这两种状态下,启动器、托管集成和 `ocx export` 都会省略不带前缀的 `gpt-*` 行,而不是提供一个无法运行的模型。 + ## 你的配置绝不会被修改 启动器不会复制或重写 `~/.config/opencode/opencode.json`、项目中的 `opencode.json` / `opencode.jsonc`,也不会处理任何其他磁盘上的配置层。它可能会读取全局或项目配置,以检测是否存在 `provider.opencodex` 或 `providers.opencodex` 覆盖;而你现有的 providers、agents、keybinds、MCP 条目以及相对路径的 `{file:…}` 引用,都会继续从它们原本的文件中解析。 diff --git a/docs-site/src/content/docs/zh-tw/guides/opencode.md b/docs-site/src/content/docs/zh-tw/guides/opencode.md index 517f5ce066e..e2d3472b4c3 100644 --- a/docs-site/src/content/docs/zh-tw/guides/opencode.md +++ b/docs-site/src/content/docs/zh-tw/guides/opencode.md @@ -20,6 +20,8 @@ opencodex/kiro/glm-5 opencodex/gpt-5.6-sol # native slugs stay unprefixed ``` +只有在標準 `openai` 供應商已啟用且未處於 Codex Direct 模式時,不帶前綴的原生 OpenAI `gpt-*` 列才會出現;開啟 Codex Direct 模式時,可用的帳號限定 `/gpt-*` 列仍會保留在匯出結果中。Direct 模式會轉送每個呼叫者自己的 OpenAI 憑證,而 opencode 送出的是代理的密鑰;當 `openai` 供應商被停用時,代理會拒絕所有不帶前綴的 `gpt-*` 選擇器。在這兩種狀態下,啟動器、受管理的整合與 `ocx export` 都會省略不帶前綴的 `gpt-*` 列,而不是提供一個無法執行的模型。 + ## 你自己的設定絕不會被修改 啟動器不會複製或改寫 `~/.config/opencode/opencode.json`、專案的 `opencode.json` / `opencode.jsonc`,或任何其他磁碟上的設定層。它可能會讀取全域或專案設定以偵測 `provider.opencodex` 或 `providers.opencodex` 覆寫,而你既有的供應商、agents、keybinds、MCP 項目,以及相對路徑的 `{file:…}` 參考,仍會從原本的檔案解析。 diff --git a/src/cli/opencode.ts b/src/cli/opencode.ts index 39989946744..0bce0b65b85 100644 --- a/src/cli/opencode.ts +++ b/src/cli/opencode.ts @@ -26,6 +26,7 @@ import { OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG, OPENCODE_PROVIDER_ID, buildOpencodeProviderBlockFromCatalog, + isBareNativeRow, opencodeGlobalConfigPath, opencodeProviderBlocks, opencodeProxyBaseUrl, @@ -41,7 +42,7 @@ import type { } from "../clients/config-export"; import type { EffectiveModelExportMetadata } from "../clients/config-export/contracts"; import { resolveExportReasoningAxes } from "../clients/config-export/reasoning-metadata"; -import { filterCatalogVisibleModels, visibleNativeSlugs } from "../codex/catalog"; +import { filterCatalogVisibleModels, isNativeOpenAiProviderEnabled, visibleNativeSlugs } from "../codex/catalog"; import { commandInvocation } from "../lib/win-exec"; import { configuredAdminToken, opencodeCatalogToken } from "../lib/admin-secrets"; import { localManagementOrigin } from "../lib/local-destinations"; @@ -161,10 +162,16 @@ export function opencodeModelKey(provider: string, id: string): string { } /** - * Native OpenAI slugs advertised to opencode. Omitted in Codex Direct mode because native - * chat-completions require the caller's real ChatGPT OAuth bearer, not proxy admission. + * Native OpenAI slugs advertised to opencode. + * + * Omitted in Codex Direct mode because native chat-completions require the caller's real + * ChatGPT OAuth bearer, not proxy admission — the same reason the Pi, DSH and shared export + * rosters drop them. Also omitted when the canonical OpenAI provider is disabled, because then + * the router refuses every bare `gpt-*` selector with `NoEnabledOpenAiProviderError` no matter + * which account mode is configured. */ export function opencodeLaunchNativeSlugs(config: OcxConfig): string[] { + if (!isNativeOpenAiProviderEnabled(config)) return []; if (providerCodexAccountMode("openai", config.providers?.openai) === "direct") return []; return [...visibleNativeSlugs(config)]; } @@ -369,7 +376,8 @@ export function opencodeCatalogFromProxyRows( rows: readonly OpencodeProxyModelRow[], config: OcxConfig, ): OpencodeCatalogModel[] { - const omitNative = providerCodexAccountMode("openai", config.providers?.openai) === "direct"; + const omitAllNative = !isNativeOpenAiProviderEnabled(config); + const omitBareNative = providerCodexAccountMode("openai", config.providers?.openai) === "direct"; const routedRows = rows.filter((row): row is OpencodeProxyModelRow & { provider: string; id: string } => row.native !== true && typeof row.provider === "string" && typeof row.id === "string"); const visibleRouted = new Set(filterCatalogVisibleModels(routedRows, config)); @@ -378,7 +386,7 @@ export function opencodeCatalogFromProxyRows( for (const row of rows) { const namespaced = row.namespaced?.trim(); if (!namespaced || row.disabled === true) continue; - if (omitNative && row.native === true) continue; + if (row.native === true && (omitAllNative || (omitBareNative && isBareNativeRow({ native: true, namespaced }, config)))) continue; if (row.native !== true && typeof row.provider === "string" && typeof row.id === "string" && !visibleRouted.has(row)) continue; if (seen.has(namespaced)) continue; diff --git a/src/clients/config-export.ts b/src/clients/config-export.ts index 77db8f4c977..2124669439d 100644 --- a/src/clients/config-export.ts +++ b/src/clients/config-export.ts @@ -897,9 +897,27 @@ export function buildOpencodeProviderBlockFromCatalog( * opencode's decision, not a consequence of where we write it. Both blocks are generated in * one pass so they cannot disagree about the model set, the names, or the connection. */ +export { filterDirectModeBareNative, isBareNativeRow } from "./config-export/contracts"; +import { filterDirectModeBareNative, isBareNativeRow } from "./config-export/contracts"; + function buildOpencodeClientConfig(ctx: ExportContext): OpencodeGeneratedConfig { - const models = normalizeExportModels(ctx.models); const config = ctx.config ?? OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG; + // Codex Direct forwards each caller's own bearer, while opencode sends the proxy's + // admission key, so a *bare* native row could only ever answer 401. Pi, DSH and the + // CLI's `ocx export` already drop those rows in that mode; the managed integration is + // the same client surface and has to agree, or a managed apply would list models that + // fail when selected. `ctx.config` is undefined for a caller that has no live config, + // and Direct cannot be claimed without one. + // + // Account-qualified rows (`/`), which also carry `native: true`, are + // deliberately kept: `routeModelInternal` assigns `codexAccountMode: "pool"` with the + // namespace's fixed account. Non-main namespaces always resolve to that exact stored pool + // account regardless of any caller bearer; the `__main__` namespace resolves to the stored + // `main-pool` credential for proxy-key / loopback clients (no caller-owned Codex JWT), while + // callers carrying their own Codex JWT preserve their existing caller-owned `main` context + // (`src/codex/auth-context.ts`). In both cases these rows remain servable in Direct mode. + const models = normalizeExportModels(ctx.models).filter(model => + !(isBareNativeRow(model, config) && providerCodexAccountMode("openai", config.providers?.openai) === "direct")); const blocks = opencodeProviderBlocks(ctx.baseUrl, models, config, { keylessInference: ctx.keylessInference === true }); return { $schema: OPENCODE_CONFIG_SCHEMA, @@ -929,10 +947,10 @@ export interface PiProviderCompat { interface PiExportOptions { sendSessionAffinityHeaders?: boolean; /** - * Drop native OpenAI rows when the serving proxy runs Codex Direct (`codexAccountMode: direct`). - * Direct mode forwards the caller's own bearer, and Pi sends the loopback placeholder key, so a - * native row would only ever answer 401. The CLI-built Pi export omitted them before the export - * moved onto the serving proxy's roster (#8172); this keeps that behaviour. + * Drop bare native OpenAI `gpt-*` rows when the serving proxy runs Codex Direct + * (`codexAccountMode: direct`). Defaults to `true` because every client built by + * `buildPiClientConfig` (Pi, Prime, Aside, omo, Gentle Shell) sends the loopback placeholder + * key rather than a caller-owned OpenAI bearer, so a bare native row would answer 401. */ omitNativeInCodexDirect?: boolean; /** @@ -1112,10 +1130,10 @@ export interface GajaeGeneratedConfig { function buildPiClientConfig(ctx: ExportContext, options: PiExportOptions = {}): PiGeneratedConfig { const models: PiModelEntry[] = []; const roster = options.rawNestedModelIds ? selectNestedSelectors(ctx.models) : ctx.models; - const omitNative = options.omitNativeInCodexDirect === true + const omitBareNative = options.omitNativeInCodexDirect !== false && providerCodexAccountMode("openai", ctx.config?.providers?.openai) === "direct"; for (const model of normalizeExportModels(roster)) { - if (omitNative && model.native === true) continue; + if (omitBareNative && isBareNativeRow(model, ctx.config)) continue; // Text is the one modality every routed model supports; anything richer must come // from the catalog rather than an assumption — and must still be inside the enum // Pi accepts, because one rejected value empties the whole config. @@ -1282,7 +1300,7 @@ function buildKimiClientConfig(ctx: ExportContext): KimiGeneratedConfig { function buildGajaeClientConfig(ctx: ExportContext): GajaeGeneratedConfig { const models: GajaeModelEntry[] = []; - for (const model of normalizeExportModels(ctx.models)) { + for (const model of normalizeExportModels(filterDirectModeBareNative(ctx.models, ctx.config))) { // Gajae's enum is text|image and it rejects the whole file over one bad // value, naming the offending index in the error. const input = inputModalitiesForClient("gajae", model.inputModalities); diff --git a/src/clients/config-export/agent-clients.ts b/src/clients/config-export/agent-clients.ts index 95547e0a306..7db746bc62e 100644 --- a/src/clients/config-export/agent-clients.ts +++ b/src/clients/config-export/agent-clients.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { isLoopbackHostname, shouldInjectApiAuthHeader } from "../../codex/loopback-target"; import { absoluteClientPath } from "../client-path"; import { parseSegment } from "../../integrations/merge"; -import type { ExportContext, ExportClientId, ManagedContribution, OpencodeLaunchEnv } from "./contracts"; +import { filterDirectModeBareNative, type ExportContext, type ExportClientId, type ManagedContribution, type OpencodeLaunchEnv } from "./contracts"; import { LOOPBACK_API_KEY_PLACEHOLDER } from "./constants"; import { normalizeExportModels, authoritativeContextWindow } from "./model-metadata"; import { buildQoderClientConfig, buildQoderContribution } from "./qoder"; @@ -37,7 +37,7 @@ function modelSelector(id: string): string | null { } function workbuddyRows(ctx: ExportContext) { - return normalizeExportModels(ctx.models).map(model => { + return normalizeExportModels(filterDirectModeBareNative(ctx.models, ctx.config)).map(model => { return { id: model.namespaced, name: `OpenCodex: ${model.displayName ?? model.namespaced}`, diff --git a/src/clients/config-export/alias-selectors.ts b/src/clients/config-export/alias-selectors.ts index ddcdd3a6732..169d316dd92 100644 --- a/src/clients/config-export/alias-selectors.ts +++ b/src/clients/config-export/alias-selectors.ts @@ -1,4 +1,4 @@ -import type { ExportClientId, ExportContext, ExportModel } from "./contracts"; +import { filterDirectModeBareNative, type ExportClientId, type ExportContext, type ExportModel } from "./contracts"; import { resolveModelNames, selectExportModelNames } from "./model-names"; import { effectiveModelAliases, effectiveProviderAlias, MODEL_ALIAS_PATTERN } from "../../providers/default-aliases"; import { knownModelIdsForProvider, previewRouteModel, type RouteResult } from "../../router"; @@ -98,11 +98,12 @@ export function attachExportAliasSelectors(config: OcxConfig, input: readonly Ex } export function namedExportContext(client: ExportClientId, ctx: ExportContext): ExportContext { + const scopedModels = filterDirectModeBareNative(ctx.models, ctx.config); const mode = resolveModelNames(client, ctx.modelNames); - if (mode === "routed") return ctx; + if (mode === "routed") return { ...ctx, models: scopedModels }; // Use the caller's exact captured configuration. Discovery may have returned // an old projection, or caches may have changed since the retained proof. - const models = ctx.config ? attachExportAliasSelectors(ctx.config, ctx.models) - : ctx.models.map(({ aliasNamespaced: _priorCandidate, ...model }) => model); + const models = ctx.config ? attachExportAliasSelectors(ctx.config, scopedModels) + : scopedModels.map(({ aliasNamespaced: _priorCandidate, ...model }) => model); return { ...ctx, models: selectExportModelNames(models, mode) }; } diff --git a/src/clients/config-export/contracts.ts b/src/clients/config-export/contracts.ts index b89e924e974..d71ad530a79 100644 --- a/src/clients/config-export/contracts.ts +++ b/src/clients/config-export/contracts.ts @@ -2,6 +2,7 @@ import type { ExportClientId } from "../client-ids"; export type { ExportClientId } from "../client-ids"; import { canonicalizeReasoningEfforts } from "../../reasoning-effort"; +import { providerCodexAccountMode } from "../../providers/registry"; import type { OcxConfig } from "../../types"; import type { ConfigFormat } from "../../integrations/serialize"; import type { ExportModelNames } from "./model-names"; @@ -195,6 +196,46 @@ export function knownReasoningSupport(evidence: ExportCapabilityEvidence): boole return undefined; } +/** + * A native row addressed by its bare `gpt-*` slug, as opposed to an account-qualified + * `/` row. Bare rows require a caller-owned bearer in Codex Direct and 401 + * for proxy-key / loopback clients. Account-qualified rows route with `codexAccountMode: "pool"` + * and a fixed account: non-main namespaces always use that exact stored pool account, and the + * `__main__` namespace uses stored `main-pool` for proxy-key / loopback clients (while preserving + * the existing caller-owned `main` context when a caller supplies its own Codex JWT). + * + * A row is account-qualified when its first path segment is a configured Codex account + * namespace — the same spelling `routeModelInternal` uses to resolve + * `config.codexAccountNamespaces` — so this tracks the router rather than guessing from a + * slash that a routed row could also carry. + */ +export function isBareNativeRow( + model: { native?: boolean; namespaced: string }, + config?: Pick, +): boolean { + if (model.native !== true) return false; + const slash = model.namespaced.indexOf("/"); + if (slash <= 0) return true; + const namespace = model.namespaced.slice(0, slash); + return !Object.keys(config?.codexAccountNamespaces ?? {}).includes(namespace); +} + +/** + * Drop bare native OpenAI `gpt-*` rows when the serving config runs canonical `openai` in + * Codex Direct mode. Managed/exported clients send loopback placeholders or proxy admission + * keys rather than caller-owned OpenAI bearers, so bare Direct rows cannot run while + * account-qualified `/gpt-*` rows remain servable. + */ +export function filterDirectModeBareNative( + models: readonly T[], + config?: OcxConfig, +): T[] { + if (providerCodexAccountMode("openai", config?.providers?.openai) !== "direct") { + return [...models]; + } + return models.filter(model => !isBareNativeRow(model, config)); +} + export interface ExportContext { modelNames?: ExportModelNames; /** `http://host:port/v1` — the OpenAI-compatible surface the client dials. */ diff --git a/src/clients/config-export/dsh.ts b/src/clients/config-export/dsh.ts index a29de31ee92..b385975c360 100644 --- a/src/clients/config-export/dsh.ts +++ b/src/clients/config-export/dsh.ts @@ -1,5 +1,5 @@ // DSH config export. -import type { ExportModel, ExportContext, ManagedContribution } from "./contracts"; +import { isBareNativeRow, type ExportModel, type ExportContext, type ManagedContribution } from "./contracts"; import type { OcxConfig } from "../../types"; import { providerCodexAccountMode } from "../../providers/registry"; import { normalizeExportModels, authoritativeContextWindow, exportModelLabel, knownOutputBudget, singleFragment } from "./model-metadata"; @@ -97,7 +97,7 @@ export function buildDshClientConfig(ctx: ExportContext): DshGeneratedConfig { const direct = providerCodexAccountMode("openai", ctx.config?.providers?.openai) === "direct"; const models: DshModelEntry[] = []; for (const model of normalizeExportModels(ctx.models)) { - if (direct && (model.native === true || model.provider === "openai")) continue; + if (direct && (isBareNativeRow(model, ctx.config) || (model.native !== true && model.provider === "openai"))) continue; if (direct && model.provider === "combo" && (!ctx.config || !isKnownSafeDshCombo(model, ctx.config))) continue; const input = dshInputModalities(model.inputModalities); if (input === null) continue; diff --git a/src/clients/config-export/omp.ts b/src/clients/config-export/omp.ts index 61d986a0437..6f37df4dd52 100644 --- a/src/clients/config-export/omp.ts +++ b/src/clients/config-export/omp.ts @@ -1,5 +1,5 @@ // Oh My Pi config export. -import type { PiModelEntry, ExportModel, ExportContext, ManagedContribution } from "./contracts"; +import { filterDirectModeBareNative, type PiModelEntry, type ExportModel, type ExportContext, type ManagedContribution } from "./contracts"; import { PI_API_DIALECT, OPENCODE_PROVIDER_ID, LOOPBACK_API_KEY_PLACEHOLDER } from "./constants"; import { normalizeExportModels, inputModalitiesForClient, exportModelLabel, authoritativeContextWindow, outputBudgetFor, singleFragment } from "./model-metadata"; @@ -55,7 +55,7 @@ function ompEfforts(model: ExportModel): string[] { */ export function buildOmpClientConfig(ctx: ExportContext): OmpGeneratedConfig { const models: OmpModelEntry[] = []; - for (const model of normalizeExportModels(ctx.models)) { + for (const model of normalizeExportModels(filterDirectModeBareNative(ctx.models, ctx.config))) { const input = inputModalitiesForClient("pi", model.inputModalities); if (input === null) continue; const entry: OmpModelEntry = { diff --git a/src/codex/catalog.ts b/src/codex/catalog.ts index eab54289c4f..d18c9424894 100644 --- a/src/codex/catalog.ts +++ b/src/codex/catalog.ts @@ -2,7 +2,7 @@ // Public surface preserved exactly; importers keep using "src/codex/catalog". export { isMediaGenerationModelId, shouldExposeRoutedModel, readCodexCatalogPath, readCatalog, normalizeRoutedCatalogEntry, catalogModelSlug, filterSupportedNativeSlugs, catalogModelSupportsReasoningSummaries } from "./catalog/parsing"; export type { CatalogModel, MultiAgentMode } from "./catalog/parsing"; -export { accountBoundNativeOpenAiSlugs, accountBoundNativeOpenAiSlugsBySelector, CODEX_NATIVE_ALIAS_CATALOG_KIND, NATIVE_DAYBREAK_BLUE_MODEL, NATIVE_GPT6_ASTRA_MODEL, NATIVE_GPT56_CONTEXT_WINDOW, NATIVE_GPT56_MAX_INPUT_TOKENS, NATIVE_GPT56_OPT_IN_CONTEXT_WINDOW, NATIVE_OPENAI_CAPABILITY_ALIAS_MODELS, NATIVE_OPENAI_MODELS, configuredNativeAliasSlugs, desktopAllowlistSuppressedNativeSlugs, isNativeAliasCatalogEntry, isNativeOpenAiCapabilityAliasModel, nativeContextLimits, nativeOpenAiCapabilitySourceSlug, nativeOpenAiContextWindow, nativeOpenAiMaxInputTokens, nativeOpenAiMaxOutputTokens, nativeOpenAiContextTier, disabledNativeSlugs, visibleNativeSlugs, desktopVisibleNativeSlugs, nativeModelRows, applyNativeVisibility, observedAccountBoundNativeEntries, observedAccountBoundNativeOpenAiSlugs, upstreamNativeEntry, nativeOpenAiSlugs, listCatalogNativeSlugs, nativeInputModalities, nativeReasoningEfforts, nativeDefaultReasoningEffort, shouldIncludeAccountBoundNativeOpenAi, shouldIncludeNativeOpenAi, type NativeContextLimits, type NativeContextLimitsInput } from "./catalog/metadata"; +export { accountBoundNativeOpenAiSlugs, accountBoundNativeOpenAiSlugsBySelector, CODEX_NATIVE_ALIAS_CATALOG_KIND, NATIVE_DAYBREAK_BLUE_MODEL, NATIVE_GPT6_ASTRA_MODEL, NATIVE_GPT56_CONTEXT_WINDOW, NATIVE_GPT56_MAX_INPUT_TOKENS, NATIVE_GPT56_OPT_IN_CONTEXT_WINDOW, NATIVE_OPENAI_CAPABILITY_ALIAS_MODELS, NATIVE_OPENAI_MODELS, configuredNativeAliasSlugs, desktopAllowlistSuppressedNativeSlugs, isNativeAliasCatalogEntry, isNativeOpenAiCapabilityAliasModel, nativeContextLimits, nativeOpenAiCapabilitySourceSlug, nativeOpenAiContextWindow, nativeOpenAiMaxInputTokens, nativeOpenAiMaxOutputTokens, nativeOpenAiContextTier, disabledNativeSlugs, visibleNativeSlugs, desktopVisibleNativeSlugs, nativeModelRows, applyNativeVisibility, observedAccountBoundNativeEntries, observedAccountBoundNativeOpenAiSlugs, upstreamNativeEntry, nativeOpenAiSlugs, listCatalogNativeSlugs, nativeInputModalities, nativeReasoningEfforts, nativeDefaultReasoningEffort, shouldIncludeAccountBoundNativeOpenAi, shouldIncludeNativeOpenAi, isNativeOpenAiProviderEnabled, type NativeContextLimits, type NativeContextLimitsInput } from "./catalog/metadata"; export { isSpawnableCodexCandidate, codexExecInvocation, loadBundledCodexCatalog, materializeBundledCodexCatalog, loadCatalogTemplate } from "./catalog/bundled"; export { nativeEffortClamp, shouldApplyNativeEffortClamp, catalogModelEfforts, catalogModelLadders, codexSupportedReasoningEfforts, clampedDefaultEffort, clampEntryToCodexSupportedEfforts, clampCatalogModelsToCodexSupport } from "./catalog/effort"; export { applyProviderConfigHints, isDatedVariantId, filterCatalogVisibleModels, gatherRoutedModels, clearGatherRoutedModelsInflight, augmentRoutedModelsWithRegistryOpenAiApiRows, augmentRoutedModelsWithMetadata, resolveComboCatalogMember, configuredComboTargetModelsByProvider } from "./catalog/provider-fetch"; diff --git a/src/codex/catalog/metadata.ts b/src/codex/catalog/metadata.ts index 5ad781ffc2c..a4213703a2f 100644 --- a/src/codex/catalog/metadata.ts +++ b/src/codex/catalog/metadata.ts @@ -506,6 +506,24 @@ export function shouldIncludeAccountBoundNativeOpenAi( return isCanonicalOpenAiForwardProvider(canonical); } +/** + * Whether the canonical OpenAI provider can route a bare native selector at all. + * + * This is the router's own admission for a bare `gpt-*` model (`routeModelInternal`): the + * provider is present and not disabled, whatever its auth mode. It is deliberately weaker than + * `shouldIncludeAccountBoundNativeOpenAi`, whose exact-account routes additionally require + * canonical forward auth, and it deliberately omits `shouldIncludeNativeOpenAi`'s + * no-enabled-provider bootstrap exception, which keeps the Codex catalog listable rather than + * claiming that any native row can be served. + * + * Everything that promises a client a selectable model has to use this: a disabled provider is + * what makes `NoEnabledOpenAiProviderError` the answer for every bare native id. + */ +export function isNativeOpenAiProviderEnabled(config: Pick): boolean { + const provider = config.providers[OPENAI_CODEX_PROVIDER_ID]; + return provider !== undefined && provider.disabled !== true; +} + /** Whether native ChatGPT/Codex rows belong in this provider configuration. */ export function shouldIncludeNativeOpenAi(config: Pick): boolean { const hasEnabledProvider = Object.values(config.providers) diff --git a/src/server/management/model-rows.ts b/src/server/management/model-rows.ts index b418344aac6..e9ca198de28 100644 --- a/src/server/management/model-rows.ts +++ b/src/server/management/model-rows.ts @@ -28,6 +28,7 @@ import { nativeModelRows, nativeReasoningEfforts, uniqueCatalogModelsForPublicList, + isNativeOpenAiProviderEnabled, shouldIncludeAccountBoundNativeOpenAi, catalogModelEfforts, } from "../../codex/catalog"; @@ -710,8 +711,15 @@ export async function loadExportModels( // Management deliberately lists the full roster so hidden models can be enabled. // A client picker must also honor the provider selection, not just its blocklist. const visibleRouted = new Set(filterCatalogVisibleModels(rows.filter(row => !row.native), admitted)); + // A native row is only selectable while the canonical OpenAI provider can route it. The + // router answers a bare `gpt-*` with `NoEnabledOpenAiProviderError` as soon as that provider + // is disabled, so exporting the row would hand a client a selector the proxy refuses. The + // account-qualified rows that `listManagementModelRows` only builds under + // `shouldIncludeAccountBoundNativeOpenAi` are therefore already absent here in that state. + const nativeRoutable = isNativeOpenAiProviderEnabled(admitted); const projected = attachNestedSelectors(admitted, attachExportAliasSelectors(admitted, rows.map(toExportModel))); - const exported = projected.filter((_, index) => !rows[index]!.disabled && (rows[index]!.native || visibleRouted.has(rows[index]!))); + const exported = projected.filter((_, index) => !rows[index]!.disabled + && (rows[index]!.native ? nativeRoutable : visibleRouted.has(rows[index]!))); // Retain the FINAL projection, not an input to it. A preview that rebuilt from raw provider // caches would miss static and forward providers, which never populate one, and would skip the // retention, metadata, combo and filtering this function applies afterwards. diff --git a/structure/clients/export-model-names.md b/structure/clients/export-model-names.md index e9d4b0e2219..c788fc4c923 100644 --- a/structure/clients/export-model-names.md +++ b/structure/clients/export-model-names.md @@ -82,6 +82,51 @@ Refresh does not recreate a removed managed block. Alias edits and client-file migration are separate operations; a previously saved selector can be stale until refresh succeeds. +## Native-row admission + +`loadExportModels` keeps a native row only while the canonical OpenAI provider +can route it. `isNativeOpenAiProviderEnabled` in +`src/codex/catalog/metadata.ts` is the router's own admission for a bare `gpt-*` +selector — the provider exists and is not disabled, in either account mode — and +`NoEnabledOpenAiProviderError` is what a client would otherwise hit. This is +deliberately weaker than `shouldIncludeAccountBoundNativeOpenAi`, whose +account-qualified routes also require canonical forward auth, and it omits +`shouldIncludeNativeOpenAi`'s no-enabled-provider bootstrap exception, which +keeps the Codex catalog listable rather than promising a servable row. The +launcher applies the same rule in `opencodeCatalogFromProxyRows` and +`opencodeLaunchNativeSlugs` (`src/cli/opencode.ts`), so `ocx opencode`, +`ocx export --client opencode` and every integration route agree about which +native selectors a client may choose. + +Admission is only half of what a client may be offered. Codex Direct is a +separate omission that applies after admission succeeds: direct mode forwards +each caller's own OpenAI bearer while a client sends the proxy's key, so a bare +native `gpt-*` selector (and its synthetic `--fast` row) would answer 401. +Account-qualified `/` rows (and their synthetic Fast rows), +whose first path segment names a configured `codexAccountNamespaces` entry, +route with `codexAccountMode: "pool"` and the namespace's fixed account even +while the provider is globally Direct (`src/router.ts`): non-main namespaces +always resolve to that exact stored pool account regardless of any caller +bearer, while a namespace bound to `__main__` resolves to stored `main-pool` +for proxy-key / loopback clients (no caller-owned Codex JWT) and preserves the +existing caller-owned `main` context when a caller supplies its own Codex JWT +(`src/server/responses/core-auth.ts`, `src/codex/auth-context.ts`). Every affected surface shares `isBareNativeRow` / `filterDirectModeBareNative` +(`src/clients/config-export/contracts.ts`, enforced centrally in +`namedExportContext` for every client in `EXPORT_CLIENTS`, plus the direct +OpenCode, Pi-family, DSH, OMP, WorkBuddy, and Gajae builders and the OpenCode +launcher's `opencodeCatalogFromProxyRows` / `opencodeLaunchNativeSlugs`) to +drop bare native rows in Direct mode while keeping account-qualified ones, +while the roster itself still exports bare rows for clients that select their +own credential. When `providers.openai` is disabled or absent, every native row +(bare and account-qualified alike) is omitted. Coverage: +`tests/server/management-model-roster.test.ts` (the roster, both account modes +and an absent provider), `tests/providers/opencode-cli.test.ts` (the launcher's +slug selection and proxy-row catalog, including account-qualified and Fast rows) +and `tests/config/client-config-export.test.ts` (all exported clients in Direct +and Pool modes, plus HTTP-layer `resolveResponsesCodexAuth` resolution across +loopback, dedicated proxy header, proxy bearer admission, and distinct caller +Codex JWT credentials). + ## CLI and API boundary `src/cli/integration-input.ts` parses `--model-names alias|routed`. diff --git a/tests/cli/cli-export-command.test.ts b/tests/cli/cli-export-command.test.ts index a7a87d5347f..acabd883399 100644 --- a/tests/cli/cli-export-command.test.ts +++ b/tests/cli/cli-export-command.test.ts @@ -30,7 +30,18 @@ function config(extra?: Partial): OcxConfig { port: 10100, hostname: "127.0.0.1", defaultProvider: "mock", - providers: { mock: { adapter: "openai-chat", baseUrl: "http://127.0.0.1/v1" } }, + providers: { + mock: { adapter: "openai-chat", baseUrl: "http://127.0.0.1/v1" }, + // The rows below include a native one, and only an enabled canonical OpenAI provider + // routes a bare `gpt-*` selector. Every configuration `loadConfig` produces carries this + // row (a fresh install enables it), so exporting native rows without it described a state + // that cannot exist on disk and the router refuses. + openai: { + adapter: "openai-responses", + authMode: "forward", + baseUrl: "https://chatgpt.com/backend-api/codex", + }, + }, ...extra, } as OcxConfig; } diff --git a/tests/config/client-config-export.test.ts b/tests/config/client-config-export.test.ts index 5061461f3a1..de182e7f002 100644 --- a/tests/config/client-config-export.test.ts +++ b/tests/config/client-config-export.test.ts @@ -26,6 +26,12 @@ import { buildOpencodeProviderBlockFromCatalog, opencodeCatalogFromProxyRows, op import { exportModelsFromProxyRows } from "../../src/cli/export-command"; import { attachNestedSelectors } from "../../src/clients/config-export/nested-selectors"; import { routeModel } from "../../src/router"; +import { resolveResponsesCodexAuth } from "../../src/server/responses/core-auth"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearMainAccountInfoCache } from "../../src/codex/main-account-cache"; +import { clearCodexUpstreamHealth, clearThreadAccountMap } from "../../src/codex/routing"; +import { clearAccountQuota } from "../../src/codex/quota"; +import { tryAdmitTurn } from "../../src/server/lifecycle"; import type { OcxConfig } from "../../src/types"; import { configSchema } from "../../src/config/schema/config-schema"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -124,6 +130,269 @@ test("OpenCode selects the protocol for each concrete model in both config gener } }); +test("OpenCode managed document drops native rows in Codex Direct and keeps them in pool", () => { + // Direct forwards the caller's own bearer while opencode sends the proxy key, so a native + // row would only answer 401. The launcher, Pi and DSH already omit them; the managed + // integration writes the same client's file and must agree, or an applied config lists a + // model that fails when selected. + const models: ExportModel[] = [ + { namespaced: "gpt-5.6-luna", provider: "openai", id: "gpt-5.6-luna", native: true, fastRowAvailable: true }, + { namespaced: "openai/gpt-routed", provider: "openai", id: "gpt-routed" }, + { namespaced: "safe/model", provider: "safe", id: "model" }, + ]; + const direct = cfg({ + providers: { + openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", codexAccountMode: "direct" }, + safe: { adapter: "openai-chat", baseUrl: "https://safe.example/v1" }, + }, + }); + + const routedKeys = ["openai/gpt-routed", "safe/model"]; + const directDoc = opencodeConfig(ctx({ models, config: direct })); + for (const block of [directDoc.provider.opencodex!.models, directDoc.providers.opencodex!.models]) { + // The synthetic Fast row inherits the native flag, so it must go with its parent. + expect(Object.keys(block).sort()).toEqual(routedKeys); + } + + const pool = cfg({ ...direct, providers: { ...direct.providers, openai: { ...direct.providers.openai!, codexAccountMode: "pool" } } }); + const poolDoc = opencodeConfig(ctx({ models, config: pool })); + for (const block of [poolDoc.provider.opencodex!.models, poolDoc.providers.opencodex!.models]) { + expect(Object.keys(block).sort()).toEqual(["gpt-5.6-luna", "gpt-5.6-luna--fast", ...routedKeys].sort()); + } +}); + +test("OpenCode, Pi-family (pi/prime/aside/omo/gentle-shell), and DSH drop bare native rows and keep account-qualified rows in Direct mode", () => { + // Bare native `gpt-*` rows require a caller-owned bearer in Codex Direct and 401 for + // proxy-key / loopback clients. Account-qualified `/gpt-*` rows route with + // `codexAccountMode: "pool"` and a fixed account, so every proxy-key/loopback export + // keeps them while omitting only the bare form. + const models: ExportModel[] = [ + { namespaced: "gpt-5.6-luna", provider: "openai", id: "gpt-5.6-luna", native: true, fastRowAvailable: true, contextWindow: 128_000 }, + { namespaced: "main/gpt-5.6-luna", provider: "openai", id: "main/gpt-5.6-luna", native: true, fastRowAvailable: true, contextWindow: 128_000 }, + { namespaced: "work/gpt-5.6-luna", provider: "openai", id: "work/gpt-5.6-luna", native: true, fastRowAvailable: true, contextWindow: 128_000 }, + { namespaced: "safe/model", provider: "safe", id: "model", contextWindow: 128_000 }, + ]; + const direct = cfg({ + codexAccountNamespaces: { main: "__main__", work: "acct_work" }, + providers: { + openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", codexAccountMode: "direct" }, + safe: { adapter: "openai-chat", baseUrl: "https://safe.example/v1" }, + }, + }); + const pool = cfg({ + ...direct, + providers: { ...direct.providers, openai: { ...direct.providers.openai!, codexAccountMode: "pool" } }, + }); + const directExpected = [ + "main/gpt-5.6-luna", "main/gpt-5.6-luna--fast", + "safe/model", + "work/gpt-5.6-luna", "work/gpt-5.6-luna--fast", + ]; + const poolExpected = ["gpt-5.6-luna", "gpt-5.6-luna--fast", ...directExpected].sort(); + + const doc = opencodeConfig(ctx({ models, config: direct })); + for (const block of [doc.provider.opencodex!.models, doc.providers.opencodex!.models]) { + expect(Object.keys(block).sort()).toEqual(directExpected); + } + + for (const client of ["pi", "prime", "aside", "omo", "gentle-shell"] as const) { + const directExport = buildClientConfig(client, ctx({ models, config: direct })) as PiGeneratedConfig; + expect(directExport.providers.opencodex.models.map(m => m.id).sort()).toEqual(directExpected); + const directContrib = buildClientContribution(client, ctx({ models, config: direct })); + const contribModels = (directContrib.fragments[0]!.value as { models: Array<{ id: string }> }).models; + expect(contribModels.map(m => m.id).sort()).toEqual(directExpected); + + const poolExport = buildClientConfig(client, ctx({ models, config: pool })) as PiGeneratedConfig; + expect(poolExport.providers.opencodex.models.map(m => m.id).sort()).toEqual(poolExpected); + } + + const dsh = dshConfig(ctx({ models, config: direct })); + expect(dsh["llm-pi-ai"].providers.opencodex!.models.map(m => m.id).sort()).toEqual(directExpected); + + // OMP, WorkBuddy / WorkBuddy AI, Gajae, and every other exported client in EXPORT_CLIENT_IDS + // also drop bare native rows in Codex Direct mode while keeping account-qualified rows. + const omp = buildClientConfig("omp", ctx({ models, config: direct })) as { providers: { opencodex: { models: Array<{ id: string }> } } }; + expect(omp.providers.opencodex.models.map(m => m.id).sort()).toEqual(directExpected); + const gajae = buildClientConfig("gajae", ctx({ models, config: direct })) as { providers: { opencodex: { models: Array<{ id: string }> } } }; + expect(gajae.providers.opencodex.models.map(m => m.id).sort()).toEqual(directExpected); + for (const wbClient of ["workbuddy", "workbuddy-ai"] as const) { + const wb = buildClientConfig(wbClient, ctx({ models, config: direct })) as { models: Array<{ id: string }> }; + expect(wb.models.map(m => m.id).sort()).toEqual(directExpected); + } + for (const client of EXPORT_CLIENT_IDS) { + const text = buildClientConfigText(client, ctx({ models, config: direct })).text; + expect(text).not.toContain('"gpt-5.6-luna"'); + expect(text).not.toContain("id: gpt-5.6-luna\n"); + expect(text).toContain("work/gpt-5.6-luna"); + expect(text).toContain("safe/model"); + } +}); + +test("HTTP-layer Direct-mode auth resolution across loopback, dedicated proxy key, proxy bearer, and caller Codex JWT", async () => { + const dir = mkdtempSync(join(tmpdir(), "ocx-direct-cred-routing-")); + const oldCodex = process.env.CODEX_HOME; + const oldOcx = process.env.OPENCODEX_HOME; + process.env.CODEX_HOME = dir; + process.env.OPENCODEX_HOME = dir; + clearThreadAccountMap(); + clearCodexUpstreamHealth(); + clearAccountQuota(); + clearMainAccountInfoCache(); + try { + const part = (value: object) => Buffer.from(JSON.stringify(value)).toString("base64url"); + const makeJwt = (sub: string, accountId: string) => + `${part({ alg: "none" })}.${part({ sub, exp: Math.floor(Date.now() / 1000) + 3600, "https://api.openai.com/auth": { chatgpt_account_id: accountId } })}.sig`; + + const callerJwt = makeJwt("caller-user", "acct-caller-distinct"); + const storedMainJwt = makeJwt("stored-main-user", "acct-stored-main-distinct"); + const storedWorkJwt = makeJwt("stored-work-user", "acct-stored-work-distinct"); + const proxySecret = "ocx-proxy-admission-secret-distinct"; + + writeFileSync(join(dir, "auth.json"), JSON.stringify({ + tokens: { access_token: storedMainJwt, refresh_token: "fake-main-refresh", account_id: "acct-stored-main-distinct" }, + })); + clearMainAccountInfoCache(); + saveCodexAccountCredential("acct_work", { + accessToken: storedWorkJwt, + refreshToken: "fake-work-refresh", + expiresAt: Date.now() + 3600_000, + chatgptAccountId: "acct-stored-work-distinct", + }); + + const directConfig = cfg({ + codexAccounts: [{ id: "acct_work", email: "work@example.test", chatgptAccountId: "acct-stored-work-distinct", isMain: false }], + codexAccountNamespaces: { main: "__main__", work: "acct_work" }, + providers: { + openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", codexAccountMode: "direct" }, + }, + }); + + const resolveHttp = async (model: string, headers: Record, admission?: { kind: "configured"; keyId: string; source: "dedicated" | "bearer" }) => { + const lease = tryAdmitTurn(); + expect(lease).not.toBeNull(); + try { + const route = routeModel(directConfig, model); + const req = new Request("http://127.0.0.1:10100/v1/responses", { method: "POST", headers }); + return { + route, + result: await resolveResponsesCodexAuth(req, directConfig, route, { + admission, + turnAdmissionLease: lease!, + }), + }; + } finally { + lease?.release(); + } + }; + + // 1. Loopback placeholder (Pi/Prime/Aside/omo/Gentle Shell/OpenCode/OMP/WorkBuddy/Gajae on loopback): + // - bare `gpt-5.6-luna` stays in caller-Direct mode without substituting stored credentials + // (so the placeholder key reaches upstream and 401s — why exports omit bare Direct rows); + // - `main/gpt-5.6-luna` resolves to stored `main-pool` with storedMainJwt; + // - `work/gpt-5.6-luna` resolves to exact stored `acct_work` with storedWorkJwt. + const loopbackBare = await resolveHttp("gpt-5.6-luna", { authorization: `Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}` }); + expect(loopbackBare.route.codexAccountMode).toBe("direct"); + expect(loopbackBare.result.ok).toBe(true); + if (loopbackBare.result.ok) { + expect(loopbackBare.result.authCtx).toMatchObject({ kind: "main", accountId: null }); + expect(loopbackBare.result.substituteMainCredential).toBe(false); + expect(loopbackBare.result.headers.get("authorization")).toBe(`Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}`); + expect(loopbackBare.result.headers.get("authorization")).not.toContain(storedMainJwt); + expect(loopbackBare.result.headers.get("authorization")).not.toContain(storedWorkJwt); + } + + const loopbackMain = await resolveHttp("main/gpt-5.6-luna", { authorization: `Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}` }); + expect(loopbackMain.result.ok).toBe(true); + if (loopbackMain.result.ok) { + expect(loopbackMain.result.authCtx).toMatchObject({ kind: "main-pool", accountId: "__main__", fixedAccount: true }); + expect(loopbackMain.result.headers.get("authorization")).toBe(`Bearer ${storedMainJwt}`); + expect(loopbackMain.result.headers.get("chatgpt-account-id")).toBe("acct-stored-main-distinct"); + } + + const loopbackWork = await resolveHttp("work/gpt-5.6-luna", { authorization: `Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}` }); + expect(loopbackWork.result.ok).toBe(true); + if (loopbackWork.result.ok) { + expect(loopbackWork.result.authCtx).toMatchObject({ kind: "pool", accountId: "acct_work", fixedAccount: true }); + expect(loopbackWork.result.headers.get("authorization")).toBe(`Bearer ${storedWorkJwt}`); + expect(loopbackWork.result.headers.get("chatgpt-account-id")).toBe("acct-stored-work-distinct"); + } + + // 2. Dedicated proxy admission header (`x-opencodex-api-key`, OpenCode non-loopback path): + // - bare `gpt-5.6-luna` never substitutes stored credentials or leaks proxySecret; + // - `work/gpt-5.6-luna` resolves strictly to stored `acct_work` and never leaks proxySecret. + const dedicatedAdmission = { kind: "configured" as const, keyId: "k1", source: "dedicated" as const }; + const dedicatedBare = await resolveHttp("gpt-5.6-luna", { + "x-opencodex-api-key": proxySecret, + authorization: `Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}`, + }, dedicatedAdmission); + expect(dedicatedBare.result.ok).toBe(true); + if (dedicatedBare.result.ok) { + expect(dedicatedBare.result.authCtx).toMatchObject({ kind: "main", accountId: null }); + expect(dedicatedBare.result.substituteMainCredential).toBe(false); + expect(dedicatedBare.result.headers.get("authorization")).toBe(`Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}`); + expect(dedicatedBare.result.headers.get("authorization")).not.toContain(storedMainJwt); + expect(dedicatedBare.result.headers.get("authorization")).not.toContain(proxySecret); + } + + const dedicatedWork = await resolveHttp("work/gpt-5.6-luna", { + "x-opencodex-api-key": proxySecret, + authorization: `Bearer ${LOOPBACK_API_KEY_PLACEHOLDER}`, + }, dedicatedAdmission); + expect(dedicatedWork.result.ok).toBe(true); + if (dedicatedWork.result.ok) { + expect(dedicatedWork.result.headers.get("authorization")).toBe(`Bearer ${storedWorkJwt}`); + expect(dedicatedWork.result.headers.get("authorization")).not.toContain(proxySecret); + } + + // 3. Proxy bearer admission (`Authorization: Bearer `, admission.source === "bearer"): + // - bare `gpt-5.6-luna` substitutes stored main credential (never forwards proxySecret); + // - `work/gpt-5.6-luna` resolves strictly to stored `acct_work` (never stored main or proxySecret). + const bearerAdmission = { kind: "configured" as const, keyId: "k1", source: "bearer" as const }; + const bearerBare = await resolveHttp("gpt-5.6-luna", { authorization: `Bearer ${proxySecret}` }, bearerAdmission); + expect(bearerBare.result.ok).toBe(true); + if (bearerBare.result.ok) { + expect(bearerBare.result.substituteMainCredential).toBe(true); + expect(bearerBare.result.headers.get("authorization")).toBe(`Bearer ${storedMainJwt}`); + expect(bearerBare.result.headers.get("authorization")).not.toContain(proxySecret); + } + + const bearerWork = await resolveHttp("work/gpt-5.6-luna", { authorization: `Bearer ${proxySecret}` }, bearerAdmission); + expect(bearerWork.result.ok).toBe(true); + if (bearerWork.result.ok) { + expect(bearerWork.result.authCtx).toMatchObject({ kind: "pool", accountId: "acct_work", fixedAccount: true }); + expect(bearerWork.result.headers.get("authorization")).toBe(`Bearer ${storedWorkJwt}`); + } + + // 4. Caller carrying its own distinct Codex JWT: + // - `work/gpt-5.6-luna` (non-main namespace) uses exact stored `acct_work` (never callerJwt); + // - `main/gpt-5.6-luna` preserves the pre-existing #7410 caller-owned `main` contract (`callerJwt`). + const callerHeaders = { authorization: `Bearer ${callerJwt}`, "chatgpt-account-id": "acct-caller-distinct" }; + const callerWork = await resolveHttp("work/gpt-5.6-luna", callerHeaders); + expect(callerWork.result.ok).toBe(true); + if (callerWork.result.ok) { + expect(callerWork.result.authCtx).toMatchObject({ kind: "pool", accountId: "acct_work", fixedAccount: true }); + expect(callerWork.result.headers.get("authorization")).toBe(`Bearer ${storedWorkJwt}`); + expect(callerWork.result.headers.get("chatgpt-account-id")).toBe("acct-stored-work-distinct"); + } + + const callerMain = await resolveHttp("main/gpt-5.6-luna", callerHeaders); + expect(callerMain.result.ok).toBe(true); + if (callerMain.result.ok) { + expect(callerMain.result.authCtx).toMatchObject({ kind: "main", accountId: null }); + expect(callerMain.result.headers.get("authorization")).toBe(`Bearer ${callerJwt}`); + expect(callerMain.result.headers.get("chatgpt-account-id")).toBe("acct-caller-distinct"); + } + } finally { + clearThreadAccountMap(); + clearCodexUpstreamHealth(); + clearAccountQuota(); + clearMainAccountInfoCache(); + if (oldCodex === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = oldCodex; + if (oldOcx === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = oldOcx; + removeTreeWithRetry(dir); + } +}); + function piConfig(context: ExportContext = ctx()): PiGeneratedConfig { return buildClientConfig("pi", context) as PiGeneratedConfig; } diff --git a/tests/providers/opencode-cli.test.ts b/tests/providers/opencode-cli.test.ts index 5d4879fc41c..2d09a919a83 100644 --- a/tests/providers/opencode-cli.test.ts +++ b/tests/providers/opencode-cli.test.ts @@ -437,8 +437,22 @@ describe("ocx opencode proxy model catalog", () => { { namespaced: "opencode-go/undeclared", provider: "opencode-go", id: "undeclared" }, { namespaced: "opencode-go/hidden", provider: "opencode-go", id: "hidden", disabled: true, inputModalities: ["text", "image"] }, ]; - const catalog = opencodeCatalogFromProxyRows(rows, cfg()); - const blocks = buildOpencodeProviderBlocksFromCatalog(10100, catalog, undefined, cfg()); + // Pool mode, because only an enabled canonical OpenAI provider routes the native row. A + // config without one is what the launcher now drops it from, and that state cannot arise on + // disk: a fresh install materializes `providers.openai` enabled (pool). + const poolConfig = cfg({ + providers: { + mock: { adapter: "openai-chat", baseUrl: "http://x/v1" }, + openai: { + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + codexAccountMode: "pool", + }, + }, + }); + const catalog = opencodeCatalogFromProxyRows(rows, poolConfig); + const blocks = buildOpencodeProviderBlocksFromCatalog(10100, catalog, undefined, poolConfig); for (const block of [blocks.v1]) { expect(block.models["gpt-5.6-luna"]).toMatchObject({ @@ -532,6 +546,35 @@ describe("ocx opencode proxy model catalog", () => { "gpt-5.6-sol", "kiro/glm-5", ]); + + // Same rows, provider disabled: the proxy refuses the bare slug in either account mode, so + // the management catalog must not list it either. `ocx export --client opencode` and + // `ocx opencode` both read this function. + const disabled = cfg({ + codexAccountNamespaces: { main: "acct_primary" }, + providers: { + mock: { adapter: "openai-chat", baseUrl: "http://x/v1" }, + openai: { ...poolConfig.providers.openai!, disabled: true }, + }, + }); + expect(opencodeCatalogFromProxyRows(rows, disabled).map(m => m.namespaced)).toEqual(["kiro/glm-5"]); + + const directWithAccount = cfg({ + codexAccountNamespaces: { main: "acct_primary" }, + providers: directConfig.providers, + }); + const accountRows = [ + ...rows, + { namespaced: "main/gpt-5.6-sol", native: true, disabled: false, provider: "openai", id: "main/gpt-5.6-sol", fastRowAvailable: true }, + { namespaced: "main/gpt-5.6-sol--fast", native: true, disabled: false, provider: "openai", id: "main/gpt-5.6-sol--fast" }, + ]; + expect(opencodeCatalogFromProxyRows(accountRows, directWithAccount).map(m => m.namespaced)).toEqual([ + "kiro/glm-5", + "main/gpt-5.6-sol", + "main/gpt-5.6-sol--fast", + ]); + // When providers.openai is disabled, account-qualified native rows are dropped too. + expect(opencodeCatalogFromProxyRows(accountRows, disabled).map(m => m.namespaced)).toEqual(["kiro/glm-5"]); }); }); @@ -567,6 +610,28 @@ describe("ocx opencode native slug selection", () => { }); expect(opencodeLaunchNativeSlugs(config).length).toBeGreaterThan(0); }); + + test("omits native slugs when the canonical OpenAI provider is disabled", () => { + // The router answers every bare `gpt-*` with `NoEnabledOpenAiProviderError` in this state, + // in both account modes, so advertising the slugs would hand opencode a picker of rows that + // cannot run. `ocx integration client enable` and the export roster drop them for the same + // reason; the launcher used to be the one surface that did not. + for (const codexAccountMode of ["direct", "pool"] as const) { + const config = cfg({ + providers: { + mock: { adapter: "openai-chat", baseUrl: "http://x/v1" }, + openai: { + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + codexAccountMode, + disabled: true, + }, + }, + }); + expect(opencodeLaunchNativeSlugs(config)).toEqual([]); + } + }); }); /** diff --git a/tests/server/management-client-config-route.test.ts b/tests/server/management-client-config-route.test.ts index e8d19f5e2a3..d7676b43eb9 100644 --- a/tests/server/management-client-config-route.test.ts +++ b/tests/server/management-client-config-route.test.ts @@ -109,6 +109,16 @@ function baseConfig(overrides: Partial = {}): OcxConfig { liveModels: false, models: ["no-context"], }, + // Every configuration `loadConfig` produces carries this row, and the native rows the + // export roster lists are only routable through it. Omitting it described a state that + // cannot exist on disk. + openai: { + adapter: "openai-responses", + authMode: "forward", + liveModels: false, + baseUrl: "https://chatgpt.com/backend-api/codex", + models: [], + }, }, ...overrides, } as OcxConfig; diff --git a/tests/server/management-model-roster.test.ts b/tests/server/management-model-roster.test.ts index 493fb7f265c..6e176c7d611 100644 --- a/tests/server/management-model-roster.test.ts +++ b/tests/server/management-model-roster.test.ts @@ -74,6 +74,59 @@ describe("a supplied roster replaces the gather and keeps the projection", () => }); }); +/** + * A native row is only a real choice while the canonical OpenAI provider can route it. This is + * the export half of a defect the launcher had too: `/api/client-config` and every integration + * route read this roster, so listing bare `gpt-*` rows under a disabled provider handed a client + * a picker whose selections the router refuses with `NoEnabledOpenAiProviderError`. + */ +describe("native rows follow the provider that can actually serve them", () => { + const FORWARDED = { + adapter: "openai-responses" as const, + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward" as const, + }; + const ROSTER: CatalogModel[] = [{ id: "supplied-model", provider: "supplied" }]; + + function withOpenAi(provider: Record | undefined): OcxConfig { + return { + ...CONFIG, + providers: { + supplied: { adapter: "openai-chat", baseUrl: "http://127.0.0.1/v1" }, + ...(provider === undefined ? {} : { openai: provider }), + }, + } as OcxConfig; + } + + const nativesOf = (models: readonly { native?: boolean; namespaced: string }[]) => + models.filter(model => model.native).map(model => model.namespaced); + + test("an enabled provider keeps them, in both account modes", async () => { + for (const codexAccountMode of ["direct", "pool"] as const) { + const exported = await loadExportModels(withOpenAi({ ...FORWARDED, codexAccountMode }), ROSTER); + expect(nativesOf(exported).length).toBeGreaterThan(0); + } + }); + + test("a disabled provider drops them, in both account modes", async () => { + for (const codexAccountMode of ["direct", "pool"] as const) { + const exported = await loadExportModels( + withOpenAi({ ...FORWARDED, codexAccountMode, disabled: true }), ROSTER, + ); + expect(nativesOf(exported)).toEqual([]); + // The routed rows are untouched: only the native half depends on this provider. + expect(exported.some(model => model.namespaced === "supplied/supplied-model")).toBe(true); + } + }); + + test("an absent provider drops them too", async () => { + // A fresh install materializes `providers.openai`, so this is the pre-materialization shape + // of a non-OpenAI-only config. The router refuses bare slugs here as well. + const exported = await loadExportModels(withOpenAi(undefined), ROSTER); + expect(nativesOf(exported)).toEqual([]); + }); +}); + describe("a preview reads only a roster an authoritative load already finished", () => { test("a cold process has none, and an ordinary load leaves the final projection behind", async () => { resetExportSnapshotForTests(); From c691c4cc3f50a0f6500665486530b498586156fe Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 06:31:01 +0900 Subject: [PATCH 35/64] fix(usage): price native Ultrafast requests at the published Ultrafast rate (#9178) * fix(usage): price transmitted Ultrafast tiers in Logs and usage totals Native Codex Ultrafast requests were priced at Standard rates: no Ultrafast schedule existed, and the native outcome (service_tier ultrafast on the wire, a non-authoritative "default" echo) carried no tier the estimator recognized. Add OpenAI's published Ultrafast schedule (GPT-6.2 Astra and Sol 3x Standard through 2027-02-28 and 6x from 2027-03-01 Pacific; GPT-6 Astra and GPT-6.1 Sol 6x) and select the step from the logged row's timestamp. An authoritative response tier decides first, an explicit refusal keeps Standard, and otherwise a serialized Ultrafast wire value prices the attempt as an estimate with the new service_tier_transmitted reason. A requested-only tier never selects the Ultrafast price. Each combo attempt uses its own evidence. Closes #9138 * docs(dashboard): describe Ultrafast list-price estimates * fix(usage): keep Ultrafast evidence and dates per attempt A combo attempt without its own tier record fell back to the request-level outcome, which can describe another attempt, so it could be priced at Ultrafast without evidence. Attempts now use only their own outcome and take just the timestamp from the request. Expanded Logs attempts were priced without the row's timestamp, so after 2027-03-01 a pre-transition GPT-6.2 attempt would show 6x while its parent showed 3x. requestLogDto now passes the request timestamp to each attempt. * fix(usage): take Ultrafast evidence only from tier-outcome records An expanded Logs attempt without its own tier record inherited the parent row's scalar responseServiceTier, so it could display an Ultrafast price while the combo total priced the same attempt at Standard. Scalar tier fields can describe another attempt and every Ultrafast-capable release records tier outcomes, so Ultrafast pricing now reads only outcome records. * fix(logs): price expanded attempts with the request's derived tier An expanded Logs attempt without its own tier record copied the parent row's raw tier fields, which can hold an earlier response's echo, while the request total gave the same attempt the tier derived from the final outcome. requestLogDto now hands expanded attempts that derived context, so their amounts match the total. * fix(usage): price Ultrafast once and document tier precedence - A canonical Priority outcome that a fastWire mapping serialized as ultrafast took the 2x Priority premium and then the dated Ultrafast multiplier. Ultrafast now replaces the Priority premium in both the per-attempt and per-request estimators; ordinary Priority keeps 2x. - The Logs and Usage guides (en, es) state that an authoritative response tier or an explicit refusal keeps Standard, and that the transmitted tier prices a row only when neither is present. - The service_tier_transmitted note says at least one attempt was priced at the Ultrafast rate, in all 12 locales, and names the tier as what the proxy sent. --- .../content/docs/es/guides/web-dashboard.md | 2 +- .../src/content/docs/guides/web-dashboard.md | 6 + gui/src/i18n/de.ts | 1 + gui/src/i18n/en.ts | 1 + gui/src/i18n/es.ts | 1 + gui/src/i18n/fr.ts | 1 + gui/src/i18n/ja.ts | 1 + gui/src/i18n/ko.ts | 1 + gui/src/i18n/pt.ts | 1 + gui/src/i18n/ru.ts | 1 + gui/src/i18n/tr.ts | 1 + gui/src/i18n/vi.ts | 1 + gui/src/i18n/zh-TW.ts | 1 + gui/src/i18n/zh.ts | 1 + gui/src/pages/Logs.tsx | 1 + gui/src/pages/logs-cost-format.ts | 5 +- scripts/test-layout/layout.json | 2 +- src/server/management/shared.ts | 13 +- src/usage/cost.ts | 138 ++++++++++++++-- src/usage/expected-prices.ts | 39 +++++ structure/pricing.md | 23 +++ tests/fixtures/test-layout-expected.json | 1 + tests/usage/usage-ultrafast-pricing.test.ts | 154 ++++++++++++++++++ 23 files changed, 378 insertions(+), 18 deletions(-) create mode 100644 tests/usage/usage-ultrafast-pricing.test.ts diff --git a/docs-site/src/content/docs/es/guides/web-dashboard.md b/docs-site/src/content/docs/es/guides/web-dashboard.md index d5858695c17..093fd64a748 100644 --- a/docs-site/src/content/docs/es/guides/web-dashboard.md +++ b/docs-site/src/content/docs/es/guides/web-dashboard.md @@ -194,7 +194,7 @@ El selector de idioma incluye **Português** (portugués brasileño, `pt-BR`). E Las secciones del panel tienen enlaces directos: `#dashboard` abre Vista general, y `#dashboard/providers` y `#dashboard/models` abren las otras dos secciones. Al recargar, usar un marcador o volver atrás se conserva la sección. **Registros** funciona de la misma manera con `#logs` y `#logs/debug`. Los marcadores antiguos a `#providers/workspace` ahora abren `#providers`. -Valores de costos en **Registros** y **Uso** son equivalentes de lista-precio de API calculados a partir de tokens notificado. Para un intervalo de uso personalizado, el servidor debe confirmar las horas de inicio y fin solicitadas. Si un proxy de ejecución anterior no admite esos límites, el panel de control y CLI rechazan su informe; Actualizar y reiniciar ese proxy antes de volver a intentarlo. Restablecer un precio de modelo manual afecta solo a modelo, conservando otras tasas ahorradas independientemente. Los **Uso** Las tablas de resumen y Modelos/Proveedores muestran el rendimiento de salida de extremo a extremo del historial de uso para el rango y los filtros seleccionados: salida sumada tokens dividida por segundos de reloj de pared sumados, no un promedio de tasas individuales. El recuento de muestras se mide por intentos (o solicitudes de filas heredadas sin intentos); se excluyen las muestras que carecen de salida finita positiva tokens o duración. Un guión significa que no hay muestra calificada o el servidor devolvió una tasa inutilizable. Esto incluye la espera de predecodificación y no es una velocidad de decodificación estimada. +Valores de costos en **Registros** y **Uso** son equivalentes de lista-precio de API calculados a partir de tokens notificado. Una solicitud OpenAI Ultrafast usa el múltiplo Ultrafast publicado de la tarifa Standard para su modelo y la fecha de la solicitud, en lugar del recargo Priority. Un nivel autoritativo en la respuesta del proveedor decide el precio, así que una respuesta autoritativa Standard conserva el precio Standard, igual que un rechazo explícito de Ultrafast. Solo cuando la respuesta no informa un nivel autoritativo ni lo rechaza, el precio sigue el nivel Ultrafast que envió el proxy y **Registros** marca ese valor como estimado. Un nivel solo solicitado conserva el precio Standard. Para un intervalo de uso personalizado, el servidor debe confirmar las horas de inicio y fin solicitadas. Si un proxy de ejecución anterior no admite esos límites, el panel de control y CLI rechazan su informe; Actualizar y reiniciar ese proxy antes de volver a intentarlo. Restablecer un precio de modelo manual afecta solo a modelo, conservando otras tasas ahorradas independientemente. Los **Uso** Las tablas de resumen y Modelos/Proveedores muestran el rendimiento de salida de extremo a extremo del historial de uso para el rango y los filtros seleccionados: salida sumada tokens dividida por segundos de reloj de pared sumados, no un promedio de tasas individuales. El recuento de muestras se mide por intentos (o solicitudes de filas heredadas sin intentos); se excluyen las muestras que carecen de salida finita positiva tokens o duración. Un guión significa que no hay muestra calificada o el servidor devolvió una tasa inutilizable. Esto incluye la espera de predecodificación y no es una velocidad de decodificación estimada. En **Registros**, si un Combo combina cargos por créditos y por tokens, `≥` indica que al menos un intento valorado por tokens tiene un límite inferior conocido. Cada uno de los demás intentos valorados por tokens debe tener un límite inferior conocido o un importe calculado sin estimaciones y con datos de caché observados. diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index a985dd41982..d9769b9e2bf 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -309,6 +309,12 @@ on. **Logs** works the same way with `#logs` and `#logs/debug`. An older `#provi bookmark now lands on `#providers`. Cost values in **Logs** and **Usage** are API list-price equivalents calculated from reported tokens. +An OpenAI Ultrafast request uses the published Ultrafast multiple of the Standard rate for its +model and request date, in place of the Priority premium. An authoritative tier in the upstream +response decides the price, so an authoritative Standard response keeps the Standard price, and so +does an explicit refusal of Ultrafast. Only when the response neither reports an authoritative tier +nor refuses does the price follow the Ultrafast tier the proxy sent, and **Logs** marks that value +as an estimate. A tier that was only requested keeps the Standard price. For a **Logs** Combo that mixes credit and token charges, `≥` means at least one token-priced attempt has a known lower bound and every other token-priced attempt is either a known lower bound or has a non-estimated amount with observed cache detail. diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index aab905c6079..b2bbe2534e8 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -1413,6 +1413,7 @@ export const de: Record = { "logs.detail.estimate.expected_price_overlay": "Ein verifizierter Expected-Listenpreis wurde verwendet.", "logs.detail.estimate.provider_cost_overlay": "Ein vom Anbieter konfiguriertes Preis-Overlay wurde verwendet.", "logs.detail.estimate.priority_lower_bound": "Der bestätigte Priority-Preis ist nicht verfügbar; die angezeigte Schätzung ist eine bekannte Untergrenze.", + "logs.detail.estimate.service_tier_transmitted": "Mindestens ein Versuch ist zum Preis der vom Proxy gesendeten Ultrafast-Stufe berechnet; die Upstream-Antwort hat diese Stufe nicht bestätigt.", "logs.col.error": "Fehler", "logs.col.upstreamReason": "Upstream-Grund", "logs.col.failureDetail": "Fehlerdetail", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 11c72bb338c..b17d27c2b57 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1471,6 +1471,7 @@ export const en = { "logs.detail.estimate.expected_price_overlay": "A verified expected list price was used.", "logs.detail.estimate.provider_cost_overlay": "A provider-configured price overlay was used.", "logs.detail.estimate.priority_lower_bound": "The confirmed Priority price is unavailable; the displayed estimate is a known lower bound.", + "logs.detail.estimate.service_tier_transmitted": "At least one attempt is priced at the rate for the Ultrafast tier the proxy sent; the upstream response did not confirm that tier.", "logs.col.error": "Error", "logs.col.upstreamReason": "Upstream reason", "logs.col.failureDetail": "Failure detail", diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index ba689534df6..fdd9c7939b5 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -1458,6 +1458,7 @@ export const es = { "logs.detail.estimate.expected_price_overlay": "Se utilizó un precio de lista esperado verificado.", "logs.detail.estimate.provider_cost_overlay": "Se utilizó una superposición de precios configurada por el proveedor.", "logs.detail.estimate.priority_lower_bound": "El precio Prioridad confirmado no está disponible; la estimación mostrada es un límite inferior conocido.", + "logs.detail.estimate.service_tier_transmitted": "Al menos un intento se calcula con la tarifa del nivel Ultrafast que envió el proxy; la respuesta del proveedor no confirmó ese nivel.", "logs.col.error": "Error", "logs.col.upstreamReason": "Razón ascendente", "logs.col.failureDetail": "Detalle del fallo", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 47298c6d010..f7695182750 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1452,6 +1452,7 @@ export const fr: Record = { "logs.detail.estimate.expected_price_overlay": "Un tarif catalogue attendu et vérifié a été utilisé.", "logs.detail.estimate.provider_cost_overlay": "Un remplacement de tarif configuré pour le fournisseur a été utilisé.", "logs.detail.estimate.priority_lower_bound": "Le tarif Priority confirmé n’est pas disponible ; l’estimation affichée est une borne inférieure connue.", + "logs.detail.estimate.service_tier_transmitted": "Au moins une tentative est calculée au tarif du niveau Ultrafast envoyé par le proxy ; la réponse en amont n’a pas confirmé ce niveau.", "logs.col.error": "Erreur", "logs.col.upstreamReason": "Motif en amont", "logs.col.failureDetail": "Détail de l'échec", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 39789d3a51b..c9d27a36d84 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1354,6 +1354,7 @@ export const ja: Record = { "logs.detail.estimate.expected_price_overlay": "検証済みの予想定価が使用されました。", "logs.detail.estimate.provider_cost_overlay": "プロバイダー設定の価格オーバーレイが使用されました。", "logs.detail.estimate.priority_lower_bound": "確認済みの Priority 価格を利用できないため、表示される見積もりは既知の下限です。", + "logs.detail.estimate.service_tier_transmitted": "少なくとも 1 回の試行は、プロキシが送信した Ultrafast ティアの料金で算出しています。上流の応答ではこのティアが確認されていません。", "logs.col.error": "エラー", "logs.col.upstreamReason": "上流の理由", "logs.col.failureDetail": "失敗の詳細", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 2b045cad0a9..50027e7338d 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -1452,6 +1452,7 @@ export const ko: Record = { "logs.detail.estimate.expected_price_overlay": "검증된 expected 정가를 사용했습니다.", "logs.detail.estimate.provider_cost_overlay": "프로바이더 구성 가격 오버레이를 사용했습니다.", "logs.detail.estimate.priority_lower_bound": "확인된 Priority 가격을 사용할 수 없어 표시된 추정치는 알려진 하한입니다.", + "logs.detail.estimate.service_tier_transmitted": "적어도 한 번의 시도는 프록시가 보낸 Ultrafast 티어의 요금으로 계산했습니다. 상류 응답에서 이 티어가 확인되지 않았습니다.", "logs.col.error": "오류", "logs.col.upstreamReason": "업스트림 원인", "logs.col.failureDetail": "실패 상세", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index f34d0c11335..f849bf35d2b 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -1466,6 +1466,7 @@ export const pt: Record = { "logs.detail.estimate.expected_price_overlay": "Foi usado um preço de tabela esperado verificado.", "logs.detail.estimate.provider_cost_overlay": "Foi usada uma sobreposição de preço configurada no provedor.", "logs.detail.estimate.priority_lower_bound": "O preço Priority confirmado está indisponível; a estimativa exibida é um limite inferior conhecido.", + "logs.detail.estimate.service_tier_transmitted": "Pelo menos uma tentativa é calculada com a tarifa do nível Ultrafast enviado pelo proxy; a resposta upstream não confirmou esse nível.", "logs.col.error": "Erro", "logs.col.upstreamReason": "Motivo do upstream", "logs.col.failureDetail": "Detalhe da falha", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index ef4a2340bcb..6b0603e5bc1 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1430,6 +1430,7 @@ export const ru: Record = { "logs.detail.estimate.expected_price_overlay": "Использована подтверждённая ожидаемая цена из прайс-листа.", "logs.detail.estimate.provider_cost_overlay": "Использован ценовой оверлей провайдера.", "logs.detail.estimate.priority_lower_bound": "Подтверждённая цена Priority недоступна; показанная оценка является известной нижней границей.", + "logs.detail.estimate.service_tier_transmitted": "Хотя бы одна попытка рассчитана по тарифу уровня Ultrafast, который отправил прокси; ответ upstream не подтвердил этот уровень.", "logs.col.error": "Ошибка", "logs.col.upstreamReason": "Причина от провайдера", "logs.col.failureDetail": "Подробности сбоя", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 2b696b9accb..82fbfcd0581 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1457,6 +1457,7 @@ export const tr: Record = { "logs.detail.estimate.expected_price_overlay": "Doğrulanmış liste fiyatı kullanıldı.", "logs.detail.estimate.provider_cost_overlay": "Kullanıcı tarafından yapılandırılan bir sağlayıcı fiyat katmanı kullanıldı.", "logs.detail.estimate.priority_lower_bound": "Doğrulanan Priority fiyatı kullanılamıyor; gösterilen tahmin bilinen bir alt sınırdır.", + "logs.detail.estimate.service_tier_transmitted": "En az bir deneme, Proxy'nin gönderdiği Ultrafast hizmet katmanının tarifesiyle hesaplandı; upstream yanıtı bu katmanı doğrulamadı.", "logs.col.error": "Hata", "logs.col.upstreamReason": "Yukarı akış nedeni", "logs.col.failureDetail": "Hata ayrıntısı", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 693ed649511..6e701ada8fd 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -1451,6 +1451,7 @@ export const vi: Record = { "logs.detail.estimate.expected_price_overlay": "Một giá niêm yết kỳ vọng (expected list price) đã xác minh được sử dụng.", "logs.detail.estimate.provider_cost_overlay": "Sử dụng giá tuỳ chỉnh do provider cấu hình.", "logs.detail.estimate.priority_lower_bound": "Giá Ưu tiên (Priority price) đã xác nhận không khả dụng; ước tính hiển thị là giới hạn dưới đã biết.", + "logs.detail.estimate.service_tier_transmitted": "Ít nhất một lần thử được tính theo giá của cấp Ultrafast mà proxy đã gửi; phản hồi từ upstream không xác nhận cấp này.", "logs.col.error": "Lỗi", "logs.col.upstreamReason": "Lý do upstream", "logs.col.failureDetail": "Chi tiết lỗi", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 61172373e43..30a5c8b63e1 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -3407,6 +3407,7 @@ export const zhTW: Record = { "logs.detail.resend.refusedFutile": "未重送:相同請求仍會失敗", "logs.detail.estimate.provider_cost_overlay": "已使用供應商設定的價格覆蓋。", "logs.detail.estimate.priority_lower_bound": "無法取得已確認的 Priority 價格;目前顯示的估算是已知下限。", + "logs.detail.estimate.service_tier_transmitted": "至少有一次嘗試依 Proxy 送出的 Ultrafast 層級費率計算;上游回應未確認此層級。", "pws.geminiNativePassthrough": "Gemini 原生透傳", "pws.geminiNativePassthroughDesc": "為符合條件的 Antigravity OAuth 路由保留 Gemini 請求和回應。", "pws.geminiNativePassthroughLoadFailed": "無法載入 Gemini 原生透傳設定。", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 8b8cdc5315b..8e389e5a83d 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -1425,6 +1425,7 @@ export const zh: Record = { "logs.detail.estimate.expected_price_overlay": "使用了已验证的 Expected 标价。", "logs.detail.estimate.provider_cost_overlay": "使用了用户配置的提供方价格覆盖。", "logs.detail.estimate.priority_lower_bound": "暂无已确认的 Priority 价格;当前显示的估算是已知下界。", + "logs.detail.estimate.service_tier_transmitted": "至少有一次尝试按代理发送的 Ultrafast 层级费率计算;上游响应未确认该层级。", "logs.col.error": "错误", "logs.col.upstreamReason": "上游原因", "logs.col.failureDetail": "失败详情", diff --git a/gui/src/pages/Logs.tsx b/gui/src/pages/Logs.tsx index a6efc651ab2..8e51784bb57 100644 --- a/gui/src/pages/Logs.tsx +++ b/gui/src/pages/Logs.tsx @@ -353,6 +353,7 @@ const ESTIMATE_REASON_KEYS = { expected_price_overlay: "logs.detail.estimate.expected_price_overlay", provider_cost_overlay: "logs.detail.estimate.provider_cost_overlay", priority_lower_bound: "logs.detail.estimate.priority_lower_bound", + service_tier_transmitted: "logs.detail.estimate.service_tier_transmitted", } as const satisfies Record; /** diff --git a/gui/src/pages/logs-cost-format.ts b/gui/src/pages/logs-cost-format.ts index 85421e8f570..dea316dbee6 100644 --- a/gui/src/pages/logs-cost-format.ts +++ b/gui/src/pages/logs-cost-format.ts @@ -10,7 +10,8 @@ export type CostEstimateReason = | "cache_detail_missing" | "expected_price_overlay" | "provider_cost_overlay" - | "priority_lower_bound"; + | "priority_lower_bound" + | "service_tier_transmitted"; /** * What a billed estimate can say about itself. @@ -40,7 +41,7 @@ export function effectivePriorityLowerBound(estimate: BillingBasis & { priorityL * credits-only total keeps none of them. */ const TOKEN_PRICE_REASONS: ReadonlySet = new Set([ - "cache_detail_missing", "expected_price_overlay", "provider_cost_overlay", "priority_lower_bound", + "cache_detail_missing", "expected_price_overlay", "provider_cost_overlay", "priority_lower_bound", "service_tier_transmitted", ]); export function estimateReasonsForBilling( diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index bffb030fa9d..7a7b90728bf 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1861,7 +1861,7 @@ "upstream-transient-retry.test.ts": "providers", "url-normalization.test.ts": "config", "usage-aggregate-cache.test.ts": "usage", - "usage-anthropic-fast-pricing.test.ts": "usage", + "usage-anthropic-fast-pricing.test.ts": "usage", "usage-ultrafast-pricing.test.ts": "usage", "usage-cursor-fast-pricing.test.ts": "usage", "usage-attempt-delivery.test.ts": "usage", "usage-cost.test.ts": "usage", "usage-haiku-5-5-pricing.test.ts": "usage", "usage-fable-5-2-pricing.test.ts": "usage", "gpt61-terra-pricing.test.ts": "usage", diff --git a/src/server/management/shared.ts b/src/server/management/shared.ts index 9713b9851c4..37c276ba816 100644 --- a/src/server/management/shared.ts +++ b/src/server/management/shared.ts @@ -108,7 +108,8 @@ export type CostEstimateReason = | "cache_detail_missing" | "expected_price_overlay" | "provider_cost_overlay" - | "priority_lower_bound"; + | "priority_lower_bound" + | "service_tier_transmitted"; export type CostResult = | { kind: "value"; estimate: NonNullable>; estimateReasons: CostEstimateReason[] } @@ -116,6 +117,8 @@ export type CostResult = | { kind: "unavailable"; reason: MetricUnavailableReason }; export type MetricSource = Pick & { + /** Request time; selects dated tier prices such as the Ultrafast schedule. */ + timestamp?: number; attempts?: readonly PersistedUsageAttempt[]; }; @@ -297,6 +300,8 @@ export function costResult(entry: MetricSource): CostResult { priceSources.includes("expected") ? "expected_price_overlay" as const : undefined, priceSources.includes("user") ? "provider_cost_overlay" as const : undefined, estimate.priorityLowerBound ? "priority_lower_bound" as const : undefined, + // A credit charge never used the token rates the Ultrafast multiplier scaled. + !creditOnly && estimate.serviceTierPricing?.basis === "transmitted" ? "service_tier_transmitted" as const : undefined, ].filter((reason): reason is CostEstimateReason => reason !== undefined); return { kind: "value", estimate, estimateReasons }; } @@ -336,6 +341,7 @@ export function requestLogDto( entry: RequestLogEntry, { includeDecodeRate = true }: { includeDecodeRate?: boolean } = {}, ): Record { + const requestTier = serviceTierContext(entry); return { ...entry, ...publicLogUsage(entry.usage), @@ -358,7 +364,10 @@ export function requestLogDto( tokPerSecond: tokPerSecondResult(attempt), // Each attempt measures its own attempt-relative TTFT. ...(includeDecodeRate ? { decodeTokPerSecond: decodeTokPerSecondResult(attempt) } : {}), - cost: costResult({ ...attempt, attempts: undefined, routeDecision: entry.routeDecision, requestedServiceTier: entry.requestedServiceTier, configuredServiceTier: entry.configuredServiceTier, responseServiceTier: entry.responseServiceTier }), + // Attempts carry no time of their own; dated tier prices follow the request's. + // An attempt without its own tier record gets the tier the request total gives it (estimateComboCost): + // the request's derived context, never a raw parent scalar that may describe an earlier response. + cost: costResult({ ...attempt, attempts: undefined, timestamp: entry.timestamp, routeDecision: entry.routeDecision, requestedServiceTier: requestTier.requestedServiceTier, configuredServiceTier: requestTier.configuredServiceTier, responseServiceTier: requestTier.responseServiceTier }), }, })), } diff --git a/src/usage/cost.ts b/src/usage/cost.ts index f797aa9a71b..dfeebe88706 100644 --- a/src/usage/cost.ts +++ b/src/usage/cost.ts @@ -35,6 +35,7 @@ import { findContextTier, isLongContext, pricingFamilyProvider, + ultrafastPriceMultiplier, type Cost4, type ExpectedPriceOverlay, type ExpectedPriceStatus, @@ -61,6 +62,8 @@ export interface ServiceTierContext { requestedServiceTier?: string; configuredServiceTier?: string; tierOutcome?: AttemptTierOutcome; + /** Request time in epoch ms; selects a dated tier schedule. Absent prices at the current time. */ + pricedAt?: number; } export interface CostTokens { @@ -108,6 +111,8 @@ export interface AttemptCostEstimate { customThresholdApplied?: true; /** The numeric estimate is a known floor because the exact Priority price is unavailable. */ priorityLowerBound?: boolean; + /** Set when the Ultrafast schedule priced this attempt (#9138). */ + serviceTierPricing?: ServiceTierPricing; /** * How this attempt was billed. Present only when provider credits priced it: `cost` is then * `providerCredits x creditPriceUsd` and its four token fields carry no allocation. @@ -129,6 +134,8 @@ export interface CostEstimate { customThresholdApplied?: true; /** The aggregate satisfies the lower-bound rule for its billing basis. */ priorityLowerBound?: boolean; + /** Ultrafast pricing applied to the request or, for a combo, to at least one attempt. */ + serviceTierPricing?: ServiceTierPricing; /** * Billing basis for the aggregate. `provider-credits` means every priced attempt shared one * credit price and the credits are summed; `mixed` means the attempts were not all billed the @@ -472,14 +479,16 @@ export type ServiceTierInput = string | ServiceTierContext; * distinguish a response-confirmed Fast request from a merely requested one, * and long-context exclusivity depends on that distinction. */ -export function serviceTierContext(entry: ServiceTierContext): ServiceTierContext { +export function serviceTierContext(entry: ServiceTierContext & { timestamp?: number }): ServiceTierContext { + const pricedAt = typeof entry.timestamp === "number" && Number.isFinite(entry.timestamp) ? { pricedAt: entry.timestamp } : {}; if (entry.tierOutcome) { - return { ...serviceTierContextFromOutcome(entry.tierOutcome), tierOutcome: entry.tierOutcome }; + return { ...serviceTierContextFromOutcome(entry.tierOutcome), tierOutcome: entry.tierOutcome, ...pricedAt }; } return { responseServiceTier: entry.responseServiceTier, requestedServiceTier: entry.requestedServiceTier, configuredServiceTier: entry.configuredServiceTier, + ...pricedAt, }; } @@ -609,6 +618,84 @@ function applyPriorityMultiplier( * definite standard cost for a request that may well have been billed as priority, which is the * one thing a cost estimate must never do. */ +/** + * How Ultrafast pricing was established. `confirmed`: an authoritative response echoed Ultrafast. + * `transmitted`: the adapter serialized Ultrafast on the wire and no authoritative echo or + * explicit refusal contradicts it, so the price is an estimate. + */ +export interface ServiceTierPricing { + tier: "ultrafast"; + multiplier: number; + basis: "confirmed" | "transmitted"; +} + +/** + * Ultrafast evidence, strongest first: an authoritative response tier decides; an explicit + * refusal rules Ultrafast out; otherwise the serialized wire value counts. A tier the caller only + * requested proves nothing about what was sent, so it never selects the Ultrafast price. Evidence + * comes only from a tier-outcome record: a scalar tier copied from a parent row may describe a + * different attempt, and every Ultrafast-capable release records outcomes. + */ +function ultrafastBasis(tier: ServiceTierInput | undefined, outcome: AttemptTierOutcome | undefined): ServiceTierPricing["basis"] | undefined { + const evidence = outcome ?? (typeof tier === "object" ? tier.tierOutcome : undefined); + if (evidence) { + if (evidence.responseTierAuthoritative !== false && evidence.responseServiceTier !== undefined) { + return canonicalFastTierMarker(evidence.responseServiceTier) === "ultrafast" ? "confirmed" : undefined; + } + if (evidence.fastDowngradeReason === "response-declined") return undefined; + return evidence.wireKind === "service-tier" + && typeof evidence.wireValue === "string" + && canonicalFastTierMarker(evidence.wireValue) === "ultrafast" + ? "transmitted" + : undefined; + } + return undefined; +} + +/** + * Apply the dated Ultrafast multiplier. A long-context band stacks only where the provider + * declares Fast stacking; otherwise the Standard long-context price is reported as a floor. + */ +function applyUltrafastMultiplier( + cost4: Cost4, + provider: string, + modelId: string, + tier: ServiceTierInput | undefined, + outcome: AttemptTierOutcome | undefined, + contextTier: ContextTierName | undefined, +): { cost4: Cost4; pricing?: ServiceTierPricing; lowerBound?: true } { + const basis = ultrafastBasis(tier, outcome); + if (!basis) return { cost4 }; + const pricedAt = typeof tier === "object" && tier.pricedAt !== undefined ? tier.pricedAt : Date.now(); + const multiplier = ultrafastPriceMultiplier(provider, modelId, pricedAt); + if (multiplier === undefined) return { cost4 }; + if (contextTier && findContextTier(provider, modelId)?.confirmedPriorityRelation !== "stack") return { cost4, lowerBound: true }; + return { + cost4: { + input: cost4.input * multiplier, + output: cost4.output * multiplier, + cacheRead: cost4.cacheRead * multiplier, + cacheWrite: cost4.cacheWrite * multiplier, + }, + pricing: { tier: "ultrafast", multiplier, basis }, + }; +} + +/** + * True when the dated Ultrafast rate prices this attempt. Ultrafast replaces the Priority premium + * rather than stacking on it: a fastWire mapping can record canonical `priority` while the wire + * carried `ultrafast`, and that request is billed once, at the Ultrafast rate. + */ +function ultrafastPrices( + provider: string, + modelId: string, + tier: ServiceTierInput | undefined, + outcome: AttemptTierOutcome | undefined, +): boolean { + if (!ultrafastBasis(tier, outcome)) return false; + const pricedAt = typeof tier === "object" && tier.pricedAt !== undefined ? tier.pricedAt : Date.now(); + return ultrafastPriceMultiplier(provider, modelId, pricedAt) !== undefined; +} function isOpenRouterPriorityLowerBound( provider: string, outcome: AttemptTierOutcome | undefined, @@ -745,17 +832,24 @@ export function estimateAttemptCost( const [tieredCost4, contextTier, contextPriorityLowerBound, customThresholdApplied] = applyPromptLengthPricing( price.cost4, price.provider, attempt.model, attempt.usage.inputTokens, attemptServiceTier, price.promptLengthPricing, ); - const [effectiveCost4, multiplier] = applyPriorityMultiplier( - tieredCost4, price.provider, attempt.model, attemptServiceTier, contextTier, customThresholdApplied, + // Only the attempt's own outcome is Ultrafast evidence: a request-level record may describe another + // attempt of the same combo. The request context supplies just the timestamp. + const requestPricedAt = typeof serviceTier === "object" && serviceTier.pricedAt !== undefined ? { pricedAt: serviceTier.pricedAt } : {}; + const [effectiveCost4, multiplier] = ultrafastPrices(price.provider, attempt.model, requestPricedAt, attempt.tierOutcome) + ? [tieredCost4, 1] as const + : applyPriorityMultiplier(tieredCost4, price.provider, attempt.model, attemptServiceTier, contextTier, customThresholdApplied); + const ultrafast = applyUltrafastMultiplier( + effectiveCost4, price.provider, attempt.model, requestPricedAt, attempt.tierOutcome, contextTier, ); - const billed = resolveAttemptCost(attempt.provider, attempt.usage, creditPrices, tokens, effectiveCost4); + const billed = resolveAttemptCost(attempt.provider, attempt.usage, creditPrices, tokens, ultrafast.cost4); if (!billed) return null; // A credit charge is `providerCredits x creditPriceUsd`. The token rates were still resolved to // decide whether this row falls back to them, but they did not produce the amount, so the // `priorityLowerBound` they imply is a statement about a price nobody was charged. A lower bound // is only honest for the rate that actually priced the row. const priorityLowerBound = billed.billing === undefined - && (contextPriorityLowerBound || isOpenRouterPriorityLowerBound(price.provider, attempt.tierOutcome)); + && (contextPriorityLowerBound || ultrafast.lowerBound === true || isOpenRouterPriorityLowerBound(price.provider, attempt.tierOutcome)); + const serviceTierPricing = billed.billing === undefined ? ultrafast.pricing : undefined; return { ordinal: attempt.ordinal, provider: attempt.provider, @@ -763,11 +857,13 @@ export function estimateAttemptCost( tokens, price, cost: billed.cost, - estimated: isEstimated(attempt.usage, attempt.usageStatus, billed.billing ? "verified" : price.status), + estimated: isEstimated(attempt.usage, attempt.usageStatus, billed.billing ? "verified" : price.status) + || serviceTierPricing?.basis === "transmitted", ...(multiplier !== 1 ? { priorityMultiplier: multiplier } : {}), ...(contextTier ? { contextTier } : {}), ...(customThresholdApplied ? { customThresholdApplied } : {}), ...(priorityLowerBound ? { priorityLowerBound: true } : {}), + ...(serviceTierPricing ? { serviceTierPricing } : {}), ...(billed.billing ? { billing: billed.billing } : {}), }; } @@ -825,6 +921,15 @@ function comboIsLowerBound( }); } +/** A combo is `transmitted` when any Ultrafast attempt is an estimate; multipliers can differ per attempt. */ +function comboServiceTierPricing(estimates: readonly AttemptCostEstimate[]): ServiceTierPricing { + const priced = estimates.flatMap(est => est.serviceTierPricing ?? []); + return { + tier: "ultrafast", + multiplier: Math.max(...priced.map(pricing => pricing.multiplier)), + basis: priced.some(pricing => pricing.basis === "transmitted") ? "transmitted" : "confirmed", + }; +} /** * Combo: price every attempt with its own rate and sum. Fail closed — if ANY * attempt is unpriced, return null rather than a partial sum. @@ -875,6 +980,9 @@ export function estimateComboCost( ...(estimates.some(est => est.contextTier) ? { contextTier: "long" as const } : {}), ...(estimates.some(est => est.customThresholdApplied) ? { customThresholdApplied: true as const } : {}), ...(comboIsLowerBound(attempts, estimates, billing) ? { priorityLowerBound: true as const } : {}), + ...(estimates.some(est => est.serviceTierPricing) + ? { serviceTierPricing: comboServiceTierPricing(estimates) } + : {}), }; } @@ -899,26 +1007,32 @@ export function estimateRequestCost( const [tieredCost4, contextTier, contextPriorityLowerBound, customThresholdApplied] = applyPromptLengthPricing( price.cost4, price.provider, input.model, input.usage.inputTokens, input.serviceTier, price.promptLengthPricing, ); - const [effectiveCost4, multiplier] = applyPriorityMultiplier( - tieredCost4, price.provider, input.model, input.serviceTier, contextTier, customThresholdApplied, + const [effectiveCost4, multiplier] = ultrafastPrices(price.provider, input.model, input.serviceTier, undefined) + ? [tieredCost4, 1] as const + : applyPriorityMultiplier(tieredCost4, price.provider, input.model, input.serviceTier, contextTier, customThresholdApplied); + const ultrafast = applyUltrafastMultiplier( + effectiveCost4, price.provider, input.model, input.serviceTier, undefined, contextTier, ); - const billed = resolveAttemptCost(input.provider, input.usage, creditPrices, tokens, effectiveCost4); + const billed = resolveAttemptCost(input.provider, input.usage, creditPrices, tokens, ultrafast.cost4); if (!billed) return null; // See `estimateAttemptCost`: a credit charge is exact for its configured price, so it must not // inherit the token-rate floor that the fallback path resolved on the way in. - const priorityLowerBound = billed.billing === undefined && (contextPriorityLowerBound || isOpenRouterPriorityLowerBound( + const priorityLowerBound = billed.billing === undefined && (contextPriorityLowerBound || ultrafast.lowerBound === true || isOpenRouterPriorityLowerBound( price.provider, typeof input.serviceTier === "object" ? input.serviceTier.tierOutcome : undefined, )); + const serviceTierPricing = billed.billing === undefined ? ultrafast.pricing : undefined; return { tokens, price, cost: billed.cost, - estimated: isEstimated(input.usage, input.usageStatus, billed.billing ? "verified" : price.status), + estimated: isEstimated(input.usage, input.usageStatus, billed.billing ? "verified" : price.status) + || serviceTierPricing?.basis === "transmitted", ...(multiplier !== 1 ? { priorityMultiplier: multiplier } : {}), ...(contextTier ? { contextTier } : {}), ...(customThresholdApplied ? { customThresholdApplied } : {}), ...(priorityLowerBound ? { priorityLowerBound: true } : {}), + ...(serviceTierPricing ? { serviceTierPricing } : {}), ...(billed.billing ? { billing: billed.billing } : {}), }; } diff --git a/src/usage/expected-prices.ts b/src/usage/expected-prices.ts index 3264bf62c7b..c9233143113 100644 --- a/src/usage/expected-prices.ts +++ b/src/usage/expected-prices.ts @@ -864,6 +864,45 @@ export const PRIORITY_PRICING_RULES: readonly PriorityPricingRule[] = [ })), ]; +/** + * Ultrafast (#9138): a published multiple of the Standard rate, uniform across fresh input, cached + * input, cache writes and output. GPT-6.2 Astra and Sol cost 3x through 2027-02-28 and 6x from + * 2027-03-01, both in Pacific time; GPT-6 Astra and GPT-6.1 Sol are 6x. Login and API-key routes + * share the API-equivalent value, as for Standard and Fast. + */ +export interface UltrafastPricingRule { + provider: string; + modelId: string; + /** Ordered steps; a step applies to requests before its `untilMs`, the last step has none. */ + schedule: readonly { untilMs?: number; multiplier: number }[]; + source: string; + verifiedAt: string; +} + +const OPENAI_ULTRAFAST_PRICING = "https://developers.openai.com/api/docs/pricing?latest-pricing=ultrafast"; +/** 2027-03-01 00:00 PST (UTC-8): Daylight saving time starts later that month. */ +export const GPT62_ULTRAFAST_6X_FROM_MS = Date.UTC(2027, 2, 1, 8); + +export const ULTRAFAST_PRICING_RULES: readonly UltrafastPricingRule[] = ["openai", "openai-apikey"].flatMap(provider => [ + ...["gpt-6.2-astra", "gpt-6.2-sol"].map((modelId): UltrafastPricingRule => ({ + provider, modelId, schedule: [{ untilMs: GPT62_ULTRAFAST_6X_FROM_MS, multiplier: 3 }, { multiplier: 6 }], + source: OPENAI_ULTRAFAST_PRICING, verifiedAt: "2026-11-28", + })), + ...["gpt-6-astra", "gpt-6.1-sol"].map((modelId): UltrafastPricingRule => ({ + provider, modelId, schedule: [{ multiplier: 6 }], source: OPENAI_ULTRAFAST_PRICING, verifiedAt: "2026-11-28", + })), +]); + +/** The Ultrafast multiplier for an exact provider/model at a request time, or undefined when unpublished. */ +export function ultrafastPriceMultiplier( + provider: string, + modelId: string, + atMs: number, + rules: readonly UltrafastPricingRule[] = ULTRAFAST_PRICING_RULES, +): number | undefined { + const rule = rules.find(candidate => candidate.provider === provider && candidate.modelId === modelId); + return rule?.schedule.find(step => step.untilMs === undefined || atMs < step.untilMs)?.multiplier; +} /** Exact provider/model priority-pricing lookup. */ export function findPriorityPricingRule( provider: string, diff --git a/structure/pricing.md b/structure/pricing.md index 33c58ef6363..3bec792d23b 100644 --- a/structure/pricing.md +++ b/structure/pricing.md @@ -32,6 +32,29 @@ when the submitted base rates equal the old baseline. Unrelated saves still adop the replacement row, so a base-rate edit never silently drops a Flat or Custom policy; its receipt must echo the same policy, with absent and `automatic` treated as equal. +## Ultrafast + +`ULTRAFAST_PRICING_RULES` in `src/usage/expected-prices.ts` records OpenAI's published Ultrafast +schedule for the `openai` and `openai-apikey` routes: GPT-6.2 Astra and Sol at 3x Standard +before 2027-03-01 00:00 Pacific (`GPT62_ULTRAFAST_6X_FROM_MS`) and 6x from then on, GPT-6 Astra +and GPT-6.1 Sol at 6x. The multiplier scales every token bucket. `src/usage/cost.ts` selects the +step from `ServiceTierContext.pricedAt`, which `serviceTierContext()` takes from the logged row's +`timestamp`, so Logs (`costResult` in `src/server/management/shared.ts`) and usage totals +(`computeEntryCost` in `src/usage/summary.ts`) price a row by its own request time; without a +timestamp the current time applies. + +Evidence is read per attempt from its own tier-outcome record, strongest first; a scalar tier copied from a parent row or the request context never selects Ultrafast, and the context contributes only the timestamp. An authoritative response tier decides: an +Ultrafast echo is `confirmed`, any other tier keeps Standard. An explicit `response-declined` +refusal keeps Standard. Otherwise an attempt whose adapter serialized `service_tier: ultrafast` +(`wireKind: "service-tier"`) is priced as `transmitted`: the estimate is marked `estimated` and +Logs shows the `service_tier_transmitted` reason. A tier the caller only requested never selects +the Ultrafast price. A long-context band stacks only where the catalog rule declares `stack`; +otherwise the Standard long-context price is reported with `priorityLowerBound`. Estimates carry +`serviceTierPricing` with the tier, multiplier and basis. When the Ultrafast rate prices an attempt it +replaces the Priority premium instead of stacking on it, including a canonical `priority` outcome +that a `fastWire` mapping serialized as `ultrafast`. `tests/usage/usage-ultrafast-pricing.test.ts` +pins the schedule boundary, the evidence order, mixed routes, the single premium and both read paths. + ## Dialog and estimates `gui/src/components/ModelPriceDialog.tsx` edits base rates plus Automatic, Flat rate or Custom diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index cdd1533bdbf..a6b194b561e 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1603,6 +1603,7 @@ "upstream-retry-zero-output.test.ts": "lib", "upstream-transient-retry.test.ts": "providers", "url-normalization.test.ts": "config", "usage-aggregate-cache.test.ts": "usage", "usage-anthropic-fast-pricing.test.ts": "usage", "usage-cursor-fast-pricing.test.ts": "usage", + "usage-ultrafast-pricing.test.ts": "usage", "usage-attempt-delivery.test.ts": "usage", "usage-client-attribution.test.ts": "usage", "usage-cost.test.ts": "usage", "usage-cost-antigravity-gemini4.test.ts": "usage", "usage-haiku-5-5-pricing.test.ts": "usage", "usage-fable-5-2-pricing.test.ts": "usage", "gpt61-terra-pricing.test.ts": "usage", "usage-credit-ledger-regressions.test.ts": "usage", "usage-provider-credit-price.test.ts": "usage", diff --git a/tests/usage/usage-ultrafast-pricing.test.ts b/tests/usage/usage-ultrafast-pricing.test.ts new file mode 100644 index 00000000000..9737bf0233b --- /dev/null +++ b/tests/usage/usage-ultrafast-pricing.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, test } from "bun:test"; +import { costResult, requestLogDto } from "../../src/server/management/shared"; +import type { RequestLogEntry } from "../../src/server/request-log"; +import type { AttemptTierOutcome } from "../../src/types"; +import { estimateAttemptCost, estimateComboCost, estimateRequestCost, serviceTierContext } from "../../src/usage/cost"; +import type { PersistedUsageEntry } from "../../src/usage/log"; +import { computeEntryCost } from "../../src/usage/summary"; + +// Synthetic: 100k input of which 90k cached, 100 output. GPT-6.2 Sol Standard prices it at $0.0300. +const usage = { inputTokens: 100_000, outputTokens: 100, cacheReadInputTokens: 90_000 }; +const NOV_2026 = Date.UTC(2026, 10, 27, 12); +// Ultrafast for GPT-6.2 moves from 3x to 6x at 2027-03-01 00:00 Pacific (PST, UTC-8). +const STEP = Date.UTC(2027, 2, 1, 8); + +/** The native Codex record from the report: the tier went out on the wire, the echo is not authoritative. */ +const transmitted: AttemptTierOutcome = { + wireKind: "service-tier", + wireValue: "ultrafast", + fastOutcome: "downgraded", + fastDowngradeReason: "wire-unavailable", + confirmation: "downgraded", + responseServiceTier: "default", + responseTierAuthoritative: false, +}; + +function attempt(tierOutcome: AttemptTierOutcome | undefined, extra: Record = {}) { + return { ordinal: 1, provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported" as const, usage, ...(tierOutcome ? { tierOutcome } : {}), ...extra }; +} + +function attemptTotal(tierOutcome: AttemptTierOutcome | undefined, pricedAt = NOV_2026, provider = "openai", model = "gpt-6.2-sol") { + return estimateAttemptCost(attempt(tierOutcome, { provider, model }), undefined, { pricedAt }); +} + +describe("Ultrafast pricing", () => { + test("a transmitted Ultrafast tier without an authoritative echo prices at the dated Ultrafast rate, as an estimate", () => { + expect(attemptTotal(undefined)?.cost.total).toBeCloseTo(0.03, 10); + const est = attemptTotal(transmitted)!; + expect(est.cost.total).toBeCloseTo(0.09, 10); + expect(est.estimated).toBe(true); + expect(est.serviceTierPricing).toEqual({ tier: "ultrafast", multiplier: 3, basis: "transmitted" }); + }); + + test("GPT-6.2 moves from 3x to 6x at the published Pacific-time boundary; GPT-6.1 Sol and GPT-6 Astra stay 6x", () => { + expect(attemptTotal(transmitted, STEP - 1)?.cost.total).toBeCloseTo(0.09, 10); + expect(attemptTotal(transmitted, STEP)?.cost.total).toBeCloseTo(0.18, 10); + expect(attemptTotal(transmitted, NOV_2026, "openai", "gpt-6.1-sol")?.cost.total).toBeCloseTo(0.18, 10); + // GPT-6 Astra Standard is 10 / 50 / 1.00: 10k fresh, 90k cached and 100 output make $0.195; Ultrafast is 6x. + expect(attemptTotal(transmitted, NOV_2026, "openai", "gpt-6-astra")?.cost.total).toBeCloseTo(1.17, 10); + }); + + test("an authoritative Standard echo, an explicit refusal or a requested-only tier keeps the Standard price", () => { + const authoritativeStandard: AttemptTierOutcome = { ...transmitted, responseTierAuthoritative: true }; + const refused: AttemptTierOutcome = { ...transmitted, fastDowngradeReason: "response-declined" }; + const requestedOnly: AttemptTierOutcome = { ...transmitted, wireValue: null }; + for (const outcome of [authoritativeStandard, refused, requestedOnly]) { + const est = attemptTotal(outcome)!; + expect(est.cost.total).toBeCloseTo(0.03, 10); + expect(est.serviceTierPricing).toBeUndefined(); + } + // A legacy row that only says the caller asked for Ultrafast proves nothing about the wire. + const legacy = estimateRequestCost({ provider: "openai", model: "gpt-6.2-sol", usage, usageStatus: "reported", serviceTier: { requestedServiceTier: "ultrafast", pricedAt: NOV_2026 } }); + expect(legacy?.cost.total).toBeCloseTo(0.03, 10); + }); + + test("an authoritative Ultrafast echo is confirmed, not estimated", () => { + const confirmed: AttemptTierOutcome = { ...transmitted, fastOutcome: "unknown", confirmation: "unknown", responseServiceTier: "ultrafast", responseTierAuthoritative: true }; + delete confirmed.fastDowngradeReason; + const est = attemptTotal(confirmed, NOV_2026, "openai-apikey")!; + expect(est.cost.total).toBeCloseTo(0.09, 10); + expect(est.estimated).toBe(false); + expect(est.serviceTierPricing).toEqual({ tier: "ultrafast", multiplier: 3, basis: "confirmed" }); + }); + + test("a mixed route prices each attempt with its own tier evidence", () => { + const combo = estimateComboCost([ + attempt(transmitted), + { ...attempt(undefined), ordinal: 2 }, + ], undefined, { pricedAt: NOV_2026 })!; + expect(combo.attempts!.map(est => Number(est.cost.total.toFixed(6)))).toEqual([0.09, 0.03]); + expect(combo.cost.total).toBeCloseTo(0.12, 10); + expect(combo.estimated).toBe(true); + }); + + test("Logs and usage totals price a logged row from its own timestamp", () => { + const entry = { + timestamp: NOV_2026, provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported", usage, + durationMs: 1000, status: 200, tierOutcome: transmitted, requestedServiceTier: "ultrafast", + } as unknown as PersistedUsageEntry; + expect(serviceTierContext(entry).pricedAt).toBe(NOV_2026); + const logs = costResult(entry); + expect(logs.kind).toBe("value"); + if (logs.kind !== "value") return; + expect(logs.estimate.cost.total).toBeCloseTo(0.09, 10); + expect(logs.estimateReasons).toContain("service_tier_transmitted"); + expect(computeEntryCost(entry).costTotal).toBeCloseTo(0.09, 10); + const later = { ...entry, timestamp: STEP } as PersistedUsageEntry; + expect(computeEntryCost(later).costTotal).toBeCloseTo(0.18, 10); + }); + test("an attempt without its own tier record never inherits another attempt's Ultrafast evidence", () => { + const combo = estimateComboCost([ + attempt(transmitted), + { ...attempt(undefined), ordinal: 2 }, + ], undefined, { tierOutcome: transmitted, pricedAt: NOV_2026 })!; + expect(combo.attempts!.map(est => Number(est.cost.total.toFixed(6)))).toEqual([0.09, 0.03]); + expect(combo.attempts![1]!.serviceTierPricing).toBeUndefined(); + }); + + test("expanded Logs attempts price at the row's own date", () => { + const after = STEP + 24 * 60 * 60 * 1000; + const entry = { + requestId: "r", timestamp: after, provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported", usage, durationMs: 1000, status: 200, + tierOutcome: transmitted, + attempts: [{ ordinal: 1, provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported", usage, durationMs: 1000, status: 200, + sendCount: 1, recoveryKinds: [], tierOutcome: transmitted }], + } as unknown as RequestLogEntry; + const dto = requestLogDto(entry) as { displayMetrics: { cost: { estimate: { cost: { total: number } } } }; attempts: Array<{ displayMetrics: { cost: { estimate: { cost: { total: number } } } } }> }; + expect(dto.displayMetrics.cost.estimate.cost.total).toBeCloseTo(0.18, 10); + expect(dto.attempts[0]!.displayMetrics.cost.estimate.cost.total).toBeCloseTo(0.18, 10); + }); + test("an expanded attempt without its own tier record does not borrow the parent's Ultrafast response", () => { + const confirmed: AttemptTierOutcome = { ...transmitted, fastOutcome: "unknown", confirmation: "unknown", responseServiceTier: "ultrafast", responseTierAuthoritative: true }; + delete confirmed.fastDowngradeReason; + const plain = { provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported", usage, durationMs: 1000, status: 200, sendCount: 1, recoveryKinds: [] }; + const entry = { + requestId: "r", timestamp: NOV_2026, ...plain, responseServiceTier: "ultrafast", tierOutcome: confirmed, + attempts: [{ ordinal: 1, ...plain }, { ordinal: 2, ...plain, tierOutcome: confirmed }], + } as unknown as RequestLogEntry; + const dto = requestLogDto(entry) as { displayMetrics: { cost: { estimate: { cost: { total: number } } } }; attempts: Array<{ displayMetrics: { cost: { estimate: { cost: { total: number } } } } }> }; + expect(dto.attempts.map(a => Number(a.displayMetrics.cost.estimate.cost.total.toFixed(6)))).toEqual([0.03, 0.09]); + expect(dto.displayMetrics.cost.estimate.cost.total).toBeCloseTo(0.12, 10); + }); + test("an expanded attempt uses the request tier the total gives it, not a stale parent scalar", () => { + const plain = { provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported", usage, durationMs: 1000, status: 200, sendCount: 1, recoveryKinds: [] }; + const entry = { + requestId: "r", timestamp: NOV_2026, ...plain, responseServiceTier: "priority", tierOutcome: transmitted, + attempts: [{ ordinal: 1, ...plain }, { ordinal: 2, ...plain, tierOutcome: transmitted }], + } as unknown as RequestLogEntry; + const dto = requestLogDto(entry) as { displayMetrics: { cost: { estimate: { cost: { total: number }; attempts: Array<{ cost: { total: number } }> } } }; attempts: Array<{ displayMetrics: { cost: { estimate: { cost: { total: number } } } } }> }; + const totals = dto.displayMetrics.cost.estimate.attempts.map(a => Number(a.cost.total.toFixed(6))); + expect(totals).toEqual([0.03, 0.09]); + expect(dto.attempts.map(a => Number(a.displayMetrics.cost.estimate.cost.total.toFixed(6)))).toEqual(totals); + }); + test("a canonical Priority request serialized as Ultrafast takes only the Ultrafast premium", () => { + const mapped: AttemptTierOutcome = { canonical: "priority", wireKind: "service-tier", wireValue: "ultrafast", fastOutcome: "applied", confirmation: "assumed" }; + const est = attemptTotal(mapped)!; + expect(est.cost.total).toBeCloseTo(0.09, 10); + expect(est.serviceTierPricing).toEqual({ tier: "ultrafast", multiplier: 3, basis: "transmitted" }); + const request = estimateRequestCost({ provider: "openai", model: "gpt-6.2-sol", usageStatus: "reported", usage, + serviceTier: serviceTierContext({ tierOutcome: mapped, timestamp: NOV_2026 }) })!; + expect(request.cost.total).toBeCloseTo(0.09, 10); + // Ordinary Priority keeps its 2x premium. + expect(attemptTotal({ ...mapped, wireValue: "priority" })?.cost.total).toBeCloseTo(0.06, 10); + }); +}); From d886a6d10127a040aa55204c33bd75dfc747a7bc Mon Sep 17 00:00:00 2001 From: JUN Date: Sat, 28 Nov 2026 12:56:13 +0900 Subject: [PATCH 36/64] feat(advisor): add external client MCP integration, stability fixes, and 12-locale UI copy (carry #8884) (#9189) * feat(advisor): add external client MCP integration, stability fixes, and 11-locale UI copy * fix(advisor): address CodeRabbit review findings after dev rebase * fix(advisor): address maintainer review blockers and hardening findings * fix(advisor): keep client MCP writes owned, quoted, opt-in and isolated - Tests and previews: an explicit homeDir without an explicit env no longer reads the host's client config-directory overrides (QODER_CONFIG_DIR, WORKBUDDY_CONFIG_DIR, ...), so they cannot reach a real client config. The hardening tests pass an empty env. - Hooks: the script's BUN_BIN and CFG_PATH assignments and the registered hook command are POSIX single-quoted, so paths with spaces, $() or backticks stay literal. Only the exact registered command (or the unquoted path an earlier build wrote) is treated as owned; a same-named hook at another path is left alone. - autoMountMcp defaults to off: writing into another tool's configuration needs an explicit opt-in or a manual client selection. - An opencodex-advisor MCP entry is replaced or removed only when it is exactly what OpenCodex writes now or what it recorded writing in /advisor-mcp-entries.json; a user's same-named entry is refused on mount and kept on unmount. - A streamed answer must end with [DONE], a finish_reason or response.completed, and a malformed event fails the consultation, so truncated advice is never reported as complete. - Completed consultations are no longer evicted before their 30-minute retention; a full store answers 429 advisor_capacity_exceeded. * fix(advisor): confirm Routing Undo over Advisor edits and require recorded MCP ownership - An Advisor write on a shared Routing JSON config still advances the Routing ownership record, so Routing toggles do not see a conflict, but no longer advances the Undo journal. Undo of the Routing apply now sees the Advisor edit as drift and asks before restoring a snapshot that would remove Advisor's MCP entry and hooks. The journal result-update machinery this needed is removed. - An opencodex-advisor MCP entry counts as OpenCodex's only when advisor-mcp-entries.json records writing exactly those bytes. An identical unrecorded entry is used as it is but never recorded or deleted. - With auto-connect off by default, the client panel's mode badge says Off instead of claiming it follows routes (12 locales). * docs(advisor): say auto-mount is off by default in the CLI surface * fix(advisor): translate the hook and skill badge and keep Spanish numerals aligned The gui localization gates refused advisor.mcp.badgeHookSkill shipped in English in the Spanish and French catalogs, and a Spanish advisor.adaptiveNote numeral the English copy does not have. * Fix Advisor SSE event framing and completion * Prefer requested Advisor transcript and filter prior consultations * Clarify Advisor CLI polling and MCP defaults * Mark Advisor MCP consultations as mutating * Correct Advisor consent recovery command * Report retained consultation capacity and expiry * Guard Advisor readiness and qualify transcript guidance * Keep auto mount enabled in consent revocation test * Reject empty Advisor MCP client lists * Report Advisor MCP reconciliation errors in CLI * Keep prompt cache keys out of Advisor identity * Place Advisor shared-file fingerprint contract with ownership * Keep Advisor MCP retry available until reconciliation succeeds * Enable Advisor auto sync and label client controls * Correct Spanish Advisor effort hint * Map Advisor management route to its contract * Show Advisor installation notes only after mounting * Describe Advisor inactivity and streaming limits in every locale * Clarify Advisor automatic frequency in all locales * Document Advisor external clients and timeout semantics * Exercise matching Advisor hook among preserved siblings * Bound Advisor MCP transport and response reads * Bound Advisor transcript reads after discovery * Match Advisor self routes by resolved destination * Recognize recorded Advisor ownership across shared client slots * Protect shared Advisor files across path aliases * Retain Advisor ownership when cleanup path changes * Keep translated Advisor polling commands complete * Clean the recorded Advisor MCP path after a config-directory move Unmount now cleans the file named by the ownership record when the client's config directory has moved since the mount, under the same recorded-bytes check: an unchanged entry is removed, a user edit is kept, and a missing file only drops the record. Previously the record was kept and every sync reported an error that nothing could clear. * Record Advisor hook registrations and reconcile moved client directories - A UserPromptSubmit command is rewritten or removed only when /advisor-hook-registrations.json records OpenCodex registering exactly that command in that file. An unrecorded registration of the same command is the user's and is left as it is on mount and unmount. - Mounting a selected client whose config directory moved since the last mount first cleans the recorded old MCP entry and hook registration (same recorded bytes check; a file another client also recorded is left to that client) instead of replacing the record and orphaning the old location. - The SSE reader ignores everything after [DONE], whether or not it arrived in the same transport chunk. * Queue Advisor client cleanup and remove only provable registrations Review round 2 on #9189 found that a recorded hook command still removed every item running that command, that unmount deleted the hook script while a user's registration still ran it, and that a moved client changed the old location before the new one was validated. - Mount appends one standalone UserPromptSubmit group and records it, with the hook script and skill path, in advisor-hook-registrations.json. A command the user already registers, or registers ambiguously, is left alone and not recorded. - Cleanup goes through advisor-pending-cleanup.json. Unmount queues everything the client recorded; a mount whose config directory moved queues the old entry, registration, script and skill only after the destination passed its checks. Mount, unmount and sync work the queue. - A hook registration is removed only when exactly one group exactly as OpenCodex wrote it runs the command and nothing else does; a hook script is removed only when no hook still runs it. Unreadable files and ambiguous registrations stay queued for a later pass instead of blocking the new mount. * Keep scripts a user hook runs and isolate cleanup failures Review round 3 on #9189: - The record keeps the hook config that may run the hook script separately from ownership of the registration, so moving a client never deletes a script that an unrecorded user hook still runs. - Each queued cleanup item runs in its own try/catch: a failed write or unlink keeps that item queued and reports it, and the other items and clients still reconcile. A failure on the queue file itself is reported by sync. * Require recorded content for Advisor files and match hooks by script path Review round 4 on #9189: - Hook scripts and skill files are OpenCodex's only when a record names the path with the SHA-256 of exactly the current content. A marker alone no longer allows overwriting or deleting a file; a marked file OpenCodex did not record writing makes mount refuse, an edited recorded file is left on unmount, and unmount no longer queues unrecorded current files. - A hook item counts as running the script when its command is the quoted command or contains the script path, so an unquoted user hook keeps the script, and mount does not add a second registration next to it. * Move shared owners to rewritten Advisor entries and files Review round 5 on #9189: when one of two clients sharing a config directory rewrote the shared MCP entry, hook script or skill (an upgrade changing the runtime path), the other client's record kept the old bytes or hash. Cleanup for the first client then deleted an entry the other still used, and the other client's later cleanup missed the rewritten script. Every other record that described the replaced content now moves to the new entry bytes or content hash in the same write. * Address CodeRabbit round on Advisor client ownership and hook readiness - Another client's record makes a shared MCP entry this client's only when OpenCodex would write that client's entry identically; a client with a different entry format is refused (naming the client that wrote it) instead of replacing its entry. - A hook item that runs the same script through another spelling, such as a symlinked config directory, counts as running it, so the script is not registered twice. - The reminder hook uses curl --fail, so an HTTP error from /healthz is not announced as a ready Advisor. - The POSIX shell hook tests are skipped on native Windows. * Address CodeRabbit round on Advisor cleanup handoff and readiness - queueRecordedArtifacts writes the cleanup queue before releasing the MCP and artifact records, so an interrupted handoff keeps the record for the next pass instead of losing the only evidence for cleanup. - A recorded hook script or skill that exists but cannot be read stays queued and is reported; only a confirmed-missing or changed file drops the item. - Status reports a hook that runs the script through any spelling as mounted, using the same identity check as mount; removal still needs the record. - A batch sync passes every selected client's paths into the cleanup each mount runs, so a move never cleans a directory another selected client uses. - Sync treats any unprotected recorded artifact of a deselected client as a cleanup candidate, even when status sees no mount (an unparseable config). - The reminder hook requires a 2xx /healthz status and does not follow redirects. --------- Co-authored-by: Flowershangfromthebranches <152056395+Flowershangfromthebranches@users.noreply.github.com> --- .../es/reference/configuration/advisor.md | 14 +- .../fr/reference/configuration/advisor.md | 14 +- .../ja/reference/configuration/advisor.md | 14 +- .../ko/reference/configuration/advisor.md | 14 +- .../docs/reference/configuration/advisor.md | 14 +- .../ru/reference/configuration/advisor.md | 14 +- .../tr/reference/configuration/advisor.md | 14 +- .../zh-cn/reference/configuration/advisor.md | 14 +- .../zh-tw/reference/configuration/advisor.md | 14 +- gui/src/i18n/de.ts | 45 +- gui/src/i18n/en.ts | 45 +- gui/src/i18n/es.ts | 45 +- gui/src/i18n/fr.ts | 45 +- gui/src/i18n/ja.ts | 45 +- gui/src/i18n/ko.ts | 45 +- gui/src/i18n/pt.ts | 45 +- gui/src/i18n/ru.ts | 45 +- gui/src/i18n/tr.ts | 45 +- gui/src/i18n/v2-pages/proxy-copy.ts | 12 +- gui/src/i18n/vi.ts | 45 +- gui/src/i18n/zh-TW.ts | 45 +- gui/src/i18n/zh.ts | 45 +- gui/src/pages/Advisor.tsx | 111 +- .../pages/advisor/AdvisorClientMcpPanel.tsx | 232 +++ .../integrations/FileIntegrationPage.tsx | 68 + gui/tests/advisor-save-feedback.test.tsx | 133 ++ gui/tests/integrations-surfaces.test.tsx | 22 +- scripts/test-layout/layout.json | 2 +- .../references/01_surface_agents-routing.md | 17 +- src/advisor/client-mcp.ts | 1509 +++++++++++++++++ src/advisor/consult.ts | 279 ++- src/advisor/context.ts | 201 ++- src/advisor/external-consult.ts | 853 ++++++++++ src/advisor/mcp-server.ts | 238 +++ src/advisor/runtime.ts | 98 +- src/advisor/settings.ts | 50 +- src/advisor/state.ts | 37 +- src/advisor/transcript-read.ts | 24 + src/cli/advisor.ts | 162 +- src/cli/capabilities-agents-routing.ts | 17 +- src/cli/help.ts | 2 +- src/cli/registry.ts | 7 +- src/server/advisor-destination.ts | 13 + src/server/chat-completions.ts | 45 +- src/server/chat-native-eligibility.ts | 13 + src/server/management/advisor-routes.ts | 83 +- src/server/management/companion-routes.ts | 2 +- src/server/management/integration-routes.ts | 40 +- src/server/management/route-registry.ts | 1 + src/server/messages-native-eligibility.ts | 6 + src/server/responses/advisor-plan-slot.ts | 2 + src/server/responses/advisor-slot.ts | 43 +- src/server/responses/core-options.ts | 2 + src/server/responses/request-prepare.ts | 5 +- src/server/responses/sidecar-execution.ts | 22 +- src/types/config.ts | 10 +- src/types/request.ts | 2 + structure/INDEX.md | 2 + structure/advisor.md | 83 + structure/clients/integrations.md | 2 +- structure/gui-and-management-api.md | 2 +- structure/manifest.json | 2 + .../advisor/advisor-client-mcp-safety.test.ts | 577 +++++++ tests/advisor/advisor-consult.test.ts | 152 +- tests/advisor/advisor-context.test.ts | 203 +++ tests/advisor/advisor-guard.test.ts | 24 + tests/advisor/advisor-plan.test.ts | 44 + .../advisor/advisor-responses-wiring.test.ts | 55 + tests/advisor/advisor-settings.test.ts | 23 +- tests/advisor/advisor-state.test.ts | 25 + tests/fixtures/test-layout-expected.json | 2 +- .../chat-native-decline-reason.test.ts | 9 + .../messages-native-bridge-policy.test.ts | 38 +- .../messages-native-eligibility.test.ts | 8 + tests/server/advisor-routes.test.ts | 1051 +++++++++++- 75 files changed, 7074 insertions(+), 257 deletions(-) create mode 100644 gui/src/pages/advisor/AdvisorClientMcpPanel.tsx create mode 100644 src/advisor/client-mcp.ts create mode 100644 src/advisor/external-consult.ts create mode 100644 src/advisor/mcp-server.ts create mode 100644 src/advisor/transcript-read.ts create mode 100644 src/server/advisor-destination.ts create mode 100644 tests/advisor/advisor-client-mcp-safety.test.ts diff --git a/docs-site/src/content/docs/es/reference/configuration/advisor.md b/docs-site/src/content/docs/es/reference/configuration/advisor.md index 8ed3de8f5d6..ad980be433c 100644 --- a/docs-site/src/content/docs/es/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/es/reference/configuration/advisor.md @@ -5,10 +5,18 @@ description: "Consulta independiente a un modelo experto, con políticas manuale El asesor es un modelo experto independiente que revisa la tarea del modelo principal y devuelve recomendaciones. OpenCodex controla toda la consulta: el proxy incorpora una herramienta sintética `advisor` al turno, la ejecuta mediante el enrutamiento habitual y entrega las recomendaciones al modelo principal para que continúe. Este no delega, no crea subagentes ni maneja credenciales del proveedor para consultar al asesor. -Es distinto de los [subagentes](/es/reference/configuration/agents/), que el modelo principal inicia mediante las herramientas de colaboración de Codex. El asesor es un sidecar del proxy que el cliente no ve como herramienta; también puede asesorar a un modelo que nunca cree subagentes. +Es distinto de los [subagentes](/es/reference/configuration/agents/), que el modelo principal inicia mediante las herramientas de colaboración de Codex. Para agentes enrutados, el asesor es un sidecar del proxy que el cliente no ve como herramienta; también puede asesorar a un modelo que nunca cree subagentes. +## Clientes externos y contexto completo + +`autoMountMcp` está desactivado por defecto. Actívalo con `ocx advisor set --auto-mount-mcp on` para seguir rutas compatibles, o elige clientes con `--mcp-clients `. `auto` borra la lista explícita y `none` no selecciona clientes. Los clientes externos pueden usar `consult_advisor` mediante `ocx advisor mcp`, o `ocx advisor consult --question "..."` y consultar el resultado con `ocx advisor consult --consultation-id `. Se exige consentimiento vigente. + +`context` comparte contexto limitado; `question-only` envía solo la pregunta y pausa consultas automáticas; `full` amplía los límites y puede adjuntar una transcripción local coincidente si se indica una sesión, tarea o ruta permitida. El texto y los resultados de herramientas pueden enviarse al proveedor asesor; no se garantiza encontrar la transcripción. + +`timeoutMs` mide inactividad y los datos recibidos reinician el temporizador. El límite total es `max(4 × timeoutMs, 600000 ms)`; el valor predeterminado es 600000 ms y el máximo configurable es 1800000 ms. + ## Modo de solo pregunta Para reducir entradas repetidas, selecciona **Enviar solo la pregunta del agente** en Advisor o ejecuta: @@ -43,9 +51,9 @@ En **Advisor**, bajo **Subagentes** en la barra lateral del dashboard, elige el | `model?` | `string` | — | Modelo experto. Admite un modelo nativo sin prefijo (`gpt-6-astra`), un `provider/model` explícito (`anthropic/claude-sonnet-4-6`, `xai/grok-...`) o un modelo nativo de una cuenta concreta. El asesor y el modelo principal pueden usar proveedores distintos. | | `effort?` | `string` | `"max"` | Esfuerzo de razonamiento de la consulta (`low` a `ultra`). | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | Cuándo se consulta al asesor. | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | Intercambio de contexto. `question-only` exige una pregunta explícita del agente y suspende consultas automáticas. | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | Intercambio de contexto. `question-only` exige una pregunta explícita del agente y suspende consultas automáticas. | | `maxConsultationsPerTask?` | `integer` | `3` | Límite de intentos por tarea adaptativa, de 1 a 3, incluidas las consultas manuales. | -| `timeoutMs?` | `number` | `120000` | Plazo de la consulta mediante loopback. | +| `timeoutMs?` | `number` | `600000` | Plazo de la consulta mediante loopback. | | `contextSharingConsent?` | `"v1"` | Ausente | Consentimiento del operador para enviar el contexto al proveedor del asesor. Solo `"v1"` es vigente. Un valor ausente, obsoleto o diferente impide enviar el contexto. | Puedes administrarlo en **Advisor** —la casilla para compartir contexto empieza desmarcada— o con `ocx advisor status`, `ocx advisor on --ack-context-sharing`, `ocx advisor consent`, `ocx advisor consent --revoke`, `ocx advisor off` y `ocx advisor set --model --effort --policy `. Si falta consentimiento, `ocx advisor on` sin `--ack-context-sharing` muestra la explicación y se detiene sin habilitar el intercambio entre proveedores. `ocx advisor set` no concede consentimiento. diff --git a/docs-site/src/content/docs/fr/reference/configuration/advisor.md b/docs-site/src/content/docs/fr/reference/configuration/advisor.md index 3c65d98c1d9..316a7596676 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/fr/reference/configuration/advisor.md @@ -12,7 +12,15 @@ rien à déléguer, ne spawn rien et ne porte aucun identifiant de fournisseur. Cela se distingue de la surface des sous-agents (voir [Configuration des agents](/fr/reference/configuration/agents/)) : les sous-agents sont une délégation initiée par le worker via les outils de collaboration de Codex. Le conseiller est un -sidecar côté proxy invisible du client — même un worker qui ne spawn jamais peut être conseillé. +sidecar côté proxy invisible du client pour les workers routés — même un worker qui ne spawn jamais peut être conseillé. + +## Clients externes et contexte complet + +`autoMountMcp` est désactivé par défaut. Activez-le avec `ocx advisor set --auto-mount-mcp on` pour suivre les routes compatibles, ou choisissez les clients avec `--mcp-clients `. `auto` efface la liste explicite et `none` ne sélectionne aucun client. Les clients externes peuvent utiliser `consult_advisor` via `ocx advisor mcp`, ou démarrer avec `ocx advisor consult --question "..."` puis consulter le résultat avec `ocx advisor consult --consultation-id `. Un consentement à jour est requis. + +`context` partage un contexte limité ; `question-only` envoie seulement la question et suspend les consultations automatiques ; `full` élargit les limites et peut joindre une transcription locale correspondante lorsqu’une session, tâche ou voie autorisée est fournie. Le texte et les résultats d’outils peuvent être envoyés au fournisseur conseiller ; la découverte de transcription n’est pas garantie. + +`timeoutMs` mesure l’inactivité et les données reçues réinitialisent le délai. La limite totale est `max(4 × timeoutMs, 600000 ms)` ; la valeur par défaut est 600000 ms et le maximum configurable est 1800000 ms. ## Question uniquement @@ -46,9 +54,9 @@ Sur la page **Advisor**, choisissez le modèle dans le catalogue. Le sélecteur | `model?` | `string` | — | Le modèle expert. Toute chaîne de modèle acceptée par le routeur : modèle natif seul (`gpt-6-astra`), `provider/model` explicite (`anthropic/claude-sonnet-4-6`, `xai/grok-...`) ou modèle natif qualifié par compte. Inter-fournisseurs entièrement pris en charge. | | `effort?` | `string` | `"max"` | Intensité de raisonnement de l'appel conseiller (`low`–`ultra`). | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | Quand consulter le conseiller. | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | Partage du contexte. `question-only` exige une question explicite du worker et suspend les consultations automatiques. | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | Partage du contexte. `question-only` exige une question explicite du worker et suspend les consultations automatiques. | | `maxConsultationsPerTask?` | `integer` | `3` | Budget adaptatif par tâche (1 à 3 tentatives, appels manuels compris). | -| `timeoutMs?` | `number` | `120000` | Délai de la consultation en boucle locale. | +| `timeoutMs?` | `number` | `600000` | Délai de la consultation en boucle locale. | | `contextSharingConsent?` | `"v1"` | absent | Consentement de l'opérateur pour envoyer le contexte de la tâche au fournisseur conseiller configuré. Seul `"v1"` est courant. Une valeur absente, périmée ou autre n'autorise aucun envoi. `enabled: true` n'est pas ce consentement. | Gérez-le via la page **Advisor** du tableau de bord ou diff --git a/docs-site/src/content/docs/ja/reference/configuration/advisor.md b/docs-site/src/content/docs/ja/reference/configuration/advisor.md index 15254c5aa46..f4be0d6d560 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/ja/reference/configuration/advisor.md @@ -5,7 +5,15 @@ description: manual、preflight、証拠に基づく adaptive ポリシーによ アドバイザーはワーカーのタスクをレビューし助言を返す独立したエキスパートモデルです。相談は OpenCodex がエンドツーエンドで所有します。プロキシはワーカーのターンに合成 `advisor` ツールを注入し、通常のルーティング権威を通じて相談を自ら実行し、助言を再注入して元のワーカーを継続させます。ワーカーは委譲も spawn もせず、プロバイダー資格情報も持ちません。 -これはサブエージェントサーフェス([エージェント設定](/ja/reference/configuration/agents/)を参照)とは異なります。サブエージェントは Codex のコラボレーションツールによるワーカー主導の委譲です。アドバイザーはクライアントから見えないプロキシ側のサイドカーです — 何も spawn しないワーカーでも助言を受けられます。 +これはサブエージェントサーフェス([エージェント設定](/ja/reference/configuration/agents/)を参照)とは異なります。サブエージェントは Codex のコラボレーションツールによるワーカー主導の委譲です。ルーティングされたワーカーでは、アドバイザーはクライアントから見えないプロキシ側のサイドカーです — 何も spawn しないワーカーでも助言を受けられます。 + +## 外部クライアントと全コンテキスト + +`autoMountMcp` の既定値は `false` です。`ocx advisor set --auto-mount-mcp on` で対応ルートに自動接続するか、`--mcp-clients ` で選択します。`auto` は明示リストを解除し、`none` は選択を空にします。外部クライアントは `ocx advisor mcp` の `consult_advisor`、または `ocx advisor consult --question "..."` と `ocx advisor consult --consultation-id ` による取得を使えます。現在の同意が必要です。 + +`context` は制限されたコンテキスト、`question-only` は質問のみを送り自動相談を停止します。`full` は上限を拡張し、セッション・タスクIDまたは許可パスがあれば一致するローカル記録を添付できる場合があります。記録やツール結果は相談先プロバイダーへ送信されることがあり、記録の発見は保証されません。 + +`timeoutMs` は無通信の制限で、受信データによりリセットされます。全体の上限は `max(4 × timeoutMs, 600000 ms)`、既定値は 600000 ms、設定可能な最大値は 1800000 ms です。 ## 質問のみ送信 @@ -39,9 +47,9 @@ ocx advisor set --context-mode question-only | `model?` | `string` | — | エキスパートモデル。ルーターが受け付ける任意のモデル文字列:ネイティブモデル(`gpt-6-astra`)、明示的な `provider/model`(`anthropic/claude-sonnet-4-6`、`xai/grok-...`)、アカウント修飾ネイティブモデル。クロスプロバイダーを完全にサポートします。 | | `effort?` | `string` | `"max"` | アドバイザー呼び出しの推論強度(`low`〜`ultra`)。 | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | 相談のタイミング。 | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | コンテキスト共有。`question-only` はワーカーの明示的な質問を必要とし、自動相談を停止します。 | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | コンテキスト共有。`question-only` はワーカーの明示的な質問を必要とし、自動相談を停止します。 | | `maxConsultationsPerTask?` | `integer` | `3` | 適応型タスクの相談上限(1〜3回、手動呼び出しを含む)。 | -| `timeoutMs?` | `number` | `120000` | ループバック相談のタイムアウト。 | +| `timeoutMs?` | `number` | `600000` | ループバック相談のタイムアウト。 | | `contextSharingConsent?` | `"v1"` | なし | 設定されたアドバイザーのプロバイダーへタスク文脈を送ることへの操作者の同意。現在有効な値は `"v1"` だけです。欠落、古い値、その他の値ではタスク内容は送られません。`enabled: true` だけでは同意になりません。 | ダッシュボードの **Advisor** ページまたは `ocx advisor status|on|off|set --model --effort --policy ` で管理します。 diff --git a/docs-site/src/content/docs/ko/reference/configuration/advisor.md b/docs-site/src/content/docs/ko/reference/configuration/advisor.md index b52d0a6caea..087ab3cfbe5 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/ko/reference/configuration/advisor.md @@ -5,7 +5,15 @@ description: manual, preflight 및 증거 기반 adaptive 정책을 제공하는 어드바이저는 워커의 작업을 검토하고 조언을 반환하는 독립 전문가 모델입니다. 상담은 OpenCodex가 엔드투엔드로 소유합니다. 프록시가 워커 턴에 합성 `advisor` 도구를 주입하고, 정상적인 라우팅 권위를 통해 상담을 직접 실행하며, 조언을 재주입해 원래 워커가 계속 진행하게 합니다. 워커는 위임하지 않고, 아무것도 spawn하지 않으며, 제공자 자격 증명도 가지지 않습니다. -이는 서브에이전트 서피스([에이전트 구성](/ko/reference/configuration/agents/) 참조)와 다릅니다. 서브에이전트는 Codex 협업 도구를 통한 워커 주도 위임입니다. 어드바이저는 클라이언트에게 보이지 않는 프록시 측 사이드카입니다 — 아무것도 spawn하지 않는 워커도 조언을 받을 수 있습니다. +이는 서브에이전트 서피스([에이전트 구성](/ko/reference/configuration/agents/) 참조)와 다릅니다. 서브에이전트는 Codex 협업 도구를 통한 워커 주도 위임입니다. 라우팅된 워커의 어드바이저는 클라이언트에게 보이지 않는 프록시 측 사이드카입니다 — 아무것도 spawn하지 않는 워커도 조언을 받을 수 있습니다. + +## 외부 클라이언트와 전체 맥락 + +`autoMountMcp` 기본값은 `false`입니다. `ocx advisor set --auto-mount-mcp on`으로 호환 라우트를 자동 연결하거나 `--mcp-clients `로 직접 선택합니다. `auto`는 명시적 목록을 지우고 `none`은 아무 클라이언트도 선택하지 않습니다. 외부 클라이언트는 `ocx advisor mcp`의 `consult_advisor` 도구를 쓰거나 `ocx advisor consult --question "..."`로 시작하고 `ocx advisor consult --consultation-id `로 결과를 확인할 수 있습니다. 현재 버전의 동의가 필요합니다. + +`context`는 제한된 맥락을 공유하고, `question-only`는 질문만 보내며 자동 상담을 중지합니다. `full`은 제한을 늘리고 세션·작업 ID 또는 허용된 경로가 제공되면 일치하는 로컬 기록을 첨부할 수 있습니다. 기록과 도구 결과가 어드바이저 제공자에게 전송될 수 있으며 기록을 찾는다고 보장하지 않습니다. + +`timeoutMs`는 무응답 제한이며 데이터를 받으면 타이머가 초기화됩니다. 전체 상한은 `max(4 × timeoutMs, 600000 ms)`입니다. 기본값은 600000 ms, 설정 가능한 최대값은 1800000 ms입니다. ## 질문만 전송 @@ -39,9 +47,9 @@ ocx advisor set --context-mode question-only | `model?` | `string` | — | 전문가 모델. 라우터가 허용하는 모든 모델 문자열: 네이티브 모델(`gpt-6-astra`), 명시적 `provider/model`(`anthropic/claude-sonnet-4-6`, `xai/grok-...`), 계정 한정 네이티브 모델. 크로스 프로바이더를 완전히 지원합니다. | | `effort?` | `string` | `"max"` | 어드바이저 호출의 추론 강도(`low`~`ultra`). | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | 상담 시점. | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | 맥락 공유. `question-only`는 워커의 명시적 질문을 요구하며 자동 자문을 중지합니다. | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | 맥락 공유. `question-only`는 워커의 명시적 질문을 요구하며 자동 자문을 중지합니다. | | `maxConsultationsPerTask?` | `integer` | `3` | 적응형 작업 상담 한도(1–3회 시도, 수동 호출 포함). | -| `timeoutMs?` | `number` | `120000` | 루프백 상담 타임아웃. | +| `timeoutMs?` | `number` | `600000` | 루프백 상담 타임아웃. | | `contextSharingConsent?` | `"v1"` | 없음 | 설정된 어드바이저 프로바이더로 작업 맥락을 보내는 운영자 동의. 현재 값은 `"v1"`뿐입니다. 없거나, 오래되었거나, 다른 값이면 작업 내용을 보내지 않습니다. `enabled: true`만으로는 동의가 아닙니다. | 대시보드 **Advisor** 페이지 또는 `ocx advisor status|on|off|set --model --effort --policy `로 관리합니다. diff --git a/docs-site/src/content/docs/reference/configuration/advisor.md b/docs-site/src/content/docs/reference/configuration/advisor.md index ad04c3046d6..613db5963c2 100644 --- a/docs-site/src/content/docs/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/reference/configuration/advisor.md @@ -11,9 +11,17 @@ anything, or carries provider credentials. This is distinct from the subagent surface (see [Agent configuration](/reference/configuration/agents/)): subagents are worker-initiated -delegation through Codex's collaboration tools. The advisor is a proxy-side sidecar the client +delegation through Codex's collaboration tools. For routed workers, the advisor is a proxy-side sidecar the client never sees — even a worker that never spawns anything can be advised. +## External clients and full context + +`autoMountMcp` defaults to `false`. Enable it with `ocx advisor set --auto-mount-mcp on` to follow compatible active routes, or choose explicit clients with `--mcp-clients `; `auto` clears the explicit list and `none` selects no clients. External clients can use the `consult_advisor` MCP tool served by `ocx advisor mcp`, or start a consultation with `ocx advisor consult --question "..."` and poll it with `ocx advisor consult --consultation-id `. Current context-sharing consent is required. + +`context` is the default bounded context, `question-only` sends the question only and pauses automatic consultations, and `full` uses expanded bounds and can attach a matching local transcript when a session or task ID or permitted transcript path is supplied. Transcript text and tool results may be sent to the configured Advisor provider. A transcript is not guaranteed to be found. + +`timeoutMs` is an inactivity timeout: response data resets it. A separate hard ceiling is `max(4 × timeoutMs, 600000 ms)`; the default is 600000 ms and the maximum configurable inactivity timeout is 1800000 ms. + ## Question-only mode To reduce repeated input, select **Send only the worker’s question** in the Advisor page, or run: @@ -46,9 +54,9 @@ On the dashboard **Advisor** page (under the **Subagents** sidebar row), choose | `model?` | `string` | — | The expert model. Any model string the router accepts: a bare native model (`gpt-6-astra`), an explicit `provider/model` (`anthropic/claude-sonnet-4-6`, `xai/grok-...`), or an account-qualified native model. Cross-provider is fully supported: the worker and the advisor do not need to share a provider. | | `effort?` | `string` | `"max"` | Reasoning effort for the advisor call (`low` through `ultra`). | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | When the advisor is consulted. | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | Context sharing. `question-only` requires an explicit worker question and pauses automatic consultations. | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | Context sharing. `question-only` requires an explicit worker question and pauses automatic consultations. | | `maxConsultationsPerTask?` | `integer` | `3` | Adaptive task allowance (1–3 attempts), including manual calls. | -| `timeoutMs?` | `number` | `120000` | Loopback consultation timeout. | +| `timeoutMs?` | `number` | `600000` | Loopback consultation timeout. | | `contextSharingConsent?` | `"v1"` | absent | Operator consent to send task context to the configured Advisor provider. Only `"v1"` is current. Absent, stale, or any other value means no task context is sent. | Manage it from the dashboard **Advisor** page (the context-sharing checkbox starts unchecked) or diff --git a/docs-site/src/content/docs/ru/reference/configuration/advisor.md b/docs-site/src/content/docs/ru/reference/configuration/advisor.md index 58d33d34a5c..b0d7663b9ed 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/ru/reference/configuration/advisor.md @@ -5,7 +5,15 @@ description: Независимые консультации с политика Консультант — независимая экспертная модель, которая анализирует задачу воркера и возвращает рекомендации. Консультацией владеет OpenCodex от начала до конца: прокси внедряет синтетический инструмент `advisor` в ход воркера, сам выполняет консультацию через штатный маршрутизирующий механизм и возвращает рекомендацию, чтобы исходный воркер продолжил работу. Воркеру не нужно делегировать, spawn-ить что-либо или держать провайдерские учётные данные. -Это отличается от поверхности сабагентов (см. [Конфигурацию агентов](/ru/reference/configuration/agents/)): сабагенты — это инициированная воркером делегация через инструменты совместной работы Codex. Консультант — прокси-sidecar, невидимый для клиента: даже воркер, который никогда ничего не spawn-ит, может получить совет. +Это отличается от поверхности сабагентов (см. [Конфигурацию агентов](/ru/reference/configuration/agents/)): сабагенты — это инициированная воркером делегация через инструменты совместной работы Codex. Для маршрутизируемого воркера консультант — прокси-sidecar, невидимый для клиента: даже воркер, который никогда ничего не spawn-ит, может получить совет. + +## Внешние клиенты и полный контекст + +`autoMountMcp` по умолчанию равен `false`. Включите его через `ocx advisor set --auto-mount-mcp on` для совместимых маршрутов или выберите клиенты через `--mcp-clients `. `auto` очищает явный список, `none` не выбирает клиентов. Внешние клиенты используют `consult_advisor` через `ocx advisor mcp` либо `ocx advisor consult --question "..."` с последующей проверкой `ocx advisor consult --consultation-id `. Требуется актуальное согласие. + +`context` передаёт ограниченный контекст, `question-only` — только вопрос и приостанавливает автоматические консультации, а `full` расширяет лимиты и может приложить найденный локальный транскрипт по ID сессии, задачи или разрешённому пути. Текст и результаты инструментов могут быть переданы провайдеру советника; наличие транскрипта не гарантируется. + +`timeoutMs` ограничивает бездействие и сбрасывается при получении данных. Общий предел — `max(4 × timeoutMs, 600000 ms)`; значение по умолчанию 600000 ms, максимальное настраиваемое — 1800000 ms. ## Только вопрос @@ -39,9 +47,9 @@ ocx advisor set --context-mode question-only | `model?` | `string` | — | Экспертная модель. Любая строка модели, которую принимает роутер: «голая» нативная модель (`gpt-6-astra`), явный `provider/model` (`anthropic/claude-sonnet-4-6`, `xai/grok-...`) или модель с квалификацией аккаунта. Полная поддержка межпровайдерных сценариев. | | `effort?` | `string` | `"max"` | Интенсивность рассуждений вызова консультанта (`low`–`ultra`). | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | Когда консультировать. | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | Передача контекста. `question-only` требует явного вопроса исполнителя и приостанавливает автоматические консультации. | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | Передача контекста. `question-only` требует явного вопроса исполнителя и приостанавливает автоматические консультации. | | `maxConsultationsPerTask?` | `integer` | `3` | Бюджет адаптивной задачи: 1–3 попытки, включая ручные вызовы. | -| `timeoutMs?` | `number` | `120000` | Тайм-аут loopback-консультации. | +| `timeoutMs?` | `number` | `600000` | Тайм-аут loopback-консультации. | | `contextSharingConsent?` | `"v1"` | нет | Согласие оператора отправлять контекст задачи настроенному провайдеру консультанта. Текущая версия только `"v1"`. Отсутствие, устаревшее или иное значение означает, что содержимое задачи не отправляется. `enabled: true` само по себе не согласие. | Управляйте через страницу **Advisor** на дашборде или `ocx advisor status|on|off|set --model --effort --policy `. diff --git a/docs-site/src/content/docs/tr/reference/configuration/advisor.md b/docs-site/src/content/docs/tr/reference/configuration/advisor.md index b7e056d275d..e1c961d46bb 100644 --- a/docs-site/src/content/docs/tr/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/tr/reference/configuration/advisor.md @@ -5,7 +5,15 @@ description: manual, preflight ve kanıta dayalı adaptive politikalarıyla bağ Danışman, worker'ın görevini inceleyen ve tavsiye döndüren bağımsız bir uzman modeldir. Danışmayı uçtan uca OpenCodex sahiplenir: proxy, worker'ın turuna sentetik `advisor` aracını enjekte eder, danışmayı normal yönlendirme otoritesi aracılığıyla kendisi yürütür ve tavsiyeyi geri enjekte ederek özgün worker'ın devam etmesini sağlar. Worker'ın bir şey devretmesine, spawn etmesine veya sağlayıcı kimlik bilgisi taşımasına gerek yoktur. -Bu, alt ajan yüzeyinden farklıdır (bkz. [Ajan yapılandırması](/tr/reference/configuration/agents/)): alt ajanlar, Codex'in işbirliği araçları üzerinden worker tarafından başlatılan delegasyondur. Danışman, istemcinin hiç görmediği proxy tarafı bir sidecar'dır — hiçbir şey spawn etmeyen bir worker bile tavsiye alabilir. +Bu, alt ajan yüzeyinden farklıdır (bkz. [Ajan yapılandırması](/tr/reference/configuration/agents/)): alt ajanlar, Codex'in işbirliği araçları üzerinden worker tarafından başlatılan delegasyondur. Yönlendirilen worker için danışman, istemcinin görmediği proxy tarafı bir sidecar'dır — hiçbir şey spawn etmeyen bir worker bile tavsiye alabilir. + +## Harici istemciler ve tam bağlam + +`autoMountMcp` varsayılan olarak `false` değerindedir. Uyumlu rotaları izlemek için `ocx advisor set --auto-mount-mcp on`, istemci seçmek için `--mcp-clients ` kullanın. `auto` açık listeyi temizler, `none` hiçbir istemci seçmez. Harici istemciler `ocx advisor mcp` üzerinden `consult_advisor` kullanabilir veya `ocx advisor consult --question "..."` ile başlayıp `ocx advisor consult --consultation-id ` ile sonucu sorgulayabilir. Güncel onay gerekir. + +`context` sınırlı bağlam paylaşır; `question-only` yalnızca soruyu gönderir ve otomatik danışmaları duraklatır; `full` sınırları genişletir ve oturum, görev kimliği veya izin verilen yol sağlanırsa eşleşen yerel dökümü ekleyebilir. Metin ve araç sonuçları danışman sağlayıcısına gönderilebilir; dökümün bulunması garanti değildir. + +`timeoutMs` hareketsizlik sınırıdır ve gelen veri sayacı sıfırlar. Toplam üst sınır `max(4 × timeoutMs, 600000 ms)` değeridir; varsayılan 600000 ms, ayarlanabilir azami değer 1800000 ms'dir. ## Yalnızca soru @@ -39,9 +47,9 @@ Kontrol panelindeki **Advisor** sayfasında katalogdan model seçin. Yerel, sağ | `model?` | `string` | — | Uzman model. Yönlendiricinin kabul ettiği herhangi bir model dizisi: çıplak yerel model (`gpt-6-astra`), açık `provider/model` (`anthropic/claude-sonnet-4-6`, `xai/grok-...`) veya hesap nitelemeli yerel model. Sağlayıcılar arası tam desteklenir. | | `effort?` | `string` | `"max"` | Danışman çağrısının muhakeme düzeyi (`low`–`ultra`). | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | Ne zaman danışılır. | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | Bağlam paylaşımı. `question-only` çalışanın açık sorusunu gerektirir ve otomatik danışmaları duraklatır. | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | Bağlam paylaşımı. `question-only` çalışanın açık sorusunu gerektirir ve otomatik danışmaları duraklatır. | | `maxConsultationsPerTask?` | `integer` | `3` | Uyarlanabilir görev bütçesi: manuel çağrılar dahil 1–3 deneme. | -| `timeoutMs?` | `number` | `120000` | Loopback danışma zaman aşımı. | +| `timeoutMs?` | `number` | `600000` | Loopback danışma zaman aşımı. | | `contextSharingConsent?` | `"v1"` | yok | Yapılandırılmış danışman sağlayıcısına görev bağlamını gönderme onayı. Güncel değer yalnızca `"v1"`. Yok, eskimiş veya başka bir değer görev içeriğinin gönderilmemesi demektir. `enabled: true` bu onay değildir. | Panodaki **Advisor** sayfası veya `ocx advisor status|on|off|set --model --effort --policy ` ile yönetin. diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/advisor.md b/docs-site/src/content/docs/zh-cn/reference/configuration/advisor.md index b59ca79ba6a..35659aad246 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/advisor.md @@ -5,7 +5,15 @@ description: 独立专家咨询,支持 manual、preflight 与基于证据的 a 顾问是一个独立的专家模型,审阅 Worker 的任务并返回建议。OpenCodex 端到端地拥有整个咨询过程:代理向 Worker 的回合注入合成的 `advisor` 工具,自己通过正常路由权威执行咨询,并回注建议使原 Worker 继续。Worker 无需委托、无需 spawn 任何东西、也不携带 provider 凭据。 -这与子代理面(见[代理配置](/zh-cn/reference/configuration/agents/))不同:子代理是通过 Codex 协作工具由 Worker 发起的委托。顾问是客户端完全不可见的代理侧 sidecar —— 即使从不 spawn 的 Worker 也能获得建议。 +这与子代理面(见[代理配置](/zh-cn/reference/configuration/agents/))不同:子代理是通过 Codex 协作工具由 Worker 发起的委托。对经代理路由的 Worker,顾问是客户端不可见的代理侧 sidecar —— 即使从不 spawn 的 Worker 也能获得建议。 + +## 外部客户端与完整上下文 + +`autoMountMcp` 默认是 `false`。通过 `ocx advisor set --auto-mount-mcp on` 跟随兼容路由,或用 `--mcp-clients ` 指定客户端。`auto` 清除显式列表,`none` 不选择客户端。外部客户端可通过 `ocx advisor mcp` 使用 `consult_advisor`,或用 `ocx advisor consult --question "..."` 发起并用 `ocx advisor consult --consultation-id ` 查询。需要当前版本的同意。 + +`context` 共享受限上下文;`question-only` 只发送问题并暂停自动咨询;`full` 扩大限制,并可在提供会话、任务 ID 或允许的路径时附加匹配的本地记录。记录和工具结果可能发送给顾问提供商,不能保证找到记录。 + +`timeoutMs` 是无数据超时,收到数据会重置计时器。总上限为 `max(4 × timeoutMs, 600000 ms)`;默认 600000 ms,可配置最大值 1800000 ms。 ## 仅发送问题 @@ -39,9 +47,9 @@ ocx advisor set --context-mode question-only | `model?` | `string` | — | 专家模型。任何路由权威接受的模型字符串:裸原生模型(`gpt-6-astra`)、显式 `provider/model`(`anthropic/claude-sonnet-4-6`、`xai/grok-...`)或账户限定的原生模型。完整支持跨 provider:Worker 与 Advisor 无需同属一个 provider。 | | `effort?` | `string` | `"max"` | Advisor 调用的推理强度(`low` 至 `ultra`)。 | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | 何时咨询顾问。 | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | 上下文共享方式。`question-only` 要求主模型主动提问,并暂停自动咨询。 | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | 上下文共享方式。`question-only` 要求主模型主动提问,并暂停自动咨询。 | | `maxConsultationsPerTask?` | `integer` | `3` | 自适应任务咨询上限(1–3 次尝试),包含手动调用。 | -| `timeoutMs?` | `number` | `120000` | 回环咨询超时。 | +| `timeoutMs?` | `number` | `600000` | 回环咨询超时。 | | `contextSharingConsent?` | `"v1"` | 缺省 | 操作者同意把任务上下文发给所配置的顾问 provider。只有 `"v1"` 是当前版本。缺省、过期或其他值都表示不发送任务内容。`enabled: true` 本身不是同意。 | 通过仪表盘的 **Advisor** 页面或 `ocx advisor status|on|off|set --model --effort --policy ` 管理。 diff --git a/docs-site/src/content/docs/zh-tw/reference/configuration/advisor.md b/docs-site/src/content/docs/zh-tw/reference/configuration/advisor.md index 486a1fe30d8..ee2370e1627 100644 --- a/docs-site/src/content/docs/zh-tw/reference/configuration/advisor.md +++ b/docs-site/src/content/docs/zh-tw/reference/configuration/advisor.md @@ -5,7 +5,15 @@ description: 獨立專家諮詢,支援 manual、preflight 與依據證據的 a 顧問是一個獨立的專家模型,審閱 Worker 的任務並返回建議。OpenCodex 端到端地擁有整個諮詢過程:代理向 Worker 的回合注入合成的 `advisor` 工具,自己透過正常路由權威執行諮詢,並回注建議使原 Worker 繼續。Worker 無需委託、無需 spawn 任何東西、也不攜帶 provider 憑證。 -這與子代理面(見[代理設定](/zh-tw/reference/configuration/agents/))不同:子代理是透過 Codex 協作工具由 Worker 發起的委託。顧問是客户端完全不可見的代理側 sidecar —— 即使從不 spawn 的 Worker 也能獲得建議。 +這與子代理面(見[代理設定](/zh-tw/reference/configuration/agents/))不同:子代理是透過 Codex 協作工具由 Worker 發起的委託。對經代理路由的 Worker,顧問是用戶端不可見的代理側 sidecar —— 即使從不 spawn 的 Worker 也能獲得建議。 + +## 外部用戶端與完整上下文 + +`autoMountMcp` 預設為 `false`。使用 `ocx advisor set --auto-mount-mcp on` 跟隨相容路由,或以 `--mcp-clients ` 指定用戶端。`auto` 清除明確清單,`none` 不選擇用戶端。外部用戶端可透過 `ocx advisor mcp` 使用 `consult_advisor`,或以 `ocx advisor consult --question "..."` 啟動並用 `ocx advisor consult --consultation-id ` 查詢。需要目前版本的同意。 + +`context` 分享受限上下文;`question-only` 只傳送問題並暫停自動諮詢;`full` 擴大限制,並可在提供工作階段、任務 ID 或允許路徑時附加相符的本機紀錄。紀錄和工具結果可能傳送給顧問供應商,不能保證找到紀錄。 + +`timeoutMs` 是無資料逾時,收到資料會重設計時器。總上限為 `max(4 × timeoutMs, 600000 ms)`;預設 600000 ms,可設定最大值 1800000 ms。 ## 僅傳送問題 @@ -39,9 +47,9 @@ ocx advisor set --context-mode question-only | `model?` | `string` | — | 專家模型。任何路由權威接受的模型字串:裸原生模型(`gpt-6-astra`)、明確 `provider/model`(`anthropic/claude-sonnet-4-6`、`xai/grok-...`)或帳戶限定的原生模型。完整支援跨 provider:Worker 與 Advisor 無需同屬一個 provider。 | | `effort?` | `string` | `"max"` | Advisor 呼叫的推理強度(`low` 至 `ultra`)。 | | `policy?` | `"manual" \| "preflight" \| "adaptive"` | `"manual"` | 何時諮詢顧問。 | -| `contextMode?` | `"context" \| "question-only"` | `"context"` | 上下文共享方式。`question-only` 要求主模型主動提問,並暫停自動諮詢。 | +| `contextMode?` | `"context" \| "full" \| "question-only"` | `"context"` | 上下文共享方式。`question-only` 要求主模型主動提問,並暫停自動諮詢。 | | `maxConsultationsPerTask?` | `integer` | `3` | 自適應任務諮詢上限(1–3 次嘗試),包含手動呼叫。 | -| `timeoutMs?` | `number` | `120000` | 回環諮詢逾時。 | +| `timeoutMs?` | `number` | `600000` | 回環諮詢逾時。 | | `contextSharingConsent?` | `"v1"` | 缺省 | 操作者同意把任務上下文傳送給所設定的顧問 provider。只有 `"v1"` 是目前版本。缺省、過期或其他值都表示不傳送任務內容。`enabled: true` 本身不是同意。 | 透過儀表板的 **Advisor** 頁面或 `ocx advisor status|on|off|set --model --effort --policy ` 管理。 diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index b2bbe2534e8..bc189c7593b 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -289,7 +289,7 @@ export const de: Record = { "nav.subagents": "Sub-Agenten", "nav.advisor": "Berater", - "advisor.description": "Ein unabhängiges Expertenmodell, das die Aufgabe des Workers prüft und Rat zurückgibt. Die Konsultation gehört OpenCodex: Der Worker kann das synthetische Advisor-Tool aufrufen, und die Preflight-Politik versucht zusätzlich automatisch eine Konsultation pro Aufgabe — sobald die Aufgabe Orientierungsbelege geliefert hat (ein Tool-Aufruf des Assistenten oder ein Tool-Ergebnis nach der letzten Nutzernachricht) und ohne Mitwirkung des Workers. Der Versuch wird für Clients mit einer stabilen Konversationsidentität pro Aufgabe dedupliziert; ein Client ohne eine solche überspringt diese Deduplizierung und kann den Versuch bei jeder neu geeigneten Anfrage erneut erleben.", + "advisor.description": "Ein Expertenmodell für Ihre Coding-KI. Manuell erfolgt die Beratung auf Anfrage. Für geroutete Modelle folgt die Vorprüfung auf Tool-Nutzung und adaptive Hilfe auf wiederholte Reparaturfehler; externe Clients können MCP nutzen.", "advisor.enabled": "Berater aktiviert", "advisor.model": "Expertenmodell", "advisor.modelClear": "Modell entfernen", @@ -301,11 +301,11 @@ export const de: Record = { "advisor.policy": "Richtlinie", "advisor.questionOnly": "Nur die Frage des Workers senden", "advisor.questionOnlyNote": "Gesendet werden nur die Frage des Workers (bis zu 2000 Zeichen; bei Kürzung mit einem Hinweis) und eine feste Berateranweisung. Verlauf, Werkzeugergebnisse und Aufgabenkontext werden nicht angehängt. Der Worker muss nötige Hintergrundinformationen ergänzen. Automatische Beratungen pausieren; bestehende Limits gelten weiter.", - "advisor.policy.manual": "Manuell — nur wenn der Worker fragt", - "advisor.policy.preflight": "Preflight — automatischer Konsultationsversuch, sobald Orientierungsbelege vorliegen", - "advisor.policy.adaptive": "Adaptiv — Orientierung und fehlgeschlagene Reparaturen", + "advisor.policy.manual": "Manuell (Standard) — nur wenn die KI fragt oder Sie es wünschen", + "advisor.policy.preflight": "Auto nach Tool-Nutzung", + "advisor.policy.adaptive": "Auto nach Tools + Rettung — 1× nach Tool-Reads + Hilfe bei Fehler-Schleifen", "advisor.taskLimit": "Beratungen pro Aufgabe", - "advisor.adaptiveNote": "Automatische Beratungen erfordern eine stabile Gesprächskennung. Die erste Beratung folgt auf Orientierungshinweise (einen Werkzeugaufruf oder ein Ergebnis). Eine Beratung nach fehlgeschlagener Reparatur erfordert eine fehlgeschlagene Prüfung, eine abgeschlossene Dateiänderung und danach einen erneuten Fehlschlag desselben Befehls im selben Verzeichnis; wiederholte Fehlschläge allein reichen nicht aus. Manuelle Aufrufe zählen zum Aufgabenbudget. Reservierungen gelten 24 Stunden und überstehen Proxy-Neustarts.", + "advisor.adaptiveNote": "Auslösung: Auto-Modi starten nie bei der ersten Eingabe oder reinen Textfragen. Nachdem die KI per Tool Dateien oder Logs gelesen hat, läuft die automatische Prüfung einmal pro Aufgabe mit stabiler Sitzungs-ID (sonst einmal pro Anfrage); Auto-Rettung greift erst bei der Schleife Prüfung fehlgeschlagen → Datei bearbeitet → erneut fehlgeschlagen. Manuelle Aufrufe teilen das Aufgabenlimit nur bei stabiler Sitzungs-ID; der adaptive Modus benötigt eine stabile Sitzungs-ID für sein Aufgabenbudget.", "advisor.activity.title": "Letzte Berateraktivitäten", "advisor.activity.note": "Bis zu 100 Einträge dieses Prozesses für 24 Stunden. Keine Aufgabentexte oder Ratschläge werden gespeichert. Denkaufwand: angefordert → vom Adapter zugeordnet; fehlende Angaben bestätigen keine Unterstützung. Tokens: gemeldete Eingabe / Ausgabe. Übernahme und genaue Kosten werden nicht abgeleitet.", "advisor.activity.empty": "Noch keine Beratungen erfasst.", @@ -333,6 +333,41 @@ export const de: Record = { "advisor.disclosure": "Eine Konsultation kann die letzte Nutzeraufgabe, geparsten Nutzer-/Assistenten-/Entwicklertext, Tool-Aufrufe und Argumente, Tool-Ergebnisse, den Tool-Katalog des Workers, die Worker-Identität, das konfigurierte Berater-Modell und eine optionale Fokusfrage senden. OpenCodex fügt keine Provider-API-Schlüssel, Authorization-Header, OAuth-Token, Backend-Geheimnisse, Prozessumgebung oder verborgenes Chain-of-Thought ein. Aufgabeninhalt wird nicht von Geheimnissen bereinigt: ein eingefügter Schlüssel, ein Geheimnis in einer Datei oder ein von einem Tool ausgegebenes Token kann mitgesendet werden. Der Berater-Anbieter kann vom Worker-Anbieter abweichen.", "advisor.consent.label": "Ich verstehe, dass Berater-Konsultationen die Konversation dieser Aufgabe, Tool-Aufrufe und Tool-Ergebnisse an den konfigurierten Berater-Anbieter senden können, der vom Worker-Anbieter abweichen kann. Aufgabeninhalt wird nicht von Geheimnissen bereinigt.", "advisor.consent.required": "Der Berater ist nicht lauffähig, solange die Zustimmung zur Kontextfreigabe fehlt. Ohne sie wird kein Aufgabeninhalt gesendet.", + "advisor.fullContext": "Vollständigen Verlauf und lokale Sitzungsprotokolle senden", + "advisor.fullContextHint": "Erweitert Limits (128k/512k Zeichen) und bereinigt Client-Ballast. Hängt lokale Sitzungshistorien nur bei externen MCP-Beratungen an, wenn eine Sitzungs-ID oder ein Transkriptpfad übergeben wird.", + "advisor.mcp.title": "Client-Verbindungen (MCP & Erinnerungen)", + "advisor.mcp.subtitle": "Bindet externe Clients (einschließlich eingebauter Modelle wie WorkBuddy oder Qoder) per MCP und Erinnerungen ein, damit der Berater in langen Chats nicht vergessen wird.", + "advisor.mcp.proxyNativeTitle": "Über OpenCodex geleitete Clients", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP usw. erhalten das integrierte Berater-Tool und Erinnerungen direkt über den Proxy ohne zusätzliches MCP.", + "advisor.mcp.autoMountLabel": "opencodex-advisor-MCP automatisch für aktive kompatible Routen eintragen", + "advisor.mcp.autoMountHint": "Zweiwege-Sync: Funktioniert unabhängig davon, ob Sie zuerst den Berater oder zuerst die Client-Route aktivieren (außer bei manueller Auswahl).", + "advisor.mcp.selectionModeAuto": "Automatisch — folgt aktiven kompatiblen Routen", + "advisor.mcp.selectionModeOff": "Aus — Clients unten auswählen oder automatisches Verbinden einschalten", + "advisor.mcp.selectionModeManual": "Manuell — verbindet nur unten gewählte Clients", + "advisor.mcp.useAutoMode": "Automatischen Sync nutzen", + "advisor.mcp.selectRouted": "Alle gerouteten Clients auswählen", + "advisor.mcp.badgeRouted": "Geroutet", + "advisor.mcp.badgeDetected": "Installiert", + "advisor.mcp.badgeMounted": "Verbunden", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "Vertraut", + "advisor.mcp.trust.actionRequired": "Im Client auf Vertrauen klicken", + "advisor.mcp.trust.needsConfirmation": "In Client-MCP-Einstellungen prüfen", + "advisor.mcp.trust.autoEnabled": "Aktiviert", + "advisor.mcp.trust.notMounted": "Nicht verbunden", + "advisor.mcp.emptyHint": "Einstellungen speichern, um Client-MCP-Status anzuzeigen.", + "advisor.mcp.syncPartial": "Advisor-Einstellungen gespeichert, aber MCP-Synchronisierung fehlgeschlagen für: {clients}.", + "advisor.mcp.routeNoticeWillMount": "Automatische Berater-Verbindung aktiv: Beim Einschalten dieser Route wird opencodex-advisor unter {path} eingetragen.", + "advisor.mcp.routeNoticeMounted": "Advisor-MCP (opencodex-advisor) ist unter {path} eingerichtet.", + "advisor.mcp.routeNoticeManual": "Manuelle Client-Auswahl aktiv. Auf der Berater-Seite verwalten.", + "advisor.mcp.note.workbuddy": "Nach dem Speichern von mcp.json und Hook einmalig im MCP-Manager von WorkBuddy auf Vertrauen klicken.", + "advisor.mcp.note.workbuddy-ai": "Nach dem Speichern von mcp.json und Hook einmalig im MCP-Manager von WorkBuddy AI auf Vertrauen klicken.", + "advisor.mcp.note.qoder": "In Qoder settings.json (MCP + UserPromptSubmit-Hook) und SKILL.md eingetragen; unter Einstellungen -> MCP prüfen (nach Updates MCP neu starten).", + "advisor.mcp.note.qoder-cn": "In Qoder CN settings.json (MCP + UserPromptSubmit-Hook) und SKILL.md eingetragen; unter Einstellungen -> MCP prüfen (nach Updates MCP neu starten).", + "advisor.mcp.note.commandcode": "In Command Code mcp.json eingetragen; bei Rückfrage beim ersten Aufruf opencodex-advisor erlauben.", + "advisor.mcp.note.cline": "In cline_mcp_settings.json eingetragen (timeout: 900s); bestätige consult_advisor bei der Nachfrage in Cline (oder aktiviere Auto-Approve in den Cline-Einstellungen).", + "advisor.mcp.note.opencode": "In opencode.json unter mcp.opencodex-advisor (enabled: true, timeout: 900000ms) inklusive Erinnerungs-Skill eingetragen.", + "advisor.mcp.note.claude": "Claude Code nutzt über den OpenCodex-Proxy bereits das integrierte Berater-Tool; externes MCP muss beim nächsten Start bestätigt werden.", // routing intelligence "routing.title": "Routing-Intelligenz (beta)", "routing.subtitle": "Policy-Profile, Trockenlauf-Bewertung und routinggestützte Analysen.", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index b17d27c2b57..0e01dd21ce0 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -290,7 +290,7 @@ export const en = { "nav.combos": "Combos", "nav.subagents": "Subagents", "nav.advisor": "Advisor", - "advisor.description": "An independent expert model that reviews the worker's task and returns advice. OpenCodex owns the consultation: the worker can call the synthetic advisor tool, and policy preflight additionally attempts one automatic consultation per task without any worker cooperation — firing once the task has produced orientation evidence (an assistant tool call or a tool result after the latest user message). The attempt is deduplicated per task for clients that carry a stable conversation identity; a client without one skips that dedup and may receive the attempt again on every newly eligible request.", + "advisor.description": "An expert model your coding AI can consult. Manual mode calls it on request. For routed models, preflight follows tool use and adaptive rescue follows repeated repair failures; external clients can use MCP.", "advisor.enabled": "Advisor enabled", "advisor.model": "Expert model", "advisor.modelClear": "Clear model", @@ -302,11 +302,11 @@ export const en = { "advisor.policy": "Policy", "advisor.questionOnly": "Send only the worker's question", "advisor.questionOnlyNote": "Only the worker's question (up to 2000 retained characters, plus a truncation notice when longer) is sent, with a fixed advisor instruction. History, tool results and task context are not attached. The worker must include essential background. Automatic consultations are paused; existing consultation limits still apply.", - "advisor.policy.manual": "Manual — only when the worker asks", - "advisor.policy.preflight": "Preflight — automatic consultation attempt once orientation evidence exists", - "advisor.policy.adaptive": "Adaptive — orientation and failed-repair consultations", + "advisor.policy.manual": "Manual (default) — only when the AI asks or you tell it to", + "advisor.policy.preflight": "Auto after tool use", + "advisor.policy.adaptive": "Auto after tools + rescue — once after tool use, plus help if fixes keep failing", "advisor.taskLimit": "Consultations per task", - "advisor.adaptiveNote": "Automatic consultations require a stable conversation identity. Initial advice follows orientation evidence (a tool call or result). Failed-repair advice requires a failed validation, a completed file edit, then a new failure of the same command in the same directory; repeated failures alone do not qualify. Manual calls also consume the task budget; reservations expire after 24 hours and survive proxy restarts.", + "advisor.adaptiveNote": "How it works: auto modes do not fire on the initial user message or plain text replies. After the AI uses tools to read files or command output, the automatic check runs once per task when the client sends a stable session ID, or once per request without one. Rescue mode adds extra help only when a failed check → file edit → repeated failure loop occurs. Manual calls share the per-task limit only when a stable session ID is present, and adaptive mode requires a stable session ID for its task budget.", "advisor.activity.title": "Recent advisor activity", "advisor.activity.note": "Up to 100 records from this process, retained for 24 hours. No task text or advice is stored. Reasoning shows requested → adapter-mapped effort; unreported does not confirm support. Tokens show reported input / output. Advice adoption and exact cost are not inferred.", "advisor.activity.empty": "No consultations recorded yet.", @@ -334,6 +334,41 @@ export const en = { "advisor.disclosure": "A consultation may send the latest user task, parsed user/assistant/developer text, tool calls and arguments, tool results, the worker tool catalog, worker identity, the configured Advisor model, and an optional focus question. OpenCodex does not insert provider API keys, authorization headers, OAuth tokens, backend secrets, process environment, or hidden chain-of-thought. Task content is not secret-redacted: a pasted key, a secret in a file, or a token printed by a tool can be sent. The Advisor provider may differ from the worker provider.", "advisor.consent.label": "I understand that Advisor consultations may send this task's conversation, tool calls, and tool results to the configured Advisor provider, which may differ from the worker provider. Task content is not secret-redacted.", "advisor.consent.required": "Advisor is not runnable until context-sharing consent is recorded. No task content is sent without it.", + "advisor.fullContext": "Send full history & local session logs", + "advisor.fullContextHint": "Raises context limits (128k chars/msg, 512k total) and strips client boilerplate tags. Attaches local session history only for external MCP consultations that provide a session ID or transcript path.", + "advisor.mcp.title": "Client Connections (MCP & Anti-Forgetting Reminders)", + "advisor.mcp.subtitle": "Connects external clients (including ones using their own built-in models) to opencodex-advisor MCP with reminders so they do not forget the advisor in long chats.", + "advisor.mcp.proxyNativeTitle": "Clients routed through OpenCodex", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP, and similar routed clients already receive the built-in advisor tool and long-session reminders automatically.", + "advisor.mcp.autoMountLabel": "Auto-connect opencodex-advisor MCP for compatible active routes", + "advisor.mcp.autoMountHint": "Two-way sync: turning on Routing or Advisor in either order automatically updates compatible client configs (unless manual selection is enabled below).", + "advisor.mcp.selectionModeAuto": "Auto — follows active compatible routes", + "advisor.mcp.selectionModeOff": "Off — choose clients below or turn on auto-connect", + "advisor.mcp.selectionModeManual": "Manual — connects only checked clients below", + "advisor.mcp.useAutoMode": "Use automatic sync", + "advisor.mcp.selectRouted": "Select all routed clients", + "advisor.mcp.badgeRouted": "Routed", + "advisor.mcp.badgeDetected": "Installed", + "advisor.mcp.badgeMounted": "Connected", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "Trusted", + "advisor.mcp.trust.actionRequired": "Click Trust in client", + "advisor.mcp.trust.needsConfirmation": "Confirm in client MCP settings", + "advisor.mcp.trust.autoEnabled": "Enabled", + "advisor.mcp.trust.notMounted": "Not connected", + "advisor.mcp.emptyHint": "Save settings to sync and inspect client connection status.", + "advisor.mcp.syncPartial": "Advisor settings saved, but MCP sync failed for: {clients}.", + "advisor.mcp.routeNoticeWillMount": "Advisor auto-connect is on: enabling this client will also register opencodex-advisor MCP at {path}.", + "advisor.mcp.routeNoticeMounted": "Advisor MCP (opencodex-advisor) is connected for this client at {path}.", + "advisor.mcp.routeNoticeManual": "Advisor is in manual client selection mode. Manage whether this client connects on the Advisor page.", + "advisor.mcp.note.workbuddy": "After saving mcp.json and the prompt hook, click Trust once in WorkBuddy's MCP manager before first use.", + "advisor.mcp.note.workbuddy-ai": "After saving mcp.json and the prompt hook, click Trust once in WorkBuddy AI's MCP manager before first use.", + "advisor.mcp.note.qoder": "Written to Qoder settings.json (MCP + UserPromptSubmit hook) and SKILL.md; verify it is enabled in Qoder Settings -> MCP (restart/toggle MCP after upgrades).", + "advisor.mcp.note.qoder-cn": "Written to Qoder CN settings.json (MCP + UserPromptSubmit hook) and SKILL.md; verify it is enabled in Qoder CN Settings -> MCP (restart/toggle MCP after upgrades).", + "advisor.mcp.note.commandcode": "Written to Command Code mcp.json; approve opencodex-advisor if prompted on first call.", + "advisor.mcp.note.cline": "Written to cline_mcp_settings.json (timeout: 900s); approve consult_advisor when prompted in Cline (or opt into auto-approve in Cline settings).", + "advisor.mcp.note.opencode": "Written to opencode.json under mcp.opencodex-advisor (enabled: true, timeout: 900000ms) with the reminder Skill.", + "advisor.mcp.note.claude": "Claude Code already receives the built-in proxy advisor when routed through OpenCodex; enabling external MCP requires trusting it on next launch.", "nav.logs": "Logs & Debug", "nav.usage": "Usage", "common.github": "GitHub", diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index fdd9c7939b5..065fc0c48f8 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -285,7 +285,7 @@ export const es = { "nav.combos": "Combos", "nav.subagents": "Subagentes", "nav.advisor": "Asesor", - "advisor.description": "Un modelo experto independiente que revisa la tarea del agente ejecutor y devuelve recomendaciones. OpenCodex administra la consulta: el agente puede llamar a la herramienta sintética de Advisor y la política de comprobación previa también intenta una consulta automática por tarea, sin requerir su colaboración. El intento se activa cuando hay evidencia inicial de orientación: una llamada a herramientas del asistente o un resultado de herramienta posterior al último mensaje del usuario. Se evita repetir el intento por tarea en clientes con una identidad estable de conversación. Sin esa identidad, puede repetirse en cada nueva solicitud compatible.", + "advisor.description": "Un modelo experto que puede consultar tu IA de programación. En modo manual se invoca a petición. En modelos enrutados, la comprobación previa sigue al uso de herramientas y el rescate adaptativo a fallos repetidos; los clientes externos pueden usar MCP.", "advisor.enabled": "Asesor habilitado", "advisor.model": "Modelo experto", "advisor.modelClear": "Quitar modelo", @@ -297,11 +297,11 @@ export const es = { "advisor.policy": "Política", "advisor.questionOnly": "Enviar solo la pregunta del agente ejecutor", "advisor.questionOnlyNote": "Solo se envía la pregunta del agente ejecutor (hasta 2000 caracteres, con un aviso si se recorta), junto con una instrucción fija para el asesor. No se adjuntan el historial, los resultados de las herramientas ni el contexto de la tarea. El agente ejecutor debe incluir la información imprescindible. Las consultas automáticas se pausan y los límites de consulta se mantienen.", - "advisor.policy.manual": "Manual — solo cuando el trabajador pregunta", - "advisor.policy.preflight": "Prevuelo — intento de consulta automática una vez que existe evidencia de orientación", - "advisor.policy.adaptive": "Orientación adaptativa — y consultas de reparación fallida", + "advisor.policy.manual": "Manual (predeterminado) — solo cuando la IA pregunta o se lo pides", + "advisor.policy.preflight": "Auto tras usar herramientas", + "advisor.policy.adaptive": "Auto tras herramientas + rescate — una vez tras usar herramientas y ayuda extra si siguen fallando las correcciones", "advisor.taskLimit": "Consultas por tarea", - "advisor.adaptiveNote": "Las consultas automáticas requieren una identidad de conversación estable. El asesoramiento inicial sigue a la evidencia de orientación (una llamada a herramientas o resultado). El asesoramiento de reparación fallida requiere una validación fallida, una edición completa del archivo y luego un nuevo fallo del mismo comando en el mismo directorio; los fallos repetidos por sí solos no califican. Las llamadas manuales también consumen el presupuesto de la tarea; las reservas caducan después de 24 horas y sobreviven a los reinicios del proxy.", + "advisor.adaptiveNote": "Cómo funciona: los modos automáticos no se activan en el mensaje inicial ni en respuestas de texto simple. Solo tras usar herramientas para leer archivos o salidas de comandos se ejecuta una comprobación por tarea cuando el cliente envía un ID de sesión estable (o por solicitud sin él). El modo rescate añade ayuda extra solo ante un bucle de fallo → edición → fallo repetido. Las llamadas manuales comparten el límite por tarea cuando hay un ID de sesión estable, y el modo adaptativo requiere un ID estable para su presupuesto.", "advisor.activity.title": "Actividad reciente del asesor", "advisor.activity.note": "Hasta 100 registros de este proceso, retenidos durante 24 horas. No se almacena ningún texto de tarea o consejo. Razonamiento muestra el esfuerzo asignado por el adaptador → solicitado; no reportado no confirma soporte. Los tokens muestran la entrada / salida reportada. La adopción de consejos y el costo exacto no se infieren.", "advisor.activity.empty": "Aún no se han registrado consultas.", @@ -329,6 +329,41 @@ export const es = { "advisor.disclosure": "Una consulta puede enviar la tarea más reciente del usuario; el texto analizado de mensajes de usuario, asistente y desarrollador; las llamadas a herramientas con sus argumentos y resultados; el catálogo de herramientas y la identidad del agente ejecutor; el modelo de Advisor configurado y una pregunta opcional de enfoque. OpenCodex no añade claves API de proveedores, encabezados de autorización, tokens OAuth, secretos del backend, variables del entorno del proceso ni cadenas de pensamiento ocultas. No se eliminan los secretos que ya estén en el contenido de la tarea: una clave pegada, un secreto en un archivo o un token mostrado por una herramienta pueden enviarse. El proveedor de Advisor puede ser distinto del proveedor del agente ejecutor.", "advisor.consent.label": "Entiendo que las consultas de Advisor pueden enviar la conversación, las llamadas a herramientas y sus resultados al proveedor configurado de Advisor, que puede ser distinto del proveedor del agente ejecutor. No se eliminan los secretos que ya estén en el contenido.", "advisor.consent.required": "El asesor no se puede ejecutar hasta que se registre el consentimiento de intercambio de contexto. Ningún contenido de tarea se envía sin él.", + "advisor.fullContext": "Enviar historial completo y registros de sesión locales", + "advisor.fullContextHint": "Amplía los límites de contexto (128k caracteres/msg, 512k en total) y limpia las etiquetas estándar del cliente. Adjunta el historial local de sesión solo en consultas MCP externas que proporcionen un ID de sesión o ruta de transcripción.", + "advisor.mcp.title": "Conexiones de clientes (MCP y recordatorios anti-olvido)", + "advisor.mcp.subtitle": "Conecta clientes externos (incluidos los que usan sus propios modelos integrados) al MCP opencodex-advisor con recordatorios para que no olviden al asesor en chats largos.", + "advisor.mcp.proxyNativeTitle": "Clientes enrutados por OpenCodex", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP y clientes similares ya reciben automáticamente la herramienta integrada del asesor y recordatorios de sesión larga.", + "advisor.mcp.autoMountLabel": "Conectar automáticamente opencodex-advisor MCP en rutas activas compatibles", + "advisor.mcp.autoMountHint": "Sincronización bidireccional: activar Routing o Advisor en cualquier orden actualiza automáticamente la configuración de los clientes compatibles (salvo que uses selección manual abajo).", + "advisor.mcp.selectionModeAuto": "Auto — sigue las rutas activas compatibles", + "advisor.mcp.selectionModeOff": "Desactivado: elige clientes abajo o activa la conexión automática", + "advisor.mcp.selectionModeManual": "Manual — conecta solo los clientes marcados abajo", + "advisor.mcp.useAutoMode": "Usar sincronización automática", + "advisor.mcp.selectRouted": "Seleccionar todos los enrutados", + "advisor.mcp.badgeRouted": "Enrutado", + "advisor.mcp.badgeDetected": "Instalado", + "advisor.mcp.badgeMounted": "Conectado", + "advisor.mcp.badgeHookSkill": "Hook + habilidad", + "advisor.mcp.trust.trusted": "Confiable", + "advisor.mcp.trust.actionRequired": "Haz clic en Confiar en el cliente", + "advisor.mcp.trust.needsConfirmation": "Confirmar en ajustes MCP del cliente", + "advisor.mcp.trust.autoEnabled": "Habilitado", + "advisor.mcp.trust.notMounted": "No conectado", + "advisor.mcp.emptyHint": "Guarda la configuración para sincronizar e inspeccionar el estado de conexión.", + "advisor.mcp.syncPartial": "Configuración del asesor guardada, pero falló la sincronización MCP para: {clients}.", + "advisor.mcp.routeNoticeWillMount": "La autoconexión del asesor está activa: al habilitar este cliente también se registrará opencodex-advisor MCP en {path}.", + "advisor.mcp.routeNoticeMounted": "Advisor MCP (opencodex-advisor) está conectado para este cliente en {path}.", + "advisor.mcp.routeNoticeManual": "El asesor está en modo de selección manual de clientes. Gestiona si este cliente se conecta en la página de Advisor.", + "advisor.mcp.note.workbuddy": "Tras guardar mcp.json y el prompt hook, haz clic en Trust (Confiar) una vez en el gestor MCP de WorkBuddy antes del primer uso.", + "advisor.mcp.note.workbuddy-ai": "Tras guardar mcp.json y el prompt hook, haz clic en Trust (Confiar) una vez en el gestor MCP de WorkBuddy AI antes del primer uso.", + "advisor.mcp.note.qoder": "Escrito en settings.json de Qoder (MCP + hook UserPromptSubmit) y SKILL.md; verifica que esté habilitado en Qoder Settings -> MCP (reinicia o alterna MCP tras actualizar).", + "advisor.mcp.note.qoder-cn": "Escrito en settings.json de Qoder CN (MCP + hook UserPromptSubmit) y SKILL.md; verifica que esté habilitado en Qoder CN Settings -> MCP (reinicia o alterna MCP tras actualizar).", + "advisor.mcp.note.commandcode": "Escrito en mcp.json de Command Code; aprueba opencodex-advisor si se solicita en la primera llamada.", + "advisor.mcp.note.cline": "Escrito en cline_mcp_settings.json (timeout: 900s); aprueba consult_advisor cuando Cline lo solicite (o activa autoApprove en los ajustes de Cline).", + "advisor.mcp.note.opencode": "Escrito en opencode.json bajo mcp.opencodex-advisor (enabled: true, timeout: 900000ms) junto con la Skill de recordatorio.", + "advisor.mcp.note.claude": "Claude Code ya recibe el asesor integrado del proxy al enrutarse por OpenCodex; habilitar MCP externo requiere confiar en él al próximo inicio.", "nav.logs": "Registros y depuración", "nav.usage": "Uso", "common.github": "GitHub", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index f7695182750..f4f45638e26 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -287,7 +287,7 @@ export const fr: Record = { "nav.combos": "Combinaisons", "nav.subagents": "Sous-agents", "nav.advisor": "Conseiller", - "advisor.description": "Un modèle expert indépendant qui examine la tâche du worker et renvoie des conseils. La consultation appartient à OpenCodex : le worker peut appeler l'outil synthétique advisor, et la politique preflight tente en plus automatiquement une consultation par tâche — dès que la tâche a produit une preuve d'orientation (un appel d'outil de l'assistant ou un résultat d'outil après le dernier message utilisateur), sans coopération du worker. La tentative est dédupliquée par tâche pour les clients dotés d'une identité de conversation stable ; un client qui n'en a pas peut en recevoir à plusieurs reprises, une par requête éligible.", + "advisor.description": "Un modèle expert que votre IA de code peut consulter. En mode manuel, il est appelé sur demande. Pour les modèles routés, la vérification après usage d’outils a lieu une fois par tâche avec une identité de conversation stable, sinon une fois par requête admissible. Le secours adaptatif intervient après des échecs répétés ; les clients externes peuvent utiliser MCP.", "advisor.enabled": "Conseiller activé", "advisor.model": "Modèle expert", "advisor.modelClear": "Effacer le modèle", @@ -299,11 +299,11 @@ export const fr: Record = { "advisor.policy": "Politique", "advisor.questionOnly": "Envoyer uniquement la question du worker", "advisor.questionOnlyNote": "Seules la question du worker (jusqu’à 2000 caractères conservés, avec un avis en cas de troncature) et une instruction fixe sont envoyées. Aucun historique, résultat d’outil ou contexte de tâche n’est joint. Le worker doit inclure les informations essentielles. Les consultations automatiques sont suspendues ; les limites existantes restent actives.", - "advisor.policy.manual": "Manuel — uniquement à la demande du worker", - "advisor.policy.preflight": "Preflight — tentative automatique dès qu'une preuve d'orientation existe", - "advisor.policy.adaptive": "Adaptatif — orientation et réparation en échec", + "advisor.policy.manual": "Manuel (défaut) — uniquement à la demande de l'IA ou de vous-même", + "advisor.policy.preflight": "Auto après outils", + "advisor.policy.adaptive": "Auto après outils + secours — 1× après outils + aide si les échecs persistent", "advisor.taskLimit": "Consultations par tâche", - "advisor.adaptiveNote": "Les consultations automatiques exigent un identifiant de conversation stable. Le conseil initial suit un indice d’orientation (un appel d’outil ou un résultat). Le conseil après réparation échouée exige une vérification en échec, une modification de fichier terminée, puis un nouvel échec de la même commande dans le même répertoire ; des échecs répétés seuls ne suffisent pas. Les appels manuels comptent aussi dans le budget. Les réservations expirent après 24 heures et survivent aux redémarrages du proxy.", + "advisor.adaptiveNote": "Fonctionnement : les modes auto ne partent pas au premier message ni sur des questions texte simples. Après que l'IA a lu des fichiers ou logs via un outil, le contrôle auto s'exécute une fois par tâche si le client fournit un ID de session stable, sinon une fois par requête ; le secours n'intervient qu'après une boucle échec → édition → nouvel échec. Les appels manuels partagent la limite par tâche uniquement lorsqu'un ID de session stable est présent, et le mode adaptatif requiert un ID de session stable pour son budget de tâche.", "advisor.activity.title": "Activité récente du conseiller", "advisor.activity.note": "Jusqu’à 100 entrées de ce processus, conservées 24 heures. Aucun texte de tâche ni conseil enregistré. Raisonnement : demandé → traduit par l’adaptateur ; une valeur non signalée ne confirme pas la prise en charge. Tokens : entrée / sortie signalées. Adoption et coût exact ne sont pas déduits.", "advisor.activity.empty": "Aucune consultation enregistrée.", @@ -331,6 +331,41 @@ export const fr: Record = { "advisor.disclosure": "Une consultation peut envoyer la dernière demande, le texte utilisateur/assistant/développeur analysé, les appels d'outils et leurs arguments, les résultats d'outils, le catalogue d'outils du worker, l'identité du worker, le modèle conseiller configuré et une question de focus facultative. OpenCodex n'insère ni clés d'API, ni en-têtes Authorization, ni jetons OAuth, ni secrets de backend, ni environnement du processus, ni chaîne de pensée cachée. Le contenu de la tâche n'est pas expurgé : une clé collée, un secret dans un fichier ou un jeton imprimé par un outil peut être envoyé. Le fournisseur conseiller peut différer de celui du worker.", "advisor.consent.label": "Je comprends que les consultations du conseiller peuvent envoyer la conversation de cette tâche, les appels d'outils et leurs résultats au fournisseur conseiller configuré, qui peut différer de celui du worker. Le contenu de la tâche n'est pas expurgé de secrets.", "advisor.consent.required": "Le conseiller n'est pas exécutable tant que le consentement de partage de contexte n'est pas enregistré. Aucun contenu de tâche n'est envoyé sans lui.", + "advisor.fullContext": "Envoyer l'historique complet et les sessions locales", + "advisor.fullContextHint": "Étend les limites (128k/512k caractères) et retire les balises system-reminder superflues. Joint l'historique local uniquement lors d'une consultation MCP externe fournissant un identifiant de session ou un chemin de transcription.", + "advisor.mcp.title": "Connexions clients (MCP et rappels anti-oubli)", + "advisor.mcp.subtitle": "Connecte les clients externes (y compris sur leurs modèles intégrés comme WorkBuddy ou Qoder) à opencodex-advisor MCP avec des rappels pour éviter d'oublier le conseiller.", + "advisor.mcp.proxyNativeTitle": "Clients routés via OpenCodex", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP, etc. reçoivent automatiquement l'outil advisor intégré et les rappels sans MCP supplémentaire.", + "advisor.mcp.autoMountLabel": "Connecter automatiquement opencodex-advisor MCP aux routes compatibles actives", + "advisor.mcp.autoMountHint": "Synchronisation bidirectionnelle : quel que soit l'ordre d'activation (conseiller ou routage), le MCP est configuré automatiquement hors sélection manuelle.", + "advisor.mcp.selectionModeAuto": "Automatique — suit les clients compatibles routés", + "advisor.mcp.selectionModeOff": "Désactivé — choisissez des clients ci-dessous ou activez la connexion automatique", + "advisor.mcp.selectionModeManual": "Manuel — connecte uniquement les clients cochés", + "advisor.mcp.useAutoMode": "Revenir à la synchro auto", + "advisor.mcp.selectRouted": "Tout sélectionner (routés)", + "advisor.mcp.badgeRouted": "Routé", + "advisor.mcp.badgeDetected": "Installé", + "advisor.mcp.badgeMounted": "Connecté", + "advisor.mcp.badgeHookSkill": "Hook + compétence", + "advisor.mcp.trust.trusted": "Approuvé", + "advisor.mcp.trust.actionRequired": "Cliquer sur Approuver dans le client", + "advisor.mcp.trust.needsConfirmation": "Confirmer dans les réglages MCP", + "advisor.mcp.trust.autoEnabled": "Activé", + "advisor.mcp.trust.notMounted": "Non connecté", + "advisor.mcp.emptyHint": "Enregistrez pour synchroniser et voir l'état par client.", + "advisor.mcp.syncPartial": "Paramètres Advisor enregistrés, mais la synchronisation MCP a échoué pour : {clients}.", + "advisor.mcp.routeNoticeWillMount": "Connexion auto active : activer cette route ajoutera opencodex-advisor MCP dans {path}.", + "advisor.mcp.routeNoticeMounted": "Le serveur MCP opencodex-advisor est connecté dans {path}.", + "advisor.mcp.routeNoticeManual": "Sélection manuelle active. Gérez ce client sur la page Conseiller.", + "advisor.mcp.note.workbuddy": "Après l'écriture de mcp.json et du hook, cliquez une fois sur Faire confiance dans le gestionnaire MCP de WorkBuddy.", + "advisor.mcp.note.workbuddy-ai": "Après l'écriture de mcp.json et du hook, cliquez une fois sur Faire confiance dans le gestionnaire MCP de WorkBuddy AI.", + "advisor.mcp.note.qoder": "Enregistré dans Qoder settings.json (MCP + hook UserPromptSubmit) et SKILL.md ; vérifiez Paramètres -> MCP (relancez le MCP après mise à jour).", + "advisor.mcp.note.qoder-cn": "Enregistré dans Qoder CN settings.json (MCP + hook UserPromptSubmit) et SKILL.md ; vérifiez Paramètres -> MCP (relancez le MCP après mise à jour).", + "advisor.mcp.note.commandcode": "Écrit dans Command Code mcp.json ; approuvez opencodex-advisor au premier appel si demandé.", + "advisor.mcp.note.cline": "Écrit dans cline_mcp_settings.json (timeout : 900s) ; approuvez consult_advisor lorsque Cline le demande (ou activez l'approbation automatique dans les paramètres Cline).", + "advisor.mcp.note.opencode": "Écrit dans opencode.json sous mcp.opencodex-advisor (enabled: true, timeout: 900000ms) avec la Skill de rappel.", + "advisor.mcp.note.claude": "Claude Code via le proxy OpenCodex dispose déjà de l'outil intégré ; activer le MCP externe demande une confirmation au prochain lancement.", "nav.logs": "Journaux et débogage", "nav.usage": "Utilisation", "common.github": "GitHub", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index c9d27a36d84..5d8296f0236 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -289,7 +289,7 @@ export const ja: Record = { "nav.subagents": "サブエージェント", "nav.advisor": "アドバイザー", - "advisor.description": "Worker のタスクをレビューし助言を返す独立したエキスパートモデル。相談は OpenCodex 自身が実行します。Worker は合成 advisor ツールを呼び出せて、preflight ポリシーはタスクが方向性の証拠(最新のユーザーメッセージ以降のアシスタントのツール呼び出しまたはツール結果)を出した後に 1 回の自動相談を試みます(Worker の協力は不要)。この試行は、安定した会話識別子を持つクライアントではタスクごとに重複排除されますが、識別子を持たないクライアントではこの重複排除が行われず、条件を満たすリクエストごとに相談が再度発生することがあります。", + "advisor.description": "コーディングAIが相談できる専門家モデルです。手動モードは要求時に呼び出します。ルーティングモデルではツール使用後に事前確認、修正失敗が続くと適応型の救済を行います。外部クライアントはMCPを使用できます。", "advisor.enabled": "アドバイザーを有効化", "advisor.model": "エキスパートモデル", "advisor.modelClear": "モデルを解除", @@ -301,11 +301,11 @@ export const ja: Record = { "advisor.policy": "ポリシー", "advisor.questionOnly": "ワーカーの質問のみ送信", "advisor.questionOnlyNote": "ワーカーの質問(最大2000文字を保持し、超過時は切り詰め通知を追加)と固定のアドバイザー指示のみを送信します。会話履歴、ツール結果、タスクの文脈は自動添付されません。必要な背景情報はワーカーが質問に含めます。自動相談は停止し、既存の回数制限は引き続き適用されます。", - "advisor.policy.manual": "手動 — Worker が要求したときのみ", - "advisor.policy.preflight": "Preflight — 方向性の証拠が出たら自動相談を試みる", - "advisor.policy.adaptive": "適応型 — 初期調査と修正失敗時に相談", + "advisor.policy.manual": "手動(既定)— AI が相談したいとき・指示したときだけ呼ぶ", + "advisor.policy.preflight": "ツール利用後に自動", + "advisor.policy.adaptive": "ツール後 1 回+自動救済 — ツール利用後に 1 回+修正失敗が続いたとき自動介入", "advisor.taskLimit": "タスクごとの相談上限", - "advisor.adaptiveNote": "自動相談には安定した会話 ID が必要です。初回の助言は初期調査の証拠(ツール呼び出しまたは結果)が得られた後に行われます。修正失敗時の助言には、検証の失敗、ファイル編集の完了、その後の同じディレクトリでの同じコマンドの再実行と失敗が必要です。失敗の繰り返しだけでは対象になりません。手動呼び出しもタスク予算に含みます。予約は24時間で期限切れとなり、プロキシの再起動後も残ります。", + "advisor.adaptiveNote": "動作条件:自動モードは最初の送信直後やテキストだけの会話では動きません。AI がツールでファイルやコマンド結果を確認した後、安定した会話 ID がある場合はタスクごと最大 1 回、ない場合はリクエストごと最大 1 回自動で動きます。自動救済は「検証失敗 → ファイル編集 → 再実行でも失敗」のループ時に介入します。手動相談は安定した会話 ID がある場合のみタスク上限を共有し、適応モードはタスク予算のため安定した会話 ID が必要です。", "advisor.activity.title": "最近のアドバイザー活動", "advisor.activity.note": "このプロセスの直近24時間、最大100件を表示します。タスク本文や助言は保存しません。推論は要求値 → アダプターの変換値です。未報告は対応を意味しません。トークンは報告された入力 / 出力です。助言の採用や正確な費用は推測しません。", "advisor.activity.empty": "相談の記録はまだありません。", @@ -333,6 +333,41 @@ export const ja: Record = { "advisor.disclosure": "相談では、最新のユーザー依頼、解析済みのユーザー/アシスタント/開発者テキスト、ツール呼び出しと引数、ツール結果、ワーカーのツール一覧、ワーカーの識別子、設定されたアドバイザーモデル、手動相談時の任意の焦点質問が送られることがあります。OpenCodex はプロバイダー API キー、Authorization ヘッダー、OAuth トークン、バックエンドの秘密、プロセス環境、隠された思考連鎖をプロンプトへは入れません。タスク内容の秘密は一般には除去されません。貼り付けた鍵、ファイル内の秘密、ツールが出力したトークンは送られることがあります。アドバイザーのプロバイダーはワーカーと異なる場合があります。", "advisor.consent.label": "アドバイザーへの相談が、このタスクの会話・ツール呼び出し・ツール結果を、設定されたアドバイザーのプロバイダー(ワーカーと異なる場合があります)へ送ることがあると理解しました。タスク内容の秘密は除去されません。", "advisor.consent.required": "コンテキスト共有への同意が記録されるまで、アドバイザーは実行できません。同意がなければタスク内容は送信されません。", + "advisor.fullContext": "全履歴とローカルセッション記録を送信", + "advisor.fullContextHint": "履歴の上限を広げ(1 メッセージ 128k / 合計 512k 文字)クライアント側の定型タグを取り除きます。ローカルの会話履歴は、セッション ID またはトランスクリプトパスを指定した外部 MCP 相談時のみ添付されます。", + "advisor.mcp.title": "クライアント連携(MCP と忘却防止リマインダー)", + "advisor.mcp.subtitle": "OpenCodex を経由しないクライアント(内蔵モデルを使う WorkBuddy・Qoder など)にアドバイザー MCP を接続し、長い会話でも相談を忘れないよう補助します。", + "advisor.mcp.proxyNativeTitle": "OpenCodex 経由で自動対応するクライアント", + "advisor.mcp.proxyNativeDesc": "Codex CLI、Claude Code、ZCode、T3 Code、Droid、Kimi、Kilo、Pi、OMP など OpenCodex 経由のクライアントには、追加 MCP なしで内蔵ツールとリマインダーが自動提供されます。", + "advisor.mcp.autoMountLabel": "対応ルートの有効化に合わせて opencodex-advisor MCP を自動設定", + "advisor.mcp.autoMountHint": "双方向同期:ルーティングとアドバイザーのどちらを先にオンにしても自動設定されます(下で手動選択している場合は選択済みのみ)。", + "advisor.mcp.selectionModeAuto": "自動 — ルーティング中の対応クライアントに追従", + "advisor.mcp.selectionModeOff": "オフ — 下でクライアントを選ぶか、自動接続をオンにしてください", + "advisor.mcp.selectionModeManual": "手動 — 下で選んだクライアントのみ接続", + "advisor.mcp.useAutoMode": "自動同期に戻す", + "advisor.mcp.selectRouted": "ルーティング済みをすべて選択", + "advisor.mcp.badgeRouted": "ルーティング中", + "advisor.mcp.badgeDetected": "検出済み", + "advisor.mcp.badgeMounted": "接続済み", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "信頼済み", + "advisor.mcp.trust.actionRequired": "クライアントで信頼確認が必要", + "advisor.mcp.trust.needsConfirmation": "クライアント MCP 設定で確認が必要", + "advisor.mcp.trust.autoEnabled": "有効", + "advisor.mcp.trust.notMounted": "未接続", + "advisor.mcp.emptyHint": "設定を保存すると各クライアントの接続状態を表示します。", + "advisor.mcp.syncPartial": "Advisor 設定を保存しましたが、次のクライアントの MCP 同期に失敗しました: {clients}。", + "advisor.mcp.routeNoticeWillMount": "アドバイザー自動接続が有効です:このルートをオンにすると {path} に opencodex-advisor MCP が自動追加されます。", + "advisor.mcp.routeNoticeMounted": "このクライアントに opencodex-advisor MCP({path})を接続済みです。", + "advisor.mcp.routeNoticeManual": "アドバイザーは手動選択モードです。接続設定はアドバイザーページから変更できます。", + "advisor.mcp.note.workbuddy": "mcp.json とプロンプト Hook を保存した後、初回のみ WorkBuddy の MCP 管理画面で「信頼」を押してください。", + "advisor.mcp.note.workbuddy-ai": "mcp.json とプロンプト Hook を保存した後、初回のみ WorkBuddy AI の MCP 管理画面で「信頼」を押してください。", + "advisor.mcp.note.qoder": "Qoder の settings.json(MCP と忘却防止 Hook)および SKILL.md に書き込み済みです。初回は設定 -> MCP で有効化を確認してください(更新後は MCP のオン/オフ切替推奨)。", + "advisor.mcp.note.qoder-cn": "Qoder CN の settings.json(MCP と忘却防止 Hook)および SKILL.md に書き込み済みです。初回は設定 -> MCP で有効化を確認してください(更新後は MCP のオン/オフ切替推奨)。", + "advisor.mcp.note.commandcode": "Command Code の mcp.json に書き込みました。初回実行時に確認が出たら opencodex-advisor を許可してください。", + "advisor.mcp.note.cline": "cline_mcp_settings.json に書き込み済みです(timeout: 900 秒)。初回呼び出し時に Cline で consult_advisor を許可してください(自動許可が必要な場合は Cline 設定で有効にできます)。", + "advisor.mcp.note.opencode": "opencode.json の mcp.opencodex-advisor(enabled: true、timeout: 900000ms)とリマインダー Skill を設定済みです。", + "advisor.mcp.note.claude": "Claude Code が OpenCodex 経由のときは内蔵ツールが使えます。外部 MCP も併用する場合は次回 CLI 起動時に信頼を承認してください。", // routing intelligence "routing.title": "ルーティングインテリジェンス (beta)", "routing.subtitle": "ポリシープロファイル、ドライラン評価、ソース連携のルーティング分析。", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 50027e7338d..63973e601ce 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -289,7 +289,7 @@ export const ko: Record = { "nav.subagents": "서브에이전트", "nav.advisor": "어드바이저", - "advisor.description": "Worker의 작업을 검토하고 조언을 반환하는 독립 전문가 모델입니다. 상담은 OpenCodex가 직접 실행하며, Worker는 합성 advisor 도구를 호출할 수 있고 preflight 정책은 작업이 방향 증거(최신 사용자 메시지 이후의 어시스턴트 도구 호출 또는 도구 결과)를 낸 뒤 한 번의 자동 상담을 시도합니다(워커 협력 불필요). 이 시도는 안정적인 대화 식별자를 가진 클라이언트에서는 작업별로 중복 제거되지만, 식별자가 없는 클라이언트에서는 요청마다 상담이 다시 발생할 수 있습니다.", + "advisor.description": "코딩 AI가 상의할 수 있는 전문가 모델입니다. 수동 모드는 요청 시 호출합니다. 라우팅 모델의 사전 확인은 도구 사용 후, 적응형 구조는 반복된 수정 실패 후 실행됩니다. 외부 클라이언트는 MCP를 사용할 수 있습니다.", "advisor.enabled": "어드바이저 사용", "advisor.model": "전문가 모델", "advisor.modelClear": "모델 지우기", @@ -301,11 +301,11 @@ export const ko: Record = { "advisor.policy": "정책", "advisor.questionOnly": "워커의 질문만 전송", "advisor.questionOnlyNote": "워커의 질문(최대 2000자를 유지하며, 초과하면 잘림 안내 추가)과 고정된 자문 지침만 전송합니다. 대화 기록, 도구 결과, 작업 맥락은 자동으로 첨부하지 않습니다. 워커가 필요한 배경을 질문에 포함해야 합니다. 자동 자문은 일시 중지되며 기존 횟수 제한은 유지됩니다.", - "advisor.policy.manual": "수동 — Worker가 요청할 때만", - "advisor.policy.preflight": "Preflight — 방향 증거가 생기면 자동 상담 시도", - "advisor.policy.adaptive": "적응형 — 초기 탐색 및 수정 실패 시 상담", + "advisor.policy.manual": "수동(기본값) — AI가 요청하거나 사용자가 지시할 때만 호출", + "advisor.policy.preflight": "도구 사용 후 자동", + "advisor.policy.adaptive": "도구 후 1회 + 자동 구조 — 도구 조회 후 1회 + 반복 수정 실패 시 개입", "advisor.taskLimit": "작업별 상담 한도", - "advisor.adaptiveNote": "자동 상담에는 안정적인 대화 식별자가 필요합니다. 초기 상담은 탐색 증거(도구 호출 또는 결과)가 생긴 뒤 이루어집니다. 수정 실패 상담에는 검증 실패, 파일 수정 완료, 이후 같은 디렉터리에서 같은 명령을 새로 실행한 뒤의 재실패가 필요하며, 실패 반복만으로는 부족합니다. 수동 호출도 작업 예산에 포함됩니다. 예약은 24시간 후 만료되며 프록시를 다시 시작해도 남습니다.", + "advisor.adaptiveNote": "동작 조건: 자동 모드는 첫 메시지 직후나 일반 텍스트 문답에서는 실행되지 않습니다. AI가 도구로 파일이나 명령 출력을 확인한 뒤 안정적인 세션 ID가 있으면 작업당 1회, 없으면 요청당 1회 자동으로 실행되며, 자동 구조는 검증 실패 → 파일 수정 → 재실행 실패가 이어질 때만 개입합니다. 수동 호출은 안정적인 세션 ID가 있을 때만 작업 한도를 공유하며, 적응형 모드는 작업 예산을 위해 안정적인 세션 ID가 필요합니다.", "advisor.activity.title": "최근 Advisor 활동", "advisor.activity.note": "이 프로세스의 최근 24시간 기록을 최대 100개 표시합니다. 작업 본문이나 조언은 저장하지 않습니다. 추론은 요청값 → 어댑터 매핑값입니다. 미보고는 지원을 확인하지 않습니다. 토큰은 보고된 입력 / 출력입니다. 조언 채택이나 정확한 비용은 추정하지 않습니다.", "advisor.activity.empty": "아직 상담 기록이 없습니다.", @@ -333,6 +333,41 @@ export const ko: Record = { "advisor.disclosure": "상담은 최신 사용자 요청, 파싱된 사용자/어시스턴트/개발자 텍스트, 도구 호출과 인자, 도구 결과, 워커 도구 목록, 워커 식별, 설정된 어드바이저 모델, 그리고 수동 호출의 선택적 초점 질문을 보낼 수 있습니다. OpenCodex는 프로바이더 API 키, Authorization 헤더, OAuth 토큰, 백엔드 비밀, 프로세스 환경, 숨겨진 사고 과정을 프롬프트에 넣지 않습니다. 작업 내용의 비밀은 일반적으로 제거되지 않습니다. 붙여 넣은 키, 파일 속 비밀, 도구가 출력한 토큰은 전송될 수 있습니다. 어드바이저 프로바이더는 워커와 다를 수 있습니다.", "advisor.consent.label": "어드바이저 상담이 이 작업의 대화, 도구 호출, 도구 결과를 설정된 어드바이저 프로바이더(워커와 다를 수 있음)로 보낼 수 있음을 이해합니다. 작업 내용의 비밀은 제거되지 않습니다.", "advisor.consent.required": "컨텍스트 공유 동의가 기록되기 전에는 어드바이저를 실행할 수 없습니다. 동의가 없으면 작업 내용은 전송되지 않습니다.", + "advisor.fullContext": "전체 대화 기록 및 로컬 세션 로그 전송", + "advisor.fullContextHint": "전달 한도를 늘리고(메시지 128k / 전체 512k자) 클라이언트 시스템 태그를 제거합니다. 로컬 세션 기록은 세션 ID나 트랜스크립트 경로가 전달된 외부 MCP 상담에서만 첨부됩니다.", + "advisor.mcp.title": "호환 클라이언트 연결 (MCP 및 망각 방지 알림)", + "advisor.mcp.subtitle": "OpenCodex 프록시를 거치지 않는 클라이언트(자체 내장 모델을 쓰는 WorkBuddy, Qoder 등)에 어드바이저 MCP와 알림 스크립트를 연결해 긴 대화에서도 어드바이저 호출을 잊지 않도록 돕습니다.", + "advisor.mcp.proxyNativeTitle": "OpenCodex 프록시를 거치는 클라이언트", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP 등 OpenCodex 프록시로 연결된 클라이언트는 별도 MCP 없이도 내장 도구와 재안내가 자동으로 제공됩니다.", + "advisor.mcp.autoMountLabel": "활성화된 호환 라우트에 opencodex-advisor MCP 자동 연결", + "advisor.mcp.autoMountHint": "양방향 동기화: 라우팅과 어드바이저 중 무엇을 먼저 켜도 자동으로 설정됩니다(아래에서 수동 선택 시 선택한 항목만 반영).", + "advisor.mcp.selectionModeAuto": "자동 — 활성화된 호환 라우트 추적", + "advisor.mcp.selectionModeOff": "끔 — 아래에서 클라이언트를 선택하거나 자동 연결을 켜세요", + "advisor.mcp.selectionModeManual": "수동 — 아래에서 선택한 클라이언트만 연결", + "advisor.mcp.useAutoMode": "자동 동기화 사용", + "advisor.mcp.selectRouted": "라우팅된 클라이언트 모두 선택", + "advisor.mcp.badgeRouted": "라우팅됨", + "advisor.mcp.badgeDetected": "설치됨", + "advisor.mcp.badgeMounted": "연결됨", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "신뢰됨", + "advisor.mcp.trust.actionRequired": "클라이언트에서 신뢰 승인 필요", + "advisor.mcp.trust.needsConfirmation": "클라이언트 MCP 설정에서 확인", + "advisor.mcp.trust.autoEnabled": "활성화됨", + "advisor.mcp.trust.notMounted": "연결 안 됨", + "advisor.mcp.emptyHint": "설정을 저장하면 클라이언트별 MCP 연결 상태를 표시합니다.", + "advisor.mcp.syncPartial": "Advisor 설정이 저장되었지만 다음 클라이언트의 MCP 동기화에 실패했습니다: {clients}.", + "advisor.mcp.routeNoticeWillMount": "어드바이저 자동 연결이 켜져 있습니다. 이 라우트를 켜면 {path}에 opencodex-advisor MCP가 자동 추가됩니다.", + "advisor.mcp.routeNoticeMounted": "이 클라이언트에 opencodex-advisor MCP가 연결되었습니다({path}).", + "advisor.mcp.routeNoticeManual": "어드바이저가 수동 선택 모드입니다. 어드바이저 페이지에서 연결 여부를 지정하세요.", + "advisor.mcp.note.workbuddy": "mcp.json과 프롬프트 훅을 저장한 뒤, 처음 한 번 WorkBuddy MCP 관리 화면에서 신뢰를 승인해야 동작합니다.", + "advisor.mcp.note.workbuddy-ai": "mcp.json과 프롬프트 훅을 저장한 뒤, 처음 한 번 WorkBuddy AI MCP 관리 화면에서 신뢰를 승인해야 동작합니다.", + "advisor.mcp.note.qoder": "Qoder settings.json(MCP + UserPromptSubmit 훅)과 SKILL.md를 기록했습니다. 설정 -> MCP에서 활성화 여부를 확인하세요(업데이트 후에는 MCP를 껐다 켜는 것을 권장합니다).", + "advisor.mcp.note.qoder-cn": "Qoder CN settings.json(MCP + UserPromptSubmit 훅)과 SKILL.md를 기록했습니다. 설정 -> MCP에서 활성화 여부를 확인하세요(업데이트 후에는 MCP를 껐다 켜는 것을 권장합니다).", + "advisor.mcp.note.commandcode": "Command Code mcp.json에 기록했습니다. 첫 호출 시 도구 승인을 물으면 opencodex-advisor를 허용하세요.", + "advisor.mcp.note.cline": "cline_mcp_settings.json에 기록했습니다(timeout: 900초). Cline에서 첫 호출 시 consult_advisor를 승인해 주세요(자동 승인이 필요하면 Cline 설정에서 켤 수 있습니다).", + "advisor.mcp.note.opencode": "opencode.json의 mcp.opencodex-advisor(enabled: true, timeout: 900000ms)와 알림 Skill을 함께 설치했습니다.", + "advisor.mcp.note.claude": "Claude Code가 OpenCodex 프록시를 거칠 때는 기본 어드바이저 도구가 자동 제공됩니다. 외부 MCP를 추가로 켜려면 다음 CLI 실행 시 신뢰를 승인하세요.", // routing intelligence "routing.title": "라우팅 인텔리전스 (beta)", "routing.subtitle": "정책 프로필, 드라이런 평가, 소스 기반 라우팅 분석.", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index f849bf35d2b..15476c76247 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -171,7 +171,7 @@ export const pt: Record = { "sidecar.poolMixed": "Esta seleção explícita pode usar um pool diferente da solicitação principal.", "provider.name.anthropic2": "Anthropic · Pool 2", "nav.advisor": "Advisor", - "advisor.description": "Um modelo especialista independente que analisa a tarefa do worker e devolve recomendações. O worker pode chamar a ferramenta advisor; a política preflight também tenta uma consulta automática quando houver uma chamada de ferramenta ou um resultado após a última mensagem do usuário. A deduplicação é por tarefa e modelo do worker quando há uma identidade estável da conversa; sem ela, a tentativa pode se repetir em cada nova requisição elegível.", + "advisor.description": "Modelo especialista que sua IA de código pode consultar. No modo manual é chamado sob demanda. Em modelos roteados, a verificação prévia segue o uso de ferramentas e o resgate adaptativo segue falhas repetidas de correção; clientes externos podem usar MCP.", "advisor.enabled": "Advisor ativado", "advisor.model": "Modelo especialista", "advisor.modelClear": "Limpar modelo", @@ -183,11 +183,11 @@ export const pt: Record = { "advisor.policy": "Política", "advisor.questionOnly": "Enviar apenas a pergunta do worker", "advisor.questionOnlyNote": "Apenas a pergunta do worker (até 2000 caracteres mantidos, com aviso em caso de truncamento) e uma instrução fixa são enviadas. Histórico, resultados de ferramentas e contexto da tarefa não são anexados. O worker deve incluir as informações essenciais. As consultas automáticas ficam pausadas; os limites existentes continuam válidos.", - "advisor.policy.manual": "Manual — somente quando o worker solicitar", - "advisor.policy.preflight": "Preflight — tentativa automática após evidência de orientação", - "advisor.policy.adaptive": "Adaptativo — orientação e falha após correção", + "advisor.policy.manual": "Manual (padrão) — só consulta quando a IA pedir ou você solicitar", + "advisor.policy.preflight": "Auto após ferramentas", + "advisor.policy.adaptive": "Auto após ferramentas + resgate — 1× após leitura + ajuda em falhas repetidas", "advisor.taskLimit": "Consultas por tarefa", - "advisor.adaptiveNote": "Consultas automáticas exigem uma identidade de conversa estável. A orientação inicial ocorre após evidências de exploração (uma chamada de ferramenta ou um resultado). A consulta após falha na correção exige uma verificação com falha, uma edição de arquivo concluída e uma nova execução da mesma instrução no mesmo diretório que falhe novamente; falhas repetidas por si só não bastam. Chamadas manuais também consomem o orçamento da tarefa. As reservas expiram após 24 horas e sobrevivem a reinicializações do proxy.", + "advisor.adaptiveNote": "Como dispara: modos automáticos não rodam na primeira mensagem nem em perguntas de texto simples. Depois que a IA usa ferramentas para ler arquivos ou logs, a checagem automática roda uma vez por tarefa quando há um ID de sessão estável, ou uma vez por requisição sem ele; o resgate só entra no ciclo falha na verificação → edição de arquivo → nova falha. Chamadas manuais compartilham o limite por tarefa apenas quando há um ID de sessão estável, e a política adaptativa exige esse ID para o orçamento da tarefa.", "advisor.activity.title": "Atividade recente do Advisor", "advisor.activity.note": "Até 100 registros deste processo, mantidos por 24 horas. Nenhum texto da tarefa ou conselho é armazenado. Raciocínio: solicitado → mapeado pelo adaptador; não informado não confirma suporte. Tokens: entrada / saída informadas. Adoção e custo exato não são inferidos.", "advisor.activity.empty": "Nenhuma consulta registrada ainda.", @@ -215,6 +215,41 @@ export const pt: Record = { "advisor.disclosure": "Uma consulta pode enviar a tarefa mais recente, textos de usuário/assistente/developer da conversa analisada, chamadas e argumentos de ferramentas, resultados, catálogo de ferramentas do worker, identidade do worker, modelo Advisor configurado e uma pergunta opcional. OpenCodex não insere chaves de API, cabeçalhos de autorização, tokens OAuth, segredos do backend, ambiente do processo ou raciocínio oculto. Segredos no conteúdo da tarefa não são removidos: uma chave colada, um segredo em um arquivo ou um token exibido por uma ferramenta pode ser enviado. O provedor do Advisor pode ser diferente do provedor do worker.", "advisor.consent.label": "Entendo que consultas do Advisor podem enviar a conversa, chamadas e resultados de ferramentas desta tarefa ao provedor configurado, que pode ser diferente do provedor do worker. Segredos no conteúdo da tarefa não são removidos.", "advisor.consent.required": "O Advisor só pode executar consultas após registrar consentimento para compartilhar contexto. Nenhum conteúdo da tarefa é enviado sem ele.", + "advisor.fullContext": "Enviar histórico completo e registros locais da sessão", + "advisor.fullContextHint": "Amplia os limites (128k/512k caracteres) e remove tags repetitivas do cliente. Anexa o histórico local apenas em consultas MCP externas que informem um ID de sessão ou caminho de transcrição.", + "advisor.mcp.title": "Conexões de Clientes (MCP e Lembretes)", + "advisor.mcp.subtitle": "Conecta clientes externos (incluindo os que usam modelos próprios como WorkBuddy ou Qoder) ao MCP opencodex-advisor com lembretes para não esquecer o conselheiro em conversas longas.", + "advisor.mcp.proxyNativeTitle": "Clientes roteados via OpenCodex", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP etc. já recebem automaticamente a ferramenta integrada e lembretes pelo proxy, sem precisar de MCP extra.", + "advisor.mcp.autoMountLabel": "Conectar opencodex-advisor MCP automaticamente para rotas compatíveis ativas", + "advisor.mcp.autoMountHint": "Sincronização bidirecional: ativar o Conselheiro ou a rota do cliente em qualquer ordem configura automaticamente (salvo na seleção manual abaixo).", + "advisor.mcp.selectionModeAuto": "Automático — acompanha rotas compatíveis ativas", + "advisor.mcp.selectionModeOff": "Desligado — escolha clientes abaixo ou ative a conexão automática", + "advisor.mcp.selectionModeManual": "Manual — conecta apenas os marcados abaixo", + "advisor.mcp.useAutoMode": "Voltar à sincronização automática", + "advisor.mcp.selectRouted": "Selecionar todos os roteados", + "advisor.mcp.badgeRouted": "Roteado", + "advisor.mcp.badgeDetected": "Instalado", + "advisor.mcp.badgeMounted": "Conectado", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "Confiável", + "advisor.mcp.trust.actionRequired": "Clique em Confiar no cliente", + "advisor.mcp.trust.needsConfirmation": "Confirmar nas configurações MCP", + "advisor.mcp.trust.autoEnabled": "Ativado", + "advisor.mcp.trust.notMounted": "Não conectado", + "advisor.mcp.emptyHint": "Salve para sincronizar e ver o estado de cada cliente.", + "advisor.mcp.syncPartial": "Configurações do Advisor salvas, mas a sincronização MCP falhou para: {clients}.", + "advisor.mcp.routeNoticeWillMount": "Conexão automática ativa: habilitar esta rota gravará opencodex-advisor MCP em {path}.", + "advisor.mcp.routeNoticeMounted": "O servidor MCP opencodex-advisor está conectado em {path}.", + "advisor.mcp.routeNoticeManual": "Seleção manual de clientes ativa. Gerencie na página do Conselheiro.", + "advisor.mcp.note.workbuddy": "Após salvar mcp.json e o hook, clique em Confiar uma vez no gerenciador MCP do WorkBuddy antes de usar.", + "advisor.mcp.note.workbuddy-ai": "Após salvar mcp.json e o hook, clique em Confiar uma vez no gerenciador MCP do WorkBuddy AI antes de usar.", + "advisor.mcp.note.qoder": "Gravado em Qoder settings.json (MCP + hook UserPromptSubmit) e SKILL.md; confirme em Configurações -> MCP (reinicie/reative o MCP após atualizar).", + "advisor.mcp.note.qoder-cn": "Gravado em Qoder CN settings.json (MCP + hook UserPromptSubmit) e SKILL.md; confirme em Configurações -> MCP (reinicie/reative o MCP após atualizar).", + "advisor.mcp.note.commandcode": "Gravado em Command Code mcp.json; aprove opencodex-advisor na primeira chamada se solicitado.", + "advisor.mcp.note.cline": "Gravado em cline_mcp_settings.json (timeout: 900s); aprove consult_advisor quando o Cline solicitar (ou ative a aprovação automática nas configurações do Cline).", + "advisor.mcp.note.opencode": "Gravado em opencode.json em mcp.opencodex-advisor (enabled: true, timeout: 900000ms) com a Skill de lembrete.", + "advisor.mcp.note.claude": "O Claude Code via proxy OpenCodex já recebe a ferramenta integrada; habilitar MCP externo exige confiar na próxima inicialização.", "compactionRouting.sources": "Origens", "compactionRouting.sourcesAll": "Todos os modelos de conversa", "compactionRouting.sourcesSelected": "Somente origens selecionadas", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 6b0603e5bc1..110e6845ac4 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -289,7 +289,7 @@ export const ru: Record = { "nav.subagents": "Подагенты", "nav.advisor": "Консультант", - "advisor.description": "Независимая экспертная модель, которая анализирует задачу воркера и возвращает рекомендации. Консультацию выполняет сам OpenCodex: воркер может вызвать синтетический инструмент advisor, а политика preflight дополнительно автоматически пытается провести одну консультацию на задачу для каждой модели воркера — как только появится ориентационное свидетельство (вызов инструмента ассистентом или результат инструмента после последнего сообщения пользователя), без участия воркера. Попытка дедуплицируется по задаче и модели воркера для клиентов со стабильным идентификатором беседы; клиент без него не проходит дедупликацию, и консультация может повториться в каждом подходящем запросе.", + "advisor.description": "Экспертная модель для консультаций вашей ИИ для программирования. Ручной режим вызывается по запросу. Для маршрутизируемых моделей проверка следует за использованием инструментов, а адаптивная помощь — за повторными неудачами; внешние клиенты могут использовать MCP.", "advisor.enabled": "Консультант включён", "advisor.model": "Экспертная модель", "advisor.modelClear": "Очистить модель", @@ -301,11 +301,11 @@ export const ru: Record = { "advisor.policy": "Политика", "advisor.questionOnly": "Отправлять только вопрос исполнителя", "advisor.questionOnlyNote": "Отправляются только вопрос исполнителя (до 2000 сохранённых символов с уведомлением при усечении) и фиксированная инструкция советнику. История, результаты инструментов и контекст задачи не добавляются. Исполнитель должен включить необходимые сведения. Автоматические консультации приостановлены; прежние ограничения числа вызовов сохраняются.", - "advisor.policy.manual": "Вручную — только по запросу воркера", - "advisor.policy.preflight": "Preflight — автоматическая попытка при появлении ориентационного свидетельства", - "advisor.policy.adaptive": "Адаптивно — начальная проверка и неудачное исправление", + "advisor.policy.manual": "Вручную (по умолчанию) — только когда ИИ просит сам или по вашей команде", + "advisor.policy.preflight": "Авто после инструментов", + "advisor.policy.adaptive": "Авто после инструментов + спасение — 1 раз после чтения + помощь при сбоях", "advisor.taskLimit": "Консультаций на задачу", - "advisor.adaptiveNote": "Для автоматических консультаций нужен стабильный идентификатор беседы. Начальная консультация следует за данными первичного исследования (вызовом инструмента или его результатом). Консультация после неудачного исправления требует сбоя проверки, завершённого редактирования файла и нового сбоя той же команды в том же каталоге; одних повторных сбоев недостаточно. Ручные вызовы тоже расходуют бюджет задачи. Резервирования истекают через 24 часа и переживают перезапуск прокси.", + "advisor.adaptiveNote": "Условия срабатывания: авторежимы не запускаются на первое сообщение или обычный текстовый вопрос. После того как ИИ использовал инструмент для чтения файлов или вывода команд, автопроверка выполняется раз на задачу при наличии стабильного ID сессии или раз на запрос без него; спасение вмешивается лишь при цикле «сбой проверки → правка файла → повторный сбой». Ручные вызовы делят лимит на задачу только при наличии стабильного ID сессии, а адаптивный режим требует стабильный ID сессии для бюджета задачи.", "advisor.activity.title": "Недавние обращения к советнику", "advisor.activity.note": "До 100 записей этого процесса за 24 часа. Текст задачи и советы не сохраняются. Рассуждение: запрос → значение адаптера; отсутствие данных не подтверждает поддержку. Токены: сообщённый ввод / вывод. Принятие советов и точная стоимость не определяются.", "advisor.activity.empty": "Консультаций пока нет.", @@ -333,6 +333,41 @@ export const ru: Record = { "advisor.disclosure": "Консультация может отправить последнюю просьбу пользователя, разобранный текст пользователя, ассистента и разработчика, вызовы инструментов и их аргументы, результаты инструментов, каталог инструментов воркера, идентификатор воркера, настроенную модель консультанта и необязательный уточняющий вопрос. OpenCodex не вставляет в запрос ключи API провайдера, заголовки Authorization, токены OAuth, секреты бэкенда, окружение процесса или скрытую цепочку рассуждений. Содержимое задачи от секретов не очищается: вставленный ключ, секрет в файле или токен, напечатанный инструментом, может быть отправлен. Провайдер консультанта может отличаться от провайдера воркера.", "advisor.consent.label": "Я понимаю, что консультации могут отправить беседу этой задачи, вызовы инструментов и их результаты настроенному провайдеру консультанта, который может отличаться от провайдера воркера. Содержимое задачи от секретов не очищается.", "advisor.consent.required": "Консультант не выполняется, пока не записано согласие на передачу контекста. Без него содержимое задачи не отправляется.", + "advisor.fullContext": "Отправлять полную историю и локальные логи сессий", + "advisor.fullContextHint": "Расширяет лимиты (128k/512k символов) и очищает служебные теги клиента. Локальная история сессии прикрепляется только при внешней MCP-консультации с переданным ID сессии или путём к транскрипту.", + "advisor.mcp.title": "Подключение клиентов (MCP и напоминания)", + "advisor.mcp.subtitle": "Подключает внешние клиенты (включая встроенные модели WorkBuddy и Qoder) к opencodex-advisor MCP с напоминаниями, чтобы ИИ не забывал о советнике в длинных чатах.", + "advisor.mcp.proxyNativeTitle": "Клиенты через прокси OpenCodex", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP и др. при работе через OpenCodex получают инструмент советника и напоминания автоматически без MCP.", + "advisor.mcp.autoMountLabel": "Автоматически подключать opencodex-advisor MCP для активных маршрутов", + "advisor.mcp.autoMountHint": "Двусторонняя синхронизация: работает независимо от порядка включения (советник или маршрут клиента), кроме ручного выбора ниже.", + "advisor.mcp.selectionModeAuto": "Авто — следует за активными маршрутами", + "advisor.mcp.selectionModeOff": "Выключено — выберите клиентов ниже или включите автоподключение", + "advisor.mcp.selectionModeManual": "Вручную — только отмеченные ниже клиенты", + "advisor.mcp.useAutoMode": "Вернуть автосинхронизацию", + "advisor.mcp.selectRouted": "Выбрать все маршрутизируемые", + "advisor.mcp.badgeRouted": "Маршрут вкл.", + "advisor.mcp.badgeDetected": "Установлен", + "advisor.mcp.badgeMounted": "Подключён", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "Подтверждён", + "advisor.mcp.trust.actionRequired": "Нажмите Доверять в клиенте", + "advisor.mcp.trust.needsConfirmation": "Проверьте в настройках MCP", + "advisor.mcp.trust.autoEnabled": "Включён", + "advisor.mcp.trust.notMounted": "Не подключён", + "advisor.mcp.emptyHint": "Сохраните настройки для синхронизации статуса клиентов.", + "advisor.mcp.syncPartial": "Настройки Advisor сохранены, но синхронизация MCP не удалась для: {clients}.", + "advisor.mcp.routeNoticeWillMount": "Автоподключение включено: при активации маршрута opencodex-advisor MCP запишется в {path}.", + "advisor.mcp.routeNoticeMounted": "Подключён opencodex-advisor MCP ({path}).", + "advisor.mcp.routeNoticeManual": "Включён ручной выбор клиентов. Настройте на странице Советника.", + "advisor.mcp.note.workbuddy": "После записи mcp.json и хука один раз нажмите «Доверять» в менеджере MCP WorkBuddy.", + "advisor.mcp.note.workbuddy-ai": "После записи mcp.json и хука один раз нажмите «Доверять» в менеджере MCP WorkBuddy AI.", + "advisor.mcp.note.qoder": "Записано в Qoder settings.json (MCP + хук UserPromptSubmit) и SKILL.md; проверьте Настройки -> MCP (после обновления перезапустите MCP).", + "advisor.mcp.note.qoder-cn": "Записано в Qoder CN settings.json (MCP + хук UserPromptSubmit) и SKILL.md; проверьте Настройки -> MCP (после обновления перезапустите MCP).", + "advisor.mcp.note.commandcode": "Записано в Command Code mcp.json; при первом запросе разрешите opencodex-advisor.", + "advisor.mcp.note.cline": "Записано в cline_mcp_settings.json (timeout: 900 сек.); подтвердите вызов consult_advisor при запросе в Cline (или включите автоподтверждение в настройках Cline).", + "advisor.mcp.note.opencode": "Записано в opencode.json -> mcp.opencodex-advisor (enabled: true, timeout: 900000ms) вместе со Skill-напоминанием.", + "advisor.mcp.note.claude": "Claude Code через прокси OpenCodex уже получает встроенного советника; внешний MCP потребует доверия при следующем запуске.", // routing intelligence "routing.title": "Интеллект маршрутизации (beta)", "routing.subtitle": "Политики маршрутизации, пробная оценка и аналитика на основе источников.", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 82fbfcd0581..cc4fffaede3 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -289,7 +289,7 @@ export const tr: Record = { "nav.combos": "Kombolar", "nav.subagents": "Alt Ajanlar", "nav.advisor": "Danışman", - "advisor.description": "Worker'ın görevini inceleyen ve öneri döndüren bağımsız bir uzman model. Danışmayı OpenCodex yürütür: worker sentetik advisor aracını çağırabilir; preflight politikası ayrıca görev yönelim kanıtı ürettiğinde (son kullanıcı mesajından sonra bir asistan araç çağrısı veya araç sonucu) görev başına bir otomatik danışma dener (worker iş birliği gerekmez). Deneme, kararlı bir konuşma kimliği taşıyan istemciler için görev başına tekilleştirilir; kimliği olmayan bir istemci için bu tekilleştirme uygulanmaz ve uygun olan her istekte danışma yeniden gerçekleşebilir.", + "advisor.description": "Kodlama yapay zekanızın danışabileceği uzman model. Manuel modda istek üzerine çağrılır. Yönlendirilen modellerde ön kontrol araç kullanımını, uyarlanabilir destek tekrarlanan onarım hatalarını izler; harici istemciler MCP kullanabilir.", "advisor.enabled": "Danışman etkin", "advisor.model": "Uzman model", "advisor.modelClear": "Modeli temizle", @@ -301,11 +301,11 @@ export const tr: Record = { "advisor.policy": "Politika", "advisor.questionOnly": "Yalnızca çalışanın sorusunu gönder", "advisor.questionOnlyNote": "Yalnızca çalışanın sorusu (en fazla 2000 karakter korunur; daha uzunsa kırpma bildirimi eklenir) ve sabit danışman talimatı gönderilir. Geçmiş, araç sonuçları ve görev bağlamı eklenmez. Çalışan gerekli arka planı soruya eklemelidir. Otomatik danışmalar duraklatılır; mevcut çağrı sınırları geçerlidir.", - "advisor.policy.manual": "Manuel — yalnızca worker istediğinde", - "advisor.policy.preflight": "Preflight — yönelim kanıtı oluşunca otomatik danışma denemesi", - "advisor.policy.adaptive": "Uyarlanabilir — başlangıç ve başarısız onarım danışmaları", + "advisor.policy.manual": "Manuel (varsayılan) — yalnızca yapay zeka sorduğunda veya siz istediğinizde", + "advisor.policy.preflight": "Araç kullanımından sonra otomatik", + "advisor.policy.adaptive": "Araç sonrası 1 kez + kurtarma — dosya okumadan sonra 1 kez + hata döngüsünde yardım", "advisor.taskLimit": "Görev başına danışma", - "advisor.adaptiveNote": "Otomatik danışmalar sabit bir konuşma kimliği gerektirir. İlk danışma, başlangıç incelemesi kanıtından (araç çağrısı veya sonucu) sonra yapılır. Başarısız onarım danışması için doğrulamanın başarısız olması, dosya düzenlemesinin tamamlanması ve ardından aynı komutun aynı dizinde yeniden çalıştırılıp başarısız olması gerekir; yalnızca tekrarlanan hatalar yeterli değildir. Manuel çağrılar da görev bütçesini tüketir. Rezervasyonlar 24 saat sonra sona erer ve proxy yeniden başlatıldığında korunur.", + "advisor.adaptiveNote": "Çalışma şekli: Otomatik modlar ilk kullanıcı mesajında veya düz metin soru-cevapta çalışmaz. Yapay zeka dosya veya komut çıktısı okumak için araç kullandıktan sonra, kararlı oturum kimliği varsa görev başına 1 kez, yoksa istek başına 1 kez çalışır; kurtarma yalnızca başarısız test → dosya düzenleme → yeniden başarısız çalıştırma döngüsünde devreye girer. Manuel çağrılar yalnızca kararlı oturum kimliği varsa görev kotasını paylaşır; uyarlamalı mod görev bütçesi için kararlı oturum kimliği gerektirir.", "advisor.activity.title": "Son danışman etkinliği", "advisor.activity.note": "Bu işlemin son 24 saatinden en fazla 100 kayıt. Görev metni veya tavsiye saklanmaz. Akıl yürütme: istenen → adaptörün eşlediği; bildirilmemesi desteği doğrulamaz. Tokenlar: bildirilen girdi / çıktı. Tavsiyenin benimsenmesi veya kesin maliyet çıkarılmaz.", "advisor.activity.empty": "Henüz danışma kaydı yok.", @@ -333,6 +333,41 @@ export const tr: Record = { "advisor.disclosure": "Bir danışma; son kullanıcı isteğini, ayrıştırılmış kullanıcı/asistan/geliştirici metnini, araç çağrılarını ve argümanlarını, araç sonuçlarını, worker araç kataloğunu, worker kimliğini, yapılandırılmış danışman modelini ve isteğe bağlı bir odak sorusunu gönderebilir. OpenCodex; sağlayıcı API anahtarlarını, Authorization başlıklarını, OAuth belirteçlerini, arka uç sırlarını, süreç ortamını veya gizli düşünce zincirini isteme koymaz. Görev içeriği sırlardan arındırılmaz: yapıştırılan bir anahtar, dosyadaki bir sır veya aracın yazdırdığı bir belirteç gönderilebilir. Danışman sağlayıcısı worker sağlayıcısından farklı olabilir.", "advisor.consent.label": "Danışman görüşmelerinin bu görevin konuşmasını, araç çağrılarını ve araç sonuçlarını, worker sağlayıcısından farklı olabilecek yapılandırılmış danışman sağlayıcısına gönderebileceğini anlıyorum. Görev içeriği sırlardan arındırılmaz.", "advisor.consent.required": "Bağlam paylaşımı onayı kaydedilmeden danışman çalışmaz. Onay olmadan görev içeriği gönderilmez.", + "advisor.fullContext": "Tam geçmişi ve yerel oturum kayıtlarını gönder", + "advisor.fullContextHint": "Karakter sınırlarını büyütür (128k/512k) ve gereksiz istemci etiketlerini temizler. Yerel oturum geçmişi yalnızca oturum kimliği veya transkript yolu sağlayan harici MCP danışmalarında eklenir.", + "advisor.mcp.title": "İstemci Bağlantıları (MCP ve Unutma Karşıtı Hatırlatıcılar)", + "advisor.mcp.subtitle": "Kendi yerleşik modelini kullanan istemcileri (WorkBuddy, Qoder vb.) uzun sohbetlerde danışmanı unutmamaları için opencodex-advisor MCP ve hatırlatıcılarla bağlar.", + "advisor.mcp.proxyNativeTitle": "OpenCodex proxy üzerinden yönlendirilen istemciler", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP gibi istemciler yerleşik danışman aracını ve hatırlatıcıları ekstra MCP olmadan otomatik alır.", + "advisor.mcp.autoMountLabel": "Etkin uyumlu yönlendirmeler için opencodex-advisor MCP'yi otomatik bağla", + "advisor.mcp.autoMountHint": "Çift yönlü eşitleme: Önce Danışmanı ya da önce istemci rotasını açmanız fark etmez (aşağıda manuel seçim açık değilse otomatik bağlanır).", + "advisor.mcp.selectionModeAuto": "Otomatik — etkin uyumlu rotaları izler", + "advisor.mcp.selectionModeOff": "Kapalı — aşağıdan istemci seçin veya otomatik bağlanmayı açın", + "advisor.mcp.selectionModeManual": "Manuel — yalnızca aşağıda seçilenleri bağlar", + "advisor.mcp.useAutoMode": "Otomatik eşitlemeye dön", + "advisor.mcp.selectRouted": "Yönlendirilenleri seç", + "advisor.mcp.badgeRouted": "Yönlendirilmiş", + "advisor.mcp.badgeDetected": "Yüklü", + "advisor.mcp.badgeMounted": "Bağlı", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "Güvenilen", + "advisor.mcp.trust.actionRequired": "İstemcide Güven'e tıklayın", + "advisor.mcp.trust.needsConfirmation": "İstemci MCP ayarlarından onaylayın", + "advisor.mcp.trust.autoEnabled": "Etkin", + "advisor.mcp.trust.notMounted": "Bağlı değil", + "advisor.mcp.emptyHint": "İstemci bağlantı durumunu görmek için ayarları kaydedin.", + "advisor.mcp.syncPartial": "Advisor ayarları kaydedildi, ancak şu istemciler için MCP eşitlemesi başarısız oldu: {clients}.", + "advisor.mcp.routeNoticeWillMount": "Otomatik bağlantı açık: Bu rotayı açmak {path} içine opencodex-advisor MCP ekler.", + "advisor.mcp.routeNoticeMounted": "Bu istemci için opencodex-advisor MCP bağlı ({path}).", + "advisor.mcp.routeNoticeManual": "Manuel istemci seçimi etkin. Danışman sayfasından yönetin.", + "advisor.mcp.note.workbuddy": "mcp.json ve hook kaydedildikten sonra ilk kullanımdan önce WorkBuddy MCP yöneticisinde bir kez Güven'e tıklayın.", + "advisor.mcp.note.workbuddy-ai": "mcp.json ve hook kaydedildikten sonra ilk kullanımdan önce WorkBuddy AI MCP yöneticisinde bir kez Güven'e tıklayın.", + "advisor.mcp.note.qoder": "Qoder settings.json (MCP + UserPromptSubmit hook) ve SKILL.md yazıldı; Ayarlar -> MCP altından etkinleştirin (güncelleme sonrası MCP'yi kapatıp açın).", + "advisor.mcp.note.qoder-cn": "Qoder CN settings.json (MCP + UserPromptSubmit hook) ve SKILL.md yazıldı; Ayarlar -> MCP altından etkinleştirin (güncelleme sonrası MCP'yi kapatıp açın).", + "advisor.mcp.note.commandcode": "Command Code mcp.json yazıldı; ilk çağrıda araç izni sorulursa opencodex-advisor'ı onaylayın.", + "advisor.mcp.note.cline": "cline_mcp_settings.json dosyasına yazıldı (timeout: 900 sn); Cline ilk çağrıda sorduğunda consult_advisor aracını onaylayın (veya Cline ayarlarından otomatik onayı açın).", + "advisor.mcp.note.opencode": "opencode.json altında mcp.opencodex-advisor (enabled: true, timeout: 900000ms) ve hatırlatıcı Skill kuruldu.", + "advisor.mcp.note.claude": "Claude Code, OpenCodex üzerinden yönlendirildiğinde yerleşik danışman aracını zaten alır; harici MCP için sonraki başlatmada güven onayı gerekir.", "nav.logs": "Günlükler & Hata Ayıklama", "nav.usage": "Kullanım", "common.github": "GitHub", diff --git a/gui/src/i18n/v2-pages/proxy-copy.ts b/gui/src/i18n/v2-pages/proxy-copy.ts index c03296f1e1e..99b6a1b4939 100644 --- a/gui/src/i18n/v2-pages/proxy-copy.ts +++ b/gui/src/i18n/v2-pages/proxy-copy.ts @@ -56,13 +56,13 @@ const rows = { telemetryConsentCheckbox: ["Share anonymous daily usage statistics", "익명 일일 사용 통계 공유하기", "Anonyme tägliche Nutzungsstatistiken teilen", "Partager les statistiques quotidiennes anonymes", "共享匿名每日使用统计", "共享匿名每日使用統計", "Делиться анонимной ежедневной статистикой", "匿名の1日ごとの利用統計を共有する", "Anonim günlük kullanım istatistiklerini paylaş", "Chia sẻ thống kê sử dụng ẩn danh hằng ngày", "Compartilhar estatísticas diárias anônimas de uso", "Compartir estadísticas diarias anónimas de uso"], telemetryConsentContinue: ["Continue", "계속", "Weiter", "Continuer", "继续", "繼續", "Продолжить", "続行", "Devam", "Tiếp tục", "Continuar", "Continuar"], // ---- Advisor ------------------------------------------------------------------------------------ - advisorLede: ["A second model that reviews the worker's progress and sends advice back.", "Worker의 작업을 검토하고 조언을 돌려주는 두 번째 모델이에요.", "Ein zweites Modell, das den Fortschritt des Workers prüft und Rat zurückgibt.", "Un second modèle qui examine l'avancement du worker et lui renvoie des conseils.", "第二个模型,审查 Worker 的进展并返回建议。", "第二個模型,審查 Worker 的進展並回傳建議。", "Вторая модель, которая проверяет ход работы и возвращает советы.", "Worker の作業を確認して助言を返す、2 つ目のモデルです。", "Worker'ın ilerlemesini inceleyip tavsiye döndüren ikinci bir model.", "Mô hình thứ hai xem xét tiến độ của worker và gửi lại lời khuyên.", "Um segundo modelo que revisa o progresso do worker e devolve conselhos.", "Un segundo modelo revisa el progreso del agente ejecutor y le envía recomendaciones."], + advisorLede: ["A second, stronger expert model your coding AI can consult when planning or stuck.", "코딩 모델이 막히거나 계획을 세울 때 조언을 구하는 더 강력한 두 번째 전문가 모델이에요.", "Ein zweites, stärkeres Expertenmodell, das Ihre Coding-KI bei Planung oder Problemen um Rat fragt.", "Un second modèle expert plus puissant que votre IA de code peut consulter en cas de doute ou de blocage.", "让你的编程 AI 在做复杂决策或卡住时,可以随时请教的第二位更强专家模型。", "讓你的程式設計 AI 在做複雜決策或卡住時,可以隨時請教的第二位更強專家模型。", "Вторая, более сильная экспертная модель, к которой ИИ может обратиться за советом при планировании или тупике.", "設計で迷ったときや行き詰まったときに、コーディング AI が相談できる強力な第 2 の専門家モデルです。", "Kodlama yapay zekanızın planlama yaparken veya takıldığında danışabileceği daha güçlü ikinci bir uzman model.", "Mô hình chuyên gia mạnh hơn thứ hai để AI lập trình hỏi ý kiến khi lên kế hoạch hoặc bị kẹt.", "Um segundo modelo especialista mais forte que sua IA de código pode consultar ao planejar ou travar.", "Un segundo modelo experto más capaz al que tu IA de programación puede consultar cuando planifica o se queda bloqueada."], advisorSettings: ["Advisor settings", "어드바이저 설정", "Berater-Einstellungen", "Réglages du conseiller", "顾问设置", "顧問設定", "Настройки советника", "アドバイザー設定", "Danışman ayarları", "Cài đặt cố vấn", "Configurações do conselheiro", "Configuración del asesor"], - enabledHint: ["Consultations run only while this is on.", "켜져 있을 때만 상담해요.", "Beratungen laufen nur, solange dies an ist.", "Les consultations n'ont lieu que lorsque cette option est active.", "仅在开启时进行咨询。", "僅在開啟時進行諮詢。", "Консультации идут, только пока это включено.", "オンのときだけ相談します。", "Danışmalar yalnızca bu açıkken çalışır.", "Chỉ tham vấn khi tùy chọn này bật.", "As consultas só acontecem enquanto isto estiver ativado.", "Solo se hacen consultas mientras esta opción está activa."], - effortHint: ["How hard the advisor thinks before it answers.", "어드바이저가 답하기 전에 얼마나 깊이 생각할지예요.", "Wie gründlich der Berater vor der Antwort nachdenkt.", "Le niveau de réflexion du conseiller avant de répondre.", "顾问回答前的思考深度。", "顧問回答前的思考深度。", "Насколько глубоко советник думает перед ответом.", "アドバイザーが答える前にどれだけ深く考えるかです。", "Danışmanın yanıt vermeden önce ne kadar düşüneceği.", "Mức độ cố vấn suy nghĩ trước khi trả lời.", "Quanto o conselheiro pensa antes de responder.", "Cuánto razonamiento usa el asesor antes de responder."], - policyHint: ["When the advisor is consulted.", "언제 상담할지 정해요.", "Wann der Berater gefragt wird.", "Quand le conseiller est consulté.", "何时咨询顾问。", "何時諮詢顧問。", "Когда обращаться к советнику.", "いつアドバイザーに相談するかです。", "Danışmana ne zaman başvurulacağı.", "Khi nào tham vấn cố vấn.", "Quando o conselheiro é consultado.", "Cuándo se consulta al asesor."], - taskLimitHint: ["The most automatic consultations one task can use.", "작업 하나에서 쓸 수 있는 자동 상담 최대 횟수예요.", "Höchstzahl automatischer Beratungen pro Aufgabe.", "Le nombre maximal de consultations automatiques par tâche.", "单个任务最多可用的自动咨询次数。", "單一任務最多可用的自動諮詢次數。", "Максимум автоматических консультаций на одну задачу.", "1 つの作業で使える自動相談の上限回数です。", "Bir görevin kullanabileceği en fazla otomatik danışma sayısı.", "Số lần tham vấn tự động tối đa cho một tác vụ.", "O máximo de consultas automáticas que uma tarefa pode usar.", "Máximo de consultas automáticas que puede usar una tarea."], - timeoutHint: ["How long to wait for advice before giving up.", "조언을 기다리다 포기하기까지의 시간이에요.", "Wie lange auf Rat gewartet wird, bevor abgebrochen wird.", "Durée d'attente des conseils avant abandon.", "放弃前等待建议的时长。", "放棄前等待建議的時間。", "Сколько ждать совета, прежде чем отказаться.", "助言をあきらめるまで待つ時間です。", "Vazgeçmeden önce tavsiye için ne kadar bekleneceği.", "Thời gian chờ lời khuyên trước khi bỏ qua.", "Quanto esperar pelo conselho antes de desistir.", "Cuánto esperar una recomendación antes de cancelar la consulta."], + enabledHint: ["Turn the expert advisor on or off.", "전문가 어드바이저 사용 여부를 정해요.", "Schaltet den Expertenberater ein oder aus.", "Active ou désactive le conseiller expert.", "总开关:关闭后不会向顾问模型发起任何请求。", "總開關:關閉後不會向顧問模型發起任何請求。", "Включает или отключает эксперта-советника.", "専門家アドバイザーのオン/オフを切り替えます。", "Uzman danışmanı açar veya kapatır.", "Bật hoặc tắt cố vấn chuyên gia.", "Ativa ou desativa o conselheiro especialista.", "Activa o desactiva el asesor experto."], + effortHint: ["How deeply the advisor thinks before replying.", "어드바이저가 답하기 전에 얼마나 깊이 생각할지 정해요.", "Wie gründlich der Berater vor seiner Antwort nachdenkt.", "Niveau de réflexion du conseiller avant de répondre.", "顾问回答前的思考深度(越高越仔细,但也越慢)。", "顧問回覆前投入的思考深度(越高越仔細,但也越慢)。", "Насколько глубоко советник обдумывает ответ (выше = точнее, но дольше).", "アドバイザーが回答前にどれだけ深く考えるかです(高いほど丁寧ですが時間がかかります)。", "Danışmanın yanıt vermeden önce ne kadar derin düşüneceği.", "Mức độ suy nghĩ sâu của cố vấn trước khi trả lời.", "Quanto o conselheiro pensa antes de responder.", "Cuánta profundidad de razonamiento usa el asesor antes de responder."], + policyHint: ["Preflight follows tool-use evidence, not plain Q&A: once per task with a stable conversation identity, otherwise once per eligible request. Adaptive rescue requires a stable identity and repeated repair failure. Routed models use OpenCodex; built-in client models use MCP.", "사전 확인은 일반 질문이 아닌 도구 사용 증거 이후 실행됩니다. 안정적인 대화 ID가 있으면 작업당 한 번, 없으면 적격 요청마다 실행됩니다. 적응형 구조는 안정적인 ID와 반복된 수정 실패가 필요합니다. 프록시 모델은 OpenCodex를, 내장 모델은 MCP를 사용합니다.", "Die Vorprüfung folgt auf Tool-Nutzung, nicht auf reine Fragen: einmal pro Aufgabe mit stabiler Gesprächs-ID, sonst pro geeigneter Anfrage. Adaptive Hilfe benötigt eine stabile ID und wiederholte Reparaturfehler. Geroutete Modelle nutzen OpenCodex, eingebaute Modelle MCP.", "La vérification suit l’usage d’outils, pas une simple question : une fois par tâche avec une identité de conversation stable, sinon par requête admissible. Le secours adaptatif exige une identité stable et des échecs répétés. Les modèles routés utilisent OpenCodex, les modèles intégrés MCP.", "预检在工具使用后而非普通问答中触发:有稳定会话标识时每任务一次,否则每个符合条件的请求一次。自适应补救需要稳定标识及重复修复失败。路由模型使用 OpenCodex,内置模型使用 MCP。", "預檢在工具使用後而非一般問答時觸發:有穩定對話識別碼時每任務一次,否則每個符合條件的請求一次。適應性補救需要穩定識別碼及重複修復失敗。路由模型使用 OpenCodex,內建模型使用 MCP。", "Предварительная проверка следует за использованием инструментов, а не простым вопросом: раз на задачу при стабильном ID диалога, иначе на каждый подходящий запрос. Адаптивная помощь требует стабильного ID и повторных неудач исправления. Маршрутизируемые модели используют OpenCodex, встроенные — MCP.", "事前確認は通常の質問ではなくツール使用後に実行されます。安定した会話IDがあればタスクごと、なければ該当するリクエストごとに1回です。適応型の救済には安定IDと修正の繰り返し失敗が必要です。ルーティングモデルはOpenCodex、内蔵モデルはMCPを使います。", "Ön kontrol basit sorularda değil araç kullanımından sonra çalışır: sabit konuşma kimliği varsa görev başına, yoksa uygun istek başına bir kez. Uyarlanabilir destek için sabit kimlik ve tekrarlanan onarım hatası gerekir. Yönlendirilen modeller OpenCodex, yerleşik modeller MCP kullanır.", "Kiểm tra trước chạy sau khi dùng công cụ, không chạy với hỏi đáp thường: một lần mỗi tác vụ nếu có danh tính hội thoại ổn định, nếu không thì mỗi yêu cầu đủ điều kiện. Hỗ trợ thích ứng cần danh tính ổn định và sửa lỗi thất bại lặp lại. Mô hình định tuyến dùng OpenCodex, mô hình tích hợp dùng MCP.", "A verificação prévia ocorre após uso de ferramentas, não em perguntas simples: uma vez por tarefa com identidade de conversa estável, caso contrário por requisição elegível. O resgate adaptativo exige identidade estável e falhas repetidas de correção. Modelos roteados usam OpenCodex; modelos integrados usam MCP.", "La comprobación previa sigue al uso de herramientas, no a preguntas simples: una vez por tarea con identidad de conversación estable; si no, una vez por solicitud apta. El rescate adaptativo exige identidad estable y fallos repetidos de reparación. Los modelos enrutados usan OpenCodex; los integrados usan MCP."], + taskLimitHint: ["Max advisor consultations allowed in a single task (includes manual calls).", "한 작업에서 허용되는 최대 상담 수예요(수동 호출 포함).", "Maximal erlaubte Beratungen pro Aufgabe (einschließlich manueller Aufrufe).", "Nombre maximal de consultations par tâche (appels manuels inclus).", "单个任务最多请顾问帮忙的次数(包含 AI 主动求助与自动触发,防止死循环刷额度)。", "單一任務最多請顧問幫忙的次數(包含 AI 主動求助與自動觸發,防止無窮迴圈耗額度)。", "Максимум обращений к советнику за одну задачу (включая ручные вызовы).", "1 つの作業で許可される相談回数の上限です(手動呼び出しも含みます)。", "Tek bir görevde izin verilen en fazla danışma sayısı (manuel çağrılar dahil).", "Số lần hỏi cố vấn tối đa trong một tác vụ (tính cả gọi thủ công).", "Máximo de consultas ao conselheiro por tarefa (inclui chamadas manuais).", "Máximo de consultas al asesor permitidas en una sola tarea (incluidas las llamadas manuales)."], + timeoutHint: ["Abort after this long without response data; received data resets the timer. The streaming ceiling is max(4× this value, 10 min). Default 600000 ms / 10 min; max 1800000 ms / 30 min.", "응답 데이터가 이 시간 동안 없으면 중단하며, 데이터를 받으면 타이머가 초기화됩니다. 스트리밍 상한은 이 값의 4배와 10분 중 큰 값입니다. 기본 600000 ms / 10분, 최대 1800000 ms / 30분.", "Abbruch nach dieser Zeit ohne Antwortdaten; empfangene Daten setzen den Timer zurück. Die Streaming-Grenze ist das Maximum aus dem Vierfachen dieses Werts und 10 Min. Standard 600000 ms / 10 Min., maximal 1800000 ms / 30 Min.", "Interrompt après cette durée sans données ; chaque donnée reçue réinitialise le délai. La limite du flux est le maximum entre quatre fois cette valeur et 10 min. Défaut : 600000 ms / 10 min ; maximum : 1800000 ms / 30 min.", "响应数据在此时长内未到达则中止;收到数据会重置计时器。流式响应的总上限为此值的 4 倍和 10 分钟中的较大值。默认 600000 ms / 10 分钟,最大 1800000 ms / 30 分钟。", "回應資料在此時間內未到達則中止;收到資料會重設計時器。串流回應的總上限為此值的 4 倍與 10 分鐘中的較大值。預設 600000 ms / 10 分鐘,最大 1800000 ms / 30 分鐘。", "Вызов прерывается после этого времени без данных; полученные данные сбрасывают таймер. Предел потока — максимум из четырёх таких интервалов и 10 мин. По умолчанию 600000 мс / 10 мин, максимум 1800000 мс / 30 мин.", "この時間、応答データが届かなければ中断し、データを受信するとタイマーをリセットします。ストリームの上限はこの値の4倍と10分の大きい方です。既定 600000 ms / 10分、最大 1800000 ms / 30分。", "Bu süre boyunca yanıt verisi gelmezse çağrı iptal edilir; gelen veri sayacı sıfırlar. Akış üst sınırı bu değerin 4 katı ile 10 dakikanın büyük olanıdır. Varsayılan 600000 ms / 10 dk, azami 1800000 ms / 30 dk.", "Hủy nếu không có dữ liệu phản hồi trong khoảng này; dữ liệu nhận được đặt lại bộ đếm. Giới hạn luồng là giá trị lớn hơn giữa 4 lần khoảng này và 10 phút. Mặc định 600000 ms / 10 phút, tối đa 1800000 ms / 30 phút.", "Cancela após esse tempo sem dados de resposta; cada dado recebido reinicia o contador. O limite do fluxo é o maior entre 4 vezes esse valor e 10 min. Padrão 600000 ms / 10 min, máximo 1800000 ms / 30 min.", "Cancela tras este tiempo sin datos de respuesta; los datos recibidos reinician el temporizador. El límite del flujo es el mayor entre 4 veces este valor y 10 min. Predeterminado 600000 ms / 10 min; máximo 1800000 ms / 30 min."], consentTitle: ["Context sharing", "컨텍스트 공유 동의", "Kontextfreigabe", "Partage du contexte", "上下文共享", "上下文共享", "Передача контекста", "コンテキスト共有", "Bağlam paylaşımı", "Chia sẻ ngữ cảnh", "Compartilhamento de contexto", "Compartir contexto"], consentNeeded: ["Required to run", "실행에 필요", "Zum Ausführen nötig", "Requis pour l'exécution", "运行所必需", "執行所必需", "Нужно для запуска", "実行に必要", "Çalışmak için gerekli", "Bắt buộc để chạy", "Necessário para executar", "Necesario para funcionar"], consentGiven: ["Agreed", "동의함", "Zugestimmt", "Accepté", "已同意", "已同意", "Согласие дано", "同意済み", "Onaylandı", "Đã đồng ý", "Aceito", "Aceptado"], diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 6e701ada8fd..a9f4d1f1af3 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -288,7 +288,7 @@ export const vi: Record = { "nav.combos": "Combos", "nav.subagents": "Subagents", "nav.advisor": "Cố vấn", - "advisor.description": "Một mô hình chuyên gia độc lập xem xét nhiệm vụ của worker và trả về lời khuyên. OpenCodex tự thực hiện việc tư vấn: worker có thể gọi công cụ advisor tổng hợp; chính sách preflight còn tự động thử một lần tư vấn cho mỗi nhiệm vụ — sau khi nhiệm vụ tạo ra bằng chứng định hướng (một lệnh gọi công cụ của trợ lý hoặc một kết quả công cụ sau tin nhắn người dùng mới nhất), không cần worker hợp tác. Lần thử được khử trùng lặp theo nhiệm vụ đối với máy khách có định danh hội thoại ổn định; máy khách không có định danh có thể nhận thêm tư vấn ở nhiều yêu cầu khác nhau.", + "advisor.description": "Mô hình chuyên gia cho AI lập trình tham vấn. Chế độ thủ công gọi khi được yêu cầu. Với mô hình định tuyến, kiểm tra trước theo sau việc dùng công cụ và hỗ trợ thích ứng theo sau các lần sửa lỗi thất bại; ứng dụng bên ngoài có thể dùng MCP.", "advisor.enabled": "Bật cố vấn", "advisor.model": "Mô hình chuyên gia", "advisor.modelClear": "Xóa mô hình", @@ -300,11 +300,11 @@ export const vi: Record = { "advisor.policy": "Chính sách", "advisor.questionOnly": "Chỉ gửi câu hỏi của worker", "advisor.questionOnlyNote": "Chỉ gửi câu hỏi của worker (giữ tối đa 2000 ký tự, kèm thông báo nếu bị cắt ngắn) cùng chỉ dẫn cố định cho cố vấn. Không tự động đính kèm lịch sử, kết quả công cụ hay ngữ cảnh tác vụ. Worker phải bổ sung thông tin nền cần thiết. Tư vấn tự động tạm dừng; các giới hạn lượt tư vấn hiện có vẫn áp dụng.", - "advisor.policy.manual": "Thủ công — chỉ khi worker yêu cầu", - "advisor.policy.preflight": "Preflight — tự động thử tư vấn khi có bằng chứng định hướng", - "advisor.policy.adaptive": "Thích ứng — khảo sát ban đầu và sửa lỗi thất bại", + "advisor.policy.manual": "Thủ công (mặc định) — chỉ hỏi khi AI tự đề nghị hoặc bạn yêu cầu", + "advisor.policy.preflight": "Tự động sau khi dùng công cụ", + "advisor.policy.adaptive": "Sau công cụ 1 lần + giải cứu — 1 lần sau khi đọc tệp + hỗ trợ nếu sửa mãi vẫn lỗi", "advisor.taskLimit": "Số lần tư vấn mỗi tác vụ", - "advisor.adaptiveNote": "Tư vấn tự động cần mã hội thoại ổn định. Tư vấn ban đầu diễn ra sau khi có bằng chứng khảo sát (lệnh gọi công cụ hoặc kết quả). Tư vấn sau sửa lỗi thất bại cần một lần kiểm tra thất bại, chỉnh sửa tệp hoàn tất, rồi chạy lại cùng lệnh trong cùng thư mục và vẫn thất bại; chỉ lặp lại thất bại thì chưa đủ. Lệnh gọi thủ công cũng dùng ngân sách tác vụ. Lượt đã giữ hết hạn sau 24 giờ và vẫn còn sau khi khởi động lại proxy.", + "advisor.adaptiveNote": "Điều kiện kích hoạt: chế độ tự động không chạy ngay ở câu đầu tiên hay hỏi đáp chữ thông thường. Sau khi AI gọi công cụ đọc tệp hoặc log lệnh, kiểm tra tự động chạy một lần mỗi tác vụ khi có mã phiên ổn định, hoặc một lần mỗi yêu cầu nếu không có; giải cứu chỉ can thiệp khi gặp vòng lặp kiểm tra lỗi → sửa tệp → chạy lại vẫn lỗi. Gọi thủ công chỉ tính chung giới hạn theo tác vụ khi có mã phiên ổn định, và chế độ thích ứng yêu cầu mã phiên ổn định cho ngân sách tác vụ.", "advisor.activity.title": "Hoạt động Advisor gần đây", "advisor.activity.note": "Tối đa 100 bản ghi của tiến trình này trong 24 giờ. Không lưu nội dung tác vụ hay lời khuyên. Suy luận: yêu cầu → mức do bộ chuyển đổi ánh xạ; chưa báo cáo không xác nhận hỗ trợ. Token: đầu vào / đầu ra được báo cáo. Không suy đoán việc áp dụng lời khuyên hay chi phí chính xác.", "advisor.activity.empty": "Chưa có bản ghi tư vấn.", @@ -332,6 +332,41 @@ export const vi: Record = { "advisor.disclosure": "Một lần tư vấn có thể gửi yêu cầu người dùng mới nhất, văn bản người dùng/trợ lý/nhà phát triển đã phân tích, lệnh gọi công cụ và đối số, kết quả công cụ, danh mục công cụ của worker, danh tính worker, model cố vấn đã cấu hình, và câu hỏi trọng tâm tùy chọn. OpenCodex không đưa khóa API của provider, header Authorization, token OAuth, bí mật backend, môi trường tiến trình, hoặc chuỗi suy nghĩ ẩn vào prompt. Nội dung nhiệm vụ không được loại bỏ bí mật: khóa dán vào, bí mật trong tệp, hoặc token do công cụ in ra đều có thể được gửi. Provider cố vấn có thể khác provider của worker.", "advisor.consent.label": "Tôi hiểu rằng các lần tư vấn của cố vấn có thể gửi hội thoại của nhiệm vụ này, lệnh gọi công cụ và kết quả công cụ tới provider cố vấn đã cấu hình, vốn có thể khác với provider của worker. Nội dung nhiệm vụ không được loại bỏ bí mật.", "advisor.consent.required": "Cố vấn chưa chạy được cho đến khi sự đồng ý chia sẻ ngữ cảnh được ghi nhận. Không có sự đồng ý thì không có nội dung nhiệm vụ nào được gửi.", + "advisor.fullContext": "Gửi toàn bộ lịch sử & nhật ký phiên cục bộ", + "advisor.fullContextHint": "Mở rộng giới hạn (128k/512k ký tự) và lọc bỏ thẻ hệ thống dư thừa. Chỉ đính kèm lịch sử phiên cục bộ trong các lượt tư vấn MCP ngoài có cung cấp mã phiên hoặc đường dẫn bản ghi.", + "advisor.mcp.title": "Kết nối ứng dụng (MCP & nhắc nhở chống quên)", + "advisor.mcp.subtitle": "Kết nối các ứng dụng ngoài (gồm các ứng dụng dùng mô hình sẵn có như WorkBuddy, Qoder) với MCP opencodex-advisor và lời nhắc để không quên hỏi cố vấn khi chat dài.", + "advisor.mcp.proxyNativeTitle": "Ứng dụng đi qua proxy OpenCodex", + "advisor.mcp.proxyNativeDesc": "Codex CLI, Claude Code, ZCode, T3 Code, Droid, Kimi, Kilo, Pi, OMP… khi chạy qua OpenCodex đã có sẵn công cụ cố vấn và nhắc cuối chuỗi công cụ, không cần cài thêm MCP.", + "advisor.mcp.autoMountLabel": "Tự động kết nối opencodex-advisor MCP cho các định tuyến tương thích đang bật", + "advisor.mcp.autoMountHint": "Đồng bộ hai chiều: bật Định tuyến trước hay bật Cố vấn trước đều tự động cấu hình (trừ khi bạn chọn thủ công bên dưới).", + "advisor.mcp.selectionModeAuto": "Tự động — theo các định tuyến tương thích đang bật", + "advisor.mcp.selectionModeOff": "Tắt — chọn client bên dưới hoặc bật tự động kết nối", + "advisor.mcp.selectionModeManual": "Thủ công — chỉ gắn các ứng dụng được tick bên dưới", + "advisor.mcp.useAutoMode": "Dùng đồng bộ tự động", + "advisor.mcp.selectRouted": "Chọn tất cả đang định tuyến", + "advisor.mcp.badgeRouted": "Đang định tuyến", + "advisor.mcp.badgeDetected": "Đã cài", + "advisor.mcp.badgeMounted": "Đã kết nối", + "advisor.mcp.badgeHookSkill": "Hook + Skill", + "advisor.mcp.trust.trusted": "Đã tin cậy", + "advisor.mcp.trust.actionRequired": "Bấm Tin cậy trong ứng dụng", + "advisor.mcp.trust.needsConfirmation": "Xác nhận trong cài đặt MCP", + "advisor.mcp.trust.autoEnabled": "Đã bật", + "advisor.mcp.trust.notMounted": "Chưa kết nối", + "advisor.mcp.emptyHint": "Lưu cài đặt để đồng bộ và xem trạng thái kết nối từng ứng dụng.", + "advisor.mcp.syncPartial": "Đã lưu cài đặt Advisor, nhưng đồng bộ MCP thất bại cho: {clients}.", + "advisor.mcp.routeNoticeWillMount": "Đang bật tự động kết nối Cố vấn: bật định tuyến này sẽ thêm opencodex-advisor MCP vào {path}.", + "advisor.mcp.routeNoticeMounted": "Đã kết nối opencodex-advisor MCP tại {path}.", + "advisor.mcp.routeNoticeManual": "Đang chọn ứng dụng thủ công. Chỉnh ở trang Cố vấn.", + "advisor.mcp.note.workbuddy": "Sau khi ghi mcp.json và hook, hãy vào trình quản lý MCP của WorkBuddy bấm Tin cậy một lần trước khi dùng.", + "advisor.mcp.note.workbuddy-ai": "Sau khi ghi mcp.json và hook, hãy vào trình quản lý MCP của WorkBuddy AI bấm Tin cậy một lần trước khi dùng.", + "advisor.mcp.note.qoder": "Đã ghi vào Qoder settings.json (MCP + hook UserPromptSubmit) và SKILL.md; kiểm tra Cài đặt -> MCP (tắt rồi bật lại MCP sau khi nâng cấp).", + "advisor.mcp.note.qoder-cn": "Đã ghi vào Qoder CN settings.json (MCP + hook UserPromptSubmit) và SKILL.md; kiểm tra Cài đặt -> MCP (tắt rồi bật lại MCP sau khi nâng cấp).", + "advisor.mcp.note.commandcode": "Đã ghi vào Command Code mcp.json; nếu hỏi xác nhận ở lần đầu gọi, hãy cho phép opencodex-advisor.", + "advisor.mcp.note.cline": "Đã ghi vào cline_mcp_settings.json (timeout: 900s); hãy chấp thuận consult_advisor khi Cline hỏi lần đầu (hoặc tự bật autoApprove trong cài đặt Cline).", + "advisor.mcp.note.opencode": "Đã ghi vào opencode.json mục mcp.opencodex-advisor (enabled: true, timeout: 900000ms) kèm Skill nhắc nhở.", + "advisor.mcp.note.claude": "Claude Code qua proxy OpenCodex đã có sẵn công cụ cố vấn; bật thêm MCP ngoài cần xác nhận tin cậy ở lần chạy tới.", "nav.logs": "Logs & Gỡ lỗi", "nav.usage": "Mức sử dụng", "common.github": "GitHub", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 30a5c8b63e1..b6f48976af7 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -281,7 +281,7 @@ export const zhTW: Record = { "nav.combos": "組合", "nav.subagents": "子代理", "nav.advisor": "顧問", - "advisor.description": "獨立的專家模型,審閱 Worker 的任務並返回建議。諮詢由 OpenCodex 自己執行:Worker 可呼叫合成的 advisor 工具;preflight 策略還會在任務產出方向性證據(最新使用者訊息之後的助手工具呼叫或工具結果)後自動嘗試一次諮詢,無需 Worker 配合。此嘗試對帶有穩定會話識別的用戶端按任務去重;沒有穩定識別的用戶端不走該去重,每個符合條件的請求都可能再次觸發諮詢。", + "advisor.description": "供程式設計 AI 諮詢的專家模型。手動模式按需呼叫。路由模型的預檢在使用工具後觸發,適應性補救在重複修復失敗後觸發;外部用戶端可使用 MCP。", "advisor.enabled": "啟用顧問", "advisor.model": "專家模型", "advisor.modelClear": "清除模型", @@ -293,11 +293,11 @@ export const zhTW: Record = { "advisor.policy": "策略", "advisor.questionOnly": "僅傳送主模型的問題", "advisor.questionOnlyNote": "僅傳送主模型填寫的問題(最多保留 2000 字元,超出時附加截斷提示)和固定顧問指令,不自動附加對話歷史、工具結果或任務上下文。主模型需要自行補充必要背景。自動諮詢暫停,現有諮詢次數限制仍然生效。", - "advisor.policy.manual": "手動 — 僅在 Worker 主動請求時", - "advisor.policy.preflight": "Preflight — 出現方向性證據後自動嘗試諮詢", - "advisor.policy.adaptive": "自適應 — 初始探查與修復失敗時諮詢", + "advisor.policy.manual": "手動(預設)— 僅在 AI 主動求助或你要求時呼叫", + "advisor.policy.preflight": "使用工具後自動", + "advisor.policy.adaptive": "呼叫工具後問 1 次 + 防卡死 — 看過線索後問 1 次,連續改錯失敗時自動救場", "advisor.taskLimit": "每項任務諮詢上限", - "advisor.adaptiveNote": "自動諮詢需要穩定的對話識別碼。初始諮詢在出現探查證據(工具呼叫或結果)後進行。修復失敗諮詢需要驗證失敗、檔案修改完成,隨後在同一目錄重新執行同一命令並再次失敗;僅重複失敗不符合條件。手動呼叫也計入任務預算;預約在 24 小時後到期,重啟代理不會歸零。", + "advisor.adaptiveNote": "說明:自動模式不會在第一句送出時就呼叫顧問,純文字聊天也不會觸發。當 AI 呼叫工具讀取檔案或命令輸出後,用戶端提供固定會話 ID 時每項任務最多自動觸發 1 次,無固定 ID 時僅在單次請求內去重(每次請求最多 1 次);防卡死救場僅在「命令報錯 → 修改檔案 → 重跑依然報錯」的循環出現時介入。手動呼叫僅在存在固定會話 ID 時共享每任務上限,自適應模式需要固定會話 ID 來維護任務預算。", "advisor.activity.title": "最近的顧問活動", "advisor.activity.note": "顯示目前程序最近 24 小時內最多 100 筆記錄,不儲存任務內文或專家建議。推理強度顯示要求等級 → 介接器映射等級;未回報不代表支援。Token 顯示已回報的輸入 / 輸出量,不推測建議採納情況或精確費用。", "advisor.activity.empty": "尚無諮詢記錄。", @@ -325,6 +325,41 @@ export const zhTW: Record = { "advisor.disclosure": "一次諮詢可能傳送:最新的使用者任務、已解析的使用者/助理/開發者文字、工具呼叫及其參數、工具結果、Worker 的工具目錄、Worker 身分、所設定的顧問模型,以及手動呼叫時的選用焦點問題。OpenCodex 不會把 provider API key、Authorization 標頭、OAuth token、後端密鑰、行程環境或隱藏的思維鏈寫進該提示。任務內容本身不做通用脫敏:貼進任務的金鑰、檔案裡的秘密、工具印出的 token 都可能被傳送。顧問 provider 可能與 Worker 的 provider 不同。", "advisor.consent.label": "我理解顧問諮詢可能把本任務的對話、工具呼叫和工具結果傳送給所設定的顧問 provider,該 provider 可能與 Worker 不同。任務內容不會做通用脫敏。", "advisor.consent.required": "在記錄上下文共享同意之前,顧問不會執行。沒有這項同意時,不會傳送任務內容。", + "advisor.fullContext": "傳送完整上下文與本機工作階段記錄", + "advisor.fullContextHint": "大幅放寬上下文上限(單則 128k / 總計 512k 字元)並清理用戶端冗餘標籤;僅在外部 MCP 諮詢且提供會話 ID 或轉錄路徑時附加本機會話歷史。", + "advisor.mcp.title": "相容用戶端接入(MCP 與防遺忘提醒)", + "advisor.mcp.subtitle": "讓不走 OpenCodex 轉發的用戶端(如使用內建模型的 WorkBuddy、Qoder)也能接入顧問,並透過提醒腳本避免長對話後忘記求助。", + "advisor.mcp.proxyNativeTitle": "走 OpenCodex 轉發的用戶端(無需配 MCP)", + "advisor.mcp.proxyNativeDesc": "Codex CLI、Claude Code、ZCode、T3 Code、Droid、Kimi、Kilo、Pi、OMP 等直接經由 OpenCodex 轉發的用戶端會自動獲得內建顧問工具與防遺忘提醒,無須額外設定 MCP。", + "advisor.mcp.autoMountLabel": "開啟路由時自動為相容用戶端接入顧問 MCP", + "advisor.mcp.autoMountHint": "雙向同步:無論先開路由或先開顧問皆會自動寫入設定(若下方改為手動勾選清單,則僅依勾選項套用)。", + "advisor.mcp.selectionModeAuto": "自動連動 — 跟隨已開啟路由的相容用戶端", + "advisor.mcp.selectionModeOff": "已關閉 — 請在下方選擇用戶端,或開啟自動連線", + "advisor.mcp.selectionModeManual": "手動指定 — 僅掛載下方勾選的用戶端", + "advisor.mcp.useAutoMode": "切回自動跟隨已路由用戶端", + "advisor.mcp.selectRouted": "全選已開啟路由的相容用戶端", + "advisor.mcp.badgeRouted": "已開啟路由", + "advisor.mcp.badgeDetected": "已安裝", + "advisor.mcp.badgeMounted": "已接入 MCP", + "advisor.mcp.badgeHookSkill": "提醒 Hook + Skill", + "advisor.mcp.trust.trusted": "已信任啟用", + "advisor.mcp.trust.actionRequired": "需至用戶端點擊一次信任", + "advisor.mcp.trust.needsConfirmation": "請於用戶端 MCP 設定確認啟用", + "advisor.mcp.trust.autoEnabled": "已設定啟用", + "advisor.mcp.trust.notMounted": "未接入", + "advisor.mcp.emptyHint": "儲存設定後可同步並檢視各用戶端的連線與信任狀態。", + "advisor.mcp.syncPartial": "顧問設定已儲存,但以下用戶端的 MCP 同步失敗:{clients}。", + "advisor.mcp.routeNoticeWillMount": "已啟用顧問自動接入:開啟此用戶端路由後,將自動寫入 opencodex-advisor MCP({path})。", + "advisor.mcp.routeNoticeMounted": "已為此用戶端接入 opencodex-advisor MCP({path})。", + "advisor.mcp.routeNoticeManual": "目前為手動選取 MCP 用戶端模式,請至「顧問」頁面設定是否接入。", + "advisor.mcp.note.workbuddy": "寫入 mcp.json 與提醒 Hook 後,仍須在 WorkBuddy 的 MCP 管理頁對該服務點擊一次「信任」才可生效。", + "advisor.mcp.note.workbuddy-ai": "寫入 mcp.json 與提醒 Hook 後,仍須在 WorkBuddy AI 的 MCP 管理頁對該服務點擊一次「信任」才可生效。", + "advisor.mcp.note.qoder": "已寫入 Qoder settings.json(MCP 與防遺忘 Hook)及 SKILL.md;首次使用請至 Qoder 設定 -> MCP 頁確認已啟用(升級後建議重開一次 MCP)。", + "advisor.mcp.note.qoder-cn": "已寫入 Qoder CN settings.json(MCP 與防遺忘 Hook)及 SKILL.md;首次使用請至 Qoder CN 設定 -> MCP 頁確認已啟用(升級後建議重開一次 MCP)。", + "advisor.mcp.note.commandcode": "已寫入 Command Code mcp.json;若用戶端跳出工具確認視窗,允許 opencodex-advisor 即可。", + "advisor.mcp.note.cline": "已寫入 cline_mcp_settings.json(逾時 900 秒);首次呼叫時請在 Cline 中確認允許 consult_advisor(如需自動放行可在 Cline 設定中自行開啟)。", + "advisor.mcp.note.opencode": "已寫入 opencode.json 的 mcp.opencodex-advisor(enabled: true,逾時 900000ms),並同步安裝防遺忘 Skill。", + "advisor.mcp.note.claude": "Claude Code 走 OpenCodex 代理時已內建顧問工具;如需額外接入外部 MCP,下次啟動 CLI 時確認信任即可。", "nav.logs": "日誌與除錯", "nav.usage": "用量", "common.github": "GitHub", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 8e389e5a83d..9a702934ab5 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -289,7 +289,7 @@ export const zh: Record = { "nav.subagents": "子代理", "nav.advisor": "顾问", - "advisor.description": "独立的专家模型,审阅 Worker 的任务并返回建议。咨询由 OpenCodex 自己执行:Worker 可调用合成的 advisor 工具;preflight 策略还会在任务产出方向性证据(最新用户消息之后的助手工具调用或工具结果)后自动尝试一次咨询,无需 Worker 配合。该尝试对带有稳定会话标识的客户端按任务去重;没有稳定标识的客户端不走该去重,每个符合条件的请求都可能再次触发咨询。", + "advisor.description": "供编程 AI 咨询的专家模型。手动模式按需调用。路由模型的预检在使用工具后触发,自适应补救在重复修复失败后触发;外部客户端可使用 MCP。", "advisor.enabled": "启用顾问", "advisor.model": "专家模型", "advisor.modelClear": "清除模型", @@ -301,11 +301,11 @@ export const zh: Record = { "advisor.policy": "策略", "advisor.questionOnly": "仅发送主模型的问题", "advisor.questionOnlyNote": "仅发送主模型填写的问题(最多保留 2000 字符,超出时附加截断提示)和固定顾问指令,不自动附带对话历史、工具结果或任务上下文。主模型需要自行补充必要背景。自动咨询暂停,现有咨询次数限制仍然生效。", - "advisor.policy.manual": "手动 — 仅在 Worker 主动请求时", - "advisor.policy.preflight": "Preflight — 出现方向性证据后自动尝试咨询", - "advisor.policy.adaptive": "自适应 — 初始探查与修复失败时咨询", + "advisor.policy.manual": "手动(默认)— 仅在 AI 主动求助或你要求时调用", + "advisor.policy.preflight": "使用工具后自动", + "advisor.policy.adaptive": "调工具后问 1 次 + 防卡死 — 查完线索后问 1 次,连续改错失败时自动救场", "advisor.taskLimit": "每任务咨询上限", - "advisor.adaptiveNote": "自动咨询需要稳定的会话标识。初始咨询在出现探查证据(工具调用或结果)后进行。修复失败咨询需要验证失败、文件修改完成,随后在同一目录重新执行同一命令并再次失败;仅重复失败不符合条件。手动调用也计入任务预算;预约在 24 小时后过期,重启代理不会清零。", + "advisor.adaptiveNote": "说明:自动模式不会在第一句话发出时就调用顾问,纯文本聊天也不会触发。当 AI 调用工具读取文件或命令输出后,客户端提供稳定会话 ID 时每任务最多自动触发 1 次,无稳定 ID 时仅在单次请求内去重(每次请求最多 1 次);防卡死救场仅在「命令报错 → 修改文件 → 重跑依然报错」的循环出现时介入。手动调用仅在存在稳定会话 ID 时计入每任务共享上限,自适应模式需要稳定会话 ID 来维护任务预算。", "advisor.activity.title": "最近的顾问活动", "advisor.activity.note": "显示当前进程最近 24 小时内最多 100 条记录,不保存任务正文或专家建议。推理强度显示请求档位 → 适配器映射档位;未报告不代表支持。Token 显示已报告的输入 / 输出量,不推测建议采纳情况或精确费用。", "advisor.activity.empty": "尚无咨询记录。", @@ -333,6 +333,41 @@ export const zh: Record = { "advisor.disclosure": "一次咨询可能发送:最新的用户任务、已解析的用户/助手/开发者文本、工具调用及其参数、工具结果、Worker 的工具目录、Worker 身份、所配置的顾问模型,以及手动调用时的可选焦点问题。OpenCodex 不会把 provider API key、Authorization 头、OAuth token、后端密钥、进程环境或隐藏的思维链写进该提示。任务内容本身不做通用脱敏:贴进任务的密钥、文件里的秘密、工具打印出的 token 都可能被发送。顾问 provider 可能与 Worker 的 provider 不同。", "advisor.consent.label": "我理解顾问咨询可能把本任务的对话、工具调用和工具结果发送给所配置的顾问 provider,该 provider 可能与 Worker 不同。任务内容不会做通用脱敏。", "advisor.consent.required": "在记录上下文共享同意之前,顾问不会运行。没有这项同意时,不会发送任务内容。", + "advisor.fullContext": "发送完整上下文与客户端本地对话记录", + "advisor.fullContextHint": "放宽上下文上限(单条 128k / 总计 512k 字符)并过滤客户端冗余标签;仅在外部 MCP 咨询且提供会话 ID 或转录路径时附加本地会话历史。", + "advisor.mcp.title": "兼容客户端接入(MCP 与防遗忘提醒)", + "advisor.mcp.subtitle": "让不走 OpenCodex 转发的客户端(如使用内置模型的 WorkBuddy、Qoder)也能接入顾问,并通过提醒脚本避免长对话后忘记求助。", + "advisor.mcp.proxyNativeTitle": "走 OpenCodex 转发的客户端(无需配 MCP)", + "advisor.mcp.proxyNativeDesc": "Codex CLI、Claude Code、ZCode、T3 Code、Droid、Kimi、Kilo、Pi、OMP 等直接经过 OpenCodex 转发的客户端会自动获得内置顾问工具与防遗忘提醒,不用额外配 MCP。", + "advisor.mcp.autoMountLabel": "开启路由时自动为兼容客户端接入顾问 MCP", + "advisor.mcp.autoMountHint": "双向同步:无论是先开客户端路由再开顾问,还是先开顾问再开路由,都会自动写好配置(下方手动勾选特定客户端时按勾选项生效)。", + "advisor.mcp.selectionModeAuto": "自动联动 — 跟随已开启路由的客户端", + "advisor.mcp.selectionModeOff": "已关闭 — 请在下方选择客户端,或开启自动连接", + "advisor.mcp.selectionModeManual": "手动指定 — 仅挂载下方勾选的客户端", + "advisor.mcp.useAutoMode": "切回自动跟随已开启路由的客户端", + "advisor.mcp.selectRouted": "全选已开路由的兼容客户端", + "advisor.mcp.badgeRouted": "已开路由", + "advisor.mcp.badgeDetected": "已安装", + "advisor.mcp.badgeMounted": "已接入 MCP", + "advisor.mcp.badgeHookSkill": "提醒 Hook + Skill", + "advisor.mcp.trust.trusted": "已信任启用", + "advisor.mcp.trust.actionRequired": "需去客户端点一次信任", + "advisor.mcp.trust.needsConfirmation": "请在客户端 MCP 设置中确认启用", + "advisor.mcp.trust.autoEnabled": "已配置启用", + "advisor.mcp.trust.notMounted": "未接入", + "advisor.mcp.emptyHint": "保存设置后将同步并显示各客户端的连接与信任状态。", + "advisor.mcp.syncPartial": "顾问设置已保存,但以下客户端的 MCP 同步失败:{clients}。", + "advisor.mcp.routeNoticeWillMount": "已开启顾问自动接入:开启此客户端路由后,会自动在 {path} 写入 opencodex-advisor MCP。", + "advisor.mcp.routeNoticeMounted": "已为该客户端接入 opencodex-advisor MCP({path})。", + "advisor.mcp.routeNoticeManual": "当前顾问使用手动选择客户端模式,可在「顾问」页面勾选是否接入此客户端。", + "advisor.mcp.note.workbuddy": "写入 mcp.json 与提醒 Hook 后,仍需在 WorkBuddy 的 MCP 管理页对该服务点击一次「信任」才可生效。", + "advisor.mcp.note.workbuddy-ai": "写入 mcp.json 与提醒 Hook 后,仍需在 WorkBuddy AI 的 MCP 管理页对该服务点击一次「信任」才可生效。", + "advisor.mcp.note.qoder": "已写入 Qoder settings.json(MCP 与防遗忘 Hook)及 SKILL.md;首次使用请在 Qoder 设置 -> MCP 页确认已开启(升级后可重开一下 MCP 刷新进程)。", + "advisor.mcp.note.qoder-cn": "已写入 Qoder CN settings.json(MCP 与防遗忘 Hook)及 SKILL.md;首次使用请在 Qoder CN 设置 -> MCP 页确认已开启(升级后可重开一下 MCP 刷新进程)。", + "advisor.mcp.note.commandcode": "已写入 Command Code mcp.json;若客户端弹出工具确认提示,允许 opencodex-advisor 即可。", + "advisor.mcp.note.cline": "已写入 cline_mcp_settings.json(超时 900 秒);首次调用时请在 Cline 中确认允许 consult_advisor(如需自动放行可在 Cline 设置中自行开启)。", + "advisor.mcp.note.opencode": "已写入 opencode.json 的 mcp.opencodex-advisor(enabled: true,超时 900000ms),并同步安装防遗忘 Skill。", + "advisor.mcp.note.claude": "Claude Code 走 OpenCodex 代理时已内置顾问工具;如需额外接入外部 MCP,下次启动 CLI 时确认信任即可。", // routing intelligence "routing.title": "路由智能 (beta)", "routing.subtitle": "策略配置文件、试运行评估以及基于来源的路由分析。", diff --git a/gui/src/pages/Advisor.tsx b/gui/src/pages/Advisor.tsx index c1c0d6c5445..123a77f64e3 100644 --- a/gui/src/pages/Advisor.tsx +++ b/gui/src/pages/Advisor.tsx @@ -7,6 +7,11 @@ import { AdvisorModelSelect } from "../components/AdvisorModelSelect"; import { HelpButton, SettingsRow, SettingsSection } from "../components/v2-proxy/settings-layout"; import AdvisorActivity from "./advisor/AdvisorActivity"; import { AdvisorConsentCallout } from "./advisor/AdvisorConsentCallout"; +import { + AdvisorClientMcpPanel, + type AdvisorMcpClientId, + type AdvisorMcpClientStatusDto, +} from "./advisor/AdvisorClientMcpPanel"; import "./advisor/advisor.css"; /** @@ -21,32 +26,57 @@ export interface AdvisorSettings { model: string; effort: string; policy: "manual" | "preflight" | "adaptive"; - contextMode?: "context" | "question-only"; + contextMode?: "context" | "full" | "question-only"; maxConsultationsPerTask?: number; timeoutMs: number; contextSharingConsent: "v1" | null; + autoMountMcp?: boolean; + mcpClients?: AdvisorMcpClientId[] | null; +} + +export interface AdvisorMcpSyncErrorDto { + clientId: AdvisorMcpClientId; + message: string; +} + +export interface AdvisorMcpSyncDto { + mounted?: AdvisorMcpClientId[]; + unmounted?: AdvisorMcpClientId[]; + errors?: AdvisorMcpSyncErrorDto[]; } export interface AdvisorDto { settings: AdvisorSettings; runnable: boolean; warning?: string; + mcpClients?: AdvisorMcpClientStatusDto[]; + mcpSync?: AdvisorMcpSyncDto; } const EFFORTS = ["low", "medium", "high", "xhigh", "max", "ultra"]; // One field width for the editor's dropdowns and the timeout box; full width on a phone. const ADVISOR_FIELD_WIDTH = "w-[16rem] max-w-full max-[640px]:w-full"; -export function AdvisorEditor({ apiBase, initial }: { apiBase: string; initial: AdvisorSettings }) { +export function AdvisorEditor({ + apiBase, + initial, + initialMcpClients = [], +}: { + apiBase: string; + initial: AdvisorSettings; + initialMcpClients?: readonly AdvisorMcpClientStatusDto[]; +}) { const t = useT(); // Mount-time snapshot. The parent remounts this editor when the first load settles // (`key` flips cold → ready), so later parent dto changes do not need to be copied here. // After mount, `saved` only advances from a successful PUT. const [saved, setSaved] = useState(initial); const [draft, setDraft] = useState(initial); + const [mcpStatus, setMcpStatus] = useState(initialMcpClients); const [saving, setSaving] = useState(false); const [savedFlash, setSavedFlash] = useState(false); const [saveError, setSaveError] = useState(""); + const [mcpSyncErrors, setMcpSyncErrors] = useState([]); const savedFlashTimerRef = useRef | null>(null); useEffect(() => { @@ -80,6 +110,8 @@ export function AdvisorEditor({ apiBase, initial }: { apiBase: string; initial: policy: submitted.policy, contextMode: submitted.contextMode ?? "context", ...(submitted.maxConsultationsPerTask !== undefined ? { maxConsultationsPerTask: submitted.maxConsultationsPerTask } : {}), + ...(submitted.autoMountMcp !== undefined ? { autoMountMcp: submitted.autoMountMcp } : {}), + ...(submitted.mcpClients !== undefined ? { mcpClients: submitted.mcpClients } : {}), timeoutMs: submitted.timeoutMs, contextSharingConsent: submitted.contextSharingConsent, }), @@ -91,24 +123,27 @@ export function AdvisorEditor({ apiBase, initial }: { apiBase: string; initial: } const body = (await response.json()) as AdvisorDto; setSaved(body.settings); + if (Array.isArray(body.mcpClients)) setMcpStatus(body.mcpClients); // Edits made while the PUT was in flight stay in the draft: only overwrite the draft // when the user has not touched it since this save started. setDraft(current => (JSON.stringify(current) === JSON.stringify(submitted) ? body.settings : current)); - setSavedFlash(true); - savedFlashTimerRef.current = setTimeout(() => { - savedFlashTimerRef.current = null; - setSavedFlash(false); - }, 2500); + const syncErrors = Array.isArray(body.mcpSync?.errors) ? body.mcpSync.errors : null; + if (syncErrors !== null) setMcpSyncErrors(syncErrors); + if (syncErrors?.length === 0 || (syncErrors === null && mcpSyncErrors.length === 0)) { + setSavedFlash(true); + savedFlashTimerRef.current = setTimeout(() => { + savedFlashTimerRef.current = null; + setSavedFlash(false); + }, 2500); + } } catch (error) { setSaveError(error instanceof Error ? error.message : String(error)); } finally { setSaving(false); } - }, [apiBase, draft]); + }, [apiBase, draft, mcpSyncErrors.length]); - // Every field edit invalidates the previous failure notice: it describes the state that was - // submitted, and it must not outlive the field the operator is now correcting. A revert to the - // saved value would otherwise leave the notice with no way to clear at all. + // Reconciliation errors remain actionable until a successful save confirms they are cleared. const edit = useCallback((patch: Partial) => { setSaveError(""); setDraft(current => ({ ...current, ...patch })); @@ -188,6 +223,27 @@ export function AdvisorEditor({ apiBase, initial }: { apiBase: string; initial: )} /> + {draft.contextMode !== "question-only" && ( + + edit({ contextMode: event.target.checked ? "full" : "context" })} + /> +