From bc332f1e823c023b684ffa09696c4a233abf1453 Mon Sep 17 00:00:00 2001 From: Matthew Cosier Date: Tue, 24 Nov 2026 14:33:22 +1100 Subject: [PATCH 1/6] fix(server): managed Codex 401s say why no ChatGPT token was given A managed ChatGPT Codex instance that could not hand Codex a token showed only a bare 401 on the thread. The token broker dropped every failed request without a reason or a log line, the helper printed one generic line, and Codex then sent its request with no credentials. The broker now answers a refused request with its reason and logs the instance, kind and message, never a token or profile key. Environment mismatches, a full job queue, shutdown and timeouts get their own reason. The helper prints that reason to stderr and still gives Codex nothing on stdout. When a managed turn fails with a 401 shortly after its sign-in profile was refused, the thread error names the reason, points to Settings, Providers, and keeps Codex's original text. Co-Authored-By: Claude Opus 5.5 --- .../src/cli/managedChatGptToken.test.ts | 102 ++++++ apps/server/src/cli/managedChatGptToken.ts | 13 +- .../Adapters/CodexAdapterV2.test.ts | 135 +++++++ .../Adapters/CodexAdapterV2.ts | 102 ++++-- .../src/provider/CodexChatGptAuth.test.ts | 332 ++++++++++++++---- .../src/provider/CodexManagedRuntime.ts | 5 +- .../src/provider/CodexManagedTokenBroker.ts | 112 +++++- .../src/provider/CodexManagedTokenProtocol.ts | 11 +- 8 files changed, 685 insertions(+), 127 deletions(-) create mode 100644 apps/server/src/cli/managedChatGptToken.test.ts diff --git a/apps/server/src/cli/managedChatGptToken.test.ts b/apps/server/src/cli/managedChatGptToken.test.ts new file mode 100644 index 0000000000000..ef2935e29daf2 --- /dev/null +++ b/apps/server/src/cli/managedChatGptToken.test.ts @@ -0,0 +1,102 @@ +// @effect-diagnostics nodeBuiltinImport:off - A fake broker listens on the helper's private socket. +import * as NodeCrypto from "node:crypto"; +import * as NodeFSP from "node:fs/promises"; +import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { afterEach, describe, expect, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import { vi } from "vite-plus/test"; +import { runManagedChatGptTokenCli } from "./managedChatGptToken.ts"; + +const profileKey = "a".repeat(64); +const refusal = { kind: "refresh", message: "Your ChatGPT connection expired. Sign in again." }; + +/** Runs the helper against a fake broker that sends `answer`, or closes when it is null. */ +const runAgainst = (answer: string | null) => + Effect.gen(function* () { + // The helper connects to a real local socket, so this follows the host like the broker does. + const platform = yield* HostProcess.Platform; + const directory = yield* Effect.acquireRelease( + Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-token-cli-"))), + (directory) => Effect.promise(() => NodeFSP.rm(directory, { recursive: true, force: true })), + ); + const endpoint = + platform === "win32" + ? `\\\\.\\pipe\\t3-token-cli-${NodeCrypto.randomUUID()}` + : NodePath.join(directory, "s"); + yield* Effect.acquireRelease( + Effect.promise(async () => { + const server = NodeNet.createServer((socket) => { + socket.once("data", () => + answer === null ? socket.destroy() : socket.end(`${answer}\n`), + ); + }); + await new Promise((resolve) => server.listen(endpoint, resolve)); + return server; + }), + (server) => + Effect.promise(() => new Promise((resolve) => server.close(() => resolve()))), + ); + const stdout: string[] = []; + const stderr: string[] = []; + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + stdout.push(String(chunk)); + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); + }), + () => Effect.sync(() => vi.restoreAllMocks()), + ); + yield* Effect.promise(() => + runManagedChatGptTokenCli([endpoint, "codex-managed", "environment-1", profileKey]), + ); + return { stdout: stdout.join(""), stderr: stderr.join(""), exitCode: process.exitCode }; + }).pipe(Effect.scoped); + +describe("managed ChatGPT token helper", () => { + const exitCode = process.exitCode; + afterEach(() => { + process.exitCode = exitCode; + }); + + it.effect("prints a broker's refusal and gives Codex no token", () => + Effect.gen(function* () { + const result = yield* runAgainst(JSON.stringify({ refusal })); + expect(result).toEqual({ stdout: "", stderr: `${refusal.message}\n`, exitCode: 1 }); + }), + ); + + it.effect("hands Codex the broker's token on stdout", () => + Effect.gen(function* () { + const result = yield* runAgainst(JSON.stringify({ token: "access-token" })); + expect(result).toEqual({ stdout: "access-token", stderr: "", exitCode }); + }), + ); + + it.effect.each([ + { name: "no answer", answer: null }, + { + name: "a token beside a refusal", + answer: JSON.stringify({ token: "access-token", refusal }), + }, + { + name: "a refusal without a message", + answer: JSON.stringify({ refusal: { kind: "refresh" } }), + }, + ])("fails without a token on $name", ({ answer }) => + Effect.gen(function* () { + const result = yield* runAgainst(answer); + expect(result.stdout).toBe(""); + expect(result.stderr).not.toBe(""); + expect(result.stderr).not.toContain("access-token"); + expect(result.exitCode).toBe(1); + }), + ); +}); diff --git a/apps/server/src/cli/managedChatGptToken.ts b/apps/server/src/cli/managedChatGptToken.ts index 84ed18fb5228a..29650f1f622c8 100644 --- a/apps/server/src/cli/managedChatGptToken.ts +++ b/apps/server/src/cli/managedChatGptToken.ts @@ -37,12 +37,13 @@ export async function runManagedChatGptTokenCli(args: ReadonlyArray): Pr ).pipe(Effect.flatMap(decodeResponse)); }).pipe(Effect.scoped); const result = await Effect.runPromiseExit(program); - if (Exit.isFailure(result)) { - process.stderr.write( - "Could not access the managed ChatGPT connection. Reconnect in T3 Code.\n", - ); - process.exitCode = 1; + const response = Exit.isSuccess(result) ? result.value : undefined; + if (response !== undefined && "token" in response) { + process.stdout.write(response.token); return; } - process.stdout.write(result.value.token); + process.stderr.write( + `${response?.refusal.message ?? "Could not access the managed ChatGPT connection. Reconnect in T3 Code."}\n`, + ); + process.exitCode = 1; } diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 390d1f334739e..1b452f6ae0945 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1734,6 +1734,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { promptSuggestions: Effect.Effect = Effect.succeed(false), onNotification: (method: string) => Effect.Effect = () => Effect.void, models?: CodexAdapterV2.CodexAdapterV2Options["models"], + resolveRuntime?: CodexAdapterV2.CodexAdapterV2Options["resolveRuntime"], ) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1798,6 +1799,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { clientFactory, ...(onUsageLimits ? { onUsageLimits } : {}), ...(models ? { models } : {}), + ...(resolveRuntime ? { resolveRuntime } : {}), digest: yield* Digest.Digest, fileSystem, idAllocator, @@ -8956,6 +8958,139 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + // Codex sends requests without credentials after T3 refuses its managed token request. + it.effect.each([ + { name: "a managed 401 notice", managed: true, notification: true, explained: true }, + { name: "a managed 401 completion", managed: true, notification: false, explained: true }, + { name: "a managed 401 retry", managed: true, retry: true, explained: true }, + { name: "an unrefused managed 401", managed: true, unrefused: true, explained: false }, + { name: "a managed 503", managed: true, status: 503, explained: false }, + { name: "a local Codex 401", managed: false, explained: false }, + ] as const)("explains $name with the managed token refusal", (scenario) => + Effect.gen(function* () { + const nativeThreadId = `native-token-refusal-${scenario.name}`; + const nativeTurnId = `turn-token-refusal-${scenario.name}`; + const status = "status" in scenario ? scenario.status : 401; + const nativeMessage = `unexpected status ${status}: Missing authentication header, url: https://api.openai.com/v1/responses`; + const errorInfo = + "retry" in scenario + ? { responseTooManyFailedAttempts: { httpStatusCode: status } } + : { httpConnectionFailed: { httpStatusCode: status } }; + const refusal = { + kind: "refresh", + message: "Your ChatGPT connection expired. Sign in again.", + }; + const notification = "notification" in scenario ? scenario.notification : true; + const transcript = makeCodexReplayTranscript({ + scenario: `codex-token-refusal-${scenario.name}`, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + ...("retry" in scenario + ? [ + { + type: "emit_inbound" as const, + label: "error/retry", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 1/5", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: status } }, + additionalDetails: nativeMessage, + }, + }, + }, + }, + ] + : []), + ...(notification + ? [ + { + type: "emit_inbound" as const, + label: "error", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: false, + error: { message: nativeMessage, codexErrorInfo: errorInfo }, + }, + }, + }, + ] + : []), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), + error: { message: nativeMessage, codexErrorInfo: errorInfo }, + }, + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + scenario.managed + ? Effect.succeed({ + config: DEFAULT_CODEX_SETTINGS, + environment: {}, + revision: "managed-profile", + recentTokenRefusal: Effect.succeed("unrefused" in scenario ? undefined : refusal), + }) + : undefined, + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-token-refusal-${scenario.name}`), + }), + ); + yield* harness.firstTerminal; + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + if (scenario.explained) { + assert.equal(terminal.failure.code, `managed_token_${refusal.kind}`); + assert.include(terminal.failure.message, refusal.message); + assert.include(terminal.failure.message, nativeMessage); + } else { + assert.equal(terminal.failure.code, "httpConnectionFailed"); + assert.equal(terminal.failure.message, nativeMessage); + } + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #17501 Codex 429 retry exhaustion classifies as a usage limit it.effect.each([ { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index c7a7343d515fe..f3214c2a591b4 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -18,6 +18,7 @@ import { import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot"; import type { CodexEffectiveRuntime } from "../../provider/CodexManagedRuntime.ts"; import { classifyCodexManagedError } from "../../provider/CodexManagedErrors.ts"; +import type { Refusal } from "../../provider/CodexManagedTokenProtocol.ts"; import { buildCodexInitializeParams, codexAppServerEnvironment, @@ -1420,6 +1421,23 @@ function withCodexManagedFailure( }; } +/** + * Codex sends requests without credentials after T3 refuses its managed token + * request, so the 401 it reports hides the refusal that caused it. + */ +function withManagedTokenRefusal( + failure: OrchestrationV2ProviderFailure, + refusal: Refusal | undefined, +): OrchestrationV2ProviderFailure { + if (refusal === undefined) return failure; + return makeProviderFailure({ + message: `Codex could not get a ChatGPT token from T3 Code: ${refusal.message} Check the connection in Settings → Providers. Codex reported: ${failure.message}`, + code: `managed_token_${refusal.kind}`, + class: failure.class, + retryable: failure.retryable, + }); +} + function failureResetAt( failure: OrchestrationV2ProviderFailure, snapshot: CodexRateLimitSnapshot | undefined, @@ -2155,6 +2173,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( environment: resolvedRuntime?.environment ?? adapterOptions.environment, }); const codexZone = codexTimeZone(resolvedRuntime?.environment ?? adapterOptions.environment); + const explainTokenRefusal = ( + failure: OrchestrationV2ProviderFailure, + errorInfo: CodexErrorInfo | null | undefined, + ) => + resolvedRuntime?.recentTokenRefusal === undefined || + codexErrorHttpStatus(errorInfo) !== 401 + ? Effect.succeed(failure) + : resolvedRuntime.recentTokenRefusal.pipe( + Effect.map((refusal) => withManagedTokenRefusal(failure, refusal)), + ); const additionalContextByThread = yield* Ref.make( new Map>(), ); @@ -5463,16 +5491,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(payload.error.codexErrorInfo === undefined ? {} : { errorInfo: payload.error.codexErrorInfo }), - failure: withCodexManagedFailure( - makeProviderFailure({ - message: payload.error.additionalDetails?.trim() || payload.error.message, - code: notificationCode, - class: codexTerminalFailureClass( - payload.error.codexErrorInfo, - notificationCode, - ), - }), - payload.error, + failure: yield* explainTokenRefusal( + withCodexManagedFailure( + makeProviderFailure({ + message: payload.error.additionalDetails?.trim() || payload.error.message, + code: notificationCode, + class: codexTerminalFailureClass( + payload.error.codexErrorInfo, + notificationCode, + ), + }), + payload.error, + ), + payload.error.codexErrorInfo, ), }; return; @@ -5488,21 +5519,25 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }; const code = codexErrorInfoCode(payload.error.codexErrorInfo); const additionalDetails = payload.error.additionalDetails?.trim(); - const failure = withCodexManagedFailure( - makeProviderFailure({ - message: - additionalDetails === undefined || additionalDetails.length === 0 - ? payload.error.message - : additionalDetails, - code, - class: codexUsageLimitError(code, payload.error.codexErrorInfo) - ? "usage_limit" - : code?.startsWith("http") === true || code?.startsWith("responseStream") === true - ? "transport_error" - : "provider_error", - retryable: true, - }), - payload.error, + const failure = yield* explainTokenRefusal( + withCodexManagedFailure( + makeProviderFailure({ + message: + additionalDetails === undefined || additionalDetails.length === 0 + ? payload.error.message + : additionalDetails, + code, + class: codexUsageLimitError(code, payload.error.codexErrorInfo) + ? "usage_limit" + : code?.startsWith("http") === true || + code?.startsWith("responseStream") === true + ? "transport_error" + : "provider_error", + retryable: true, + }), + payload.error, + ), + payload.error.codexErrorInfo, ); const itemOrdinal = previous?.itemOrdinal ?? @@ -6667,13 +6702,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( (failureCode === undefined || failureCode === previousFailure.nativeCode) && (!completionHasClass || previousFailure.failure.class === failureClass) ? previousFailure.failure - : withCodexManagedFailure( - makeProviderFailure({ - message: input.failureMessage, - code: failureCode, - class: failureClass, - }), - input.failureMessage, + : yield* explainTokenRefusal( + withCodexManagedFailure( + makeProviderFailure({ + message: input.failureMessage, + code: failureCode, + class: failureClass, + }), + input.failureMessage, + ), + input.failureErrorInfo, ); const retry = input.providerRetry; const notification = input.context.latestProviderFailure; diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 5426fa8398242..40f21d2db22d6 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -17,6 +17,8 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as Fiber from "effect/Fiber"; import * as Deferred from "effect/Deferred"; +import * as Logger from "effect/Logger"; +import * as Queue from "effect/Queue"; import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts"; import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; @@ -24,6 +26,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; +import { COMMAND_TIMEOUT_MS } from "./CodexManagedTokenProtocol.ts"; const assertSameCallback = (actual: string | null, expected: string | null) => { const left = new URL(actual!); @@ -1770,87 +1773,113 @@ it.effect("a running session renews its bound profile but refuses a replacement ), ); -const makeRenewalBroker = Effect.gen(function* () { - const oauthEntered = yield* Deferred.make(); - const oauthRelease = yield* Deferred.make(); - let pauseOAuth = false; - const refreshTokens: string[] = []; - const credentials = { - clientId: "oaiapp_broker", - subject: "broker-user", - idToken: "broker-sign-in", - email: null, - accessToken: "expired-access", - refreshToken: "single-use-refresh", - expiresAt: 0, - earliestRefreshAt: null, - scopes: ["chatgpt.tokens.use.direct"], - }; - const environmentId = EnvironmentId.make("00000000-0000-4000-8000-000000000001"); - const http = HttpClient.make((request) => - Effect.gen(function* () { - if (request.url.endsWith("openid-configuration")) { +const brokerCredentials = { + clientId: "oaiapp_broker", + subject: "broker-user", + idToken: "broker-sign-in", + email: null, + accessToken: "expired-access", + refreshToken: "single-use-refresh" as string | null, + expiresAt: 0, + earliestRefreshAt: null as number | null, + scopes: ["chatgpt.tokens.use.direct"], +}; +const makeRenewalBrokerWith = ( + options: { + /** Saved bytes in place of the default sign-in; null saves nothing. */ + readonly saved?: string | null; + readonly credentials?: Partial; + readonly renewal?: { readonly status: number; readonly body: unknown }; + /** More instances saved with the same sign-in. */ + readonly instances?: ReadonlyArray; + } = {}, +) => + Effect.gen(function* () { + const oauthEntered = yield* Deferred.make(); + const oauthEntries = yield* Queue.unbounded(); + const oauthRelease = yield* Deferred.make(); + let pauseOAuth = false; + const refreshTokens: string[] = []; + const credentials = { ...brokerCredentials, ...options.credentials }; + const environmentId = EnvironmentId.make("00000000-0000-4000-8000-000000000001"); + const http = HttpClient.make((request) => + Effect.gen(function* () { + if (request.url.endsWith("openid-configuration")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ + issuer: "https://auth.openai.com", + authorization_endpoint: "https://auth.openai.com/authorize", + token_endpoint: "https://auth.openai.com/token", + jwks_uri: "https://auth.openai.com/jwks", + }), + ); + } + assert.equal(request.url, "https://auth.openai.com/token"); + assert.equal(request.body._tag, "Uint8Array"); + if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing refresh body"); + const body = new URLSearchParams(new TextDecoder().decode(request.body.body)); + refreshTokens.push(body.get("refresh_token")!); + yield* Deferred.succeed(oauthEntered, undefined); + yield* Queue.offer(oauthEntries, undefined); + // A paused renewal ignores cancellation, like a request already on the wire. + if (pauseOAuth) yield* Deferred.await(oauthRelease).pipe(Effect.uninterruptible); + if (options.renewal) + return HttpClientResponse.fromWeb( + request, + Response.json(options.renewal.body, { status: options.renewal.status }), + ); return HttpClientResponse.fromWeb( request, Response.json({ - issuer: "https://auth.openai.com", - authorization_endpoint: "https://auth.openai.com/authorize", - token_endpoint: "https://auth.openai.com/token", - jwks_uri: "https://auth.openai.com/jwks", + access_token: "renewed-access", + refresh_token: "rotated-refresh", + expires_in: 3600, + token_type: "Bearer", + scope: "chatgpt.tokens.use.direct", }), ); + }), + ); + return yield* Effect.gen(function* () { + const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); + const saved = options.saved === undefined ? JSON.stringify(credentials) : options.saved; + if (saved !== null) yield* store.set(new TextEncoder().encode(saved)); + for (const other of options.instances ?? []) { + const otherStore = yield* ProviderCredentialStore.make("codex-chatgpt", other); + yield* otherStore.set(new TextEncoder().encode(JSON.stringify(credentials))); } - assert.equal(request.url, "https://auth.openai.com/token"); - assert.equal(request.body._tag, "Uint8Array"); - if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing refresh body"); - const body = new URLSearchParams(new TextDecoder().decode(request.body.body)); - refreshTokens.push(body.get("refresh_token")!); - yield* Deferred.succeed(oauthEntered, undefined); - if (pauseOAuth) yield* Deferred.await(oauthRelease); - return HttpClientResponse.fromWeb( - request, - Response.json({ - access_token: "renewed-access", - refresh_token: "rotated-refresh", - expires_in: 3600, - token_type: "Bearer", - scope: "chatgpt.tokens.use.direct", - }), - ); - }), - ); - return yield* Effect.gen(function* () { - const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); - yield* store.set(new TextEncoder().encode(JSON.stringify(credentials))); - const auth = yield* makeCodexChatGptAuth({ instanceId }); - const profileKey = yield* auth.profileKey(credentials); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer((exit) => Scope.close(scope, exit)); - const context = yield* Layer.buildWithScope(CodexManagedTokenBroker.layer, scope); - const broker = Context.get(context, CodexManagedTokenBroker.CodexManagedTokenBroker); - const endpoint = yield* broker.endpoint; - yield* Effect.addFinalizer(() => Deferred.succeed(oauthRelease, undefined)); - return { - auth, - store, - broker, - endpoint, - refreshTokens, - request: { version: 1, instanceId, environmentId, profileKey }, - oauthEntered, - oauthRelease, - pause: () => { - pauseOAuth = true; - }, - }; - }).pipe( - Effect.provide(ServerSecretStore.layer), - Effect.provideService(HttpClient.HttpClient, http), - Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { - getEnvironmentId: Effect.succeed(environmentId), - }), - ); -}); + const auth = yield* makeCodexChatGptAuth({ instanceId }); + const profileKey = yield* auth.profileKey(credentials); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer((exit) => Scope.close(scope, exit)); + const context = yield* Layer.buildWithScope(CodexManagedTokenBroker.layer, scope); + const broker = Context.get(context, CodexManagedTokenBroker.CodexManagedTokenBroker); + const endpoint = yield* broker.endpoint; + yield* Effect.addFinalizer(() => Deferred.succeed(oauthRelease, undefined)); + return { + auth, + store, + broker, + endpoint, + refreshTokens, + request: { version: 1, instanceId, environmentId, profileKey }, + oauthEntered, + oauthEntries, + oauthRelease, + pause: () => { + pauseOAuth = true; + }, + }; + }).pipe( + Effect.provide(ServerSecretStore.layer), + Effect.provideService(HttpClient.HttpClient, http), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(environmentId), + }), + ); + }); +const makeRenewalBroker = makeRenewalBrokerWith(); const brokerClient = (endpoint: string, request: unknown) => Effect.acquireRelease( @@ -1923,7 +1952,9 @@ it.live("the private broker refuses another environment, instance, or sign-in pr Effect.scoped( Effect.gen(function* () { const client = yield* brokerClient(h.endpoint, request); - assert.equal(yield* Effect.promise(() => client.response), ""); + const response = parseBrokerResponse(yield* Effect.promise(() => client.response)); + assert.notProperty(response, "token"); + assert.property(response, "refusal"); }), ), ); @@ -1938,3 +1969,152 @@ it.live("the private broker refuses another environment, instance, or sign-in pr }), ), ); + +const parseBrokerResponse = ( + text: string, +): { token?: string; refusal?: { kind: string; message: string } } => + text === "" ? {} : JSON.parse(text); +const brokerSecrets = (profileKey: string) => [ + brokerCredentials.accessToken, + brokerCredentials.refreshToken!, + brokerCredentials.idToken, + "renewed-access", + "rotated-refresh", + profileKey, +]; +const captureLogs = () => { + const entries: Array<{ level: string; message: unknown }> = []; + const logger = Logger.make(({ logLevel, message }) => { + entries.push({ level: logLevel, message }); + }); + return { entries, layer: Logger.layer([logger], { mergeWithExisting: false }) }; +}; + +it.effect.each([ + { name: "no saved sign-in", kind: "access", options: { saved: null } }, + { name: "a replaced sign-in", kind: "access", request: { profileKey: "0".repeat(64) } }, + { + name: "disabled token sharing", + kind: "sharing", + options: { credentials: { scopes: [] as Array } }, + }, + { + name: "a renewal ChatGPT defers", + kind: "refresh", + options: { credentials: { earliestRefreshAt: 4_102_444_800_000 } }, + }, + { + name: "an expiry with no renewal token", + kind: "refresh", + options: { credentials: { refreshToken: null } }, + }, + { + name: "a failed renewal", + kind: "refresh", + options: { renewal: { status: 500, body: { error: "server_error" } } }, + }, + { + name: "an invalid renewal", + kind: "refresh", + options: { + renewal: { + status: 200, + body: { + access_token: "renewed-access", + expires_in: 3600, + token_type: "Bearer", + scope: "chatgpt.tokens.use.direct", + }, + }, + }, + }, + { name: "an unreadable sign-in", kind: "read", options: { saved: "not json" } }, + { + name: "another environment", + kind: "environment", + unrecorded: true, + request: { environmentId: EnvironmentId.make("00000000-0000-4000-8000-000000000002") }, + }, +] as const)("the private broker tells the helper why it refused $name", (scenario) => { + const logs = captureLogs(); + return provideBroker( + Effect.gen(function* () { + const h = yield* makeRenewalBrokerWith("options" in scenario ? scenario.options : {}); + const request = { ...h.request, ...("request" in scenario ? scenario.request : {}) }; + const client = yield* brokerClient(h.endpoint, request); + const text = yield* Effect.promise(() => client.response); + const response = parseBrokerResponse(text); + assert.equal(response.refusal?.kind, scenario.kind); + assert.notProperty(response, "token"); + yield* h.broker.awaitIdle; + const warnings = logs.entries.filter((entry) => entry.level === "Warn"); + assert.deepInclude( + warnings.flatMap((entry) => (Array.isArray(entry.message) ? entry.message : [])), + { + instanceId, + kind: scenario.kind, + message: response.refusal?.message, + }, + ); + const logged = JSON.stringify(logs.entries); + for (const secret of [...brokerSecrets(h.request.profileKey), request.profileKey]) { + assert.notInclude(text, secret); + assert.notInclude(logged, secret); + } + const recorded = yield* h.broker.recentRefusal(instanceId, request.profileKey); + assert.equal(recorded?.kind, "unrecorded" in scenario ? undefined : scenario.kind); + yield* TestClock.adjust("1 hour"); + assert.isUndefined(yield* h.broker.recentRefusal(instanceId, request.profileKey)); + }), + ).pipe(Effect.provide(logs.layer)); +}); + +it.effect("the private broker refuses a request past its job limit until one succeeds", () => + provideBroker( + Effect.gen(function* () { + const others = Array.from({ length: 15 }, (_, index) => + ProviderInstanceId.make(`managed-codex-busy-${index}`), + ); + const h = yield* makeRenewalBrokerWith({ instances: others }); + h.pause(); + const held = yield* Effect.forEach([instanceId, ...others], (id) => + brokerClient(h.endpoint, { ...h.request, instanceId: id }), + ); + yield* Effect.forEach(held, () => Queue.take(h.oauthEntries)); + const refused = yield* brokerClient(h.endpoint, h.request); + const response = parseBrokerResponse(yield* Effect.promise(() => refused.response)); + assert.equal(response.refusal?.kind, "busy"); + assert.notProperty(response, "token"); + assert.equal((yield* h.broker.recentRefusal(instanceId, h.request.profileKey))?.kind, "busy"); + yield* Deferred.succeed(h.oauthRelease, undefined); + for (const client of held) { + assert.deepEqual(parseBrokerResponse(yield* Effect.promise(() => client.response)), { + token: "renewed-access", + }); + } + yield* h.broker.awaitIdle; + assert.isUndefined(yield* h.broker.recentRefusal(instanceId, h.request.profileKey)); + }), + ), +); + +it.effect("the private broker refuses a request that outlasts the helper's wait", () => + provideBroker( + Effect.gen(function* () { + const h = yield* makeRenewalBroker; + h.pause(); + const client = yield* brokerClient(h.endpoint, h.request); + yield* Deferred.await(h.oauthEntered); + yield* TestClock.adjust(COMMAND_TIMEOUT_MS); + yield* Deferred.succeed(h.oauthRelease, undefined); + const response = parseBrokerResponse(yield* Effect.promise(() => client.response)); + assert.equal(response.refusal?.kind, "timeout"); + assert.notProperty(response, "token"); + yield* h.broker.awaitIdle; + assert.equal( + (yield* h.broker.recentRefusal(instanceId, h.request.profileKey))?.kind, + "timeout", + ); + }), + ), +); diff --git a/apps/server/src/provider/CodexManagedRuntime.ts b/apps/server/src/provider/CodexManagedRuntime.ts index 5fea80bc66b63..165a01df2b09c 100644 --- a/apps/server/src/provider/CodexManagedRuntime.ts +++ b/apps/server/src/provider/CodexManagedRuntime.ts @@ -11,13 +11,15 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime"; import * as CodexInstallation from "./CodexInstallation.ts"; import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; -import { COMMAND_TIMEOUT_MS } from "./CodexManagedTokenProtocol.ts"; +import { COMMAND_TIMEOUT_MS, type Refusal } from "./CodexManagedTokenProtocol.ts"; import { materializeCodexShadowHome } from "./Drivers/CodexHomeLayout.ts"; export interface CodexEffectiveRuntime { readonly config: CodexSettings; readonly environment: NodeJS.ProcessEnv; readonly revision: string; + /** Why T3 last refused this session's token request, for explaining Codex's 401. */ + readonly recentTokenRefusal?: Effect.Effect; } const decodeSettings = Schema.decodeSync(CodexSettings); const managedCodexLaunchArgs = (command: string, args: ReadonlyArray) => @@ -133,6 +135,7 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func }), environment, revision: profileKey, + recentTokenRefusal: broker.recentRefusal(options.instanceId, profileKey), } satisfies CodexEffectiveRuntime; }); return { auth, resolve, installation, homePath, homeLayout }; diff --git a/apps/server/src/provider/CodexManagedTokenBroker.ts b/apps/server/src/provider/CodexManagedTokenBroker.ts index 4a1e861827142..9c2f2b1f4603f 100644 --- a/apps/server/src/provider/CodexManagedTokenBroker.ts +++ b/apps/server/src/provider/CodexManagedTokenBroker.ts @@ -4,8 +4,10 @@ import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeCrypto from "node:crypto"; -import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; +import { EnvironmentId, ProviderInstanceId, ProviderSetupError } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FiberSet from "effect/FiberSet"; @@ -19,6 +21,10 @@ import * as Protocol from "./CodexManagedTokenProtocol.ts"; const MAX_CONNECTIONS = 32; const MAX_JOBS = 16; +const MAX_REFUSALS = 64; +// Codex asks once before its first request, then retries the unauthenticated +// request for a while before it reports the 401. +const RECENT_REFUSAL_MS = 10 * 60_000; // Stay below macOS's 104-byte and Linux's 108-byte sockaddr_un limits, including NUL. const UNIX_SOCKET_PATH_BYTES = 100; const encodeResponse = Schema.encodeSync(Schema.fromJsonString(Protocol.Response)); @@ -37,6 +43,11 @@ export class CodexManagedTokenBroker extends Context.Service< { readonly endpoint: Effect.Effect; readonly awaitIdle: Effect.Effect; + /** The latest refused token request for a sign-in profile, unless a later one succeeded. */ + readonly recentRefusal: ( + instanceId: ProviderInstanceId, + profileKey: string, + ) => Effect.Effect; } >()("t3/provider/CodexManagedTokenBroker") {} @@ -111,8 +122,41 @@ const acquireListener = Effect.gen(function* () { const connections = yield* FiberSet.make(); const runConnection = yield* FiberSet.runtime(connections)(); const sockets = new Set(); + // Sessions launched before a new sign-in keep the old profile, so its refusals stay theirs. + const refusals = new Map(); + const refusalKey = (instanceId: string, profileKey: string) => `${profileKey}:${instanceId}`; let closing = false; let admitted = 0; + const refuse = Effect.fn("CodexManagedTokenBroker.refuse")(function* ( + socket: NodeNet.Socket, + request: { readonly instanceId: ProviderInstanceId; readonly profileKey: string }, + refusal: Protocol.Refusal, + record = true, + ) { + yield* Effect.logWarning("Managed ChatGPT token request refused.", { + instanceId: request.instanceId, + kind: refusal.kind, + message: refusal.message, + }); + if (record) { + const key = refusalKey(request.instanceId, request.profileKey); + refusals.delete(key); + refusals.set(key, { ...refusal, at: yield* Clock.currentTimeMillis }); + if (refusals.size > MAX_REFUSALS) refusals.delete(refusals.keys().next().value!); + } + yield* Protocol.writeFrame(socket, encodeResponse({ refusal }), Protocol.RESPONSE_BYTES).pipe( + Effect.ignore, + ); + }); + const recentRefusal = Effect.fn("CodexManagedTokenBroker.recentRefusal")(function* ( + instanceId: ProviderInstanceId, + profileKey: string, + ) { + const refusal = refusals.get(refusalKey(instanceId, profileKey)); + if (refusal === undefined) return undefined; + if ((yield* Clock.currentTimeMillis) - refusal.at > RECENT_REFUSAL_MS) return undefined; + return { kind: refusal.kind, message: refusal.message }; + }); // Keep branded validation here so the helper need not load the contracts graph. const decode = Schema.decodeUnknownEffect( Schema.fromJsonString( @@ -143,7 +187,28 @@ const acquireListener = Effect.gen(function* () { Protocol.REQUEST_BYTES, Protocol.SOCKET_IDLE_MS, ).pipe(Effect.flatMap(decode)); - if (closing || admitted >= MAX_JOBS || request.environmentId !== environmentId) return; + // Another environment's request says nothing about this environment's instance. + if (request.environmentId !== environmentId) + return yield* refuse( + socket, + request, + { + kind: "environment", + message: + "This Codex session belongs to another T3 Code environment. Start a new session.", + }, + false, + ); + if (closing) + return yield* refuse(socket, request, { + kind: "closing", + message: "T3 Code is shutting down. Start a new session after it restarts.", + }); + if (admitted >= MAX_JOBS) + return yield* refuse(socket, request, { + kind: "busy", + message: "Too many managed ChatGPT token requests are waiting. Try again shortly.", + }); admitted++; transferred = true; runJob( @@ -154,16 +219,23 @@ const acquireListener = Effect.gen(function* () { expectedProfileKey: request.profileKey, }); // Retire abandoned permit waits; access saves a started rotation before honoring interruption. - const credentials = yield* auth.access.pipe( - Effect.timeout(Protocol.COMMAND_TIMEOUT_MS), - ); - yield* Protocol.writeFrame( - socket, - encodeResponse({ token: credentials.accessToken }), - Protocol.RESPONSE_BYTES, - ); + return yield* auth.access.pipe(Effect.timeout(Protocol.COMMAND_TIMEOUT_MS)); }), ).pipe( + Effect.matchCauseEffect({ + onSuccess: (credentials) => { + refusals.delete(refusalKey(request.instanceId, request.profileKey)); + return Protocol.writeFrame( + socket, + encodeResponse({ token: credentials.accessToken }), + Protocol.RESPONSE_BYTES, + ); + }, + onFailure: (cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause) + : refuse(socket, request, refusalFromCause(cause)), + }), Effect.ignoreCause, Effect.ensuring( Effect.sync(() => { @@ -205,8 +277,24 @@ const acquireListener = Effect.gen(function* () { return Effect.sync(() => server.off("error", onError)); }); if (platform !== "win32") yield* io(() => NodeFSP.chmod(owned.endpoint, 0o600)); - return { endpoint: owned.endpoint, awaitIdle: FiberSet.awaitEmpty(jobs) }; + return { endpoint: owned.endpoint, awaitIdle: FiberSet.awaitEmpty(jobs), recentRefusal }; }); +const isSetupError = Schema.is(ProviderSetupError); +const refusalFromCause = (cause: Cause.Cause): Protocol.Refusal => { + const error = Cause.squash(cause); + if (Cause.isTimeoutError(error)) + return { + kind: "timeout", + message: "Timed out waiting for the managed ChatGPT connection. Try again.", + }; + // Setup failures carry safe, actionable text; anything else could carry token data. + if (isSetupError(error) && error.operation.length > 0 && error.detail.length > 0) + return { kind: error.operation.slice(0, 64), message: error.detail.slice(0, 1024) }; + return { + kind: "failed", + message: "Could not access the managed ChatGPT connection. Reconnect in T3 Code.", + }; +}; const make = Effect.gen(function* () { const scope = yield* Scope.fork(yield* Effect.scope); const acquired = yield* acquireListener.pipe(Scope.provide(scope), Effect.result); @@ -215,11 +303,13 @@ const make = Effect.gen(function* () { return CodexManagedTokenBroker.of({ endpoint: Effect.fail(acquired.failure), awaitIdle: Effect.void, + recentRefusal: Effect.fn("CodexManagedTokenBroker.recentRefusal")(() => Effect.undefined), }); } return CodexManagedTokenBroker.of({ endpoint: Effect.succeed(acquired.success.endpoint), awaitIdle: acquired.success.awaitIdle, + recentRefusal: acquired.success.recentRefusal, }); }); export const layer = Layer.effect(CodexManagedTokenBroker, make); diff --git a/apps/server/src/provider/CodexManagedTokenProtocol.ts b/apps/server/src/provider/CodexManagedTokenProtocol.ts index d5f9e610d2188..dc7ca092a17f2 100644 --- a/apps/server/src/provider/CodexManagedTokenProtocol.ts +++ b/apps/server/src/provider/CodexManagedTokenProtocol.ts @@ -9,7 +9,16 @@ export const Request = Schema.Struct({ environmentId: Schema.NonEmptyString, profileKey: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u)), }); -export const Response = Schema.Struct({ token: Schema.NonEmptyString }); +// Messages are safe setup text that Codex shows in its own diagnostics. +export const Refusal = Schema.Struct({ + kind: Schema.NonEmptyString.check(Schema.isMaxLength(64)), + message: Schema.NonEmptyString.check(Schema.isMaxLength(1024)), +}); +export type Refusal = typeof Refusal.Type; +export const Response = Schema.Union([ + Schema.Struct({ token: Schema.NonEmptyString }), + Schema.Struct({ refusal: Refusal }), +]); // Selectors are small; tokens can be larger JWTs. Never truncate either frame // into something that could be accepted. export const REQUEST_BYTES = 1024; From 0c5abe3a19150fd2de7d824351ffb4bff1777f19 Mon Sep 17 00:00:00 2001 From: Matthew Cosier Date: Tue, 24 Nov 2026 15:03:08 +1100 Subject: [PATCH 2/6] fix(server): managed Codex 401s keep the right session's reason A managed Codex 401 was explained with any refusal recorded for the same sign-in, even when another session was refused or the 401 came from a token that was sent and then rejected. A turn that Codex completed with a generic code lost the reason its retries had shown, and a slow token request timed out in the helper before the broker's timeout reason arrived. - Each Codex session passes its own key to the token command, and the broker keeps refusals per session, cleared only when that session receives a token. - Only a 401 that shows Codex sent no credentials is explained. Once a turn's 401 is explained, its later error items for the same failure keep the reason whatever code Codex completes with. - The broker answers a slow request after three quarters of the shared wait, so the helper hears the timeout reason. A renewal already in flight finishes and saves on its own, so the next request succeeds without spending the refresh token again. Co-Authored-By: Claude Opus 5.5 --- .../src/cli/managedChatGptToken.test.ts | 9 +- apps/server/src/cli/managedChatGptToken.ts | 8 +- .../Adapters/CodexAdapterV2.test.ts | 319 +++++++++++------- .../Adapters/CodexAdapterV2.ts | 66 ++-- .../src/provider/CodexChatGptAuth.test.ts | 32 +- .../src/provider/CodexManagedRuntime.test.ts | 144 +++++++- .../src/provider/CodexManagedRuntime.ts | 7 +- .../provider/CodexManagedTokenBroker.test.ts | 224 ++++++++++++ .../src/provider/CodexManagedTokenBroker.ts | 92 +++-- .../src/provider/CodexManagedTokenProtocol.ts | 2 + 10 files changed, 709 insertions(+), 194 deletions(-) create mode 100644 apps/server/src/provider/CodexManagedTokenBroker.test.ts diff --git a/apps/server/src/cli/managedChatGptToken.test.ts b/apps/server/src/cli/managedChatGptToken.test.ts index ef2935e29daf2..2a72d675856ff 100644 --- a/apps/server/src/cli/managedChatGptToken.test.ts +++ b/apps/server/src/cli/managedChatGptToken.test.ts @@ -11,6 +11,7 @@ import { vi } from "vite-plus/test"; import { runManagedChatGptTokenCli } from "./managedChatGptToken.ts"; const profileKey = "a".repeat(64); +const sessionKey = "b".repeat(32); const refusal = { kind: "refresh", message: "Your ChatGPT connection expired. Sign in again." }; /** Runs the helper against a fake broker that sends `answer`, or closes when it is null. */ @@ -55,7 +56,13 @@ const runAgainst = (answer: string | null) => () => Effect.sync(() => vi.restoreAllMocks()), ); yield* Effect.promise(() => - runManagedChatGptTokenCli([endpoint, "codex-managed", "environment-1", profileKey]), + runManagedChatGptTokenCli([ + endpoint, + "codex-managed", + "environment-1", + profileKey, + sessionKey, + ]), ); return { stdout: stdout.join(""), stderr: stderr.join(""), exitCode: process.exitCode }; }).pipe(Effect.scoped); diff --git a/apps/server/src/cli/managedChatGptToken.ts b/apps/server/src/cli/managedChatGptToken.ts index 29650f1f622c8..5a258275f1f9f 100644 --- a/apps/server/src/cli/managedChatGptToken.ts +++ b/apps/server/src/cli/managedChatGptToken.ts @@ -11,6 +11,7 @@ const decodeArguments = Schema.decodeUnknownEffect( Protocol.Request.fields.instanceId, Protocol.Request.fields.environmentId, Protocol.Request.fields.profileKey, + Protocol.Request.fields.sessionKey, ]), ); const encodeRequest = Schema.encodeSync(Schema.fromJsonString(Protocol.Request)); @@ -21,14 +22,17 @@ const decodeResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(Protocol /** Codex's auth.command protocol is a bare token on stdout, never a CLI diagnostic. */ export async function runManagedChatGptTokenCli(args: ReadonlyArray): Promise { const program = Effect.gen(function* () { - const [endpoint, instanceId, environmentId, profileKey] = yield* decodeArguments(args); + const [endpoint, instanceId, environmentId, profileKey, sessionKey] = + yield* decodeArguments(args); const socket = yield* Effect.acquireRelease( Effect.sync(() => NodeNet.createConnection(endpoint)), (socket) => Effect.sync(() => socket.destroy()), ); socket.on("error", () => {}); socket.once("connect", () => - socket.write(encodeRequest({ version: 1, instanceId, environmentId, profileKey }) + "\n"), + socket.write( + encodeRequest({ version: 1, instanceId, environmentId, profileKey, sessionKey }) + "\n", + ), ); return yield* Protocol.readFrame( socket, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 1b452f6ae0945..b93ba214b1d55 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8959,136 +8959,209 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); // Codex sends requests without credentials after T3 refuses its managed token request. + const uncredentialedStream = + "unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: wss://api.openai.com/v1/responses, cf-ray: 0000-SYD, request id: req_stream"; + const uncredentialedRequest = + "unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses, cf-ray: 0000-SYD, request id: req_http"; + const revokedToken = + "unexpected status 401 Unauthorized: Your authentication token has been invalidated. Please try signing in again., url: https://api.openai.com/v1/responses, request id: req_revoked"; + const serverError = + "unexpected status 500 Internal Server Error, url: https://api.openai.com/v1/responses, request id: req_500"; + const tokenRefusalRetry = { + message: "Reconnecting... 1/5", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 401 } }, + additionalDetails: uncredentialedStream, + }; + const tokenRefusalFinal = { + message: uncredentialedRequest, + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + }; it.effect.each([ - { name: "a managed 401 notice", managed: true, notification: true, explained: true }, - { name: "a managed 401 completion", managed: true, notification: false, explained: true }, - { name: "a managed 401 retry", managed: true, retry: true, explained: true }, - { name: "an unrefused managed 401", managed: true, unrefused: true, explained: false }, - { name: "a managed 503", managed: true, status: 503, explained: false }, - { name: "a local Codex 401", managed: false, explained: false }, - ] as const)("explains $name with the managed token refusal", (scenario) => - Effect.gen(function* () { - const nativeThreadId = `native-token-refusal-${scenario.name}`; - const nativeTurnId = `turn-token-refusal-${scenario.name}`; - const status = "status" in scenario ? scenario.status : 401; - const nativeMessage = `unexpected status ${status}: Missing authentication header, url: https://api.openai.com/v1/responses`; - const errorInfo = - "retry" in scenario - ? { responseTooManyFailedAttempts: { httpStatusCode: status } } - : { httpConnectionFailed: { httpStatusCode: status } }; - const refusal = { - kind: "refresh", - message: "Your ChatGPT connection expired. Sign in again.", - }; - const notification = "notification" in scenario ? scenario.notification : true; - const transcript = makeCodexReplayTranscript({ - scenario: `codex-token-refusal-${scenario.name}`, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), - ...("retry" in scenario - ? [ - { - type: "emit_inbound" as const, - label: "error/retry", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: true, - error: { - message: "Reconnecting... 1/5", - codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: status } }, - additionalDetails: nativeMessage, - }, - }, - }, - }, - ] - : []), - ...(notification - ? [ - { - type: "emit_inbound" as const, - label: "error", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: false, - error: { message: nativeMessage, codexErrorInfo: errorInfo }, - }, + { + name: "a retried and final uncredentialed 401", + retry: true, + final: tokenRefusalFinal, + completion: tokenRefusalFinal, + explained: true, + }, + { + name: "a final uncredentialed 401 that completes as other", + retry: true, + final: tokenRefusalFinal, + completion: { message: uncredentialedRequest, codexErrorInfo: "other" }, + explained: true, + }, + { + name: "a retried uncredentialed 401 that completes as other", + retry: true, + completion: { message: uncredentialedStream, codexErrorInfo: "other" }, + explained: true, + }, + { + name: "a retried uncredentialed 401 that completes without an error", + retry: true, + explained: true, + }, + { name: "an uncredentialed 401 completion", completion: tokenRefusalFinal, explained: true }, + { + name: "a revoked token 401", + final: { + message: revokedToken, + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + }, + completion: { + message: revokedToken, + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + }, + explained: false, + }, + { + name: "a retried uncredentialed 401 that ends in another failure", + retry: true, + completion: { message: serverError, codexErrorInfo: "other" }, + explained: false, + retryExplained: true, + }, + { + name: "an unrefused managed 401", + final: tokenRefusalFinal, + completion: tokenRefusalFinal, + unrefused: true, + explained: false, + }, + { + name: "a managed 503", + final: { + message: serverError.replace("500 Internal Server Error", "503 Service Unavailable"), + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 503 } }, + }, + completion: { + message: serverError.replace("500 Internal Server Error", "503 Service Unavailable"), + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 503 } }, + }, + explained: false, + }, + { + name: "a local Codex 401", + final: tokenRefusalFinal, + completion: tokenRefusalFinal, + local: true, + explained: false, + }, + ] as const)( + "explains $name with the managed token refusal only when it is the cause", + (scenario) => + Effect.gen(function* () { + const nativeThreadId = `native-token-refusal-${scenario.name}`; + const nativeTurnId = `turn-token-refusal-${scenario.name}`; + const refusal = { + kind: "refresh", + message: "Your ChatGPT connection expired. Sign in again.", + }; + const notice = (willRetry: boolean, error: object) => ({ + type: "emit_inbound" as const, + label: willRetry ? "error/retry" : "error", + frame: { + method: "error", + params: { threadId: nativeThreadId, turnId: nativeTurnId, willRetry, error }, + }, + }); + const transcript = makeCodexReplayTranscript({ + scenario: `codex-token-refusal-${scenario.name}`, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + ...("retry" in scenario ? [notice(true, tokenRefusalRetry)] : []), + ...("final" in scenario ? [notice(false, scenario.final)] : []), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), + ...("completion" in scenario ? { error: scenario.completion } : {}), }, }, - ] - : []), - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), - error: { message: nativeMessage, codexErrorInfo: errorInfo }, - }, }, }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness( - transcript, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - scenario.managed - ? Effect.succeed({ - config: DEFAULT_CODEX_SETTINGS, - environment: {}, - revision: "managed-profile", - recentTokenRefusal: Effect.succeed("unrefused" in scenario ? undefined : refusal), - }) - : undefined, - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - text: "Continue.", - attemptId: RunAttemptId.make(`attempt-token-refusal-${scenario.name}`), - }), - ); - yield* harness.firstTerminal; - const terminal = harness.terminalEvents()[0]; - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - if (scenario.explained) { - assert.equal(terminal.failure.code, `managed_token_${refusal.kind}`); - assert.include(terminal.failure.message, refusal.message); - assert.include(terminal.failure.message, nativeMessage); - } else { - assert.equal(terminal.failure.code, "httpConnectionFailed"); - assert.equal(terminal.failure.message, nativeMessage); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + ], + }); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + "local" in scenario + ? undefined + : Effect.succeed({ + config: DEFAULT_CODEX_SETTINGS, + environment: {}, + revision: "managed-profile", + recentTokenRefusal: Effect.succeed("unrefused" in scenario ? undefined : refusal), + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-token-refusal-${scenario.name}`), + }), + ); + yield* harness.firstTerminal; + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + const explainedCode = `managed_token_${refusal.kind}`; + const codexError = + "completion" in scenario + ? scenario.completion + : "final" in scenario + ? scenario.final + : undefined; + if (scenario.explained) { + assert.equal(terminal.failure.code, explainedCode); + assert.include(terminal.failure.message, refusal.message); + // Codex's own report stays visible. + assert.include(terminal.failure.message, "unexpected status 401 Unauthorized"); + } else { + const info = codexError?.codexErrorInfo; + assert.equal( + terminal.failure.code, + typeof info === "string" ? info : Object.keys(info ?? {})[0], + ); + assert.notInclude(terminal.failure.message, refusal.message); + } + // Every error row the turn shows for an explained 401 carries the same reason. + const errorItemCodes = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? [event.turnItem.failure.code] + : [], + ); + const retryExplained = "retryExplained" in scenario || scenario.explained; + for (const code of errorItemCodes) { + if (retryExplained) assert.equal(code, explainedCode); + else assert.notEqual(code, explainedCode); + } + if ("retry" in scenario) assert.isNotEmpty(errorItemCodes); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); // regression: #17501 Codex 429 retry exhaustion classifies as a usage limit diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f3214c2a591b4..2f3f269fd0002 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1421,6 +1421,9 @@ function withCodexManagedFailure( }; } +/** Codex's report of a request it sent without credentials. A sent token that fails says otherwise. */ +const UNCREDENTIALED_REQUEST = /missing bearer or basic authentication/iu; + /** * Codex sends requests without credentials after T3 refuses its managed token * request, so the 401 it reports hides the refusal that caused it. @@ -1459,6 +1462,8 @@ interface ActiveCodexTurnContext { capacityRetryPending?: Deferred.Deferred; closedCommandItemIds?: ReadonlySet; recoveredProviderRetries?: number; + /** The managed token refusal that explained this turn's request sent without credentials. */ + tokenRefusal?: Refusal; latestProviderFailure?: { readonly nativeMessage: string; readonly nativeCode: string | null; @@ -2173,16 +2178,23 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( environment: resolvedRuntime?.environment ?? adapterOptions.environment, }); const codexZone = codexTimeZone(resolvedRuntime?.environment ?? adapterOptions.environment); - const explainTokenRefusal = ( + // This session's refusal explains only a 401 Codex sent without credentials. The + // turn's later reports of that failure keep the reason, whatever code they carry. + const explainTokenRefusal = Effect.fnUntraced(function* ( + context: ActiveCodexTurnContext, failure: OrchestrationV2ProviderFailure, errorInfo: CodexErrorInfo | null | undefined, - ) => - resolvedRuntime?.recentTokenRefusal === undefined || - codexErrorHttpStatus(errorInfo) !== 401 - ? Effect.succeed(failure) - : resolvedRuntime.recentTokenRefusal.pipe( - Effect.map((refusal) => withManagedTokenRefusal(failure, refusal)), - ); + nativeText: string, + ) { + const recentTokenRefusal = resolvedRuntime?.recentTokenRefusal; + if (recentTokenRefusal === undefined || !UNCREDENTIALED_REQUEST.test(nativeText)) + return failure; + if (context.tokenRefusal === undefined && codexErrorHttpStatus(errorInfo) === 401) { + const refusal = yield* recentTokenRefusal; + if (refusal !== undefined) context.tokenRefusal = refusal; + } + return withManagedTokenRefusal(failure, context.tokenRefusal); + }); const additionalContextByThread = yield* Ref.make( new Map>(), ); @@ -5492,6 +5504,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ? {} : { errorInfo: payload.error.codexErrorInfo }), failure: yield* explainTokenRefusal( + context, withCodexManagedFailure( makeProviderFailure({ message: payload.error.additionalDetails?.trim() || payload.error.message, @@ -5504,6 +5517,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload.error, ), payload.error.codexErrorInfo, + `${payload.error.message}\n${payload.error.additionalDetails ?? ""}`, ), }; return; @@ -5520,6 +5534,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const code = codexErrorInfoCode(payload.error.codexErrorInfo); const additionalDetails = payload.error.additionalDetails?.trim(); const failure = yield* explainTokenRefusal( + context, withCodexManagedFailure( makeProviderFailure({ message: @@ -5538,6 +5553,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload.error, ), payload.error.codexErrorInfo, + `${payload.error.message}\n${payload.error.additionalDetails ?? ""}`, ); const itemOrdinal = previous?.itemOrdinal ?? @@ -6695,24 +6711,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const completionHasClass = failureCode != null && !codexTerminalErrorNeedsEvidence(input.failureErrorInfo, failureCode); - let failure = + const reused = previousFailure !== undefined && (input.failureMessage === undefined || input.failureMessage === previousFailure.nativeMessage) && (failureCode === undefined || failureCode === previousFailure.nativeCode) && - (!completionHasClass || previousFailure.failure.class === failureClass) - ? previousFailure.failure - : yield* explainTokenRefusal( - withCodexManagedFailure( - makeProviderFailure({ - message: input.failureMessage, - code: failureCode, - class: failureClass, - }), - input.failureMessage, - ), - input.failureErrorInfo, - ); + (!completionHasClass || previousFailure.failure.class === failureClass); + let failure = reused + ? previousFailure.failure + : withCodexManagedFailure( + makeProviderFailure({ + message: input.failureMessage, + code: failureCode, + class: failureClass, + }), + input.failureMessage, + ); const retry = input.providerRetry; const notification = input.context.latestProviderFailure; // Codex 0.164 reports an exhausted stream error as `other` with the same details. @@ -6735,6 +6749,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { failure = { ...failure, class: "transport_error" }; } + // A reused report was explained when Codex first sent it. + if (!reused) + failure = yield* explainTokenRefusal( + input.context, + failure, + input.failureErrorInfo, + input.failureMessage ?? "", + ); const failureItemId = codexFailureItemId(input.context); return { type: "turn.terminal", diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 40f21d2db22d6..db97664442490 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -1863,7 +1863,7 @@ const makeRenewalBrokerWith = ( broker, endpoint, refreshTokens, - request: { version: 1, instanceId, environmentId, profileKey }, + request: { version: 1, instanceId, environmentId, profileKey, sessionKey: "5e".repeat(16) }, oauthEntered, oauthEntries, oauthRelease, @@ -2061,10 +2061,16 @@ it.effect.each([ assert.notInclude(text, secret); assert.notInclude(logged, secret); } - const recorded = yield* h.broker.recentRefusal(instanceId, request.profileKey); + const recorded = yield* h.broker.recentRefusal( + instanceId, + request.profileKey, + request.sessionKey, + ); assert.equal(recorded?.kind, "unrecorded" in scenario ? undefined : scenario.kind); yield* TestClock.adjust("1 hour"); - assert.isUndefined(yield* h.broker.recentRefusal(instanceId, request.profileKey)); + assert.isUndefined( + yield* h.broker.recentRefusal(instanceId, request.profileKey, request.sessionKey), + ); }), ).pipe(Effect.provide(logs.layer)); }); @@ -2085,7 +2091,11 @@ it.effect("the private broker refuses a request past its job limit until one suc const response = parseBrokerResponse(yield* Effect.promise(() => refused.response)); assert.equal(response.refusal?.kind, "busy"); assert.notProperty(response, "token"); - assert.equal((yield* h.broker.recentRefusal(instanceId, h.request.profileKey))?.kind, "busy"); + assert.equal( + (yield* h.broker.recentRefusal(instanceId, h.request.profileKey, h.request.sessionKey)) + ?.kind, + "busy", + ); yield* Deferred.succeed(h.oauthRelease, undefined); for (const client of held) { assert.deepEqual(parseBrokerResponse(yield* Effect.promise(() => client.response)), { @@ -2093,26 +2103,30 @@ it.effect("the private broker refuses a request past its job limit until one suc }); } yield* h.broker.awaitIdle; - assert.isUndefined(yield* h.broker.recentRefusal(instanceId, h.request.profileKey)); + assert.isUndefined( + yield* h.broker.recentRefusal(instanceId, h.request.profileKey, h.request.sessionKey), + ); }), ), ); -it.effect("the private broker refuses a request that outlasts the helper's wait", () => +it.effect("the private broker refuses a request that outlasts the helper's wait in time", () => provideBroker( Effect.gen(function* () { const h = yield* makeRenewalBroker; h.pause(); const client = yield* brokerClient(h.endpoint, h.request); yield* Deferred.await(h.oauthEntered); - yield* TestClock.adjust(COMMAND_TIMEOUT_MS); - yield* Deferred.succeed(h.oauthRelease, undefined); + // Codex starts its wait before the helper starts and reaches the broker. + yield* TestClock.adjust(COMMAND_TIMEOUT_MS - 20_000); const response = parseBrokerResponse(yield* Effect.promise(() => client.response)); assert.equal(response.refusal?.kind, "timeout"); assert.notProperty(response, "token"); + yield* Deferred.succeed(h.oauthRelease, undefined); yield* h.broker.awaitIdle; assert.equal( - (yield* h.broker.recentRefusal(instanceId, h.request.profileKey))?.kind, + (yield* h.broker.recentRefusal(instanceId, h.request.profileKey, h.request.sessionKey)) + ?.kind, "timeout", ); }), diff --git a/apps/server/src/provider/CodexManagedRuntime.test.ts b/apps/server/src/provider/CodexManagedRuntime.test.ts index 2c697f8fa8531..d679871b09887 100644 --- a/apps/server/src/provider/CodexManagedRuntime.test.ts +++ b/apps/server/src/provider/CodexManagedRuntime.test.ts @@ -20,7 +20,7 @@ import * as ServerConfig from "../config.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as CodexInstallation from "./CodexInstallation.ts"; -import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts"; +import { makeCodexManagedRuntime, type CodexEffectiveRuntime } from "./CodexManagedRuntime.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; import { codexAppServerArgs } from "./codexLaunchArgs.ts"; @@ -277,3 +277,145 @@ it.live.each( ), ), ); + +it.live("a refused token request explains only the Codex session that asked for it", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("codex"); + const fs = yield* FileSystem.FileSystem; + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-session-refusal-" }); + const data = new Map(); + let renewalStatus = 200; + const executable = { + executablePath: "/isolated/tools/codex/0.156.1/bin/codex", + managedVersionDirectory: "/isolated/tools/codex/0.156.1", + source: "managed" as const, + version: "0.156.1", + }; + yield* Effect.gen(function* () { + const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); + const credentials = { + clientId: "oaiapp_test", + accessToken: "dummy-owned-access", + refreshToken: "dummy-refresh", + expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000, + earliestRefreshAt: null, + scopes: ["chatgpt.tokens.use.direct"], + subject: "test-user", + email: null, + }; + yield* store.set(new TextEncoder().encode(yield* encodeJson(credentials))); + const hostEnv = yield* HostProcess.Environment; + const runtime = yield* makeCodexManagedRuntime({ + instanceId, + enabled: true, + config: decodeSettings({ setupMode: "managed", homePath: sharedHome }), + environment: { PATH: hostEnv.PATH, SystemRoot: hostEnv.SystemRoot }, + }); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // Runs the token command Codex was given, as Codex does before a request. + const askForToken = (effective: CodexEffectiveRuntime) => + Effect.gen(function* () { + const provider = codexAppServerArgs(effective.config.launchArgs).find((arg) => + arg.startsWith("model_providers.openai_token_sharing="), + )!; + const match = /auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u.exec(provider)!; + const [command, args] = decodeCommand(`[${match[1]},${match[2]}]`); + const child = yield* spawner.spawn( + ChildProcess.make(command, args, { extendEnv: false, env: effective.environment }), + ); + const [stdout, code] = yield* Effect.all( + [child.stdout.pipe(Stream.decodeText(), Stream.mkString), child.exitCode], + { concurrency: "unbounded" }, + ); + return { stdout, code: Number(code) }; + }).pipe(Effect.scoped); + yield* Effect.gen(function* () { + const first = yield* runtime.resolve; + const second = yield* runtime.resolve; + assert.deepEqual(yield* askForToken(first), { stdout: "dummy-owned-access", code: 0 }); + + // The second session's renewal fails while the first already has its token. + yield* store.set( + new TextEncoder().encode(yield* encodeJson({ ...credentials, expiresAt: 0 })), + ); + renewalStatus = 500; + assert.deepEqual(yield* askForToken(second), { stdout: "", code: 1 }); + assert.equal((yield* second.recentTokenRefusal!)?.kind, "refresh"); + assert.isUndefined(yield* first.recentTokenRefusal!); + + // The first session renews; the second session's refusal is still its own reason. + renewalStatus = 200; + assert.deepEqual(yield* askForToken(first), { stdout: "renewed-access", code: 0 }); + assert.isUndefined(yield* first.recentTokenRefusal!); + assert.equal((yield* second.recentTokenRefusal!)?.kind, "refresh"); + }).pipe(Effect.scoped); + }).pipe( + Effect.provide(CodexManagedTokenBroker.layer), + Effect.provideService(HostProcess.Arguments, [ + process.execPath, + NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)), + ]), + Effect.provideService( + ServerSecretStore.ServerSecretStore, + ServerSecretStore.ServerSecretStore.of({ + get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))), + set: (key, value) => + Effect.sync(() => { + data.set(key, value); + }), + remove: (key) => + Effect.sync(() => { + data.delete(key); + }), + create: () => Effect.die("unused"), + getOrCreateRandom: () => Effect.die("unused"), + }), + ), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed( + EnvironmentId.make("00000000-0000-4000-8000-000000000001"), + ), + }), + Effect.provide( + Layer.mock(CodexInstallation.CodexInstallation)({ + managedDirectory: "/isolated/tools/codex", + resolve: () => Effect.succeed(executable), + acquire: () => Effect.succeed(executable), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => + HttpClientResponse.fromWeb( + request, + !request.url.endsWith("/token") + ? Response.json({ + issuer: "https://auth.openai.com", + authorization_endpoint: "https://auth.openai.com/api/accounts/authorize", + token_endpoint: "https://auth.openai.com/api/accounts/oauth/token", + jwks_uri: "https://auth.openai.com/jwks", + }) + : renewalStatus === 200 + ? Response.json({ + access_token: "renewed-access", + refresh_token: "renewed-refresh", + token_type: "Bearer", + expires_in: 3600, + scope: "chatgpt.tokens.use.direct", + }) + : Response.json({ error: "server_error" }, { status: renewalStatus }), + ), + ), + ), + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-managed-session-refusal-" }).pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); diff --git a/apps/server/src/provider/CodexManagedRuntime.ts b/apps/server/src/provider/CodexManagedRuntime.ts index 165a01df2b09c..af8303a88193c 100644 --- a/apps/server/src/provider/CodexManagedRuntime.ts +++ b/apps/server/src/provider/CodexManagedRuntime.ts @@ -1,6 +1,8 @@ import { resolveManagedCodexHomeLayout } from "./CodexManagedHome.ts"; import { CodexSettings, ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -47,6 +49,7 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker; const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity; const environmentId = yield* environmentIdentity.getEnvironmentId; + const random = yield* SecureRandom.SecureRandom; const invocation = yield* resolveSelfInvocation(); const auth = yield* makeCodexChatGptAuth({ instanceId: options.instanceId, @@ -87,12 +90,14 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func ); const credentials = yield* auth.access; const profileKey = yield* auth.profileKey(credentials); + const sessionKey = Hex.encode(yield* random.randomBytes(16)); const authArgs = selfInvocationArgs(invocation, [ "__managed-chatgpt-token", endpoint, options.instanceId, environmentId, profileKey, + sessionKey, ]); yield* materializeCodexShadowHome(homeLayout).pipe( Effect.provideService(FileSystem.FileSystem, fs), @@ -135,7 +140,7 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func }), environment, revision: profileKey, - recentTokenRefusal: broker.recentRefusal(options.instanceId, profileKey), + recentTokenRefusal: broker.recentRefusal(options.instanceId, profileKey, sessionKey), } satisfies CodexEffectiveRuntime; }); return { auth, resolve, installation, homePath, homeLayout }; diff --git a/apps/server/src/provider/CodexManagedTokenBroker.test.ts b/apps/server/src/provider/CodexManagedTokenBroker.test.ts new file mode 100644 index 0000000000000..0d9f6e91339f1 --- /dev/null +++ b/apps/server/src/provider/CodexManagedTokenBroker.test.ts @@ -0,0 +1,224 @@ +// @effect-diagnostics nodeBuiltinImport:off - The helper reaches the broker over its private socket. +import * as NodeURL from "node:url"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientResponse } from "effect/http"; +import { vi } from "vite-plus/test"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { runManagedChatGptTokenCli } from "../cli/managedChatGptToken.ts"; +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as CodexInstallation from "./CodexInstallation.ts"; +import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts"; +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; +import type * as Protocol from "./CodexManagedTokenProtocol.ts"; +import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; +import { codexAppServerArgs } from "./codexLaunchArgs.ts"; + +// Codex, the helper and the broker share one wait. A short one runs the race in real time. +vi.mock("./CodexManagedTokenProtocol.ts", async (importOriginal) => ({ + ...(await importOriginal()), + COMMAND_TIMEOUT_MS: 2_000, +})); + +const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); +const decodeSettings = Schema.decodeSync(CodexSettings); +const decodeCommand = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Array(Schema.String)])), +); + +/** Runs the token command in this process, so it waits as long as the broker expects. */ +const runHelper = (args: ReadonlyArray) => + Effect.gen(function* () { + const stdout: string[] = []; + const stderr: string[] = []; + const exitCode = process.exitCode; + yield* Effect.acquireRelease( + Effect.sync(() => { + vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { + stdout.push(String(chunk)); + return true; + }); + vi.spyOn(process.stderr, "write").mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); + }), + () => + Effect.sync(() => { + vi.restoreAllMocks(); + process.exitCode = exitCode; + }), + ); + yield* Effect.promise(() => runManagedChatGptTokenCli(args)); + return { stdout: stdout.join(""), stderr: stderr.join(""), exitCode: process.exitCode }; + }).pipe(Effect.scoped); + +it.live("the helper hears the broker's timeout and a late renewal still saves", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("codex"); + const initialExitCode = process.exitCode; + const fs = yield* FileSystem.FileSystem; + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-token-timeout-" }); + const data = new Map(); + const renewalEntered = yield* Deferred.make(); + const renewalRelease = yield* Deferred.make(); + const spentRefreshTokens: string[] = []; + const executable = { + executablePath: "/isolated/tools/codex/0.156.1/bin/codex", + managedVersionDirectory: "/isolated/tools/codex/0.156.1", + source: "managed" as const, + version: "0.156.1", + }; + yield* Effect.gen(function* () { + const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); + const credentials = { + clientId: "oaiapp_test", + accessToken: "launch-access", + refreshToken: "single-use-refresh", + expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000, + earliestRefreshAt: null, + scopes: ["chatgpt.tokens.use.direct"], + subject: "test-user", + email: null, + }; + yield* store.set(new TextEncoder().encode(yield* encodeJson(credentials))); + const runtime = yield* makeCodexManagedRuntime({ + instanceId, + enabled: true, + config: decodeSettings({ setupMode: "managed", homePath: sharedHome }), + environment: {}, + }); + const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker; + yield* Effect.gen(function* () { + const effective = yield* runtime.resolve; + const provider = codexAppServerArgs(effective.config.launchArgs).find((arg) => + arg.startsWith("model_providers.openai_token_sharing="), + )!; + const [, args] = decodeCommand( + `[${/auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u + .exec(provider)! + .slice(1, 3) + .join(",")}]`, + ); + const helperArgs = args.slice(args.indexOf("__managed-chatgpt-token") + 1); + + // The token expires, and its renewal is still on the wire when the wait runs out. + yield* store.set( + new TextEncoder().encode(yield* encodeJson({ ...credentials, expiresAt: 0 })), + ); + const timedOut = yield* runHelper(helperArgs); + yield* Deferred.await(renewalEntered); + // The renewal returns once the helper has its answer. + yield* Deferred.succeed(renewalRelease, undefined); + yield* broker.awaitIdle; + assert.deepEqual( + { helper: timedOut, recorded: (yield* effective.recentTokenRefusal!)?.kind }, + { + helper: { + stdout: "", + stderr: "Timed out waiting for the managed ChatGPT connection. Try again.\n", + exitCode: 1, + }, + recorded: "timeout", + }, + ); + + // The renewal that finished after the answer was saved, so the next request needs none. + assert.deepEqual(yield* runHelper(helperArgs), { + stdout: "renewed-access", + stderr: "", + exitCode: initialExitCode, + }); + assert.deepEqual(spentRefreshTokens, ["single-use-refresh"]); + }).pipe(Effect.scoped); + }).pipe( + Effect.provide(CodexManagedTokenBroker.layer), + Effect.provideService(HostProcess.Arguments, [ + process.execPath, + NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)), + ]), + Effect.provideService( + ServerSecretStore.ServerSecretStore, + ServerSecretStore.ServerSecretStore.of({ + get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))), + set: (key, value) => + Effect.sync(() => { + data.set(key, value); + }), + remove: (key) => + Effect.sync(() => { + data.delete(key); + }), + create: () => Effect.die("unused"), + getOrCreateRandom: () => Effect.die("unused"), + }), + ), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed( + EnvironmentId.make("00000000-0000-4000-8000-000000000001"), + ), + }), + Effect.provide( + Layer.mock(CodexInstallation.CodexInstallation)({ + managedDirectory: "/isolated/tools/codex", + resolve: () => Effect.succeed(executable), + acquire: () => Effect.succeed(executable), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + if (!request.url.endsWith("/token")) + return HttpClientResponse.fromWeb( + request, + Response.json({ + issuer: "https://auth.openai.com", + authorization_endpoint: "https://auth.openai.com/api/accounts/authorize", + token_endpoint: "https://auth.openai.com/api/accounts/oauth/token", + jwks_uri: "https://auth.openai.com/jwks", + }), + ); + if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing body"); + spentRefreshTokens.push( + new URLSearchParams(new TextDecoder().decode(request.body.body)).get( + "refresh_token", + )!, + ); + yield* Deferred.succeed(renewalEntered, undefined); + // A renewal on the wire ignores cancellation: ChatGPT may already have spent the token. + yield* Deferred.await(renewalRelease).pipe(Effect.uninterruptible); + return HttpClientResponse.fromWeb( + request, + Response.json({ + access_token: "renewed-access", + refresh_token: "rotated-refresh", + token_type: "Bearer", + expires_in: 3600, + scope: "chatgpt.tokens.use.direct", + }), + ); + }), + ), + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-managed-token-timeout-" }).pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); diff --git a/apps/server/src/provider/CodexManagedTokenBroker.ts b/apps/server/src/provider/CodexManagedTokenBroker.ts index 9c2f2b1f4603f..bec79e478f0df 100644 --- a/apps/server/src/provider/CodexManagedTokenBroker.ts +++ b/apps/server/src/provider/CodexManagedTokenBroker.ts @@ -10,9 +10,11 @@ import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FiberSet from "effect/FiberSet"; import * as Layer from "effect/Layer"; import * as Exit from "effect/Exit"; +import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; @@ -25,6 +27,14 @@ const MAX_REFUSALS = 64; // Codex asks once before its first request, then retries the unauthenticated // request for a while before it reports the 401. const RECENT_REFUSAL_MS = 10 * 60_000; +// Codex and the helper start the same wait before the request arrives. Answering with a +// quarter of it to spare covers the helper's start, and a renewal already on the wire +// (limited to 20 seconds of the 80) still finishes and saves on its own. +const ANSWER_TIMEOUT_MS = (Protocol.COMMAND_TIMEOUT_MS * 3) / 4; +const TIMED_OUT: Protocol.Refusal = { + kind: "timeout", + message: "Timed out waiting for the managed ChatGPT connection. Try again.", +}; // Stay below macOS's 104-byte and Linux's 108-byte sockaddr_un limits, including NUL. const UNIX_SOCKET_PATH_BYTES = 100; const encodeResponse = Schema.encodeSync(Schema.fromJsonString(Protocol.Response)); @@ -43,10 +53,11 @@ export class CodexManagedTokenBroker extends Context.Service< { readonly endpoint: Effect.Effect; readonly awaitIdle: Effect.Effect; - /** The latest refused token request for a sign-in profile, unless a later one succeeded. */ + /** A Codex session's latest refused token request, unless it has had a token since. */ readonly recentRefusal: ( instanceId: ProviderInstanceId, profileKey: string, + sessionKey: string, ) => Effect.Effect; } >()("t3/provider/CodexManagedTokenBroker") {} @@ -122,14 +133,23 @@ const acquireListener = Effect.gen(function* () { const connections = yield* FiberSet.make(); const runConnection = yield* FiberSet.runtime(connections)(); const sockets = new Set(); - // Sessions launched before a new sign-in keep the old profile, so its refusals stay theirs. + // Each Codex session keeps its own refusal: another session's token or refusal says + // nothing about why this one was sent without credentials. const refusals = new Map(); - const refusalKey = (instanceId: string, profileKey: string) => `${profileKey}:${instanceId}`; + const refusalKey = (session: { + readonly instanceId: string; + readonly profileKey: string; + readonly sessionKey: string; + }) => `${session.profileKey}:${session.instanceId}:${session.sessionKey}`; let closing = false; let admitted = 0; const refuse = Effect.fn("CodexManagedTokenBroker.refuse")(function* ( socket: NodeNet.Socket, - request: { readonly instanceId: ProviderInstanceId; readonly profileKey: string }, + request: { + readonly instanceId: ProviderInstanceId; + readonly profileKey: string; + readonly sessionKey: string; + }, refusal: Protocol.Refusal, record = true, ) { @@ -139,7 +159,7 @@ const acquireListener = Effect.gen(function* () { message: refusal.message, }); if (record) { - const key = refusalKey(request.instanceId, request.profileKey); + const key = refusalKey(request); refusals.delete(key); refusals.set(key, { ...refusal, at: yield* Clock.currentTimeMillis }); if (refusals.size > MAX_REFUSALS) refusals.delete(refusals.keys().next().value!); @@ -151,8 +171,9 @@ const acquireListener = Effect.gen(function* () { const recentRefusal = Effect.fn("CodexManagedTokenBroker.recentRefusal")(function* ( instanceId: ProviderInstanceId, profileKey: string, + sessionKey: string, ) { - const refusal = refusals.get(refusalKey(instanceId, profileKey)); + const refusal = refusals.get(refusalKey({ instanceId, profileKey, sessionKey })); if (refusal === undefined) return undefined; if ((yield* Clock.currentTimeMillis) - refusal.at > RECENT_REFUSAL_MS) return undefined; return { kind: refusal.kind, message: refusal.message }; @@ -212,30 +233,36 @@ const acquireListener = Effect.gen(function* () { admitted++; transferred = true; runJob( - Effect.scoped( - Effect.gen(function* () { - const auth = yield* makeCodexChatGptAuth({ - instanceId: request.instanceId, - expectedProfileKey: request.profileKey, - }); - // Retire abandoned permit waits; access saves a started rotation before honoring interruption. - return yield* auth.access.pipe(Effect.timeout(Protocol.COMMAND_TIMEOUT_MS)); - }), - ).pipe( - Effect.matchCauseEffect({ - onSuccess: (credentials) => { - refusals.delete(refusalKey(request.instanceId, request.profileKey)); - return Protocol.writeFrame( - socket, - encodeResponse({ token: credentials.accessToken }), - Protocol.RESPONSE_BYTES, - ); - }, - onFailure: (cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : refuse(socket, request, refusalFromCause(cause)), - }), + Effect.gen(function* () { + const access = yield* Effect.scoped( + Effect.gen(function* () { + const auth = yield* makeCodexChatGptAuth({ + instanceId: request.instanceId, + expectedProfileKey: request.profileKey, + }); + // Retire abandoned permit waits; access saves a started rotation before honoring interruption. + return yield* auth.access.pipe(Effect.timeout(Protocol.COMMAND_TIMEOUT_MS)); + }), + ).pipe(Effect.forkChild); + const answer = yield* Fiber.await(access).pipe(Effect.timeoutOption(ANSWER_TIMEOUT_MS)); + if (Option.isNone(answer)) { + // The session got no token, so its refusal stands even if the renewal then succeeds. + yield* refuse(socket, request, TIMED_OUT); + yield* Fiber.await(access); + return; + } + const result = answer.value; + if (Exit.isSuccess(result)) { + refusals.delete(refusalKey(request)); + return yield* Protocol.writeFrame( + socket, + encodeResponse({ token: result.value.accessToken }), + Protocol.RESPONSE_BYTES, + ); + } + if (!Cause.hasInterruptsOnly(result.cause)) + yield* refuse(socket, request, refusalFromCause(result.cause)); + }).pipe( Effect.ignoreCause, Effect.ensuring( Effect.sync(() => { @@ -282,11 +309,6 @@ const acquireListener = Effect.gen(function* () { const isSetupError = Schema.is(ProviderSetupError); const refusalFromCause = (cause: Cause.Cause): Protocol.Refusal => { const error = Cause.squash(cause); - if (Cause.isTimeoutError(error)) - return { - kind: "timeout", - message: "Timed out waiting for the managed ChatGPT connection. Try again.", - }; // Setup failures carry safe, actionable text; anything else could carry token data. if (isSetupError(error) && error.operation.length > 0 && error.detail.length > 0) return { kind: error.operation.slice(0, 64), message: error.detail.slice(0, 1024) }; diff --git a/apps/server/src/provider/CodexManagedTokenProtocol.ts b/apps/server/src/provider/CodexManagedTokenProtocol.ts index dc7ca092a17f2..bffc3ae099d5f 100644 --- a/apps/server/src/provider/CodexManagedTokenProtocol.ts +++ b/apps/server/src/provider/CodexManagedTokenProtocol.ts @@ -8,6 +8,8 @@ export const Request = Schema.Struct({ instanceId: Schema.NonEmptyString, environmentId: Schema.NonEmptyString, profileKey: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u)), + // Ties a refusal to the Codex session that asked, never to another session's 401. + sessionKey: Schema.String.check(Schema.isPattern(/^[a-f0-9]{32}$/u)), }); // Messages are safe setup text that Codex shows in its own diagnostics. export const Refusal = Schema.Struct({ From 58dd73cd30ea156da906a1862c219a75d203420c Mon Sep 17 00:00:00 2001 From: Matthew Cosier Date: Tue, 24 Nov 2026 15:31:56 +1100 Subject: [PATCH 3/6] fix(server): keep managed Codex refusal reasons accurate across recovery, completion details, and disconnects Three edge cases still caused managed Codex token refusal errors to report the wrong cause or fall back to a generic code: - After a turn recovered and resumed model output, a later uncredentialed 401 reused the turn's cached first refusal instead of reading the current refusal. Clearing the cached refusal on model output ensures each new 401 reads the latest reason. - When Codex completed a failed turn with code other, a short summary, and the uncredentialed 401 only in additionalDetails, the adapter dropped those details and lost the refusal reason. Passing completion additionalDetails to the refusal check preserves the reason and original 401 text. - If a helper disconnected while a token renewal was in flight, the broker deleted the session's recorded refusal before delivering the token frame. Clearing the refusal only after the token frame writes cleanly keeps the refusal intact whenever the helper receives no token. --- .../Adapters/CodexAdapterV2.test.ts | 162 +++++++++++++++ .../Adapters/CodexAdapterV2.ts | 19 +- .../provider/CodexManagedTokenBroker.test.ts | 192 ++++++++++++++++++ .../src/provider/CodexManagedTokenBroker.ts | 5 +- .../src/provider/CodexManagedTokenProtocol.ts | 19 +- 5 files changed, 390 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index b93ba214b1d55..d483d76df67d9 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8997,6 +8997,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { completion: { message: uncredentialedStream, codexErrorInfo: "other" }, explained: true, }, + { + name: "a retried uncredentialed 401 that completes as other with details only", + retry: true, + completion: { + message: "Stream disconnected before completion.", + codexErrorInfo: "other", + additionalDetails: uncredentialedStream, + }, + explained: true, + }, { name: "a retried uncredentialed 401 that completes without an error", retry: true, @@ -9164,6 +9174,158 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect( + "reads the current managed token refusal after model output confirms recovery within a turn", + () => + Effect.gen(function* () { + const nativeThreadId = "native-token-refusal-recovered-turn"; + const nativeTurnId = "turn-token-refusal-recovered-turn"; + const refreshRefusal = { + kind: "refresh", + message: "Your ChatGPT connection expired. Sign in again.", + }; + const timeoutRefusal = { + kind: "timeout", + message: "Timed out waiting for the managed ChatGPT connection. Try again.", + }; + const refusals = [refreshRefusal, timeoutRefusal] as const; + let lookups = 0; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-token-refusal-recovered-turn", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + { + type: "emit_inbound", + label: "error/retry-first", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: tokenRefusalRetry, + }, + }, + }, + { + type: "emit_inbound", + label: "item/started/recovered", + frame: { + method: "item/started", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1782622440500, + item: { + type: "agentMessage", + id: "msg-recovered", + text: "", + phase: "commentary", + memoryCitation: null, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "item/agentMessage/delta/recovered", + frame: { + method: "item/agentMessage/delta", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + itemId: "msg-recovered", + delta: "Working on it.", + }, + }, + }, + { + type: "emit_inbound", + label: "error/retry-second", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: tokenRefusalRetry, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), + error: tokenRefusalFinal, + }, + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + Effect.succeed({ + config: DEFAULT_CODEX_SETTINGS, + environment: {}, + revision: "managed-profile", + recentTokenRefusal: Effect.sync( + () => refusals[Math.min(lookups++, refusals.length - 1)], + ), + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make("attempt-token-refusal-recovered-turn"), + }), + ); + yield* harness.firstTerminal; + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.failure.code, "managed_token_timeout"); + assert.include(terminal.failure.message, timeoutRefusal.message); + assert.notInclude(terminal.failure.message, refreshRefusal.message); + const errorItems = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? [{ status: event.turnItem.status, code: event.turnItem.failure.code }] + : [], + ); + assert.deepEqual(errorItems, [ + { status: "running", code: "managed_token_refresh" }, + { status: "completed", code: "managed_token_refresh" }, + { status: "running", code: "managed_token_timeout" }, + ]); + assert.equal(lookups, 2); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #17501 Codex 429 retry exhaustion classifies as a usage limit it.effect.each([ { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 2f3f269fd0002..1dff1c5531441 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1431,10 +1431,11 @@ const UNCREDENTIALED_REQUEST = /missing bearer or basic authentication/iu; function withManagedTokenRefusal( failure: OrchestrationV2ProviderFailure, refusal: Refusal | undefined, + reported = failure.message, ): OrchestrationV2ProviderFailure { if (refusal === undefined) return failure; return makeProviderFailure({ - message: `Codex could not get a ChatGPT token from T3 Code: ${refusal.message} Check the connection in Settings → Providers. Codex reported: ${failure.message}`, + message: `Codex could not get a ChatGPT token from T3 Code: ${refusal.message} Check the connection in Settings → Providers. Codex reported: ${reported}`, code: `managed_token_${refusal.kind}`, class: failure.class, retryable: failure.retryable, @@ -2185,6 +2186,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( failure: OrchestrationV2ProviderFailure, errorInfo: CodexErrorInfo | null | undefined, nativeText: string, + nativeDetails?: string | null, ) { const recentTokenRefusal = resolvedRuntime?.recentTokenRefusal; if (recentTokenRefusal === undefined || !UNCREDENTIALED_REQUEST.test(nativeText)) @@ -2193,7 +2195,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const refusal = yield* recentTokenRefusal; if (refusal !== undefined) context.tokenRefusal = refusal; } - return withManagedTokenRefusal(failure, context.tokenRefusal); + const details = nativeDetails?.trim(); + const reported = + details && !UNCREDENTIALED_REQUEST.test(failure.message) ? details : failure.message; + return withManagedTokenRefusal(failure, context.tokenRefusal, reported); }); const additionalContextByThread = yield* Ref.make( new Map>(), @@ -2713,6 +2718,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( context: ActiveCodexTurnContext, updatedAt: DateTime.Utc, ) { + if (context.tokenRefusal !== undefined) delete context.tokenRefusal; const providerRetry = yield* Ref.modify(providerRetries, (current) => { const retry = current.get(context.providerTurnId); if (retry === undefined) { @@ -6693,6 +6699,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc; readonly failureMessage?: string; + readonly failureDetails?: string; readonly failureErrorInfo?: CodexErrorInfo; readonly providerRetry?: ActiveCodexProviderRetry; }): Effect.fn.Return { @@ -6755,7 +6762,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( input.context, failure, input.failureErrorInfo, - input.failureMessage ?? "", + `${input.failureMessage ?? ""}\n${input.failureDetails ?? ""}`, + input.failureDetails, ); const failureItemId = codexFailureItemId(input.context); return { @@ -6888,6 +6896,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc; readonly failureMessage?: string; + readonly failureDetails?: string; readonly failureErrorInfo?: CodexErrorInfo; readonly providerRetry?: ActiveCodexProviderRetry; readonly goalHoldTurn?: OrchestrationV2ProviderTurn; @@ -7110,6 +7119,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc; readonly failureMessage?: string; + readonly failureDetails?: string; readonly failureErrorInfo?: CodexErrorInfo; readonly continueRun?: boolean; readonly stalledRetry?: { @@ -7693,6 +7703,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ? {} : { failureMessage: payload.turn.error.message, + ...(payload.turn.error.additionalDetails == null + ? {} + : { failureDetails: payload.turn.error.additionalDetails }), ...(payload.turn.error.codexErrorInfo == null ? {} : { failureErrorInfo: payload.turn.error.codexErrorInfo }), diff --git a/apps/server/src/provider/CodexManagedTokenBroker.test.ts b/apps/server/src/provider/CodexManagedTokenBroker.test.ts index 0d9f6e91339f1..dd4ae9b17a194 100644 --- a/apps/server/src/provider/CodexManagedTokenBroker.test.ts +++ b/apps/server/src/provider/CodexManagedTokenBroker.test.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off - The helper reaches the broker over its private socket. +import * as NodeNet from "node:net"; import * as NodeURL from "node:url"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -222,3 +223,194 @@ it.live("the helper hears the broker's timeout and a late renewal still saves", ), ), ); + +it.live( + "keeps a session's refusal when a helper disconnects before receiving a renewed token", + () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("codex"); + const initialExitCode = process.exitCode; + const fs = yield* FileSystem.FileSystem; + const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-token-disconnect-" }); + const data = new Map(); + const renewalEntered = yield* Deferred.make(); + const renewalRelease = yield* Deferred.make(); + const spentRefreshTokens: string[] = []; + let tokenCalls = 0; + const executable = { + executablePath: "/isolated/tools/codex/0.156.1/bin/codex", + managedVersionDirectory: "/isolated/tools/codex/0.156.1", + source: "managed" as const, + version: "0.156.1", + }; + yield* Effect.gen(function* () { + const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); + const credentials = { + clientId: "oaiapp_test", + accessToken: "launch-access", + refreshToken: "single-use-refresh", + expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000, + earliestRefreshAt: null, + scopes: ["chatgpt.tokens.use.direct"], + subject: "test-user", + email: null, + }; + yield* store.set(new TextEncoder().encode(yield* encodeJson(credentials))); + const runtime = yield* makeCodexManagedRuntime({ + instanceId, + enabled: true, + config: decodeSettings({ setupMode: "managed", homePath: sharedHome }), + environment: {}, + }); + const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker; + yield* Effect.gen(function* () { + const effective = yield* runtime.resolve; + const provider = codexAppServerArgs(effective.config.launchArgs).find((arg) => + arg.startsWith("model_providers.openai_token_sharing="), + )!; + const [, args] = decodeCommand( + `[${/auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u + .exec(provider)! + .slice(1, 3) + .join(",")}]`, + ); + const helperArgs = args.slice(args.indexOf("__managed-chatgpt-token") + 1); + const [endpoint, helperInstanceId, environmentId, profileKey, sessionKey] = helperArgs; + + // First request fails renewal and records a refusal for this session. + yield* store.set( + new TextEncoder().encode(yield* encodeJson({ ...credentials, expiresAt: 0 })), + ); + const refused = yield* runHelper(helperArgs); + assert.equal(refused.exitCode, 1); + assert.equal((yield* effective.recentTokenRefusal!)?.kind, "refresh"); + + // A second helper connects over the real socket and disconnects while renewal is in flight. + const requestLine = + (yield* encodeJson({ + version: 1, + instanceId: helperInstanceId, + environmentId, + profileKey, + sessionKey, + })) + "\n"; + let receivedBytes = 0; + const disconnectedSocket = yield* Effect.callback((resume) => { + const socket = NodeNet.createConnection(endpoint!); + socket.on("error", () => {}); + socket.on("data", (chunk) => { + receivedBytes += chunk.length; + }); + socket.once("connect", () => { + socket.write(requestLine, () => resume(Effect.succeed(socket))); + }); + }); + yield* Deferred.await(renewalEntered); + yield* Effect.callback((resume) => { + if (disconnectedSocket.closed) { + resume(Effect.void); + return; + } + disconnectedSocket.once("close", () => resume(Effect.void)); + disconnectedSocket.destroy(); + }); + yield* Deferred.succeed(renewalRelease, undefined); + yield* broker.awaitIdle; + + assert.equal(receivedBytes, 0); + assert.equal((yield* effective.recentTokenRefusal!)?.kind, "refresh"); + + // The renewal was still saved; once a helper actually receives the token, the refusal clears. + assert.deepEqual(yield* runHelper(helperArgs), { + stdout: "renewed-access", + stderr: "", + exitCode: initialExitCode, + }); + assert.equal(yield* effective.recentTokenRefusal!, undefined); + assert.deepEqual(spentRefreshTokens, ["single-use-refresh", "single-use-refresh"]); + }).pipe(Effect.scoped); + }).pipe( + Effect.provide(CodexManagedTokenBroker.layer), + Effect.provideService(HostProcess.Arguments, [ + process.execPath, + NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)), + ]), + Effect.provideService( + ServerSecretStore.ServerSecretStore, + ServerSecretStore.ServerSecretStore.of({ + get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))), + set: (key, value) => + Effect.sync(() => { + data.set(key, value); + }), + remove: (key) => + Effect.sync(() => { + data.delete(key); + }), + create: () => Effect.die("unused"), + getOrCreateRandom: () => Effect.die("unused"), + }), + ), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed( + EnvironmentId.make("00000000-0000-4000-8000-000000000001"), + ), + }), + Effect.provide( + Layer.mock(CodexInstallation.CodexInstallation)({ + managedDirectory: "/isolated/tools/codex", + resolve: () => Effect.succeed(executable), + acquire: () => Effect.succeed(executable), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.gen(function* () { + if (!request.url.endsWith("/token")) + return HttpClientResponse.fromWeb( + request, + Response.json({ + issuer: "https://auth.openai.com", + authorization_endpoint: "https://auth.openai.com/api/accounts/authorize", + token_endpoint: "https://auth.openai.com/api/accounts/oauth/token", + jwks_uri: "https://auth.openai.com/jwks", + }), + ); + if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing body"); + spentRefreshTokens.push( + new URLSearchParams(new TextDecoder().decode(request.body.body)).get( + "refresh_token", + )!, + ); + tokenCalls++; + if (tokenCalls === 1) + return HttpClientResponse.fromWeb( + request, + new Response("temporary error", { status: 500 }), + ); + yield* Deferred.succeed(renewalEntered, undefined); + yield* Deferred.await(renewalRelease).pipe(Effect.uninterruptible); + return HttpClientResponse.fromWeb( + request, + Response.json({ + access_token: "renewed-access", + refresh_token: "rotated-refresh", + token_type: "Bearer", + expires_in: 3600, + scope: "chatgpt.tokens.use.direct", + }), + ); + }), + ), + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-managed-token-disconnect-" }).pipe( + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); diff --git a/apps/server/src/provider/CodexManagedTokenBroker.ts b/apps/server/src/provider/CodexManagedTokenBroker.ts index bec79e478f0df..55ee578892a09 100644 --- a/apps/server/src/provider/CodexManagedTokenBroker.ts +++ b/apps/server/src/provider/CodexManagedTokenBroker.ts @@ -253,12 +253,13 @@ const acquireListener = Effect.gen(function* () { } const result = answer.value; if (Exit.isSuccess(result)) { - refusals.delete(refusalKey(request)); - return yield* Protocol.writeFrame( + yield* Protocol.writeFrame( socket, encodeResponse({ token: result.value.accessToken }), Protocol.RESPONSE_BYTES, ); + refusals.delete(refusalKey(request)); + return; } if (!Cause.hasInterruptsOnly(result.cause)) yield* refuse(socket, request, refusalFromCause(result.cause)); diff --git a/apps/server/src/provider/CodexManagedTokenProtocol.ts b/apps/server/src/provider/CodexManagedTokenProtocol.ts index bffc3ae099d5f..05b37c6ab74e9 100644 --- a/apps/server/src/provider/CodexManagedTokenProtocol.ts +++ b/apps/server/src/provider/CodexManagedTokenProtocol.ts @@ -63,14 +63,29 @@ export const readFrame = (socket: NodeNet.Socket, maxBytes: number, timeoutMs: n export const writeFrame = (socket: NodeNet.Socket, frame: string, maxBytes: number) => Effect.callback((resume) => { - if (socket.destroyed || Buffer.byteLength(frame) + 1 > maxBytes) { + if ( + socket.destroyed || + socket.writableEnded || + !socket.writable || + Buffer.byteLength(frame) + 1 > maxBytes + ) { resume(Effect.fail(new ProtocolError())); return; } + let writeFailed = false; const fail = () => resume(Effect.fail(new ProtocolError())); socket.once("error", fail); socket.once("close", fail); - socket.end(`${frame}\n`, () => resume(Effect.void)); + socket.write(`${frame}\n`, (error) => { + if (error != null || socket.errored != null) { + writeFailed = true; + fail(); + } + }); + socket.end(() => { + if (writeFailed || socket.errored != null) fail(); + else resume(Effect.void); + }); return Effect.sync(() => { socket.off("error", fail); socket.off("close", fail); From d39833b978e53835c11847640584a4d23c6c9ca9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 04:57:13 +0000 Subject: [PATCH 4/6] test(server): keep the managed token refusal tests that catch a regression Drop the duplicated broker timeout harness, the job-limit case, and table rows that walk the same code path as a kept row. Co-Authored-By: Claude Opus 5.5 --- .../src/cli/managedChatGptToken.test.ts | 20 - .../Adapters/CodexAdapterV2.test.ts | 49 +-- .../src/provider/CodexChatGptAuth.test.ts | 72 --- .../provider/CodexManagedTokenBroker.test.ts | 416 ------------------ 4 files changed, 3 insertions(+), 554 deletions(-) delete mode 100644 apps/server/src/provider/CodexManagedTokenBroker.test.ts diff --git a/apps/server/src/cli/managedChatGptToken.test.ts b/apps/server/src/cli/managedChatGptToken.test.ts index 2a72d675856ff..d2e2999590f7f 100644 --- a/apps/server/src/cli/managedChatGptToken.test.ts +++ b/apps/server/src/cli/managedChatGptToken.test.ts @@ -86,24 +86,4 @@ describe("managed ChatGPT token helper", () => { expect(result).toEqual({ stdout: "access-token", stderr: "", exitCode }); }), ); - - it.effect.each([ - { name: "no answer", answer: null }, - { - name: "a token beside a refusal", - answer: JSON.stringify({ token: "access-token", refusal }), - }, - { - name: "a refusal without a message", - answer: JSON.stringify({ refusal: { kind: "refresh" } }), - }, - ])("fails without a token on $name", ({ answer }) => - Effect.gen(function* () { - const result = yield* runAgainst(answer); - expect(result.stdout).toBe(""); - expect(result.stderr).not.toBe(""); - expect(result.stderr).not.toContain("access-token"); - expect(result.exitCode).toBe(1); - }), - ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index d483d76df67d9..4117acf26242a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8984,19 +8984,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { completion: tokenRefusalFinal, explained: true, }, - { - name: "a final uncredentialed 401 that completes as other", - retry: true, - final: tokenRefusalFinal, - completion: { message: uncredentialedRequest, codexErrorInfo: "other" }, - explained: true, - }, - { - name: "a retried uncredentialed 401 that completes as other", - retry: true, - completion: { message: uncredentialedStream, codexErrorInfo: "other" }, - explained: true, - }, { name: "a retried uncredentialed 401 that completes as other with details only", retry: true, @@ -9007,11 +8994,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, explained: true, }, - { - name: "a retried uncredentialed 401 that completes without an error", - retry: true, - explained: true, - }, { name: "an uncredentialed 401 completion", completion: tokenRefusalFinal, explained: true }, { name: "a revoked token 401", @@ -9032,25 +9014,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { explained: false, retryExplained: true, }, - { - name: "an unrefused managed 401", - final: tokenRefusalFinal, - completion: tokenRefusalFinal, - unrefused: true, - explained: false, - }, - { - name: "a managed 503", - final: { - message: serverError.replace("500 Internal Server Error", "503 Service Unavailable"), - codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 503 } }, - }, - completion: { - message: serverError.replace("500 Internal Server Error", "503 Service Unavailable"), - codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 503 } }, - }, - explained: false, - }, { name: "a local Codex 401", final: tokenRefusalFinal, @@ -9091,7 +9054,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { threadId: nativeThreadId, turn: { ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), - ...("completion" in scenario ? { error: scenario.completion } : {}), + error: scenario.completion, }, }, }, @@ -9114,7 +9077,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { config: DEFAULT_CODEX_SETTINGS, environment: {}, revision: "managed-profile", - recentTokenRefusal: Effect.succeed("unrefused" in scenario ? undefined : refusal), + recentTokenRefusal: Effect.succeed(refusal), }), ); yield* harness.runtime.startTurn( @@ -9131,19 +9094,13 @@ describe("CodexAdapterV2 post-settle continuation", () => { assert.equal(terminal?.status, "failed"); if (terminal?.status !== "failed") return; const explainedCode = `managed_token_${refusal.kind}`; - const codexError = - "completion" in scenario - ? scenario.completion - : "final" in scenario - ? scenario.final - : undefined; if (scenario.explained) { assert.equal(terminal.failure.code, explainedCode); assert.include(terminal.failure.message, refusal.message); // Codex's own report stays visible. assert.include(terminal.failure.message, "unexpected status 401 Unauthorized"); } else { - const info = codexError?.codexErrorInfo; + const info = scenario.completion.codexErrorInfo; assert.equal( terminal.failure.code, typeof info === "string" ? info : Object.keys(info ?? {})[0], diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index db97664442490..5e4669a2d37b6 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -18,7 +18,6 @@ import * as TestClock from "effect/testing/TestClock"; import * as Fiber from "effect/Fiber"; import * as Deferred from "effect/Deferred"; import * as Logger from "effect/Logger"; -import * as Queue from "effect/Queue"; import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts"; import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; @@ -1790,13 +1789,10 @@ const makeRenewalBrokerWith = ( readonly saved?: string | null; readonly credentials?: Partial; readonly renewal?: { readonly status: number; readonly body: unknown }; - /** More instances saved with the same sign-in. */ - readonly instances?: ReadonlyArray; } = {}, ) => Effect.gen(function* () { const oauthEntered = yield* Deferred.make(); - const oauthEntries = yield* Queue.unbounded(); const oauthRelease = yield* Deferred.make(); let pauseOAuth = false; const refreshTokens: string[] = []; @@ -1821,7 +1817,6 @@ const makeRenewalBrokerWith = ( const body = new URLSearchParams(new TextDecoder().decode(request.body.body)); refreshTokens.push(body.get("refresh_token")!); yield* Deferred.succeed(oauthEntered, undefined); - yield* Queue.offer(oauthEntries, undefined); // A paused renewal ignores cancellation, like a request already on the wire. if (pauseOAuth) yield* Deferred.await(oauthRelease).pipe(Effect.uninterruptible); if (options.renewal) @@ -1845,10 +1840,6 @@ const makeRenewalBrokerWith = ( const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); const saved = options.saved === undefined ? JSON.stringify(credentials) : options.saved; if (saved !== null) yield* store.set(new TextEncoder().encode(saved)); - for (const other of options.instances ?? []) { - const otherStore = yield* ProviderCredentialStore.make("codex-chatgpt", other); - yield* otherStore.set(new TextEncoder().encode(JSON.stringify(credentials))); - } const auth = yield* makeCodexChatGptAuth({ instanceId }); const profileKey = yield* auth.profileKey(credentials); const scope = yield* Scope.make(); @@ -1865,7 +1856,6 @@ const makeRenewalBrokerWith = ( refreshTokens, request: { version: 1, instanceId, environmentId, profileKey, sessionKey: "5e".repeat(16) }, oauthEntered, - oauthEntries, oauthRelease, pause: () => { pauseOAuth = true; @@ -1992,43 +1982,16 @@ const captureLogs = () => { it.effect.each([ { name: "no saved sign-in", kind: "access", options: { saved: null } }, - { name: "a replaced sign-in", kind: "access", request: { profileKey: "0".repeat(64) } }, { name: "disabled token sharing", kind: "sharing", options: { credentials: { scopes: [] as Array } }, }, - { - name: "a renewal ChatGPT defers", - kind: "refresh", - options: { credentials: { earliestRefreshAt: 4_102_444_800_000 } }, - }, - { - name: "an expiry with no renewal token", - kind: "refresh", - options: { credentials: { refreshToken: null } }, - }, { name: "a failed renewal", kind: "refresh", options: { renewal: { status: 500, body: { error: "server_error" } } }, }, - { - name: "an invalid renewal", - kind: "refresh", - options: { - renewal: { - status: 200, - body: { - access_token: "renewed-access", - expires_in: 3600, - token_type: "Bearer", - scope: "chatgpt.tokens.use.direct", - }, - }, - }, - }, - { name: "an unreadable sign-in", kind: "read", options: { saved: "not json" } }, { name: "another environment", kind: "environment", @@ -2075,41 +2038,6 @@ it.effect.each([ ).pipe(Effect.provide(logs.layer)); }); -it.effect("the private broker refuses a request past its job limit until one succeeds", () => - provideBroker( - Effect.gen(function* () { - const others = Array.from({ length: 15 }, (_, index) => - ProviderInstanceId.make(`managed-codex-busy-${index}`), - ); - const h = yield* makeRenewalBrokerWith({ instances: others }); - h.pause(); - const held = yield* Effect.forEach([instanceId, ...others], (id) => - brokerClient(h.endpoint, { ...h.request, instanceId: id }), - ); - yield* Effect.forEach(held, () => Queue.take(h.oauthEntries)); - const refused = yield* brokerClient(h.endpoint, h.request); - const response = parseBrokerResponse(yield* Effect.promise(() => refused.response)); - assert.equal(response.refusal?.kind, "busy"); - assert.notProperty(response, "token"); - assert.equal( - (yield* h.broker.recentRefusal(instanceId, h.request.profileKey, h.request.sessionKey)) - ?.kind, - "busy", - ); - yield* Deferred.succeed(h.oauthRelease, undefined); - for (const client of held) { - assert.deepEqual(parseBrokerResponse(yield* Effect.promise(() => client.response)), { - token: "renewed-access", - }); - } - yield* h.broker.awaitIdle; - assert.isUndefined( - yield* h.broker.recentRefusal(instanceId, h.request.profileKey, h.request.sessionKey), - ); - }), - ), -); - it.effect("the private broker refuses a request that outlasts the helper's wait in time", () => provideBroker( Effect.gen(function* () { diff --git a/apps/server/src/provider/CodexManagedTokenBroker.test.ts b/apps/server/src/provider/CodexManagedTokenBroker.test.ts deleted file mode 100644 index dd4ae9b17a194..0000000000000 --- a/apps/server/src/provider/CodexManagedTokenBroker.test.ts +++ /dev/null @@ -1,416 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - The helper reaches the broker over its private socket. -import * as NodeNet from "node:net"; -import * as NodeURL from "node:url"; -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Clock from "effect/Clock"; -import * as Deferred from "effect/Deferred"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import { HttpClient, HttpClientResponse } from "effect/http"; -import { vi } from "vite-plus/test"; -import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; -import { runManagedChatGptTokenCli } from "../cli/managedChatGptToken.ts"; -import * as ServerConfig from "../config.ts"; -import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; -import * as CodexInstallation from "./CodexInstallation.ts"; -import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts"; -import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; -import type * as Protocol from "./CodexManagedTokenProtocol.ts"; -import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; -import { codexAppServerArgs } from "./codexLaunchArgs.ts"; - -// Codex, the helper and the broker share one wait. A short one runs the race in real time. -vi.mock("./CodexManagedTokenProtocol.ts", async (importOriginal) => ({ - ...(await importOriginal()), - COMMAND_TIMEOUT_MS: 2_000, -})); - -const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); -const decodeSettings = Schema.decodeSync(CodexSettings); -const decodeCommand = Schema.decodeUnknownSync( - Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Array(Schema.String)])), -); - -/** Runs the token command in this process, so it waits as long as the broker expects. */ -const runHelper = (args: ReadonlyArray) => - Effect.gen(function* () { - const stdout: string[] = []; - const stderr: string[] = []; - const exitCode = process.exitCode; - yield* Effect.acquireRelease( - Effect.sync(() => { - vi.spyOn(process.stdout, "write").mockImplementation((chunk) => { - stdout.push(String(chunk)); - return true; - }); - vi.spyOn(process.stderr, "write").mockImplementation((chunk) => { - stderr.push(String(chunk)); - return true; - }); - }), - () => - Effect.sync(() => { - vi.restoreAllMocks(); - process.exitCode = exitCode; - }), - ); - yield* Effect.promise(() => runManagedChatGptTokenCli(args)); - return { stdout: stdout.join(""), stderr: stderr.join(""), exitCode: process.exitCode }; - }).pipe(Effect.scoped); - -it.live("the helper hears the broker's timeout and a late renewal still saves", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex"); - const initialExitCode = process.exitCode; - const fs = yield* FileSystem.FileSystem; - const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-token-timeout-" }); - const data = new Map(); - const renewalEntered = yield* Deferred.make(); - const renewalRelease = yield* Deferred.make(); - const spentRefreshTokens: string[] = []; - const executable = { - executablePath: "/isolated/tools/codex/0.156.1/bin/codex", - managedVersionDirectory: "/isolated/tools/codex/0.156.1", - source: "managed" as const, - version: "0.156.1", - }; - yield* Effect.gen(function* () { - const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); - const credentials = { - clientId: "oaiapp_test", - accessToken: "launch-access", - refreshToken: "single-use-refresh", - expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000, - earliestRefreshAt: null, - scopes: ["chatgpt.tokens.use.direct"], - subject: "test-user", - email: null, - }; - yield* store.set(new TextEncoder().encode(yield* encodeJson(credentials))); - const runtime = yield* makeCodexManagedRuntime({ - instanceId, - enabled: true, - config: decodeSettings({ setupMode: "managed", homePath: sharedHome }), - environment: {}, - }); - const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker; - yield* Effect.gen(function* () { - const effective = yield* runtime.resolve; - const provider = codexAppServerArgs(effective.config.launchArgs).find((arg) => - arg.startsWith("model_providers.openai_token_sharing="), - )!; - const [, args] = decodeCommand( - `[${/auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u - .exec(provider)! - .slice(1, 3) - .join(",")}]`, - ); - const helperArgs = args.slice(args.indexOf("__managed-chatgpt-token") + 1); - - // The token expires, and its renewal is still on the wire when the wait runs out. - yield* store.set( - new TextEncoder().encode(yield* encodeJson({ ...credentials, expiresAt: 0 })), - ); - const timedOut = yield* runHelper(helperArgs); - yield* Deferred.await(renewalEntered); - // The renewal returns once the helper has its answer. - yield* Deferred.succeed(renewalRelease, undefined); - yield* broker.awaitIdle; - assert.deepEqual( - { helper: timedOut, recorded: (yield* effective.recentTokenRefusal!)?.kind }, - { - helper: { - stdout: "", - stderr: "Timed out waiting for the managed ChatGPT connection. Try again.\n", - exitCode: 1, - }, - recorded: "timeout", - }, - ); - - // The renewal that finished after the answer was saved, so the next request needs none. - assert.deepEqual(yield* runHelper(helperArgs), { - stdout: "renewed-access", - stderr: "", - exitCode: initialExitCode, - }); - assert.deepEqual(spentRefreshTokens, ["single-use-refresh"]); - }).pipe(Effect.scoped); - }).pipe( - Effect.provide(CodexManagedTokenBroker.layer), - Effect.provideService(HostProcess.Arguments, [ - process.execPath, - NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)), - ]), - Effect.provideService( - ServerSecretStore.ServerSecretStore, - ServerSecretStore.ServerSecretStore.of({ - get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))), - set: (key, value) => - Effect.sync(() => { - data.set(key, value); - }), - remove: (key) => - Effect.sync(() => { - data.delete(key); - }), - create: () => Effect.die("unused"), - getOrCreateRandom: () => Effect.die("unused"), - }), - ), - Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { - getEnvironmentId: Effect.succeed( - EnvironmentId.make("00000000-0000-4000-8000-000000000001"), - ), - }), - Effect.provide( - Layer.mock(CodexInstallation.CodexInstallation)({ - managedDirectory: "/isolated/tools/codex", - resolve: () => Effect.succeed(executable), - acquire: () => Effect.succeed(executable), - }), - ), - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.gen(function* () { - if (!request.url.endsWith("/token")) - return HttpClientResponse.fromWeb( - request, - Response.json({ - issuer: "https://auth.openai.com", - authorization_endpoint: "https://auth.openai.com/api/accounts/authorize", - token_endpoint: "https://auth.openai.com/api/accounts/oauth/token", - jwks_uri: "https://auth.openai.com/jwks", - }), - ); - if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing body"); - spentRefreshTokens.push( - new URLSearchParams(new TextDecoder().decode(request.body.body)).get( - "refresh_token", - )!, - ); - yield* Deferred.succeed(renewalEntered, undefined); - // A renewal on the wire ignores cancellation: ChatGPT may already have spent the token. - yield* Deferred.await(renewalRelease).pipe(Effect.uninterruptible); - return HttpClientResponse.fromWeb( - request, - Response.json({ - access_token: "renewed-access", - refresh_token: "rotated-refresh", - token_type: "Bearer", - expires_in: 3600, - scope: "chatgpt.tokens.use.direct", - }), - ); - }), - ), - ), - ); - }).pipe( - Effect.scoped, - Effect.provide( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-managed-token-timeout-" }).pipe( - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - ), - ), -); - -it.live( - "keeps a session's refusal when a helper disconnects before receiving a renewed token", - () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex"); - const initialExitCode = process.exitCode; - const fs = yield* FileSystem.FileSystem; - const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-token-disconnect-" }); - const data = new Map(); - const renewalEntered = yield* Deferred.make(); - const renewalRelease = yield* Deferred.make(); - const spentRefreshTokens: string[] = []; - let tokenCalls = 0; - const executable = { - executablePath: "/isolated/tools/codex/0.156.1/bin/codex", - managedVersionDirectory: "/isolated/tools/codex/0.156.1", - source: "managed" as const, - version: "0.156.1", - }; - yield* Effect.gen(function* () { - const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); - const credentials = { - clientId: "oaiapp_test", - accessToken: "launch-access", - refreshToken: "single-use-refresh", - expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000, - earliestRefreshAt: null, - scopes: ["chatgpt.tokens.use.direct"], - subject: "test-user", - email: null, - }; - yield* store.set(new TextEncoder().encode(yield* encodeJson(credentials))); - const runtime = yield* makeCodexManagedRuntime({ - instanceId, - enabled: true, - config: decodeSettings({ setupMode: "managed", homePath: sharedHome }), - environment: {}, - }); - const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker; - yield* Effect.gen(function* () { - const effective = yield* runtime.resolve; - const provider = codexAppServerArgs(effective.config.launchArgs).find((arg) => - arg.startsWith("model_providers.openai_token_sharing="), - )!; - const [, args] = decodeCommand( - `[${/auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u - .exec(provider)! - .slice(1, 3) - .join(",")}]`, - ); - const helperArgs = args.slice(args.indexOf("__managed-chatgpt-token") + 1); - const [endpoint, helperInstanceId, environmentId, profileKey, sessionKey] = helperArgs; - - // First request fails renewal and records a refusal for this session. - yield* store.set( - new TextEncoder().encode(yield* encodeJson({ ...credentials, expiresAt: 0 })), - ); - const refused = yield* runHelper(helperArgs); - assert.equal(refused.exitCode, 1); - assert.equal((yield* effective.recentTokenRefusal!)?.kind, "refresh"); - - // A second helper connects over the real socket and disconnects while renewal is in flight. - const requestLine = - (yield* encodeJson({ - version: 1, - instanceId: helperInstanceId, - environmentId, - profileKey, - sessionKey, - })) + "\n"; - let receivedBytes = 0; - const disconnectedSocket = yield* Effect.callback((resume) => { - const socket = NodeNet.createConnection(endpoint!); - socket.on("error", () => {}); - socket.on("data", (chunk) => { - receivedBytes += chunk.length; - }); - socket.once("connect", () => { - socket.write(requestLine, () => resume(Effect.succeed(socket))); - }); - }); - yield* Deferred.await(renewalEntered); - yield* Effect.callback((resume) => { - if (disconnectedSocket.closed) { - resume(Effect.void); - return; - } - disconnectedSocket.once("close", () => resume(Effect.void)); - disconnectedSocket.destroy(); - }); - yield* Deferred.succeed(renewalRelease, undefined); - yield* broker.awaitIdle; - - assert.equal(receivedBytes, 0); - assert.equal((yield* effective.recentTokenRefusal!)?.kind, "refresh"); - - // The renewal was still saved; once a helper actually receives the token, the refusal clears. - assert.deepEqual(yield* runHelper(helperArgs), { - stdout: "renewed-access", - stderr: "", - exitCode: initialExitCode, - }); - assert.equal(yield* effective.recentTokenRefusal!, undefined); - assert.deepEqual(spentRefreshTokens, ["single-use-refresh", "single-use-refresh"]); - }).pipe(Effect.scoped); - }).pipe( - Effect.provide(CodexManagedTokenBroker.layer), - Effect.provideService(HostProcess.Arguments, [ - process.execPath, - NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)), - ]), - Effect.provideService( - ServerSecretStore.ServerSecretStore, - ServerSecretStore.ServerSecretStore.of({ - get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))), - set: (key, value) => - Effect.sync(() => { - data.set(key, value); - }), - remove: (key) => - Effect.sync(() => { - data.delete(key); - }), - create: () => Effect.die("unused"), - getOrCreateRandom: () => Effect.die("unused"), - }), - ), - Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { - getEnvironmentId: Effect.succeed( - EnvironmentId.make("00000000-0000-4000-8000-000000000001"), - ), - }), - Effect.provide( - Layer.mock(CodexInstallation.CodexInstallation)({ - managedDirectory: "/isolated/tools/codex", - resolve: () => Effect.succeed(executable), - acquire: () => Effect.succeed(executable), - }), - ), - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.gen(function* () { - if (!request.url.endsWith("/token")) - return HttpClientResponse.fromWeb( - request, - Response.json({ - issuer: "https://auth.openai.com", - authorization_endpoint: "https://auth.openai.com/api/accounts/authorize", - token_endpoint: "https://auth.openai.com/api/accounts/oauth/token", - jwks_uri: "https://auth.openai.com/jwks", - }), - ); - if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing body"); - spentRefreshTokens.push( - new URLSearchParams(new TextDecoder().decode(request.body.body)).get( - "refresh_token", - )!, - ); - tokenCalls++; - if (tokenCalls === 1) - return HttpClientResponse.fromWeb( - request, - new Response("temporary error", { status: 500 }), - ); - yield* Deferred.succeed(renewalEntered, undefined); - yield* Deferred.await(renewalRelease).pipe(Effect.uninterruptible); - return HttpClientResponse.fromWeb( - request, - Response.json({ - access_token: "renewed-access", - refresh_token: "rotated-refresh", - token_type: "Bearer", - expires_in: 3600, - scope: "chatgpt.tokens.use.direct", - }), - ); - }), - ), - ), - ); - }).pipe( - Effect.scoped, - Effect.provide( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-managed-token-disconnect-" }).pipe( - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - ), - ), -); From 3166e9d6183c51506f0c73127a85ad4f24b534d5 Mon Sep 17 00:00:00 2001 From: Matthew Cosier <86030128+matthewcosier@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:14:06 +1100 Subject: [PATCH 5/6] fix(server): tighten managed Codex refusal matching, broker deadline, and frame flush checks Keep cached managed token refusals off explicit non-401 errors, display the native field carrying the uncredentialed 401 marker, preserve refusals across empty assistant deltas, and check reused failures when turn completion adds 401 details. Reserve only the socket-frame budget for the broker timeout refusal so lock contention, renewal, and save retain their full work window, and treat socket.end as failed if it reports an error or does not finish writing. --- .../Adapters/CodexAdapterV2.test.ts | 68 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 38 +++++++---- .../src/provider/CodexChatGptAuth.test.ts | 9 ++- .../src/provider/CodexManagedTokenBroker.ts | 7 +- .../src/provider/CodexManagedTokenProtocol.ts | 5 +- 5 files changed, 106 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 4117acf26242a..c74c382befbdc 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8994,6 +8994,33 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, explained: true, }, + { + name: "an uncredentialed 401 message with generic additional details", + final: { + message: uncredentialedRequest, + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + additionalDetails: "Request failed after retries", + }, + completion: { + message: uncredentialedRequest, + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + additionalDetails: "Request failed after retries", + }, + explained: true, + }, + { + name: "a generic 401 notice whose completion adds uncredentialed details", + final: { + message: "Request failed", + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + }, + completion: { + message: "Request failed", + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 401 } }, + additionalDetails: uncredentialedRequest, + }, + explained: true, + }, { name: "an uncredentialed 401 completion", completion: tokenRefusalFinal, explained: true }, { name: "a revoked token 401", @@ -9014,6 +9041,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { explained: false, retryExplained: true, }, + { + name: "a retried uncredentialed 401 that ends in a 503 mentioning missing authentication", + retry: true, + completion: { + message: uncredentialedRequest.replace("401 Unauthorized", "503 Service Unavailable"), + codexErrorInfo: { httpConnectionFailed: { httpStatusCode: 503 } }, + }, + explained: false, + retryExplained: true, + }, { name: "a local Codex 401", final: tokenRefusalFinal, @@ -9164,6 +9201,36 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, }, + { + type: "emit_inbound", + label: "item/agentMessage/delta/empty", + frame: { + method: "item/agentMessage/delta", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + itemId: "msg-recovered", + delta: "", + }, + }, + }, + { + type: "emit_inbound", + label: "error/retry-after-empty-delta", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 2/5", + codexErrorInfo: "other", + additionalDetails: uncredentialedStream, + }, + }, + }, + }, { type: "emit_inbound", label: "item/started/recovered", @@ -9266,6 +9333,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { : [], ); assert.deepEqual(errorItems, [ + { status: "running", code: "managed_token_refresh" }, { status: "running", code: "managed_token_refresh" }, { status: "completed", code: "managed_token_refresh" }, { status: "running", code: "managed_token_timeout" }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 1dff1c5531441..9d7b1c8f4cf99 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -2185,19 +2185,25 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( context: ActiveCodexTurnContext, failure: OrchestrationV2ProviderFailure, errorInfo: CodexErrorInfo | null | undefined, - nativeText: string, + nativeMessage?: string | null, nativeDetails?: string | null, ) { const recentTokenRefusal = resolvedRuntime?.recentTokenRefusal; - if (recentTokenRefusal === undefined || !UNCREDENTIALED_REQUEST.test(nativeText)) - return failure; - if (context.tokenRefusal === undefined && codexErrorHttpStatus(errorInfo) === 401) { + if (recentTokenRefusal === undefined) return failure; + const message = nativeMessage?.trim() ?? ""; + const details = nativeDetails?.trim() ?? ""; + const reported = UNCREDENTIALED_REQUEST.test(details) + ? details + : UNCREDENTIALED_REQUEST.test(message) + ? message + : undefined; + if (reported === undefined) return failure; + const status = codexErrorHttpStatus(errorInfo); + if (status !== null && status !== 401) return failure; + if (context.tokenRefusal === undefined && status === 401) { const refusal = yield* recentTokenRefusal; if (refusal !== undefined) context.tokenRefusal = refusal; } - const details = nativeDetails?.trim(); - const reported = - details && !UNCREDENTIALED_REQUEST.test(failure.message) ? details : failure.message; return withManagedTokenRefusal(failure, context.tokenRefusal, reported); }); const additionalContextByThread = yield* Ref.make( @@ -5145,6 +5151,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* client.handleServerNotification("item/agentMessage/delta", (payload) => Effect.gen(function* () { + if (payload.delta.length === 0) return; const context = (yield* Ref.get(activeTurns)).get(payload.turnId); if (context !== undefined) { yield* completeProviderRetry(context, yield* DateTime.now); @@ -5523,7 +5530,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload.error, ), payload.error.codexErrorInfo, - `${payload.error.message}\n${payload.error.additionalDetails ?? ""}`, + payload.error.message, + payload.error.additionalDetails, ), }; return; @@ -5559,7 +5567,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload.error, ), payload.error.codexErrorInfo, - `${payload.error.message}\n${payload.error.additionalDetails ?? ""}`, + payload.error.message, + payload.error.additionalDetails, ); const itemOrdinal = previous?.itemOrdinal ?? @@ -6756,13 +6765,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { failure = { ...failure, class: "transport_error" }; } - // A reused report was explained when Codex first sent it. - if (!reused) + // Keep an explanation already attached to a reused report, but still check + // when the completion adds 401 details the earlier notification lacked. + const alreadyExplained = + reused && previousFailure?.failure.code?.startsWith("managed_token_") === true; + if (!alreadyExplained) failure = yield* explainTokenRefusal( input.context, failure, - input.failureErrorInfo, - `${input.failureMessage ?? ""}\n${input.failureDetails ?? ""}`, + input.failureErrorInfo ?? (reused ? previousFailure?.errorInfo : undefined), + input.failureMessage, input.failureDetails, ); const failureItemId = codexFailureItemId(input.context); diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 5e4669a2d37b6..3ebe59ec72412 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -25,7 +25,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; -import { COMMAND_TIMEOUT_MS } from "./CodexManagedTokenProtocol.ts"; +import { COMMAND_TIMEOUT_MS, SOCKET_IDLE_MS } from "./CodexManagedTokenProtocol.ts"; const assertSameCallback = (actual: string | null, expected: string | null) => { const left = new URL(actual!); @@ -2045,8 +2045,13 @@ it.effect("the private broker refuses a request that outlasts the helper's wait h.pause(); const client = yield* brokerClient(h.endpoint, h.request); yield* Deferred.await(h.oauthEntered); + // Lock (40s) + OAuth (20s) + save can pass 60s; keep working until the IPC margin. + yield* TestClock.adjust("61 seconds"); + assert.isUndefined( + yield* h.broker.recentRefusal(instanceId, h.request.profileKey, h.request.sessionKey), + ); // Codex starts its wait before the helper starts and reaches the broker. - yield* TestClock.adjust(COMMAND_TIMEOUT_MS - 20_000); + yield* TestClock.adjust(COMMAND_TIMEOUT_MS - SOCKET_IDLE_MS - 61_000); const response = parseBrokerResponse(yield* Effect.promise(() => client.response)); assert.equal(response.refusal?.kind, "timeout"); assert.notProperty(response, "token"); diff --git a/apps/server/src/provider/CodexManagedTokenBroker.ts b/apps/server/src/provider/CodexManagedTokenBroker.ts index 55ee578892a09..43ba8b18e78a8 100644 --- a/apps/server/src/provider/CodexManagedTokenBroker.ts +++ b/apps/server/src/provider/CodexManagedTokenBroker.ts @@ -27,10 +27,9 @@ const MAX_REFUSALS = 64; // Codex asks once before its first request, then retries the unauthenticated // request for a while before it reports the 401. const RECENT_REFUSAL_MS = 10 * 60_000; -// Codex and the helper start the same wait before the request arrives. Answering with a -// quarter of it to spare covers the helper's start, and a renewal already on the wire -// (limited to 20 seconds of the 80) still finishes and saves on its own. -const ANSWER_TIMEOUT_MS = (Protocol.COMMAND_TIMEOUT_MS * 3) / 4; +// Reserve the socket-frame budget so the helper hears a timeout refusal before its +// own deadline while keeping the lock (40s), OAuth (20s) and store headroom intact. +const ANSWER_TIMEOUT_MS = Protocol.COMMAND_TIMEOUT_MS - Protocol.SOCKET_IDLE_MS; const TIMED_OUT: Protocol.Refusal = { kind: "timeout", message: "Timed out waiting for the managed ChatGPT connection. Try again.", diff --git a/apps/server/src/provider/CodexManagedTokenProtocol.ts b/apps/server/src/provider/CodexManagedTokenProtocol.ts index 05b37c6ab74e9..ec50492ca550c 100644 --- a/apps/server/src/provider/CodexManagedTokenProtocol.ts +++ b/apps/server/src/provider/CodexManagedTokenProtocol.ts @@ -82,8 +82,9 @@ export const writeFrame = (socket: NodeNet.Socket, frame: string, maxBytes: numb fail(); } }); - socket.end(() => { - if (writeFailed || socket.errored != null) fail(); + socket.end((error?: Error | null) => { + if (writeFailed || error != null || socket.errored != null || !socket.writableFinished) + fail(); else resume(Effect.void); }); return Effect.sync(() => { From 89e58685a98abd302b4960a7458ddd7943fd5f84 Mon Sep 17 00:00:00 2001 From: Matthew Cosier <86030128+matthewcosier@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:34:46 +1100 Subject: [PATCH 6/6] fix(server): a later managed Codex 401 shows the session's newest refusal Each 401 that Codex sent without credentials now reads the session's latest refusal, so a second refusal before model output resumes replaces the first reason. A report without a status keeps the reason already shown. The recovery test now checks that only new model text clears the reason. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 37 +++++++++++++------ .../Adapters/CodexAdapterV2.ts | 3 +- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index c74c382befbdc..1961d13728e70 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -9233,20 +9233,14 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, { type: "emit_inbound", - label: "item/started/recovered", + label: "error/retry-before-recovery", frame: { - method: "item/started", + method: "error", params: { threadId: nativeThreadId, turnId: nativeTurnId, - startedAtMs: 1782622440500, - item: { - type: "agentMessage", - id: "msg-recovered", - text: "", - phase: "commentary", - memoryCitation: null, - }, + willRetry: true, + error: tokenRefusalRetry, }, }, }, @@ -9263,6 +9257,23 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, }, + { + type: "emit_inbound", + label: "error/retry-after-recovery", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 3/5", + codexErrorInfo: "other", + additionalDetails: uncredentialedStream, + }, + }, + }, + }, { type: "emit_inbound", label: "error/retry-second", @@ -9335,10 +9346,12 @@ describe("CodexAdapterV2 post-settle continuation", () => { assert.deepEqual(errorItems, [ { status: "running", code: "managed_token_refresh" }, { status: "running", code: "managed_token_refresh" }, - { status: "completed", code: "managed_token_refresh" }, + { status: "running", code: "managed_token_timeout" }, + { status: "completed", code: "managed_token_timeout" }, + { status: "running", code: "other" }, { status: "running", code: "managed_token_timeout" }, ]); - assert.equal(lookups, 2); + assert.equal(lookups, 4); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 9d7b1c8f4cf99..0d911a80a80d6 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -2200,7 +2200,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (reported === undefined) return failure; const status = codexErrorHttpStatus(errorInfo); if (status !== null && status !== 401) return failure; - if (context.tokenRefusal === undefined && status === 401) { + // Each 401 reads the session's latest refusal; a report without a status keeps the last one. + if (status === 401) { const refusal = yield* recentTokenRefusal; if (refusal !== undefined) context.tokenRefusal = refusal; }