Switch Codex provider checks to app-server probe
- Use codex app-server snapshots for auth, models, and skills - Remove legacy CLI/config discovery paths and related helpers - Update tests for the new provider status flow
This commit is contained in:
1 parent
1fd0285160
commit
46fb2a207d
8 files changed
+527
-2034
No files matched your search
@@ -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",
|
||||
|
||||
@@ -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<Record<string, string>> = {
|
||||
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<ServerProviderState, "disabled">;
|
||||
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<ServerProviderModel> {
|
||||
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<ServerProviderModel>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
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<ServerProviderModel>,
|
||||
customModels: ReadonlyArray<string>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
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<ServerProviderSkill> {
|
||||
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<ServerProviderSkill> = {
|
||||
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<CodexAccountSnapshot | undefined>,
|
||||
resolveSkills?: (input: {
|
||||
probe: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<ReadonlyArray<ServerProviderSkill> | undefined>,
|
||||
readonly customModels: ReadonlyArray<string>;
|
||||
}) => 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<void>;
|
||||
readonly getDiscovery: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly cwd: string;
|
||||
}) => Effect.Effect<CodexDiscoverySnapshot | undefined>;
|
||||
}) =>
|
||||
(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),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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: <M extends "thread/start" | "thread/resume">(
|
||||
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: <M extends "thread/start" | "thread/resume">(
|
||||
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",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<CodexThreadOpenResponse, CodexErrors.CodexAppServerError> => {
|
||||
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<ProviderSession>(initialSession);
|
||||
const accountRef = yield* Ref.make<CodexAccountSnapshot>({
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
});
|
||||
|
||||
const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);
|
||||
|
||||
const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
|
||||
@@ -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,
|
||||
|
||||
@@ -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<CodexPlanType>(["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<ServerProviderModel>,
|
||||
account: CodexAccountSnapshot | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
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;
|
||||
}
|
||||
@@ -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<ServerProviderModel>;
|
||||
readonly skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}
|
||||
|
||||
export class CodexDiscoveryProbeError extends Schema.TaggedErrorClass<CodexDiscoveryProbeError>()(
|
||||
"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<ServerProviderModel> {
|
||||
return response.data.map((model) => ({
|
||||
slug: model.model,
|
||||
name: toDisplayName(model),
|
||||
isCustom: false,
|
||||
capabilities: mapCodexModelCapabilities(model),
|
||||
}));
|
||||
}
|
||||
|
||||
function appendCustomCodexModels(
|
||||
models: ReadonlyArray<ServerProviderModel>,
|
||||
customModels: ReadonlyArray<string>,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
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<ServerProviderSkill> {
|
||||
@@ -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<string>;
|
||||
}) {
|
||||
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,
|
||||
);
|
||||
@@ -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<ServerProviderModel> = [
|
||||
{
|
||||
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
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user