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 d0c35434b1..e3ddfa9e98 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -1,87 +1,36 @@ -import * as DateTime from "effect/DateTime"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Result from "effect/Result"; -import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; -import * as Types from "effect/Types"; -import * as ChildProcess from "effect/unstable/process/ChildProcess"; -import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner"; -import * as CodexClient from "effect-codex-app-server/client"; -import * as CodexSchema from "effect-codex-app-server/schema"; +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 type { - CodexSettings, - ServerProvider, - ServerProviderAuth, - ServerProviderSkill, - ServerProviderState, - ModelCapabilities, - ProviderOptionDescriptor, - ServerProviderModel, - ServerProviderSkill, -} 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 { createModelCapabilities } from "@t3tools/shared/model"; -import { resolveSpawnCommand } from "@t3tools/shared/shell"; -import { codexAppServerArgs, resolveCodexLaunchArgs } from "./codexLaunchArgs.ts"; -import { - AUTH_PROBE_TIMEOUT_MS, - buildServerProvider, - type ServerProviderDraft, -} 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({ @@ -116,372 +65,63 @@ const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider }); }; -const REASONING_EFFORT_LABELS: Readonly> = { - none: "None", - minimal: "Minimal", - low: "Low", - medium: "Medium", - high: "High", - xhigh: "Extra High", - max: "Max", - ultra: "Ultra", -}; +function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): { + readonly status: Exclude; + readonly auth: ServerProvider["auth"]; + readonly message?: string; +} { + 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"]; -const DEFAULT_SERVICE_TIER_ID = "default"; -const CURRENT_CODEX_MODELS = new Set(["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol"]); - -export function isLegacyCodexModel(model: string): boolean { - return !CURRENT_CODEX_MODELS.has(model); -} - -function reasoningEffortLabel(reasoningEffort: string): string { - return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort; -} - -function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) { - if (!account) return undefined; - if (account.type === "apiKey") return "OpenAI API Key"; - if (account.type === "amazonBedrock") return "Amazon Bedrock"; - if (account.type !== "chatgpt") return undefined; - - 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 20x Subscription"; - case "prolite": - return "ChatGPT Pro 5x 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; - } -} - -function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) { - if (!account || account.type !== "chatgpt") return undefined; - return account.email; -} - -export function mapCodexModelCapabilities( - model: CodexSchema.V2ModelListResponse__Model, -): ModelCapabilities { - const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) => - reasoningEffort === model.defaultReasoningEffort - ? { - id: reasoningEffort, - label: reasoningEffortLabel(reasoningEffort), - isDefault: true, - } - : { - id: reasoningEffort, - label: reasoningEffortLabel(reasoningEffort), - }, - ); - const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id; - const serviceTiers = - model.serviceTiers && model.serviceTiers.length > 0 - ? model.serviceTiers - : (model.additionalSpeedTiers ?? []).map((id) => ({ - id, - name: id === "fast" ? "Fast" : id, - description: "", - })); - const catalogDefaultServiceTier = serviceTiers.some( - (tier) => tier.id === model.defaultServiceTier, - ) - ? model.defaultServiceTier - : null; - const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID; - const optionDescriptors: ProviderOptionDescriptor[] = []; - - if (reasoningOptions.length > 0) { - optionDescriptors.push({ - id: "reasoningEffort", - label: "Reasoning", - type: "select", - options: reasoningOptions, - ...(defaultReasoning ? { currentValue: defaultReasoning } : {}), - }); - } - if (serviceTiers.length > 0) { - optionDescriptors.push({ - id: "serviceTier", - label: "Service Tier", - type: "select", - options: [ - { - id: DEFAULT_SERVICE_TIER_ID, - label: "Standard", - ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}), - }, - ...serviceTiers.map((tier) => ({ - id: tier.id, - label: tier.name, - ...(tier.description ? { description: tier.description } : {}), - ...(defaultServiceTier === tier.id ? { isDefault: true } : {}), - })), - ], - currentValue: defaultServiceTier, - }); + if (account.account) { + return { status: "ready", auth }; } - return createModelCapabilities({ - optionDescriptors, - }); -} - -const toDisplayName = (model: CodexSchema.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: CodexSchema.V2ModelListResponse, -): ReadonlyArray { - return response.data.map((model) => ({ - slug: model.model, - name: toDisplayName(model), - isCustom: false, - ...(model.isDefault ? { isDefault: true } : {}), - ...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}), - capabilities: mapCodexModelCapabilities(model), - })); -} - -/** - * Prefer our own default-model ranking when one of the preferred slugs is in - * the live catalog; otherwise keep whatever Codex itself flagged as default. - */ -export function applyPreferredCodexDefaultModel( - models: ReadonlyArray, -): ReadonlyArray { - const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) => - models.some((model) => model.slug === slug && !model.isCustom), - ); - if (!preferredSlug) { - return models; - } - return models.map((model) => { - if (model.slug === preferredSlug) { - return model.isDefault ? model : { ...model, isDefault: true }; - } - if (!model.isDefault) { - return model; - } - const { isDefault: _isDefault, ...rest } = model; - return rest; - }); -} - -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: CodexSchema.V2SkillsListResponse, - cwd: string, -): ReadonlyArray { - const matchingEntry = response.data.find((entry) => entry.cwd === cwd); - const skills = matchingEntry - ? matchingEntry.skills - : response.data.flatMap((entry) => entry.skills); - - return skills.map((skill) => { - const shortDescription = - skill.shortDescription ?? skill.interface?.shortDescription ?? undefined; - - const parsedSkill: Types.Mutable = { - name: skill.name, - path: skill.path, - enabled: skill.enabled, - }; - - if (skill.description) { - parsedSkill.description = skill.description; - } - if (skill.scope) { - parsedSkill.scope = skill.scope; - } - if (skill.interface?.displayName) { - parsedSkill.displayName = skill.interface.displayName; - } - if (shortDescription) { - parsedSkill.shortDescription = shortDescription; - } - - return parsedSkill; - }); -} - -const requestAllCodexModels = Effect.fn("requestAllCodexModels")(function* ( - client: CodexClient.CodexAppServerClient["Service"], -) { - const models: ServerProviderModel[] = []; - let cursor: string | null | undefined = undefined; - - do { - const response: CodexSchema.V2ModelListResponse = yield* client.request( - "model/list", - cursor ? { cursor } : {}, - ); - models.push(...parseCodexModelListResponse(response)); - cursor = response.nextCursor; - } while (cursor); - - return models; -}); - -export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams { - return { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: packageJson.version, - }, - capabilities: { - experimentalApi: true, - }, - }; -} - -const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: { - readonly binaryPath: string; - readonly homePath?: string; - readonly launchArgs?: 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 initialize = yield* client.request("initialize", { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: "0.1.0", - }, - capabilities: { - experimentalApi: true, - }, - }); - 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) { + if (account.requiresOpenaiAuth) { return { - account: accountResponse, - version, - models: appendCustomCodexModels([], input.customModels ?? []), - skills: [], - } satisfies CodexAppServerProviderSnapshot; + status: "error", + auth: { status: "unauthenticated" }, + message: "Codex CLI is not authenticated. Run `codex login` and try again.", + }; } - const [skillsResponse, models] = yield* Effect.all( - [ - client.request("skills/list", { - cwds: [input.cwd], - }), - requestAllCodexModels(client), - ], - { concurrency: "unbounded" }, - ); - - return { - account: accountResponse, - version, - models: applyPreferredCodexDefaultModel( - appendCustomCodexModels(models, input.customModels ?? []), - ), - skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), - } satisfies CodexAppServerProviderSnapshot; -}); + return { status: "ready", auth }; +} 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, @@ -492,258 +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), ); @@ -758,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 7cba731b7b..14a371af8e 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -1,21 +1,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, it, assert } from "@effect/vitest"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; -import * as Sink from "effect/Sink"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; +import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect"; import * as CodexErrors from "effect-codex-app-server/errors"; import { - ClaudeSettings, - CodexSettings, DEFAULT_SERVER_SETTINGS, ProviderDriverKind, ProviderInstanceId, @@ -31,12 +18,8 @@ import { deepMerge } from "@t3tools/shared/Struct"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; -import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; -import { checkClaudeProviderStatus } from "./ClaudeProvider.ts"; -import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts"; -import * as OpenCodeRuntime from "../opencodeRuntime.ts"; -import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; -import { ProviderInstanceRegistryHydrationLive } from "./ProviderInstanceRegistryHydration.ts"; +import { checkCodexProviderStatus } from "./CodexProvider.ts"; +import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts"; import { haveProvidersChanged, mergeProviderSnapshot, @@ -44,98 +27,16 @@ import { ProviderRegistryLive, selectProvidersByKind, } from "./ProviderRegistry.ts"; -import * as ServerConfig from "../../config.ts"; -import * as ServerSettingsModule from "../../serverSettings.ts"; -import { readProviderStatusCache, resolveProviderStatusCachePath } from "../providerStatusCache.ts"; -import type { ProviderInstance } from "../ProviderDriver.ts"; -import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts"; -import * as ProviderRegistry from "../Services/ProviderRegistry.ts"; -import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts"; -const decodeServerSettings = Schema.decodeSync(ServerSettings); -const encodeServerSettings = Schema.encodeSync(ServerSettings); -const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS); - -const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({}); -const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({}); -const decodeCodexSettings = Schema.decodeSync(CodexSettings); -const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({ - enabled: false, -}); +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 TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); - -const TestHttpClientLive = Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))), - ), -); - -const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({ - reportClientActivity: () => Effect.void, - removeRpcClient: () => Effect.void, - reportHostPowerState: () => Effect.void, - snapshot: Effect.succeed({ - hostPower: { - source: "unknown", - idle: "unknown", - idleSeconds: null, - locked: "unknown", - suspended: false, - onBattery: "unknown", - lowPowerMode: "unknown", - thermalState: "unknown", - stale: true, - updatedAt: TEST_EPOCH, - }, - leases: [], - activeForegroundLeaseCount: 0, - activeScopeKeys: [], - shouldRunOpportunisticWork: true, - updatedAt: TEST_EPOCH, - }), - streamChanges: Stream.empty, - hasDemand: () => Effect.succeed(true), - shouldRunScopeWork: () => Effect.succeed(true), - shouldRunOpportunisticWork: Effect.succeed(true), -}); - -function selectDescriptor( - id: string, - label: string, - options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>, -) { - return { - id, - label, - type: "select" as const, - options: [...options], - ...(options.find((option) => option.isDefault)?.id - ? { currentValue: options.find((option) => option.isDefault)?.id } - : {}), - }; -} - -function booleanDescriptor(id: string, label: string) { - return { - id, - label, - type: "boolean" as const, - }; -} - -type TestClaudeCapabilities = { - readonly email: string | undefined; - readonly subscriptionType: string | undefined; - readonly tokenSource: string | undefined; - readonly apiProvider: string | undefined; - readonly slashCommands: ReadonlyArray; -}; function claudeCapabilities(overrides: Partial = {}) { return () => @@ -245,40 +146,16 @@ function failingSpawnerLayer(description: string) { ); } -function hangingScopedSpawnerLayer(killCalls: Ref.Ref) { - return Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const handle = ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(1), - exitCode: Effect.never, - isRunning: Effect.succeed(true), - kill: () => Ref.update(killCalls, (current) => current + 1), - unref: Effect.succeed(Effect.void), - stdin: Sink.drain, - stdout: Stream.never, - stderr: Stream.never, - all: Stream.never, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }); - yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); - return handle; - }), - ), - ); -} - -const codexModelCapabilities = createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoningEffort", "Reasoning", [ - { id: "high", label: "High", isDefault: true }, - { id: "low", label: "Low" }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), +const codexModelCapabilities = { + reasoningEffortLevels: [ + { value: "high", label: "High", isDefault: true }, + { value: "low", label: "Low" }, ], -}) satisfies NonNullable; + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], +} satisfies NonNullable; function makeCodexProbeSnapshot( input: Partial = {}, @@ -338,13 +215,13 @@ function makeMutableServerSettingsService( }); } -it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), TestHttpClientLive))( +it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( "ProviderRegistry", (it) => { describe("checkCodexProviderStatus", () => { it.effect("uses the app-server account and model list for provider status", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + const status = yield* checkCodexProviderStatus(() => Effect.succeed( makeCodexProbeSnapshot({ skills: [ @@ -359,13 +236,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te }), ), ); + + assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.version, "1.0.0"); + assert.strictEqual(status.version, "codex-cli/1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "chatgpt"); - assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription"); - assert.strictEqual(status.auth.email, "test@example.com"); + assert.strictEqual(status.auth.type, "pro"); + assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); assert.deepStrictEqual(status.models, [ { slug: "gpt-live-codex", @@ -386,24 +264,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te }), ); - it.effect("passes configured launch args to the Codex provider probe", () => - Effect.gen(function* () { - let observedLaunchArgs: string | undefined; - const settings = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" }); - - const status = yield* checkCodexProviderStatus(settings, (input) => { - observedLaunchArgs = input.launchArgs; - return Effect.succeed(makeCodexProbeSnapshot()); - }); - - assert.strictEqual(status.status, "ready"); - assert.strictEqual(observedLaunchArgs, "--strict-config --enable foo"); - }), - ); - it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + const status = yield* checkCodexProviderStatus(() => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -427,7 +290,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te "returns ready with unknown auth when app-server does not require OpenAI auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + const status = yield* checkCodexProviderStatus(() => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -445,7 +308,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te it.effect("returns an api key label for codex api key auth", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + const status = yield* checkCodexProviderStatus(() => Effect.succeed( makeCodexProbeSnapshot({ account: { @@ -463,29 +326,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te }), ); - it.effect("returns an Amazon Bedrock label for codex Bedrock auth", () => - Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => - Effect.succeed( - makeCodexProbeSnapshot({ - account: { - account: { type: "amazonBedrock" }, - requiresOpenaiAuth: false, - }, - }), - ), - ); - - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "amazonBedrock"); - assert.strictEqual(status.auth.label, "Amazon Bedrock"); - }), - ); - it.effect("returns unavailable when codex is missing", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => + const status = yield* checkCodexProviderStatus(() => Effect.fail( new CodexErrors.CodexAppServerSpawnError({ command: "codex app-server", @@ -493,6 +336,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te }), ), ); + assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); assert.strictEqual(status.auth.status, "unknown"); @@ -502,28 +346,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te ); }), ); - - it.effect("closes the app-server probe scope when provider status times out", () => - Effect.gen(function* () { - const killCalls = yield* Ref.make(0); - const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe( - Effect.provide(hangingScopedSpawnerLayer(killCalls)), - Effect.forkChild, - ); - - yield* Effect.yieldNow; - yield* TestClock.adjust("11 seconds"); - yield* Effect.yieldNow; - - const status = yield* Fiber.join(statusFiber); - assert.strictEqual(status.status, "error"); - assert.strictEqual( - status.message, - "Timed out while checking Codex app-server provider status.", - ); - assert.strictEqual(yield* Ref.get(killCalls), 1); - }), - ); }); describe("ProviderRegistryLive", () => { @@ -821,36 +643,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te it.effect("does not run provider probes during layer construction", () => Effect.gen(function* () { - const codexDriver = ProviderDriverKind.make("codex"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const initialProvider = { - instanceId: codexInstanceId, - driver: codexDriver, - status: "warning", - enabled: true, - installed: false, - auth: { status: "unknown" }, - checkedAt: "2026-06-10T00:00:00.000Z", - version: null, - message: "Checking Codex provider status.", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshCalls = yield* Ref.make(0); - const instance = { - instanceId: codexInstanceId, - driverKind: codexDriver, - continuationIdentity: { - driverKind: codexDriver, - continuationKey: "codex:instance:codex", - }, - displayName: undefined, - enabled: true, - snapshot: { - maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ - provider: codexDriver, - packageName: null, + let spawnCount = 0; + const serverSettings = yield* makeMutableServerSettingsService( + Schema.decodeSync(ServerSettings)( + deepMerge(DEFAULT_SERVER_SETTINGS, { + providers: { + codex: { enabled: false }, + cursor: { enabled: false }, + }, }), getSnapshot: Effect.succeed(initialProvider), refresh: Ref.update(refreshCalls, (count) => count + 1).pipe( @@ -884,128 +684,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te ), Layer.provideMerge(NodeServices.layer), ), - ).pipe(Scope.provide(scope)); - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]); - assert.strictEqual(yield* Ref.get(refreshCalls), 0); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it("persists merged provider snapshots for the providers that were refreshed", () => { - const previousProviders = [ - { - instanceId: ProviderInstanceId.make("cursor"), - driver: ProviderDriverKind.make("cursor"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-14T00:00:00.000Z", - version: "2026.04.09-f2b0fcd", - models: [ - { - slug: "claude-opus-4-6", - name: "Opus 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoning", "Reasoning", [ - { id: "high", label: "High", isDefault: true }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - booleanDescriptor("thinking", "Thinking"), - ], - }), - }, - ], - slashCommands: [], - skills: [], - }, - { - instanceId: ProviderInstanceId.make("codex"), - driver: ProviderDriverKind.make("codex"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-14T00:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - }, - ] as const satisfies ReadonlyArray; - const refreshedCursor = { - ...previousProviders[0], - checkedAt: "2026-04-14T00:01:00.000Z", - models: [], - } satisfies ServerProvider; - - const mergedProviders = mergeProviderSnapshots(previousProviders, [refreshedCursor]); - const persistedProviders = selectProvidersByKind( - mergedProviders, - new Set([ProviderDriverKind.make("cursor")]), - ); - - assert.deepStrictEqual(persistedProviders, [ - { - ...refreshedCursor, - models: [...previousProviders[0].models], - }, - ]); - }); - - it.effect("persists the merged snapshot when a live update has empty models", () => - Effect.gen(function* () { - const cursorDriver = ProviderDriverKind.make("cursor"); - const cursorInstanceId = ProviderInstanceId.make("cursor"); - const initialProvider = { - instanceId: cursorInstanceId, - driver: cursorDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-14T00:00:00.000Z", - version: "2026.04.09-f2b0fcd", - models: [ - { - slug: "claude-opus-4-6", - name: "Opus 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoning", "Reasoning", [ - { id: "high", label: "High", isDefault: true }, - ]), - ], - }), - }, - ], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshedProvider = { - ...initialProvider, - checkedAt: "2026-04-14T00:01:00.000Z", - models: [], - } satisfies ServerProvider; - const changes = yield* PubSub.unbounded(); - const instance = { - instanceId: cursorInstanceId, - driverKind: cursorDriver, - continuationIdentity: { - driverKind: cursorDriver, - continuationKey: "cursor:instance:cursor", - }, - displayName: undefined, - enabled: true, - snapshot: { - maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ - provider: cursorDriver, - packageName: null, + Layer.provideMerge( + mockCommandSpawnerLayer((command, args) => { + spawnCount += 1; + const joined = args.join(" "); + if (joined === "--version") { + return { stdout: "claude 1.0.0\n", stderr: "", code: 0 }; + } + if (joined === "auth status") { + return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 }; + } + throw new Error(`Unexpected args: ${command} ${joined}`); }), getSnapshot: Effect.succeed(initialProvider), refresh: Effect.succeed(refreshedProvider), @@ -1042,673 +731,26 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te ), ).pipe(Scope.provide(scope)); - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - const config = yield* ServerConfig.ServerConfig; - const filePath = yield* resolveProviderStatusCachePath({ - cacheDir: config.providerStatusCacheDir, - instanceId: cursorInstanceId, - }); - - assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [ - ...initialProvider.models, - ]); - yield* PubSub.publish(changes, refreshedProvider); - - let cachedProvider = yield* readProviderStatusCache(filePath); - for ( - let attempt = 0; - attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt; - attempt += 1 - ) { - yield* TestClock.adjust("10 millis"); - yield* Effect.yieldNow; - cachedProvider = yield* readProviderStatusCache(filePath); - } - - assert.deepStrictEqual(cachedProvider, { - ...refreshedProvider, - models: [...initialProvider.models], - }); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it.effect( - "persists authoritative OpenCode removals without resurrecting them on a failed live refresh", - () => - Effect.gen(function* () { - const openCodeDriver = ProviderDriverKind.make("opencode"); - const openCodeInstanceId = ProviderInstanceId.make("opencode"); - const initialProvider = { - instanceId: openCodeInstanceId, - driver: openCodeDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-07-17T00:00:00.000Z", - version: "1.0.0", - models: [ - { - slug: "github/gpt-5", - name: "GPT-5", - subProvider: "GitHub", - isCustom: false, - capabilities: null, - }, - { - slug: "removed-plugin/model", - name: "Removed Plugin Model", - subProvider: "Removed Plugin", - isCustom: false, - capabilities: null, - }, - ], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const authoritativeProvider = { - ...initialProvider, - checkedAt: "2026-07-17T00:01:00.000Z", - models: [initialProvider.models[0]!], - } satisfies ServerProvider; - const failedProvider = { - ...authoritativeProvider, - status: "error", - auth: { status: "unknown" }, - checkedAt: "2026-07-17T00:02:00.000Z", - models: [], - message: "Failed to refresh OpenCode models.", - } satisfies ServerProvider; - const changes = yield* PubSub.unbounded(); - const instance = { - instanceId: openCodeInstanceId, - driverKind: openCodeDriver, - continuationIdentity: { - driverKind: openCodeDriver, - continuationKey: "opencode:instance:opencode", - }, - displayName: undefined, - enabled: true, - snapshot: { - maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ - provider: openCodeDriver, - packageName: null, - }), - getSnapshot: Effect.succeed(initialProvider), - refresh: Effect.succeed(authoritativeProvider), - streamChanges: Stream.fromPubSub(changes), - }, - adapter: {} as ProviderInstance["adapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - } satisfies ProviderInstance; - const instanceRegistryLayer = Layer.succeed( - ProviderInstanceRegistry.ProviderInstanceRegistry, - { - getInstance: (instanceId) => - Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined), - listInstances: Effect.succeed([instance]), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }, - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const runtimeServices = yield* Layer.build( - ProviderRegistryLive.pipe( - Layer.provideMerge(instanceRegistryLayer), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-opencode-authoritative-persist-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - const config = yield* ServerConfig.ServerConfig; - const filePath = yield* resolveProviderStatusCachePath({ - cacheDir: config.providerStatusCacheDir, - instanceId: openCodeInstanceId, - }); - - yield* PubSub.publish(changes, authoritativeProvider); - - let cachedProvider = yield* readProviderStatusCache(filePath); - for ( - let attempt = 0; - attempt < 50 && cachedProvider?.checkedAt !== authoritativeProvider.checkedAt; - attempt += 1 - ) { - yield* TestClock.adjust("10 millis"); - yield* Effect.yieldNow; - cachedProvider = yield* readProviderStatusCache(filePath); - } - - assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]); - - yield* PubSub.publish(changes, failedProvider); - for ( - let attempt = 0; - attempt < 50 && cachedProvider?.checkedAt !== failedProvider.checkedAt; - attempt += 1 - ) { - yield* TestClock.adjust("10 millis"); - yield* Effect.yieldNow; - cachedProvider = yield* readProviderStatusCache(filePath); - } - - assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]); - assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [ - authoritativeProvider.models[0]!, - ]); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it.effect("returns the cached provider list when a manual refresh fails", () => - Effect.gen(function* () { - const codexDriver = ProviderDriverKind.make("codex"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const cachedProvider = { - instanceId: codexInstanceId, - driver: codexDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-29T10:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const instance = { - instanceId: codexInstanceId, - driverKind: codexDriver, - continuationIdentity: { - driverKind: codexDriver, - continuationKey: "codex:instance:codex", - }, - displayName: undefined, - enabled: true, - snapshot: { - maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ - provider: codexDriver, - packageName: null, - }), - getSnapshot: Effect.succeed(cachedProvider), - refresh: Effect.die(new Error("simulated refresh failure")), - streamChanges: Stream.empty, - }, - adapter: {} as ProviderInstance["adapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - } satisfies ProviderInstance; - const instanceRegistryLayer = Layer.succeed( - ProviderInstanceRegistry.ProviderInstanceRegistry, - { - getInstance: (instanceId) => - Effect.succeed(instanceId === codexInstanceId ? instance : undefined), - listInstances: Effect.succeed([instance]), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }, - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const runtimeServices = yield* Layer.build( - ProviderRegistryLive.pipe( - Layer.provideMerge(instanceRegistryLayer), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-refresh-failure-", - }), - ), - Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), - Layer.provideMerge(NodeServices.layer), - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - - assert.deepStrictEqual(yield* registry.getProviders, [cachedProvider]); - assert.deepStrictEqual(yield* registry.refresh(codexDriver), [cachedProvider]); - assert.deepStrictEqual(yield* registry.refreshInstance(codexInstanceId), [ - cachedProvider, - ]); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it.effect("keeps consuming registry changes after one sync fails", () => - Effect.gen(function* () { - const codexDriver = ProviderDriverKind.make("codex"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const claudeDriver = ProviderDriverKind.make("claudeAgent"); - const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); - const codexProvider = { - instanceId: codexInstanceId, - driver: codexDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-29T10:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const claudeProvider = { - instanceId: claudeInstanceId, - driver: claudeDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-29T10:01:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const makeInstance = (provider: ServerProvider): ProviderInstance => ({ - instanceId: provider.instanceId, - driverKind: provider.driver, - continuationIdentity: { - driverKind: provider.driver, - continuationKey: `${provider.driver}:instance:${provider.instanceId}`, - }, - displayName: undefined, - enabled: true, - snapshot: { - maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ - provider: provider.driver, - packageName: null, - }), - getSnapshot: Effect.succeed(provider), - refresh: Effect.succeed(provider), - streamChanges: Stream.empty, - }, - adapter: {} as ProviderInstance["adapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - }); - const codexInstance = makeInstance(codexProvider); - const claudeInstance = makeInstance(claudeProvider); - const changes = yield* PubSub.unbounded(); - const instancesRef = yield* Ref.make>([codexInstance]); - const failNextList = yield* Ref.make(false); - const wait = () => Effect.yieldNow; - const instanceRegistryLayer = Layer.succeed( - ProviderInstanceRegistry.ProviderInstanceRegistry, - { - getInstance: (instanceId) => - Ref.get(instancesRef).pipe( - Effect.map((instances) => - instances.find((instance) => instance.instanceId === instanceId), - ), - ), - listInstances: Effect.gen(function* () { - const shouldFail = yield* Ref.get(failNextList); - if (shouldFail) { - yield* Ref.set(failNextList, false); - return yield* Effect.die(new Error("simulated registry list failure")); - } - return yield* Ref.get(instancesRef); - }), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.fromPubSub(changes), - subscribeChanges: PubSub.subscribe(changes), - }, - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const runtimeServices = yield* Layer.build( - ProviderRegistryLive.pipe( - Layer.provideMerge(instanceRegistryLayer), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-sync-failure-", - }), - ), - Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), - Layer.provideMerge(NodeServices.layer), - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - assert.deepStrictEqual(yield* registry.getProviders, [codexProvider]); - - yield* Ref.set(failNextList, true); - yield* PubSub.publish(changes, undefined); - - yield* Ref.set(instancesRef, [codexInstance, claudeInstance]); - yield* PubSub.publish(changes, undefined); - - let providers = yield* registry.getProviders; - for ( - let attempt = 0; - attempt < 50 && - !providers.some((provider) => provider.instanceId === claudeInstanceId); - attempt += 1 - ) { - yield* wait(); - providers = yield* registry.getProviders; - } - - assert.deepStrictEqual( - providers.map((provider) => provider.instanceId).toSorted(), - [codexInstanceId, claudeInstanceId].toSorted(), - ); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - // This test intentionally avoids `mockCommandSpawnerLayer` so the real - // `probeCodexAppServerProvider` path runs — including the full - // `codex app-server` RPC handshake via `CodexClient.layerChildProcess`. - // We point `binaryPath` at a name that cannot exist on any machine so - // the real `ChildProcessSpawner` deterministically returns ENOENT; the - // probe wraps that as `CodexAppServerSpawnError` and - // `checkCodexProviderStatus` turns it into the user-visible "not - // installed" error snapshot. If the aggregator's `syncLiveSources` - // breaks — the `codex_personal`-never-probes bug we are guarding - // against — that snapshot never lands in `getProviders` and the - // assertions below fail. - it.effect("propagates real Codex probe failures to the aggregator at boot", () => - Effect.gen(function* () { - const missingBinary = `t3code_codex_missing_`; - const serverSettings = yield* makeMutableServerSettingsService( - decodeServerSettings( - deepMerge(encodedDefaultServerSettings, { - providers: { - // Disable every built-in probe that would otherwise spawn - // on the CI host. `enabled: false` short-circuits each - // driver's probe *before* it touches the spawner, so the - // test environment stays isolated from the dev - // machine's PATH. - codex: { enabled: false }, - claudeAgent: { enabled: false }, - cursor: { enabled: false }, - grok: { enabled: false }, - opencode: { enabled: false }, - }, - // `providerInstances` keys are branded `ProviderInstanceId`; - // the branded index signature rejects plain string literals - // at the TS level even though the runtime schema happily - // accepts + decodes them. Cast the patch to `unknown` so - // the `Schema.decodeSync` below does the real validation. - providerInstances: { - // Matches the shape the user had in `.t3/dev/settings.json` - // when the bug was reported: a custom enabled Codex instance - // pointing at a binary the server has to actually spawn. - codex_personal: { - driver: "codex", - displayName: "Codex Personal", - enabled: true, - config: { - binaryPath: missingBinary, - homePath: `/tmp/${missingBinary}_home`, - }, - }, - } as unknown as ContractServerSettings["providerInstances"], - }), - ), - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const providerRegistryLayer = ProviderRegistryLive.pipe( - Layer.provideMerge(ProviderInstanceRegistryHydrationLive), - Layer.provideMerge( - Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), - ), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge(TestHttpClientLive), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), - Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), - // NO spawner mock — `ChildProcessSpawner` is supplied by the - // outer `NodeServices.layer` on `it.layer(...)` and will - // genuinely spawn a subprocess. The missing-binary ENOENT is - // what exercises the same failure mode as a misconfigured - // production `binaryPath`. - ); - 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", - ); - assert.notStrictEqual( - codexPersonal, - undefined, - `Expected the aggregator to know about codex_personal; instead saw: ${providers - .map((provider) => provider.instanceId) - .join(", ")}`, - ); - assert.strictEqual( - codexPersonal?.status, - "error", - "Real Codex probe against a missing binary should surface as 'error' in the aggregator", - ); - assert.strictEqual(codexPersonal?.installed, false); - assert.strictEqual( - codexPersonal?.message, - "Codex CLI (`codex`) is not installed or not on PATH.", - ); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - // Guards the second half of the reported bug: changing - // `providers.codex.binaryPath` in settings must tear down the live - // instance and rebuild it so a fresh probe runs with the new binary. - // This test drives the real settings stream → registry reconcile → - // aggregator sync pipeline and asserts that `getProviders` reflects - // the new background probe's outcome. - // - it.effect("re-probes when settings change the codex binaryPath", () => - Effect.gen(function* () { - const firstMissing = `t3code_codex_first_`; - const secondMissing = `t3code_codex_second_`; - const spawnedCommands: Array = []; - const serverSettings = yield* makeMutableServerSettingsService( - decodeServerSettings( - deepMerge(encodedDefaultServerSettings, { - providers: { - codex: { enabled: true, binaryPath: firstMissing }, - claudeAgent: { enabled: false }, - cursor: { enabled: false }, - grok: { enabled: false }, - opencode: { enabled: false }, - }, - }), - ), - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const providerRegistryLayer = ProviderRegistryLive.pipe( - Layer.provideMerge(ProviderInstanceRegistryHydrationLive), - Layer.provideMerge( - Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), - ), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge(TestHttpClientLive), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), - Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) => - ChildProcessSpawner.make((command) => { - spawnedCommands.push((command as { readonly command: string }).command); - return spawner.spawn(command); - }), - ), - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), - ); - const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( - Scope.provide(scope), - ); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - // Boot-time probe: the default codex instance is enabled with - // `firstMissing`, so the real spawner yields ENOENT and the - // snapshot should be `status: "error"`. - let initialProviders = yield* registry.getProviders; - for ( - let attempts = 0; - attempts < 50 && - initialProviders.find((provider) => provider.instanceId === "codex")?.status !== - "error"; - attempts += 1 - ) { - yield* TestClock.adjust("10 millis"); - yield* Effect.yieldNow; - initialProviders = yield* registry.getProviders; - } - const initialCodex = initialProviders.find( - (provider) => provider.instanceId === "codex", - ); - assert.strictEqual(initialCodex?.status, "error"); - assert.strictEqual(initialCodex?.installed, false); - assert.deepStrictEqual(spawnedCommands, [firstMissing]); - - // Drive a settings change. The Hydration layer's - // `SettingsWatcherLive` consumes this via `streamChanges`, - // calls `reconcile`, which rebuilds the codex instance (the - // envelope changed because `binaryPath` differs → `entryEqual` - // is false). The registry's `Stream.runForEach( - // instanceRegistry.streamChanges, () => syncLiveSources)` - // fires `syncLiveSources`, which subscribes and launches a fresh - // background refresh on the rebuilt instance. - yield* serverSettings.updateSettings({ - providers: { - codex: { enabled: true, binaryPath: secondMissing }, - }, - }); - - // Poll until the injected process boundary observes the new - // executable. This verifies the public settings-to-probe behavior - // without depending on timestamps assigned by TestClock. + assert.strictEqual(spawnCount > 0, true); const refreshed = yield* Effect.gen(function* () { - for (let attempts = 0; attempts < 60; attempts += 1) { + for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) { const providers = yield* registry.getProviders; - const codex = providers.find((provider) => provider.instanceId === "codex"); - if ( - codex !== undefined && - codex.status === "error" && - spawnedCommands.includes(secondMissing) - ) { + const claudeProvider = providers.find( + (provider) => provider.provider === "claudeAgent", + ); + if (claudeProvider?.status === "ready") { return providers; } - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; + yield* Effect.sleep("10 millis"); } return yield* registry.getProviders; }); - - const reprobedCodex = refreshed.find((provider) => provider.instanceId === "codex"); - assert.deepStrictEqual(spawnedCommands, [firstMissing, secondMissing]); - assert.strictEqual(reprobedCodex?.status, "error"); - assert.strictEqual(reprobedCodex?.installed, false); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it.effect("includes unavailable instance snapshots in getProviders", () => - Effect.gen(function* () { - const serverSettings = yield* makeMutableServerSettingsService( - decodeServerSettings( - deepMerge(encodedDefaultServerSettings, { - providers: { - codex: { enabled: false }, - claudeAgent: { enabled: false }, - cursor: { enabled: false }, - grok: { enabled: false }, - opencode: { enabled: false }, - }, - providerInstances: { - ghost_main: { - driver: "ghostDriver", - displayName: "A fork-only driver we don't ship", - enabled: false, - config: { arbitrary: "payload" }, - }, - } as unknown as ContractServerSettings["providerInstances"], - }), - ), - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const providerRegistryLayer = ProviderRegistryLive.pipe( - Layer.provideMerge(ProviderInstanceRegistryHydrationLive), - Layer.provideMerge( - Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), - ), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge(TestHttpClientLive), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive), - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge(BackgroundPolicyAlwaysRunLayer), - ); - const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe( - Scope.provide(scope), - ); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - const providers = yield* registry.getProviders; - const ghost = providers.find((provider) => provider.instanceId === "ghost_main"); - - assert.notStrictEqual(ghost, undefined); - assert.strictEqual(ghost?.driver, "ghostDriver"); - assert.strictEqual(ghost?.availability, "unavailable"); - assert.match(ghost?.unavailableReason ?? "", /ghostDriver/); + assert.strictEqual( + refreshed.find((provider) => provider.provider === "claudeAgent")?.status, + "ready", + ); }).pipe(Effect.provide(runtimeServices)); }), ); @@ -1763,11 +805,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te } const joined = args.join(" "); if (joined === "--version") { - return { - stdout: `${command} 1.0.0\n`, - stderr: "", - code: 0, - }; + return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 }; } if (joined === "auth status") { return { 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/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 - ); -}