diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index 6718f34e31..24d7ae3140 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -28,9 +28,7 @@ import { sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; -import { getCodexModelCapabilities } from "../../provider/codexModels.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model"; const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; @@ -155,10 +153,6 @@ const makeCodexTextGeneration = Effect.gen(function* () { ).pipe(Effect.catch(() => Effect.undefined)); const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () { - const normalizedOptions = normalizeCodexModelOptionsWithCapabilities( - getCodexModelCapabilities(modelSelection.model), - modelSelection.options, - ); const reasoningEffort = modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT; const command = ChildProcess.make( @@ -173,7 +167,7 @@ const makeCodexTextGeneration = Effect.gen(function* () { modelSelection.model, "--config", `model_reasoning_effort="${reasoningEffort}"`, - ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []), + ...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []), "--output-schema", schemaPath, "--output-last-message", diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 4017b15b89..70e31c4b3b 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -1,72 +1,36 @@ -import * as OS from "node:os"; -import type { - CodexSettings, - ServerProvider, - ServerProviderAuth, - ServerProviderSkill, - ServerProviderState, -} from "@t3tools/contracts"; -import { - Cache, - Data, - Duration, - Effect, - Equal, - FileSystem, - Layer, - Option, - Path, - Result, - Stream, -} from "effect"; -import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; +import type { CodexSettings, ServerProvider, ServerProviderState } from "@t3tools/contracts"; +import { ServerSettingsError } from "@t3tools/contracts"; +import { Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; +import * as CodexErrors from "effect-codex-app-server/errors"; +import { ChildProcessSpawner } from "effect/unstable/process"; -import { - buildServerProvider, - DEFAULT_TIMEOUT_MS, - detailFromResult, - extractAuthBoolean, - isCommandMissingCause, - parseGenericCliVersion, - providerModelsFromSettings, - spawnAndCollect, - type CommandResult, -} from "../providerSnapshot.ts"; import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import { buildServerProvider } from "../providerSnapshot.ts"; import { - formatCodexCliUpgradeMessage, - isCodexCliVersionSupported, - parseCodexCliVersion, -} from "../codexCliVersion.ts"; -import { - adjustCodexModelsForAccount, - codexAuthSubLabel, - codexAuthSubType, - type CodexAccountSnapshot, -} from "../codexAccount.ts"; -import { type CodexDiscoverySnapshot, probeCodexDiscovery } from "../codexAppServer.ts"; -import { BUILT_IN_CODEX_MODELS, DEFAULT_CODEX_MODEL_CAPABILITIES } from "../codexModels.ts"; + codexAccountAuthLabel, + probeCodexAppServerProvider, + type CodexAppServerProviderSnapshot, +} from "../codexAppServer.ts"; import { CodexProvider } from "../Services/CodexProvider.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; -import { ServerSettingsError } from "@t3tools/contracts"; const PROVIDER = "codex" as const; -const OPENAI_AUTH_PROVIDERS = new Set(["openai"]); +const PROVIDER_PROBE_TIMEOUT_MS = 8_000; -class CodexDiscoveryCacheKey extends Data.Class<{ - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; -}> {} +const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => + codexSettings.customModels + .map((model) => model.trim()) + .filter((model, index, models) => model.length > 0 && models.indexOf(model) === index) + .map((model) => ({ + slug: model, + name: model, + isCustom: true, + capabilities: null, + })); const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => { const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_CODEX_MODELS, - PROVIDER, - codexSettings.customModels, - DEFAULT_CODEX_MODEL_CAPABILITIES, - ); + const models = emptyCodexModelsFromSettings(codexSettings); if (!codexSettings.enabled) { return buildServerProvider({ @@ -101,32 +65,23 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider }); }; -export function parseAuthStatusFromOutput(result: CommandResult): { +function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): { readonly status: Exclude; - readonly auth: Pick; + readonly auth: ServerProvider["auth"]; readonly message?: string; } { - const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); + const authLabel = codexAccountAuthLabel(account.account); + const auth = { + status: account.account ? ("authenticated" as const) : ("unknown" as const), + ...(account.account?.type ? { type: account.account?.type } : {}), + ...(authLabel ? { label: authLabel } : {}), + } satisfies ServerProvider["auth"]; - if ( - lowerOutput.includes("unknown command") || - lowerOutput.includes("unrecognized command") || - lowerOutput.includes("unexpected argument") - ) { - return { - status: "warning", - auth: { status: "unknown" }, - message: "Codex CLI authentication status command is unavailable in this Codex version.", - }; + if (account.account) { + return { status: "ready", auth }; } - if ( - lowerOutput.includes("not logged in") || - lowerOutput.includes("login required") || - lowerOutput.includes("authentication required") || - lowerOutput.includes("run `codex login`") || - lowerOutput.includes("run codex login") - ) { + if (account.requiresOpenaiAuth) { return { status: "error", auth: { status: "unauthenticated" }, @@ -134,162 +89,39 @@ export function parseAuthStatusFromOutput(result: CommandResult): { }; } - const parsedAuth = (() => { - const trimmed = result.stdout.trim(); - if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) { - return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; - } - try { - return { - attemptedJsonParse: true as const, - auth: extractAuthBoolean(JSON.parse(trimmed)), - }; - } catch { - return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined }; - } - })(); - - if (parsedAuth.auth === true) { - return { status: "ready", auth: { status: "authenticated" } }; - } - if (parsedAuth.auth === false) { - return { - status: "error", - auth: { status: "unauthenticated" }, - message: "Codex CLI is not authenticated. Run `codex login` and try again.", - }; - } - if (parsedAuth.attemptedJsonParse) { - return { - status: "warning", - auth: { status: "unknown" }, - message: - "Could not verify Codex authentication status from JSON output (missing auth marker).", - }; - } - if (result.code === 0) { - return { status: "ready", auth: { status: "authenticated" } }; - } - - const detail = detailFromResult(result); - return { - status: "warning", - auth: { status: "unknown" }, - message: detail - ? `Could not verify Codex authentication status. ${detail}` - : "Could not verify Codex authentication status.", - }; + return { status: "ready", auth }; } -export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const settingsService = yield* ServerSettingsService; - const codexHome = yield* settingsService.getSettings.pipe( - Effect.map( - (settings) => - settings.providers.codex.homePath || - process.env.CODEX_HOME || - path.join(OS.homedir(), ".codex"), - ), - ); - const configPath = path.join(codexHome, "config.toml"); - - const content = yield* fileSystem - .readFileString(configPath) - .pipe(Effect.orElseSucceed(() => undefined)); - if (content === undefined) { - return undefined; - } - - let inTopLevel = true; - for (const line of content.split("\n")) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith("#")) continue; - if (trimmed.startsWith("[")) { - inTopLevel = false; - continue; - } - if (!inTopLevel) continue; - - const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/); - if (match) return match[1]; - } - return undefined; -}); - -export const hasCustomModelProvider = readCodexConfigModelProvider().pipe( - Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)), - Effect.orElseSucceed(() => false), -); - -const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; - -const probeCodexCapabilities = (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; -}) => - probeCodexDiscovery(input).pipe( - Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), - Effect.result, - Effect.map((result) => { - if (Result.isFailure(result)) return undefined; - return Option.isSome(result.success) ? result.success.value : undefined; - }), - ); - -const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray) { - const settingsService = yield* ServerSettingsService; - const codexSettings = yield* settingsService.getSettings.pipe( - Effect.map((settings) => settings.providers.codex), - ); - const command = ChildProcess.make(codexSettings.binaryPath, [...args], { - shell: process.platform === "win32", - env: { - ...process.env, - ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}), - }, - }); - return yield* spawnAndCollect(codexSettings.binaryPath, command); -}); - export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( - resolveAccount?: (input: { - readonly binaryPath: string; - readonly homePath?: string; - }) => Effect.Effect, - resolveSkills?: (input: { + probe: (input: { readonly binaryPath: string; readonly homePath?: string; readonly cwd: string; - }) => Effect.Effect | undefined>, + readonly customModels: ReadonlyArray; + }) => Effect.Effect< + CodexAppServerProviderSnapshot, + CodexErrors.CodexAppServerError, + ChildProcessSpawner.ChildProcessSpawner + > = probeCodexAppServerProvider, ): Effect.fn.Return< ServerProvider, ServerSettingsError, - | ChildProcessSpawner.ChildProcessSpawner - | FileSystem.FileSystem - | Path.Path - | ServerSettingsService + ServerSettingsService | ChildProcessSpawner.ChildProcessSpawner > { const codexSettings = yield* Effect.service(ServerSettingsService).pipe( Effect.flatMap((service) => service.getSettings), Effect.map((settings) => settings.providers.codex), ); const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_CODEX_MODELS, - PROVIDER, - codexSettings.customModels, - DEFAULT_CODEX_MODEL_CAPABILITIES, - ); + const emptyModels = emptyCodexModelsFromSettings(codexSettings); if (!codexSettings.enabled) { return buildServerProvider({ provider: PROVIDER, enabled: false, checkedAt, - models, + models: emptyModels, + skills: [], probe: { installed: false, version: null, @@ -300,257 +132,77 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu }); } - const versionProbe = yield* runCodexCommand(["--version"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); + const probeResult = yield* probe({ + binaryPath: codexSettings.binaryPath, + homePath: codexSettings.homePath, + cwd: process.cwd(), + customModels: codexSettings.customModels, + }).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result); - if (Result.isFailure(versionProbe)) { - const error = versionProbe.failure; + if (Result.isFailure(probeResult)) { + const error = probeResult.failure; + const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error); return buildServerProvider({ provider: PROVIDER, enabled: codexSettings.enabled, checkedAt, - models, + models: emptyModels, + skills: [], probe: { - installed: !isCommandMissingCause(error), + installed, version: null, status: "error", auth: { status: "unknown" }, - message: isCommandMissingCause(error) - ? "Codex CLI (`codex`) is not installed or not on PATH." - : `Failed to execute Codex CLI health check: ${error.message}.`, + message: installed + ? `Codex app-server provider probe failed: ${error.message}.` + : "Codex CLI (`codex`) is not installed or not on PATH.", }, }); } - if (Option.isNone(versionProbe.success)) { + if (Option.isNone(probeResult.success)) { return buildServerProvider({ provider: PROVIDER, enabled: codexSettings.enabled, checkedAt, - models, + models: emptyModels, + skills: [], probe: { installed: true, version: null, status: "error", auth: { status: "unknown" }, - message: "Codex CLI is installed but failed to run. Timed out while running command.", + message: "Timed out while checking Codex app-server provider status.", }, }); } - const version = versionProbe.success.value; - const parsedVersion = - parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? - parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); - if (version.code !== 0) { - const detail = detailFromResult(version); - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - auth: { status: "unknown" }, - message: detail - ? `Codex CLI is installed but failed to run. ${detail}` - : "Codex CLI is installed but failed to run.", - }, - }); - } + const snapshot = probeResult.success.value; + const accountStatus = accountProbeStatus(snapshot.account); - if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - auth: { status: "unknown" }, - message: formatCodexCliUpgradeMessage(parsedVersion), - }, - }); - } - - const skills = - (resolveSkills - ? yield* resolveSkills({ - binaryPath: codexSettings.binaryPath, - homePath: codexSettings.homePath, - cwd: process.cwd(), - }).pipe(Effect.orElseSucceed(() => undefined)) - : undefined) ?? []; - - if (yield* hasCustomModelProvider) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - skills, - probe: { - installed: true, - version: parsedVersion, - status: "ready", - auth: { status: "unknown" }, - message: "Using a custom Codex model provider; OpenAI login check skipped.", - }, - }); - } - - const authProbe = yield* runCodexCommand(["login", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - const account = resolveAccount - ? yield* resolveAccount({ - binaryPath: codexSettings.binaryPath, - homePath: codexSettings.homePath, - }) - : undefined; - const resolvedModels = adjustCodexModelsForAccount(models, account); - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: resolvedModels, - skills, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - auth: { status: "unknown" }, - message: `Could not verify Codex authentication status: ${error.message}.`, - }, - }); - } - - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models: resolvedModels, - skills, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - auth: { status: "unknown" }, - message: "Could not verify Codex authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseAuthStatusFromOutput(authProbe.success.value); - const authType = codexAuthSubType(account); - const authLabel = codexAuthSubLabel(account); return buildServerProvider({ provider: PROVIDER, enabled: codexSettings.enabled, checkedAt, - models: resolvedModels, - skills, + models: snapshot.models, + skills: snapshot.skills, probe: { installed: true, - version: parsedVersion, - status: parsed.status, - auth: { - ...parsed.auth, - ...(authType ? { type: authType } : {}), - ...(authLabel ? { label: authLabel } : {}), - }, - ...(parsed.message ? { message: parsed.message } : {}), + version: snapshot.version ?? null, + status: accountStatus.status, + auth: accountStatus.auth, + ...(accountStatus.message ? { message: accountStatus.message } : {}), }, }); }); -const applyCodexDiscoverySnapshot = ( - snapshot: ServerProvider, - discovery: CodexDiscoverySnapshot, -): ServerProvider => { - const authType = codexAuthSubType(discovery.account); - const authLabel = codexAuthSubLabel(discovery.account); - - return { - ...snapshot, - auth: { - ...snapshot.auth, - ...(authType ? { type: authType } : {}), - ...(authLabel ? { label: authLabel } : {}), - }, - models: adjustCodexModelsForAccount(snapshot.models, discovery.account), - skills: discovery.skills, - }; -}; - -const enrichCodexSnapshotViaDiscovery = (input: { - readonly settings: CodexSettings; - readonly snapshot: ServerProvider; - readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect; - readonly getDiscovery: (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - }) => Effect.Effect; -}) => - (input.settings.enabled && input.snapshot.installed - ? input - .getDiscovery({ - binaryPath: input.settings.binaryPath, - homePath: input.settings.homePath, - cwd: process.cwd(), - }) - .pipe( - Effect.flatMap((discovery) => - discovery - ? input.publishSnapshot(applyCodexDiscoverySnapshot(input.snapshot, discovery)) - : Effect.void, - ), - ) - : Effect.void - ).pipe(Effect.catchCause((cause) => Effect.logError(cause))); - export const CodexProviderLive = Layer.effect( CodexProvider, Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const accountProbeCache = yield* Cache.make({ - capacity: 4, - timeToLive: Duration.minutes(5), - lookup: (key: CodexDiscoveryCacheKey) => { - const { binaryPath, homePath, cwd } = key; - return probeCodexCapabilities({ - binaryPath, - cwd, - ...(homePath ? { homePath } : {}), - }); - }, - }); - - const getDiscovery = (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; - }) => Cache.get(accountProbeCache, new CodexDiscoveryCacheKey(input)); - const checkProvider = checkCodexProviderStatus().pipe( Effect.provideService(ServerSettingsService, serverSettings), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); @@ -565,13 +217,7 @@ export const CodexProviderLive = Layer.effect( haveSettingsChanged: (previous, next) => !Equal.equals(previous, next), initialSnapshot: makePendingCodexProvider, checkProvider, - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => - enrichCodexSnapshotViaDiscovery({ - settings, - snapshot, - publishSnapshot, - getDiscovery, - }), + refreshInterval: Duration.minutes(5), }); }), ); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 14583e6842..5830d82ee6 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -1,18 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, it, assert } from "@effect/vitest"; -import { - Effect, - Exit, - FileSystem, - Layer, - Path, - PubSub, - Ref, - Schema, - Scope, - Sink, - Stream, -} from "effect"; +import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect"; +import * as CodexErrors from "effect-codex-app-server/errors"; import { DEFAULT_SERVER_SETTINGS, ServerSettings, @@ -23,41 +12,23 @@ import * as PlatformError from "effect/PlatformError"; import { ChildProcessSpawner } from "effect/unstable/process"; import { deepMerge } from "@t3tools/shared/Struct"; -import { - checkCodexProviderStatus, - hasCustomModelProvider, - parseAuthStatusFromOutput, - readCodexConfigModelProvider, -} from "./CodexProvider.ts"; +import { checkCodexProviderStatus } from "./CodexProvider.ts"; import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts"; import { haveProvidersChanged, mergeProviderSnapshot, ProviderRegistryLive, } from "./ProviderRegistry.ts"; -import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts"; import { ServerConfig } from "../../config.ts"; import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts"; import { ProviderRegistry } from "../Services/ProviderRegistry.ts"; +import type { CodexAppServerProviderSnapshot } from "../codexAppServer.ts"; process.env.T3CODE_CURSOR_ENABLED = "1"; // ── Test helpers ──────────────────────────────────────────────────── const encoder = new TextEncoder(); -const fakeOpenCodeSnapshot: ServerProvider = { - provider: "opencode", - status: "warning", - enabled: true, - installed: false, - auth: { status: "unknown" }, - checkedAt: "2026-03-25T00:00:00.000Z", - version: null, - models: [], - slashCommands: [], - skills: [], - message: "OpenCode test stub", -}; function mockHandle(result: { stdout: string; stderr: string; code: number }) { return ChildProcessSpawner.makeHandle({ @@ -118,6 +89,43 @@ function failingSpawnerLayer(description: string) { ); } +const codexModelCapabilities = { + reasoningEffortLevels: [ + { value: "high", label: "High", isDefault: true }, + { value: "low", label: "Low" }, + ], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], +} satisfies NonNullable; + +function makeCodexProbeSnapshot( + input: Partial = {}, +): CodexAppServerProviderSnapshot { + return { + version: "1.0.0", + account: { + account: { + type: "chatgpt", + email: "test@example.com", + planType: "pro", + }, + requiresOpenaiAuth: false, + }, + models: [ + { + slug: "gpt-live-codex", + name: "GPT Live Codex", + isCustom: false, + capabilities: codexModelCapabilities, + }, + ], + skills: [], + ...input, + }; +} + function makeMutableServerSettingsService( initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS, ) { @@ -144,126 +152,43 @@ function makeMutableServerSettingsService( }); } -/** - * Create a temporary CODEX_HOME scoped to the current Effect test. - * Cleanup is registered in the test scope rather than via Vitest hooks. - */ -function withTempCodexHome(configContent?: string) { - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" }); - - yield* Effect.acquireRelease( - Effect.sync(() => { - const originalCodexHome = process.env.CODEX_HOME; - process.env.CODEX_HOME = tmpDir; - return originalCodexHome; - }), - (originalCodexHome) => - Effect.sync(() => { - if (originalCodexHome !== undefined) { - process.env.CODEX_HOME = originalCodexHome; - } else { - delete process.env.CODEX_HOME; - } - }), - ); - - if (configContent !== undefined) { - yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent); - } - - return { tmpDir } as const; - }); -} - it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "ProviderRegistry", (it) => { - // ── checkCodexProviderStatus tests ──────────────────────────────── - // - // These tests control CODEX_HOME to ensure the custom-provider detection - // in hasCustomModelProvider() does not interfere with the auth-probe - // path being tested. - describe("checkCodexProviderStatus", () => { - it.effect("returns ready when codex is installed and authenticated", () => + it.effect("uses the app-server account and model list for provider status", () => Effect.gen(function* () { - // Point CODEX_HOME at an empty tmp dir (no config.toml) so the - // default code path (OpenAI provider, auth probe runs) is exercised. - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed( + makeCodexProbeSnapshot({ + skills: [ + { + name: "github:gh-fix-ci", + path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md", + enabled: true, + displayName: "CI Debug", + shortDescription: "Debug failing GitHub Actions checks", + }, + ], + }), + ), + ); + assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "authenticated"); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns the codex plan type in auth and keeps spark for supported plans", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "chatgpt" as const, - planType: "pro" as const, - sparkEnabled: true, - }), - ); - - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.version, "codex-cli/1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "pro"); assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - true, - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("includes probed codex skills in the provider snapshot", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus( - () => - Effect.succeed({ - type: "chatgpt" as const, - planType: "pro" as const, - sparkEnabled: true, - }), - () => - Effect.succeed([ - { - name: "github:gh-fix-ci", - path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md", - enabled: true, - displayName: "CI Debug", - shortDescription: "Debug failing GitHub Actions checks", - }, - ]), - ); - + assert.deepStrictEqual(status.models, [ + { + slug: "gpt-live-codex", + name: "GPT Live Codex", + isCustom: false, + capabilities: codexModelCapabilities, + }, + ]); assert.deepStrictEqual(status.skills, [ { name: "github:gh-fix-ci", @@ -273,172 +198,81 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( shortDescription: "Debug failing GitHub Actions checks", }, ]); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + }), ); - it.effect("hides spark from codex models for unsupported chatgpt plans", () => + it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { - yield* withTempCodexHome(); const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "chatgpt" as const, - planType: "plus" as const, - sparkEnabled: false, - }), + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: null, + requiresOpenaiAuth: true, + }, + }), + ), ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "plus"); - assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - false, + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual( + status.message, + "Codex CLI is not authenticated. Run `codex login` and try again.", ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + }), ); - it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "chatgpt" as const, - planType: "team" as const, - sparkEnabled: false, - }), - ); + it.effect( + "returns ready with unknown auth when app-server does not require OpenAI auth", + () => + Effect.gen(function* () { + const status = yield* checkCodexProviderStatus(() => + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: null, + requiresOpenaiAuth: false, + }, + }), + ), + ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.auth.type, "team"); - assert.strictEqual(status.auth.label, "ChatGPT Team Subscription"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - false, - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "unknown"); + }), ); it.effect("returns an api key label for codex api key auth", () => Effect.gen(function* () { - yield* withTempCodexHome(); const status = yield* checkCodexProviderStatus(() => - Effect.succeed({ - type: "apiKey" as const, - planType: null, - sparkEnabled: false, - }), + Effect.succeed( + makeCodexProbeSnapshot({ + account: { + account: { type: "apiKey" }, + requiresOpenaiAuth: false, + }, + }), + ), ); - assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "apiKey"); assert.strictEqual(status.auth.label, "OpenAI API Key"); - assert.deepStrictEqual( - status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), - false, - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect.skipIf(process.platform === "win32")( - "inherits PATH when launching the codex probe with a CODEX_HOME override", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-test-codex-bin-", - }); - const codexPath = path.join(binDir, "codex"); - yield* fileSystem.writeFileString( - codexPath, - [ - "#!/bin/sh", - 'if [ "$1" = "--version" ]; then', - ' echo "codex-cli 1.0.0"', - " exit 0", - "fi", - 'if [ "$1" = "login" ] && [ "$2" = "status" ]; then', - ' echo "Logged in using ChatGPT"', - " exit 0", - "fi", - 'echo "unexpected args: $*" >&2', - "exit 1", - "", - ].join("\n"), - ); - yield* fileSystem.chmod(codexPath, 0o755); - const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-test-codex-home-", - }); - const previousPath = process.env.PATH; - process.env.PATH = binDir; - - try { - const serverSettingsLayer = ServerSettingsService.layerTest({ - providers: { - codex: { - homePath: customCodexHome, - }, - }, - }); - - const status = yield* checkCodexProviderStatus().pipe( - Effect.provide(serverSettingsLayer), - ); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - } finally { - process.env.PATH = previousPath; - } - }), + }), ); it.effect("returns unavailable when codex is missing", () => Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); + const status = yield* checkCodexProviderStatus(() => + Effect.fail( + new CodexErrors.CodexAppServerSpawnError({ + command: "codex app-server", + cause: new Error("spawn codex ENOENT"), + }), + ), + ); assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); @@ -447,107 +281,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( status.message, "Codex CLI (`codex`) is not installed or not on PATH.", ); - }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))), - ); - - it.effect("returns unavailable when codex is below the minimum supported version", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns unauthenticated when auth probe reports login required", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unauthenticated"); - assert.strictEqual( - status.message, - "Codex CLI is not authenticated. Run `codex login` and try again.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") { - return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 }; - } - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns unauthenticated when login status output includes 'not logged in'", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unauthenticated"); - assert.strictEqual( - status.message, - "Codex CLI is not authenticated. Run `codex login` and try again.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") - return { stdout: "Not logged in\n", stderr: "", code: 1 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns warning when login status command is unsupported", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "warning"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Codex CLI authentication status command is unavailable in this Codex version.", - ); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") { - return { stdout: "", stderr: "error: unknown command 'login'", code: 2 }; - } - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + }), ); }); @@ -677,7 +411,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( Schema.decodeSync(ServerSettings)( deepMerge(DEFAULT_SERVER_SETTINGS, { providers: { - claudeAgent: { enabled: false }, + codex: { enabled: false }, cursor: { enabled: false }, }, }), @@ -697,14 +431,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( spawnCount += 1; const joined = args.join(" "); if (joined === "--version") { - if (command === "codex") { - return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - } return { stdout: "claude 1.0.0\n", stderr: "", code: 0 }; } - if (joined === "login status") { - return { stdout: "Logged in\n", stderr: "", code: 0 }; - } if (joined === "auth status") { return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; } @@ -722,8 +450,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( const refreshed = yield* Effect.gen(function* () { for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) { const providers = yield* registry.getProviders; - const codexProvider = providers.find((provider) => provider.provider === "codex"); - if (codexProvider?.status === "ready") { + const claudeProvider = providers.find( + (provider) => provider.provider === "claudeAgent", + ); + if (claudeProvider?.status === "ready") { return providers; } yield* Effect.sleep("10 millis"); @@ -731,99 +461,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( return yield* registry.getProviders; }); assert.strictEqual( - refreshed.find((provider) => provider.provider === "codex")?.status, + refreshed.find((provider) => provider.provider === "claudeAgent")?.status, "ready", ); }).pipe(Effect.provide(runtimeServices)); }), ); - it.effect("reruns codex health when codex provider settings change", () => - Effect.gen(function* () { - const serverSettings = yield* makeMutableServerSettingsService(); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const providerRegistryLayer = ProviderRegistryLive.pipe( - Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge( - Layer.succeed(OpenCodeProvider, { - getSnapshot: Effect.succeed(fakeOpenCodeSnapshot), - refresh: Effect.succeed(fakeOpenCodeSnapshot), - streamChanges: Stream.empty, - }), - ), - Layer.provideMerge( - mockCommandSpawnerLayer((command, args) => { - const joined = args.join(" "); - if (joined === "--version") { - if (command === "codex") { - return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - } - return { stdout: "", stderr: "spawn ENOENT", code: 1 }; - } - if (joined === "about --format json") { - return { - stdout: JSON.stringify({ - cliVersion: "2026.04.09-f2b0fcd", - userEmail: null, - }), - stderr: "", - code: 0, - }; - } - if (joined === "about") { - return { stdout: "", stderr: "spawn ENOENT", code: 1 }; - } - if (joined === "login status") { - return { stdout: "Logged in\n", stderr: "", code: 0 }; - } - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ); - const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( - Scope.provide(scope), - ); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry; - - const refreshed = yield* registry.refresh("codex"); - assert.strictEqual( - refreshed.find((status) => status.provider === "codex")?.status, - "ready", - ); - - yield* serverSettings.updateSettings({ - providers: { - codex: { - binaryPath: "/custom/codex", - }, - }, - }); - - for (let attempt = 0; attempt < 20; attempt += 1) { - const updated = yield* registry.getProviders; - if (updated.find((status) => status.provider === "codex")?.status === "error") { - return; - } - yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0))); - } - - const updated = yield* registry.getProviders; - assert.strictEqual( - updated.find((status) => status.provider === "codex")?.status, - "error", - ); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - it.effect( "keeps cursor disabled and skips probing when the provider setting is disabled", () => @@ -832,6 +476,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( Schema.decodeSync(ServerSettings)( deepMerge(DEFAULT_SERVER_SETTINGS, { providers: { + codex: { + enabled: false, + }, cursor: { enabled: false, }, @@ -858,9 +505,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( if (joined === "--version") { return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 }; } - if (joined === "login status") { - return { stdout: "Logged in\n", stderr: "", code: 0 }; - } if (joined === "auth status") { return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; } @@ -919,238 +563,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ); }); - // ── Custom model provider: checkCodexProviderStatus integration ─── - - describe("checkCodexProviderStatus with custom model provider", () => { - it.effect( - "skips auth probe and returns ready when a custom model provider is configured", - () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - 'model_provider = "portkey"', - "", - "[model_providers.portkey]", - 'base_url = "https://api.portkey.ai/v1"', - 'env_key = "PORTKEY_API_KEY"', - ].join("\n"), - ); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.provider, "codex"); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Using a custom Codex model provider; OpenAI login check skipped.", - ); - }).pipe( - Effect.provide( - // The spawner only handles --version; if the test attempts - // "login status" the throw proves the auth probe was NOT skipped. - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - throw new Error(`Auth probe should have been skipped but got args: ${joined}`); - }), - ), - ), - ); - - it.effect("still reports error when codex CLI is missing even with custom provider", () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - 'model_provider = "portkey"', - "", - "[model_providers.portkey]", - 'base_url = "https://api.portkey.ai/v1"', - 'env_key = "PORTKEY_API_KEY"', - ].join("\n"), - ); - const status = yield* checkCodexProviderStatus(); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, false); - }).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))), - ); - }); - - describe("checkCodexProviderStatus with openai model provider", () => { - it.effect("still runs auth probe when model_provider is openai", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "openai"\n'); - const status = yield* checkCodexProviderStatus(); - // The auth probe runs and sees "not logged in" → error - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.auth.status, "unauthenticated"); - }).pipe( - Effect.provide( - mockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; - if (joined === "login status") - return { stdout: "Not logged in\n", stderr: "", code: 1 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - }); - - // ── parseAuthStatusFromOutput pure tests ────────────────────────── - - describe("parseAuthStatusFromOutput", () => { - it("exit code 0 with no auth markers is ready", () => { - const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); - assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.auth.status, "authenticated"); - }); - - it("JSON with authenticated=false is unauthenticated", () => { - const parsed = parseAuthStatusFromOutput({ - stdout: '[{"authenticated":false}]\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.auth.status, "unauthenticated"); - }); - - it("JSON without auth marker is warning", () => { - const parsed = parseAuthStatusFromOutput({ - stdout: '[{"ok":true}]\n', - stderr: "", - code: 0, - }); - assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.auth.status, "unknown"); - }); - }); - - // ── readCodexConfigModelProvider tests ───────────────────────────── - - describe("readCodexConfigModelProvider", () => { - it.effect("returns undefined when config file does not exist", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); - }), - ); - - it.effect("returns undefined when config has no model_provider key", () => - Effect.gen(function* () { - yield* withTempCodexHome('model = "gpt-5-codex"\n'); - assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); - }), - ); - - it.effect("returns the provider when model_provider is set at top level", () => - Effect.gen(function* () { - yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n'); - assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey"); - }), - ); - - it.effect("returns openai when model_provider is openai", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "openai"\n'); - assert.strictEqual(yield* readCodexConfigModelProvider(), "openai"); - }), - ); - - it.effect("ignores model_provider inside section headers", () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - 'model = "gpt-5-codex"', - "", - "[model_providers.portkey]", - 'base_url = "https://api.portkey.ai/v1"', - 'model_provider = "should-be-ignored"', - "", - ].join("\n"), - ); - assert.strictEqual(yield* readCodexConfigModelProvider(), undefined); - }), - ); - - it.effect("handles comments and whitespace", () => - Effect.gen(function* () { - yield* withTempCodexHome( - [ - "# This is a comment", - "", - ' model_provider = "azure" ', - "", - "[profiles.deep-review]", - 'model = "gpt-5-pro"', - ].join("\n"), - ); - assert.strictEqual(yield* readCodexConfigModelProvider(), "azure"); - }), - ); - - it.effect("handles single-quoted values in TOML", () => - Effect.gen(function* () { - yield* withTempCodexHome("model_provider = 'mistral'\n"); - assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral"); - }), - ); - }); - - // ── hasCustomModelProvider tests ─────────────────────────────────── - - describe("hasCustomModelProvider", () => { - it.effect("returns false when no config file exists", () => - Effect.gen(function* () { - yield* withTempCodexHome(); - assert.strictEqual(yield* hasCustomModelProvider, false); - }), - ); - - it.effect("returns false when model_provider is not set", () => - Effect.gen(function* () { - yield* withTempCodexHome('model = "gpt-5-codex"\n'); - assert.strictEqual(yield* hasCustomModelProvider, false); - }), - ); - - it.effect("returns false when model_provider is openai", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "openai"\n'); - assert.strictEqual(yield* hasCustomModelProvider, false); - }), - ); - - it.effect("returns true when model_provider is portkey", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "portkey"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - - it.effect("returns true when model_provider is azure", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "azure"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - - it.effect("returns true when model_provider is ollama", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "ollama"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - - it.effect("returns true when model_provider is a custom proxy", () => - Effect.gen(function* () { - yield* withTempCodexHome('model_provider = "my-company-proxy"\n'); - assert.strictEqual(yield* hasCustomModelProvider, true); - }), - ); - }); - // ── checkClaudeProviderStatus tests ────────────────────────── describe("checkClaudeProviderStatus", () => { diff --git a/apps/server/src/provider/codex/CodexSessionRuntime.test.ts b/apps/server/src/provider/codex/CodexSessionRuntime.test.ts index eb8e5471b1..3aae8d4111 100644 --- a/apps/server/src/provider/codex/CodexSessionRuntime.test.ts +++ b/apps/server/src/provider/codex/CodexSessionRuntime.test.ts @@ -1,13 +1,43 @@ import assert from "node:assert/strict"; -import { Effect } from "effect"; +import { Effect, Schema } from "effect"; import { describe, it } from "vitest"; +import { ThreadId } from "@t3tools/contracts"; +import * as CodexErrors from "effect-codex-app-server/errors"; +import * as CodexRpc from "effect-codex-app-server/rpc"; import { CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, } from "./CodexDeveloperInstructions.ts"; -import { buildTurnStartParams } from "./CodexSessionRuntime.ts"; +import { + buildTurnStartParams, + isRecoverableThreadResumeError, + openCodexThread, +} from "./CodexSessionRuntime.ts"; + +function makeThreadOpenResponse( + threadId: string, +): CodexRpc.ClientRequestResponsesByMethod["thread/start"] { + return { + cwd: "/tmp/project", + model: "gpt-5.3-codex", + modelProvider: "openai", + approvalPolicy: "never", + approvalsReviewer: "user", + sandbox: { type: "danger-full-access" }, + thread: { + id: threadId, + createdAt: "2026-04-18T00:00:00.000Z", + source: { session: "cli" }, + turns: [], + status: { + state: "idle", + activeFlags: [], + }, + }, + } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"]; +} describe("buildTurnStartParams", () => { it("includes plan collaboration mode when requested", () => { @@ -116,3 +146,109 @@ describe("buildTurnStartParams", () => { }); }); }); + +describe("isRecoverableThreadResumeError", () => { + it("matches missing thread errors", () => { + assert.equal( + isRecoverableThreadResumeError( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "Thread does not exist", + }), + ), + true, + ); + }); + + it("ignores non-recoverable resume errors", () => { + assert.equal( + isRecoverableThreadResumeError( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "Permission denied", + }), + ), + false, + ); + }); +}); + +describe("openCodexThread", () => { + it("falls back to thread/start when resume fails recoverably", async () => { + const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = []; + const started = makeThreadOpenResponse("fresh-thread"); + const client = { + request: ( + method: M, + payload: CodexRpc.ClientRequestParamsByMethod[M], + ) => { + calls.push({ method, payload }); + if (method === "thread/resume") { + return Effect.fail( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "thread not found", + }), + ); + } + return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]); + }, + }; + + const opened = await Effect.runPromise( + openCodexThread({ + client, + threadId: ThreadId.make("thread-1"), + runtimeMode: "full-access", + cwd: "/tmp/project", + requestedModel: "gpt-5.3-codex", + serviceTier: undefined, + resumeThreadId: "stale-thread", + }), + ); + + assert.equal(opened.thread.id, "fresh-thread"); + assert.deepStrictEqual( + calls.map((call) => call.method), + ["thread/resume", "thread/start"], + ); + }); + + it("propagates non-recoverable resume failures", async () => { + const client = { + request: ( + method: M, + _payload: CodexRpc.ClientRequestParamsByMethod[M], + ) => { + if (method === "thread/resume") { + return Effect.fail( + new CodexErrors.CodexAppServerRequestError({ + code: -32603, + errorMessage: "timed out waiting for server", + }), + ); + } + return Effect.succeed( + makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M], + ); + }, + }; + + await assert.rejects( + Effect.runPromise( + openCodexThread({ + client, + threadId: ThreadId.make("thread-1"), + runtimeMode: "full-access", + cwd: "/tmp/project", + requestedModel: "gpt-5.3-codex", + serviceTier: undefined, + resumeThreadId: "stale-thread", + }), + ), + (error: unknown) => + Schema.is(CodexErrors.CodexAppServerRequestError)(error) && + error.errorMessage === "timed out waiting for server", + ); + }); +}); diff --git a/apps/server/src/provider/codex/CodexSessionRuntime.ts b/apps/server/src/provider/codex/CodexSessionRuntime.ts index afa08cef5d..ede2ec60ba 100644 --- a/apps/server/src/provider/codex/CodexSessionRuntime.ts +++ b/apps/server/src/provider/codex/CodexSessionRuntime.ts @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"; import { ApprovalRequestId, + DEFAULT_MODEL_BY_PROVIDER, EventId, ProviderItemId, type ProviderApprovalDecision, @@ -25,12 +26,6 @@ import * as CodexRpc from "effect-codex-app-server/rpc"; import * as EffectCodexSchema from "effect-codex-app-server/schema"; import { buildCodexInitializeParams } from "../codexAppServer.ts"; -import { - CODEX_DEFAULT_MODEL, - readCodexAccountSnapshotResponse, - resolveCodexModelForAccount, - type CodexAccountSnapshot, -} from "../codexAccount.ts"; import { CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, @@ -46,6 +41,13 @@ const BENIGN_ERROR_LOG_SNIPPETS = [ "state db missing rollout path for thread", "state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back", ]; +const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ + "not found", + "missing thread", + "no such thread", + "unknown thread", + "does not exist", +]; export const CodexResumeCursorSchema = Schema.Struct({ threadId: Schema.String, @@ -300,7 +302,7 @@ function buildCodexCollaborationMode(input: { if (input.interactionMode === undefined) { return undefined; } - const model = normalizeCodexModelSlug(input.model) ?? CODEX_DEFAULT_MODEL; + const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL_BY_PROVIDER.codex; return { mode: input.interactionMode, settings: { @@ -379,6 +381,54 @@ function classifyCodexStderrLine(rawLine: string): { readonly message: string } return { message: line }; } +export function isRecoverableThreadResumeError(error: unknown): boolean { + const message = (error instanceof Error ? error.message : String(error)).toLowerCase(); + return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet)); +} + +type CodexThreadOpenResponse = + | CodexRpc.ClientRequestResponsesByMethod["thread/start"] + | CodexRpc.ClientRequestResponsesByMethod["thread/resume"]; + +export const openCodexThread = (input: { + readonly client: CodexClient.CodexAppServerClientShape; + readonly threadId: ThreadId; + readonly runtimeMode: RuntimeMode; + readonly cwd: string; + readonly requestedModel: string | undefined; + readonly serviceTier: EffectCodexSchema.V2ThreadStartParams__ServiceTier | undefined; + readonly resumeThreadId: string | undefined; +}): Effect.Effect => { + const resumeThreadId = input.resumeThreadId; + const startParams = buildThreadStartParams({ + cwd: input.cwd, + runtimeMode: input.runtimeMode, + model: input.requestedModel, + serviceTier: input.serviceTier, + }); + + if (resumeThreadId === undefined) { + return input.client.request("thread/start", startParams); + } + + return input.client + .request("thread/resume", { + threadId: resumeThreadId, + ...startParams, + }) + .pipe( + Effect.catchIf(isRecoverableThreadResumeError, (error) => + Effect.logWarning("codex app-server thread resume fell back to fresh start", { + threadId: input.threadId, + requestedRuntimeMode: input.runtimeMode, + resumeThreadId, + recoverable: true, + cause: error.message, + }).pipe(Effect.andThen(input.client.request("thread/start", startParams))), + ), + ); +}; + function readNotificationThreadId(notification: CodexServerNotification): string | undefined { switch (notification.method) { case "thread/started": @@ -654,12 +704,6 @@ export const makeCodexSessionRuntime = ( updatedAt: new Date().toISOString(), } satisfies ProviderSession; const sessionRef = yield* Ref.make(initialSession); - const accountRef = yield* Ref.make({ - type: "unknown", - planType: null, - sparkEnabled: false, - }); - const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid); const emitEvent = (event: Omit) => @@ -1078,37 +1122,17 @@ export const makeCodexSessionRuntime = ( yield* client.request("initialize", buildCodexInitializeParams()); yield* client.notify("initialized", undefined); - const accountSnapshot = readCodexAccountSnapshotResponse( - yield* client.request("account/read", {}), - ); - yield* Ref.set(accountRef, accountSnapshot); + const requestedModel = normalizeCodexModelSlug(options.model); - const requestedModel = resolveCodexModelForAccount( - normalizeCodexModelSlug(options.model), - accountSnapshot, - ); - - const resumedThreadId = readResumeCursorThreadId(options.resumeCursor); - const opened = - resumedThreadId !== undefined - ? yield* client.request("thread/resume", { - threadId: resumedThreadId, - ...buildThreadStartParams({ - cwd: options.cwd, - runtimeMode: options.runtimeMode, - model: requestedModel, - serviceTier: options.serviceTier, - }), - }) - : yield* client.request( - "thread/start", - buildThreadStartParams({ - cwd: options.cwd, - runtimeMode: options.runtimeMode, - model: requestedModel, - serviceTier: options.serviceTier, - }), - ); + const opened = yield* openCodexThread({ + client, + threadId: options.threadId, + runtimeMode: options.runtimeMode, + cwd: options.cwd, + requestedModel, + serviceTier: options.serviceTier, + resumeThreadId: readResumeCursorThreadId(options.resumeCursor), + }); const providerThreadId = opened.thread.id; const session = { @@ -1157,10 +1181,8 @@ export const makeCodexSessionRuntime = ( sendTurn: (input) => Effect.gen(function* () { const providerThreadId = yield* readProviderThreadId; - const account = yield* Ref.get(accountRef); - const normalizedModel = resolveCodexModelForAccount( - normalizeCodexModelSlug(input.model ?? (yield* Ref.get(sessionRef)).model), - account, + const normalizedModel = normalizeCodexModelSlug( + input.model ?? (yield* Ref.get(sessionRef)).model, ); const params = yield* buildTurnStartParams({ threadId: providerThreadId, diff --git a/apps/server/src/provider/codexAccount.ts b/apps/server/src/provider/codexAccount.ts deleted file mode 100644 index 7bae1a3602..0000000000 --- a/apps/server/src/provider/codexAccount.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type * as EffectCodexSchema from "effect-codex-app-server/schema"; -import type { ServerProviderModel } from "@t3tools/contracts"; - -export type CodexPlanType = - | "free" - | "go" - | "plus" - | "pro" - | "team" - | "business" - | "enterprise" - | "edu" - | "unknown"; - -export interface CodexAccountSnapshot { - readonly type: "apiKey" | "chatgpt" | "unknown"; - readonly planType: CodexPlanType | null; - readonly sparkEnabled: boolean; -} - -export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; -export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; -const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set(["pro"]); - -export function readCodexAccountSnapshotResponse( - response: EffectCodexSchema.V2GetAccountResponse, -): CodexAccountSnapshot { - const account = response.account; - if (!account) { - return { - type: "unknown", - planType: null, - sparkEnabled: false, - }; - } - - if (account.type === "apiKey") { - return { - type: "apiKey", - planType: null, - sparkEnabled: false, - }; - } - - return { - type: "chatgpt", - planType: account.planType as CodexPlanType, - sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(account.planType as CodexPlanType), - }; -} - -export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined { - if (account?.type === "apiKey") { - return "apiKey"; - } - - if (account?.type !== "chatgpt") { - return undefined; - } - - return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt"; -} - -export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined { - switch (codexAuthSubType(account)) { - case "apiKey": - return "OpenAI API Key"; - case "chatgpt": - return "ChatGPT Subscription"; - case "free": - return "ChatGPT Free Subscription"; - case "go": - return "ChatGPT Go Subscription"; - case "plus": - return "ChatGPT Plus Subscription"; - case "pro": - return "ChatGPT Pro Subscription"; - case "team": - return "ChatGPT Team Subscription"; - case "business": - return "ChatGPT Business Subscription"; - case "enterprise": - return "ChatGPT Enterprise Subscription"; - case "edu": - return "ChatGPT Edu Subscription"; - default: - return undefined; - } -} - -export function adjustCodexModelsForAccount( - baseModels: ReadonlyArray, - account: CodexAccountSnapshot | undefined, -): ReadonlyArray { - if (account?.sparkEnabled !== false) { - return baseModels; - } - - return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL); -} - -export function resolveCodexModelForAccount( - model: string | undefined, - account: CodexAccountSnapshot, -): string | undefined { - if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { - return model; - } - - return CODEX_DEFAULT_MODEL; -} diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts index f8fd60fd5f..4332b6f8d3 100644 --- a/apps/server/src/provider/codexAppServer.ts +++ b/apps/server/src/provider/codexAppServer.ts @@ -1,31 +1,125 @@ -import { spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; - -import type { ServerProviderSkill } from "@t3tools/contracts"; -import { Effect, Layer, Schema } from "effect"; +import type { + ModelCapabilities, + ServerProviderModel, + ServerProviderSkill, +} from "@t3tools/contracts"; +import { Effect, Layer } from "effect"; import * as CodexClient from "effect-codex-app-server/client"; import type * as EffectCodexSchema from "effect-codex-app-server/schema"; import type { Mutable } from "effect/Types"; -import { readCodexAccountSnapshotResponse, type CodexAccountSnapshot } from "./codexAccount.ts"; - -export interface CodexDiscoverySnapshot { - readonly account: CodexAccountSnapshot; +export interface CodexAppServerProviderSnapshot { + readonly account: EffectCodexSchema.V2GetAccountResponse; + readonly version: string | undefined; + readonly models: ReadonlyArray; readonly skills: ReadonlyArray; } -export class CodexDiscoveryProbeError extends Schema.TaggedErrorClass()( - "CodexDiscoveryProbeError", - { - detail: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return this.detail; +const REASONING_EFFORT_LABELS: Record< + EffectCodexSchema.V2ModelListResponse__ReasoningEffort, + string +> = { + none: "None", + minimal: "Minimal", + low: "Low", + medium: "Medium", + high: "High", + xhigh: "Extra High", +}; + +export function codexAccountAuthLabel(account: EffectCodexSchema.V2GetAccountResponse["account"]) { + if (!account) return undefined; + if (account.type === "apiKey") return "OpenAI API Key"; + + switch (account.planType) { + case "free": + return "ChatGPT Free Subscription"; + case "go": + return "ChatGPT Go Subscription"; + case "plus": + return "ChatGPT Plus Subscription"; + case "pro": + return "ChatGPT Pro Subscription"; + case "team": + return "ChatGPT Team Subscription"; + case "self_serve_business_usage_based": + case "business": + return "ChatGPT Business Subscription"; + case "enterprise_cbp_usage_based": + case "enterprise": + return "ChatGPT Enterprise Subscription"; + case "edu": + return "ChatGPT Edu Subscription"; + case "unknown": + return "ChatGPT Subscription"; + default: + account.planType satisfies never; + return undefined; } } -export function parseCodexSkillsListResponse( +function mapCodexModelCapabilities( + model: EffectCodexSchema.V2ModelListResponse__Model, +): ModelCapabilities { + return { + reasoningEffortLevels: model.supportedReasoningEfforts.map(({ reasoningEffort }) => ({ + value: reasoningEffort, + label: REASONING_EFFORT_LABELS[reasoningEffort], + ...(reasoningEffort === model.defaultReasoningEffort ? { isDefault: true } : {}), + })), + supportsFastMode: (model.additionalSpeedTiers ?? []).includes("fast"), + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }; +} + +const toDisplayName = (model: EffectCodexSchema.V2ModelListResponse__Model): string => { + // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash + return model.displayName + .replace(/^gpt/i, "GPT") // Handle start with 'gpt' or 'GPT' + .replace(/-([a-z])/g, (_, c) => "-" + c.toUpperCase()); +}; + +function parseCodexModelListResponse( + response: EffectCodexSchema.V2ModelListResponse, +): ReadonlyArray { + return response.data.map((model) => ({ + slug: model.model, + name: toDisplayName(model), + isCustom: false, + capabilities: mapCodexModelCapabilities(model), + })); +} + +function appendCustomCodexModels( + models: ReadonlyArray, + customModels: ReadonlyArray, +): ReadonlyArray { + if (customModels.length === 0) { + return models; + } + + const seen = new Set(models.map((model) => model.slug)); + const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null; + const customEntries: ServerProviderModel[] = []; + for (const rawModel of customModels) { + const slug = rawModel.trim(); + if (!slug || seen.has(slug)) { + continue; + } + seen.add(slug); + customEntries.push({ + slug, + name: slug, + isCustom: true, + capabilities: fallbackCapabilities, + }); + } + return customEntries.length === 0 ? models : [...models, ...customEntries]; +} + +function parseCodexSkillsListResponse( response: EffectCodexSchema.V2SkillsListResponse, cwd: string, ): ReadonlyArray { @@ -74,82 +168,76 @@ export function buildCodexInitializeParams(): EffectCodexSchema.V1InitializePara }; } -export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void { - if (process.platform === "win32" && child.pid !== undefined) { - try { - spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); - return; - } catch { - // Fall through to direct kill when taskkill is unavailable. - } - } +const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* ( + client: CodexClient.CodexAppServerClientShape, +) { + const models: ServerProviderModel[] = []; + let cursor: string | null | undefined = undefined; - child.kill(); -} + do { + const response: EffectCodexSchema.V2ModelListResponse = yield* client.request( + "model/list", + cursor ? { cursor } : {}, + ); + models.push(...parseCodexModelListResponse(response)); + cursor = response.nextCursor; + } while (cursor); -export const probeCodexDiscovery = Effect.fn("probeCodexDiscovery")(function* (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly cwd: string; -}) { - const clientContext = yield* Layer.build( - CodexClient.layerCommand({ - command: input.binaryPath, - args: ["app-server"], - ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}), - }), - ).pipe( - Effect.mapError( - (cause) => - new CodexDiscoveryProbeError({ - detail: `Codex discovery probe spawn failed: ${cause.message}`, - cause, - }), - ), - ); - const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( - Effect.provide(clientContext), - ); + return models; +}); - yield* client.request("initialize", buildCodexInitializeParams()).pipe( - Effect.mapError( - (cause) => - new CodexDiscoveryProbeError({ - detail: `Codex discovery probe initialize failed: ${cause.message}`, - cause, - }), - ), - ); - yield* client.notify("initialized", undefined).pipe( - Effect.mapError( - (cause) => - new CodexDiscoveryProbeError({ - detail: `Codex discovery probe initialized notification failed: ${cause.message}`, - cause, - }), - ), - ); - - const [skillsResponse, accountResponse] = yield* Effect.all( - [ - client.request("skills/list", { - cwds: [input.cwd], +export const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")( + function* (input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly cwd: string; + readonly customModels?: ReadonlyArray; + }) { + const clientContext = yield* Layer.build( + CodexClient.layerCommand({ + command: input.binaryPath, + args: ["app-server"], + cwd: input.cwd, + ...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}), }), - client.request("account/read", {}), - ], - { concurrency: "unbounded" }, - ).pipe( - Effect.mapError( - (cause) => - new CodexDiscoveryProbeError({ - detail: `Codex discovery probe request failed: ${cause.message}`, - cause, - }), - ), - ); + ); + const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( + Effect.provide(clientContext), + ); - return { - account: readCodexAccountSnapshotResponse(accountResponse), - skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), - } satisfies CodexDiscoverySnapshot; -}, Effect.scoped); + const initialize = yield* client.request("initialize", buildCodexInitializeParams()); + yield* client.notify("initialized", undefined); + + // Extract the version string after the first '/' in userAgent, up to the next space or the end + const versionMatch = initialize.userAgent.match(/\/([^\s]+)/); + const version = versionMatch ? versionMatch[1] : undefined; + + const accountResponse = yield* client.request("account/read", {}); + if (!accountResponse.account && accountResponse.requiresOpenaiAuth) { + return { + account: accountResponse, + version, + models: appendCustomCodexModels([], input.customModels ?? []), + skills: [], + } satisfies CodexAppServerProviderSnapshot; + } + + const [skillsResponse, models] = yield* Effect.all( + [ + client.request("skills/list", { + cwds: [input.cwd], + }), + requestAllCodexModels(client), + ], + { concurrency: "unbounded" }, + ); + + return { + account: accountResponse, + version, + models: appendCustomCodexModels(models, input.customModels ?? []), + skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), + } satisfies CodexAppServerProviderSnapshot; + }, + Effect.scoped, +); diff --git a/apps/server/src/provider/codexCliVersion.ts b/apps/server/src/provider/codexCliVersion.ts deleted file mode 100644 index 33f7cf85d2..0000000000 --- a/apps/server/src/provider/codexCliVersion.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts"; - -const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/; - -export const MINIMUM_CODEX_CLI_VERSION = "0.37.0"; - -export const compareCodexCliVersions = compareCliVersions; - -export function parseCodexCliVersion(output: string): string | null { - const match = CODEX_VERSION_PATTERN.exec(output); - if (!match?.[1]) { - return null; - } - - return normalizeCliVersion(match[1]); -} - -export function isCodexCliVersionSupported(version: string): boolean { - return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0; -} - -export function formatCodexCliUpgradeMessage(version: string | null): string { - const versionLabel = version ? `v${version}` : "the installed version"; - return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`; -} diff --git a/apps/server/src/provider/codexModels.ts b/apps/server/src/provider/codexModels.ts deleted file mode 100644 index a29fa90cc5..0000000000 --- a/apps/server/src/provider/codexModels.ts +++ /dev/null @@ -1,127 +0,0 @@ -import type { ModelCapabilities, ServerProviderModel } from "@t3tools/contracts"; - -export const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], -}; - -export const BUILT_IN_CODEX_MODELS: ReadonlyArray = [ - { - slug: "gpt-5.4", - name: "GPT-5.4", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.4-mini", - name: "GPT-5.4 Mini", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.3-codex", - name: "GPT-5.3 Codex", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.3-codex-spark", - name: "GPT-5.3 Codex Spark", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.2-codex", - name: "GPT-5.2 Codex", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, - { - slug: "gpt-5.2", - name: "GPT-5.2", - isCustom: false, - capabilities: { - reasoningEffortLevels: [ - { value: "xhigh", label: "Extra High" }, - { value: "high", label: "High", isDefault: true }, - { value: "medium", label: "Medium" }, - { value: "low", label: "Low" }, - ], - supportsFastMode: true, - supportsThinkingToggle: false, - contextWindowOptions: [], - promptInjectedEffortLevels: [], - }, - }, -]; - -export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities { - const slug = model?.trim(); - return ( - BUILT_IN_CODEX_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? - DEFAULT_CODEX_MODEL_CAPABILITIES - ); -} diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index bee0fd0029..baf384d6af 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -11,7 +11,6 @@ import { deriveCompletionDividerBeforeEntryId, deriveActiveWorkStartedAt, deriveActivePlanState, - PROVIDER_OPTIONS, derivePendingApprovals, derivePendingUserInputs, deriveTimelineEntries,