UNPKG

ai-sdk-provider-codex-cli

Version:

AI SDK v7 provider for OpenAI Codex CLI (use ChatGPT Plus/Pro subscription)

1,115 lines (1,100 loc) • 40.9 kB
import { ProviderV4, LanguageModelV4, UnsupportedFunctionalityError } from '@ai-sdk/provider'; import { ZodType } from 'zod'; /** * Logger interface for custom logging. */ interface Logger { debug: (message: string) => void; info: (message: string) => void; warn: (message: string) => void; error: (message: string) => void; } /** * Known Codex-capable model IDs with string fallback for forward compatibility. */ type CodexModelId = 'gpt-6-sol' | 'gpt-6-astra' | 'gpt-6-luna' | 'gpt-5.6-sol' | 'gpt-5.6-terra' | 'gpt-5.6-luna' | 'gpt-5.5' | 'gpt-5.3-codex-spark' | 'gpt-5.3-codex' | 'gpt-5.2-codex' | 'gpt-5.2-codex-max' | 'gpt-5.2-codex-mini' | 'gpt-5.1' | 'gpt-5.2' | (string & {}); /** * Approval policy for exec mode (`-c approval_policy=...`). * * `'on-failure'` is deprecated: Codex CLI 0.143 retired it (the core config * keeps it only as an alias of `'on-request'`), so the provider translates it * to `'on-request'` and warns. Note that headless `codex exec` runs force * `never` internally unless an automatic approvals reviewer is configured. */ type ApprovalMode = 'untrusted' | 'on-failure' | 'on-request' | 'never'; type SandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access'; type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra'; /** * Every reasoning effort level known to this provider, in ascending order. * Kept in compile-time sync with `ReasoningEffort`. */ declare const CODEX_REASONING_EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]; /** * Codex service tier ("fast mode"). Mirrors the `service_tier` config key and * the app-server `serviceTier` protocol field. * * - `'fast'`: Fast mode (Codex sends it as the catalog tier `priority`): * faster responses at higher usage (2.5x of a ChatGPT plan's included * limits; API-key users pay the API fast-mode rate). * - `'ultrafast'`: Ultrafast mode, only advertised by some models * (GPT-6 Astra / GPT-6.1 Sol) and plans. * - `'default'`: explicit standard speed, e.g. to override a `service_tier` * set in `~/.codex/config.toml` (as a model setting) or for a single call * (as a per-call provider option). * * Tiers are catalog-driven, so any other id advertised by the active model is * accepted as-is (`listModels()` reports `serviceTiers` / `defaultServiceTier` * per model). Codex warns and omits a tier the model does not advertise * instead of failing. When undefined, nothing is sent and Codex falls back to * config.toml / the model's default tier. */ type ServiceTier = 'fast' | 'ultrafast' | 'default' | (string & {}); /** * Service tiers known to this provider. Not exhaustive: see `ServiceTier`. */ declare const CODEX_SERVICE_TIERS: readonly ["fast", "ultrafast", "default"]; /** * Reasoning summary detail level for exec mode. */ type ReasoningSummary = 'auto' | 'detailed'; type ReasoningSummaryFormat = 'none' | 'experimental'; type ModelVerbosity = 'low' | 'medium' | 'high'; interface McpServerBase { enabled?: boolean; startupTimeoutSec?: number; toolTimeoutSec?: number; enabledTools?: string[]; disabledTools?: string[]; } interface McpServerStdio extends McpServerBase { transport: 'stdio'; command: string; args?: string[]; env?: Record<string, string>; cwd?: string; } interface McpServerHttp extends McpServerBase { transport: 'http'; url: string; bearerToken?: string; bearerTokenEnvVar?: string; httpHeaders?: Record<string, string>; envHttpHeaders?: Record<string, string>; } type McpServerConfig = McpServerStdio | McpServerHttp; type CodexConfigOverrideValue = string | number | boolean | object; interface CodexSharedSettings { cwd?: string; approvalMode?: ApprovalMode; sandboxMode?: SandboxMode; env?: Record<string, string>; verbose?: boolean; logger?: Logger | false; reasoningEffort?: ReasoningEffort; reasoningSummary?: ReasoningSummary; reasoningSummaryFormat?: ReasoningSummaryFormat; modelVerbosity?: ModelVerbosity; /** Codex service tier ("fast mode"); exec emits `-c service_tier=<tier>`. */ serviceTier?: ServiceTier; mcpServers?: Record<string, McpServerConfig>; rmcpClient?: boolean; configOverrides?: Record<string, CodexConfigOverrideValue>; } interface CodexSharedProviderOptions { reasoningEffort?: ReasoningEffort; reasoningSummary?: ReasoningSummary; reasoningSummaryFormat?: ReasoningSummaryFormat; textVerbosity?: ModelVerbosity; serviceTier?: ServiceTier; mcpServers?: Record<string, McpServerConfig>; rmcpClient?: boolean; configOverrides?: Record<string, CodexConfigOverrideValue>; } interface CodexExecSettings extends CodexSharedSettings { codexPath?: string; addDirs?: string[]; /** * @deprecated Codex CLI 0.147 removed `codex exec --full-auto`. The flag now * defaults the emitted sandbox to `workspace-write` and the approval policy * to `never` (what `--full-auto` pinned, even with * `approvals_reviewer = "auto_review"` configured). Explicit `sandboxMode` / * `approvalMode` settings (including provider `defaultSettings`) win over * those defaults, and a later `configOverrides.approval_policy` can replace * the emitted policy. `fullAuto` still suppresses * `dangerouslyBypassApprovalsAndSandbox`. To migrate, set both * `sandboxMode: 'workspace-write'` and `approvalMode: 'never'`, and drop * `dangerouslyBypassApprovalsAndSandbox` if it was configured alongside. */ fullAuto?: boolean; dangerouslyBypassApprovalsAndSandbox?: boolean; skipGitRepoCheck?: boolean; color?: 'always' | 'never' | 'auto'; allowNpx?: boolean; outputLastMessageFile?: string; profile?: string; oss?: boolean; webSearch?: boolean; configOverrides?: Record<string, CodexConfigOverrideValue>; } interface CodexExecProviderSettings { defaultSettings?: CodexExecSettings; } /** * Per-call overrides supplied through AI SDK providerOptions. */ interface CodexExecProviderOptions extends CodexSharedProviderOptions { addDirs?: string[]; } type CodexCliSettings = CodexExecSettings; type CodexCliProviderSettings = CodexExecProviderSettings; type CodexCliProviderOptions = CodexExecProviderOptions; type JsonRpcId = number | string; interface JsonRpcRequest { id: JsonRpcId; method: string; params?: unknown; } interface JsonRpcResponse<T = unknown> { id: JsonRpcId; result: T; } interface JsonRpcError { code: number; message: string; data?: unknown; } interface JsonRpcErrorResponse { id: JsonRpcId | null; error: JsonRpcError; } interface JsonRpcNotification { method: string; params?: Record<string, unknown>; } type JsonRpcMessage = JsonRpcRequest | JsonRpcResponse | JsonRpcErrorResponse | JsonRpcNotification; /** One entry of `Model.serviceTiers` from `model/list` (codex >= 0.153). */ interface ModelServiceTier { /** Catalog tier id, e.g. 'priority' (Fast) or 'ultrafast'. */ id: string; /** Display name, e.g. 'Fast'. */ name: string; description: string; } /** * Vendored subset of the codex 0.142.5 `Model` wire type (renamed upstream * from `ModelInfo`), plus fields only pre-0.142 servers return. */ interface ModelInfo { id: string; /** Underlying model slug (codex >= 0.142). */ model?: string; /** Display name; replaces the pre-0.142 `name` field (codex >= 0.142). */ displayName?: string; description?: string | null; /** Whether the model is hidden from the default picker list (codex >= 0.142). */ hidden?: boolean; isDefault?: boolean | null; /** External contract: only pre-0.142 servers return `name`. */ name?: string | null; /** External contract: only pre-0.142 servers return `modelProvider`. */ modelProvider?: string | null; /** Service tiers advertised by the model (codex >= 0.153). */ serviceTiers?: ModelServiceTier[]; /** Catalog default service tier id for this model, when one is configured (codex >= 0.153). */ defaultServiceTier?: string | null; /** @deprecated Superseded by `serviceTiers`; still emitted by codex 0.153-0.164. */ additionalSpeedTiers?: string[]; [k: string]: unknown; } interface Thread { id: string; preview?: string; modelProvider?: string; createdAt?: number; [k: string]: unknown; } interface ThreadStartParams { model?: string | null; modelProvider?: string | null; cwd?: string | null; approvalPolicy?: unknown; sandbox?: unknown; config?: Record<string, unknown> | null; baseInstructions?: string | null; developerInstructions?: string | null; personality?: 'none' | 'friendly' | 'pragmatic' | null; /** * Thread default service tier, e.g. 'fast' (codex >= 0.153; verified on * 0.153.4 and 0.164.0). Codex maps 'fast' to the catalog tier 'priority'. */ serviceTier?: string | null; ephemeral?: boolean | null; experimentalRawEvents?: boolean; /** * External contract: consumed by pre-0.142 servers only. Codex 0.142.5 * removed this param and ignores it when sent (verified empirically). */ persistExtendedHistory?: boolean; } interface ThreadStartResponse { thread: Thread; model: string; modelProvider: string; cwd: string; approvalPolicy: unknown; sandbox: unknown; reasoningEffort: string | null; /** Effective thread service tier (codex >= 0.153); absent on older servers. */ serviceTier?: string | null; } interface ThreadResumeParams { threadId: string; history?: unknown[] | null; path?: string | null; model?: string | null; modelProvider?: string | null; cwd?: string | null; approvalPolicy?: unknown; sandbox?: unknown; config?: Record<string, unknown> | null; baseInstructions?: string | null; developerInstructions?: string | null; personality?: 'none' | 'friendly' | 'pragmatic' | null; /** Thread default service tier, e.g. 'fast' (codex >= 0.153). */ serviceTier?: string | null; /** * External contract: consumed by pre-0.142 servers only. Codex 0.142.5 * removed this param and ignores it when sent. */ persistExtendedHistory?: boolean; } type ThreadResumeResponse = ThreadStartResponse; type UserInput = { type: 'text'; text: string; text_elements: unknown[]; } | { type: 'image'; url: string; /** Optional rendering detail hint (codex >= 0.142). */ detail?: 'auto' | 'low' | 'high' | 'original'; /** External contract: pre-0.142 servers read `imageUrl`; codex 0.142.5 only reads `url`. */ imageUrl?: string; } | { type: 'localImage'; path: string; /** Optional rendering detail hint (codex >= 0.142). */ detail?: 'auto' | 'low' | 'high' | 'original'; } | { type: 'skill'; name: string; path: string; } | { type: 'mention'; name: string; path: string; }; interface TurnStartParams { threadId: string; input: UserInput[]; cwd?: string | null; approvalPolicy?: unknown; sandboxPolicy?: unknown; model?: string | null; /** * Reasoning effort. Open-ended string upstream (`ReasoningEffort = string` * in codex 0.153.4); known values include 'none', 'minimal', 'low', * 'medium', 'high', 'xhigh', 'max', and 'ultra' (the last two since * codex 0.149). Per-model availability comes from `model/list`. */ effort?: string | null; summary?: 'auto' | 'concise' | 'detailed' | 'none' | null; personality?: 'none' | 'friendly' | 'pragmatic' | null; /** * Service tier override for this turn and the thread's subsequent turns * (codex >= 0.153). The provider sends the model-level `serviceTier` * setting here (never a per-call override). */ serviceTier?: string | null; /** * Override only for the turn this request starts ('default' = standard * speed; omitted/null inherits the thread's tier). Does not change the * thread's tier or a turn being steered (codex >= 0.153; present in the * 0.156.0 generated protocol). The provider sends a per-call * `providerOptions.serviceTier` here. */ serviceTierForTurn?: string | null; outputSchema?: unknown; collaborationMode?: unknown; } /** * `codexErrorInfo` carried by `TurnError` / `ErrorNotification`. * * The known string codes are listed for narrowing and autocompletion, and the * trailing `(string & {})` member mirrors the validator's forward-compat * `z.string()` catch-all, so a newer Codex CLI's string codes (0.153 added * `rateLimitExceeded`, `sessionBudgetExceeded`, `misalignmentPolicyViolation`) * are always representable and comparable without casts. Compare against the * known literals and treat anything else as a generic error. * * Object variants are enumerated explicitly and deliberately NOT given an open * `Record<string, unknown>` catch-all: an index-signature member would turn * `'httpConnectionFailed' in info` narrowing into `unknown` and break * `info.httpConnectionFailed.httpStatusCode` for every consumer. The validator * still accepts unknown object variants at runtime; they surface through the * generic error path and are added here when upstream defines them. */ type CodexErrorInfo = 'contextWindowExceeded' | 'usageLimitExceeded' | 'rateLimitExceeded' | 'sessionBudgetExceeded' | 'misalignmentPolicyViolation' | 'serverOverloaded' | 'cyberPolicy' | 'internalServerError' | 'unauthorized' | 'badRequest' | 'threadRollbackFailed' | 'sandboxError' | 'other' | { httpConnectionFailed: { httpStatusCode: number | null; }; } | { responseStreamConnectionFailed: { httpStatusCode: number | null; }; } | { responseStreamDisconnected: { httpStatusCode: number | null; }; } | { responseTooManyFailedAttempts: { httpStatusCode: number | null; }; } | { activeTurnNotSteerable: { turnKind: 'review' | 'compact' | (string & {}); }; } | (string & {}); interface TurnError { message: string; codexErrorInfo: CodexErrorInfo | null; additionalDetails: string | null; } type TurnStatus = 'completed' | 'interrupted' | 'failed' | 'inProgress'; type UserMessageItem = { type: 'userMessage'; id: string; /** Client-supplied message id echoed back by the server (codex >= 0.142). */ clientId?: string | null; content: UserInput[]; }; type AgentMessageItem = { type: 'agentMessage'; id: string; text: string; phase: string | null; /** Memory citation metadata (codex >= 0.142). */ memoryCitation?: unknown | null; }; type PlanItem = { type: 'plan'; id: string; text: string; }; type ReasoningItem = { type: 'reasoning'; id: string; summary: string[]; content: string[]; }; type CommandExecutionItem = { type: 'commandExecution'; id: string; command: string; cwd: string; processId: string | null; /** 'agent' | 'userShell' | 'unifiedExecStartup' | 'unifiedExecInteraction' (codex >= 0.142). */ source?: string; status: string; commandActions: unknown[]; aggregatedOutput: string | null; exitCode: number | null; durationMs: number | null; }; type FileChangeItem = { type: 'fileChange'; id: string; changes: unknown[]; status: string; }; type McpToolCallItem = { type: 'mcpToolCall'; id: string; server: string; tool: string; status: string; arguments: unknown; /** MCP app context; replaces `mcpAppResourceUri` (codex >= 0.142). */ appContext?: unknown | null; mcpAppResourceUri?: string; pluginId?: string | null; result: unknown | null; error: unknown | null; durationMs: number | null; }; type CollabAgentToolCallItem = { type: 'collabAgentToolCall'; id: string; tool: string; status: string; senderThreadId: string; receiverThreadIds: string[]; prompt: string | null; /** Model requested for the spawned agent, when applicable (codex >= 0.142). */ model?: string | null; /** Reasoning effort requested for the spawned agent, when applicable (codex >= 0.142). */ reasoningEffort?: string | null; agentsStates: Record<string, unknown>; }; type WebSearchItem = { type: 'webSearch'; id: string; query: string; action: unknown | null; }; type ImageViewItem = { type: 'imageView'; id: string; path: string; }; type EnteredReviewModeItem = { type: 'enteredReviewMode'; id: string; review: string; }; type ExitedReviewModeItem = { type: 'exitedReviewMode'; id: string; review: string; }; type ContextCompactionItem = { type: 'contextCompaction'; id: string; }; /** codex >= 0.142. */ type HookPromptItem = { type: 'hookPrompt'; id: string; fragments: unknown[]; }; /** SDK-registered dynamic tool call surfaced as a thread item (codex >= 0.142). */ type DynamicToolCallItem = { type: 'dynamicToolCall'; id: string; namespace: string | null; tool: string; arguments: unknown; status: string; contentItems: unknown[] | null; success: boolean | null; durationMs: number | null; }; /** codex >= 0.142. */ type SubAgentActivityItem = { type: 'subAgentActivity'; id: string; kind: string; agentThreadId: string; agentPath: string; }; /** codex >= 0.142. */ type SleepItem = { type: 'sleep'; id: string; durationMs: number; }; /** codex >= 0.142. */ type ImageGenerationItem = { type: 'imageGeneration'; id: string; status: string; revisedPrompt: string | null; result: string; savedPath?: string; }; type ThreadItem = UserMessageItem | AgentMessageItem | PlanItem | ReasoningItem | CommandExecutionItem | FileChangeItem | McpToolCallItem | DynamicToolCallItem | CollabAgentToolCallItem | HookPromptItem | SubAgentActivityItem | SleepItem | ImageGenerationItem | WebSearchItem | ImageViewItem | EnteredReviewModeItem | ExitedReviewModeItem | ContextCompactionItem; interface Turn { id: string; items: ThreadItem[]; /** 'notLoaded' | 'summary' | 'full' (codex >= 0.142). */ itemsView?: string; status: TurnStatus; error: TurnError | null; startedAt?: number | null; completedAt?: number | null; durationMs?: number | null; } interface TurnStartResponse { turn: Turn; } interface TurnInterruptParams { threadId: string; turnId: string; } type TurnInterruptResponse = Record<string, never>; interface ThreadStartedNotification { thread: Thread; } interface TurnStartedNotification { threadId: string; turn: Turn; } interface TurnCompletedNotification { threadId: string; turn: Turn; } interface ItemStartedNotification { item: ThreadItem; threadId: string; turnId: string; /** Unix timestamp (ms) when this item lifecycle started (codex >= 0.142). */ startedAtMs?: number; } interface ItemCompletedNotification { item: ThreadItem; threadId: string; turnId: string; /** Unix timestamp (ms) when this item lifecycle completed (codex >= 0.142). */ completedAtMs?: number; } interface ErrorNotification { error: TurnError; willRetry: boolean; threadId: string; turnId: string; [k: string]: unknown; } interface CommandExecutionRequestApprovalParams { threadId: string; turnId: string; itemId: string; /** Unix timestamp (ms) when this approval request started (codex >= 0.142). */ startedAtMs?: number; approvalId?: string | null; /** Environment in which the command will run (codex >= 0.142). */ environmentId?: string | null; reason?: string | null; networkApprovalContext?: unknown | null; command?: string | null; cwd?: string | null; commandActions?: unknown[] | null; /** Additional permissions requested for this command (codex >= 0.142). */ additionalPermissions?: unknown | null; proposedExecpolicyAmendment?: unknown | null; /** Proposed network policy amendments for future requests (codex >= 0.142). */ proposedNetworkPolicyAmendments?: unknown[] | null; /** Ordered decisions the client may present for this prompt (codex >= 0.142). */ availableDecisions?: unknown[] | null; } interface CommandExecutionRequestApprovalResponse { decision: 'accept' | 'acceptForSession' | 'decline' | 'cancel' | { acceptWithExecpolicyAmendment: { execpolicy_amendment: unknown; }; } | { applyNetworkPolicyAmendment: { network_policy_amendment: unknown; }; }; } interface FileChangeRequestApprovalParams { threadId: string; turnId: string; itemId: string; /** Unix timestamp (ms) when this approval request started (codex >= 0.142). */ startedAtMs?: number; reason?: string | null; grantRoot?: string | null; } interface FileChangeRequestApprovalResponse { decision: 'accept' | 'acceptForSession' | 'decline' | 'cancel'; } /** * External contract: `skill/requestApproval` was removed from the codex * 0.142.5 server-request surface; only pre-0.142 servers send it. */ interface SkillRequestApprovalParams { itemId: string; skillName: string; } /** * External contract: `skill/requestApproval` was removed from the codex * 0.142.5 server-request surface; only pre-0.142 servers send it. */ interface SkillRequestApprovalResponse { decision: 'approve' | 'decline'; } interface ToolRequestUserInputParams { threadId: string; turnId: string; itemId: string; questions: unknown[]; /** Auto-resolution deadline in milliseconds, when set (codex >= 0.142). */ autoResolutionMs?: number | null; } interface ToolRequestUserInputResponse { answers: Record<string, unknown>; } type McpServerElicitationAction = 'accept' | 'decline' | 'cancel'; interface McpServerElicitationRequestParams { threadId: string; /** Nullable: the elicitation may arrive outside of an active turn. */ turnId?: string | null; serverName: string; /** * 'form' and 'openai/form' (codex >= 0.142) requests carry * message/requestedSchema; 'url' requests carry url/elicitationId. */ mode?: string; message?: string; requestedSchema?: unknown; url?: string; elicitationId?: string; /** * For MCP tool approval elicitations, Codex sets * `codex_approval_kind: 'mcp_tool_call'` and may include `persist` hints. */ _meta?: Record<string, unknown> | null; } interface McpServerElicitationRequestResponse { action: McpServerElicitationAction; /** Structured user input for accepted elicitations; null for decline/cancel. */ content?: Record<string, unknown> | null; /** Optional client metadata for form-mode action handling (codex >= 0.142). */ _meta?: Record<string, unknown> | null; } interface DynamicToolCallParams { threadId: string; turnId: string; callId: string; /** Dynamic tool namespace (codex >= 0.142). */ namespace?: string | null; tool: string; arguments: unknown; } interface DynamicToolCallResponse { contentItems: unknown[]; success: boolean; } interface ChatgptAuthTokensRefreshParams { /** Codex 0.142.5 only sends 'unauthorized'; kept open for forward compat. */ reason: string; previousAccountId?: string | null; } interface ChatgptAuthTokensRefreshResponse { accessToken: string; chatgptAccountId: string; chatgptPlanType: string | null; } interface LocalToolDefinition<TParams = unknown, TResult = unknown> { name: string; description: string; parameters: ZodType<TParams>; execute: (params: TParams) => Promise<TResult>; } interface LocalTool { name: string; description: string; inputSchema: Record<string, unknown>; execute: (params: unknown) => Promise<unknown>; } declare function tool<TParams, TResult>(definition: LocalToolDefinition<TParams, TResult>): LocalTool; interface LocalMcpServerOptions { name: string; tools: LocalTool[]; port?: number; host?: string; allowNonLoopbackHost?: boolean; } interface LocalMcpServer { config: McpServerHttp; url: string; port: number; stop: () => Promise<void>; } declare function createLocalMcpServer(options: LocalMcpServerOptions): Promise<LocalMcpServer>; declare const SDK_MCP_SERVER_MARKER: unique symbol; interface SdkMcpServer { readonly [SDK_MCP_SERVER_MARKER]: true; readonly name: string; readonly cacheKey?: string; readonly tools: LocalTool[]; _server?: LocalMcpServer; _start(): Promise<LocalMcpServer['config']>; _stop(): Promise<void>; } interface SdkMcpServerOptions { name: string; cacheKey?: string; tools: LocalTool[]; } declare function createSdkMcpServer(options: SdkMcpServerOptions): SdkMcpServer; type AppServerThreadMode = 'stateless' | 'persistent'; type AppServerPersonality = 'none' | 'friendly' | 'pragmatic'; type AppServerReasoningSummary = 'auto' | 'concise' | 'detailed' | 'none'; /** * Fine-grained approval controls (`AskForApproval::Granular` in the codex * app-server v2 protocol; requires the experimental API, which this client * always enables). When a flag is `true`, prompts of that category are shown * to the client (via server requests); when `false`, they are auto-rejected. */ interface AppServerApprovalGranular { granular: { sandbox_approval: boolean; rules: boolean; mcp_elicitations: boolean; /** Defaults to `false` on the server when omitted. */ skill_approval?: boolean; /** Defaults to `false` on the server when omitted. */ request_permissions?: boolean; }; } /** * @deprecated Legacy `reject` form from Codex CLI ~0.105 (removed since * 0.130). Flags are *inverted* relative to `granular` (`true` = auto-reject); * the provider translates it to the equivalent `granular` policy and warns. */ interface AppServerApprovalReject { reject: { sandbox_approval: boolean; rules: boolean; mcp_elicitations: boolean; }; } /** * Approval policy sent on `thread/start`, `thread/resume` and `turn/start`. * * `'on-failure'` is deprecated: Codex CLI 0.143 retired it and app-server * >= 0.144 rejects it (`-32600 unknown variant 'on-failure'`), so the * provider translates it to `'on-request'` and warns once per model. */ type AppServerApprovalPolicy = 'untrusted' | 'on-request' | 'never' | AppServerApprovalGranular /** @deprecated Retired by Codex CLI 0.143; translated to `'on-request'`. */ | 'on-failure' | AppServerApprovalReject; type AppServerSandboxPolicy = 'read-only' | 'workspace-write' | 'danger-full-access' | { type: 'dangerFullAccess'; } | { type: 'readOnly'; access?: unknown; } | { type: 'externalSandbox'; networkAccess?: 'restricted' | 'enabled'; } | { type: 'workspaceWrite'; writableRoots?: string[]; readOnlyAccess?: unknown; networkAccess?: boolean; excludeTmpdirEnvVar?: boolean; excludeSlashTmp?: boolean; }; type AppServerUserInput = { type: 'text'; text: string; } | { type: 'image'; imageUrl: string; } | { type: 'localImage'; path: string; }; /** * Live session handle for an active app-server thread. * * Session callbacks are most useful in streaming flows where you can inject * follow-up instructions while a turn is still running. */ interface CodexAppServerSession { readonly threadId: string; readonly turnId: string | null; /** * Injects an additional user message into the current thread. */ injectMessage(content: string | AppServerUserInput[]): Promise<void>; /** * Requests interruption of the currently running turn. */ interrupt(): Promise<void>; /** * Returns whether this session currently has an active turn. */ isActive(): boolean; } interface AppServerCommandExecutionApprovalRequest { id: JsonRpcId; method: 'item/commandExecution/requestApproval'; params: CommandExecutionRequestApprovalParams; } interface AppServerFileChangeApprovalRequest { id: JsonRpcId; method: 'item/fileChange/requestApproval'; params: FileChangeRequestApprovalParams; } interface AppServerSkillApprovalRequest { id: JsonRpcId; method: 'skill/requestApproval'; params: SkillRequestApprovalParams; } interface AppServerMcpElicitationRequest { id: JsonRpcId; method: 'mcpServer/elicitation/request'; params: McpServerElicitationRequestParams; } interface AppServerToolRequestUserInputRequest { id: JsonRpcId; method: 'item/tool/requestUserInput'; params: ToolRequestUserInputParams; } interface AppServerDynamicToolCallRequest { id: JsonRpcId; method: 'item/tool/call'; params: DynamicToolCallParams; } interface AppServerAuthRefreshRequest { id: JsonRpcId; method: 'account/chatgptAuthTokens/refresh'; params: ChatgptAuthTokensRefreshParams; } interface AppServerUnhandledRequest { id: JsonRpcId; method: string; params: Record<string, unknown>; } /** * Typed handlers for server-initiated JSON-RPC requests. * * Handler precedence: * 1) per-call provider options * 2) provider default settings * 3) built-in defaults in the RPC client * 4) `onUnhandled` fallback */ interface CodexAppServerRequestHandlers { onCommandExecutionApproval?: (request: AppServerCommandExecutionApprovalRequest) => Promise<CommandExecutionRequestApprovalResponse | undefined>; onFileChangeApproval?: (request: AppServerFileChangeApprovalRequest) => Promise<FileChangeRequestApprovalResponse | undefined>; onSkillApproval?: (request: AppServerSkillApprovalRequest) => Promise<SkillRequestApprovalResponse | undefined>; /** * Handles `mcpServer/elicitation/request` (Codex >= 0.139), which includes * MCP tool call approvals (`params._meta.codex_approval_kind === 'mcp_tool_call'`). * Built-in default: accept tool call approvals when `autoApprove` is true, * decline all other elicitations. */ onMcpElicitation?: (request: AppServerMcpElicitationRequest) => Promise<McpServerElicitationRequestResponse | undefined>; onToolRequestUserInput?: (request: AppServerToolRequestUserInputRequest) => Promise<ToolRequestUserInputResponse | undefined>; onDynamicToolCall?: (request: AppServerDynamicToolCallRequest) => Promise<DynamicToolCallResponse | undefined>; onAuthRefresh?: (request: AppServerAuthRefreshRequest) => Promise<ChatgptAuthTokensRefreshResponse | undefined>; onUnhandled?: (request: AppServerUnhandledRequest) => Promise<unknown>; } type AppServerMcpServerConfig = McpServerConfig | SdkMcpServer; /** * Provider-level and model-level settings for Codex app-server mode. */ interface CodexAppServerSettings { codexPath?: string; cwd?: string; env?: Record<string, string>; verbose?: boolean; logger?: Logger | false; personality?: AppServerPersonality; effort?: ReasoningEffort; summary?: AppServerReasoningSummary; /** * Codex service tier ("fast mode"). Sent as the thread default on * `thread/start` / `thread/resume` and on every `turn/start` (including * session `injectMessage()` turns); `undefined` sends nothing and the * thread keeps Codex's configured tier. A per-call * `providerOptions.serviceTier` overrides it for that call's turn only. * See `ServiceTier`. */ serviceTier?: ServiceTier; approvalPolicy?: AppServerApprovalPolicy; sandboxPolicy?: AppServerSandboxPolicy; baseInstructions?: string; developerInstructions?: string; mcpServers?: Record<string, AppServerMcpServerConfig>; rmcpClient?: boolean; configOverrides?: Record<string, CodexConfigOverrideValue>; autoApprove?: boolean; persistExtendedHistory?: boolean; connectionTimeoutMs?: number; requestTimeoutMs?: number; idleTimeoutMs?: number; minCodexVersion?: string; threadMode?: AppServerThreadMode; resume?: string; includeRawChunks?: boolean; serverRequests?: CodexAppServerRequestHandlers; onSessionCreated?: (session: CodexAppServerSession) => void | Promise<void>; } /** * Factory options passed to `createCodexAppServer`. */ interface CodexAppServerProviderSettings { defaultSettings?: CodexAppServerSettings; } /** * Per-request overrides passed via `providerOptions['codex-app-server']`. */ interface CodexAppServerProviderOptions { threadId?: string; resume?: string; threadMode?: AppServerThreadMode; includeRawChunks?: boolean; personality?: AppServerPersonality; effort?: ReasoningEffort; summary?: AppServerReasoningSummary; /** * Service tier for this call's turn only, sent as `turn/start` * `serviceTierForTurn`. Unlike the model-level setting it never changes the * thread's tier, so later calls on a persistent / resumed thread go back to * the model-level tier. It does not apply to a turn that is already running * (steering). */ serviceTier?: ServiceTier; approvalPolicy?: AppServerApprovalPolicy; sandboxPolicy?: AppServerSandboxPolicy; baseInstructions?: string; developerInstructions?: string; mcpServers?: Record<string, AppServerMcpServerConfig>; rmcpClient?: boolean; configOverrides?: Record<string, CodexConfigOverrideValue>; autoApprove?: boolean; persistExtendedHistory?: boolean; serverRequests?: Partial<CodexAppServerRequestHandlers>; onSessionCreated?: (session: CodexAppServerSession) => void | Promise<void>; } interface CodexExecProvider extends ProviderV4 { (modelId: CodexModelId, settings?: CodexExecSettings): LanguageModelV4; languageModel(modelId: CodexModelId, settings?: CodexExecSettings): LanguageModelV4; chat(modelId: CodexModelId, settings?: CodexExecSettings): LanguageModelV4; embeddingModel(modelId: string): never; imageModel(modelId: string): never; } declare function createCodexExec(options?: CodexExecProviderSettings): CodexExecProvider; declare const codexExec: CodexExecProvider; interface CodexAppServerModelListResult { models: ModelInfo[]; defaultModel?: ModelInfo; nextCursor?: string | null; } /** * Provider interface for the persistent Codex app-server transport. * * Use this via `createCodexAppServer()` or the default `codexAppServer` export. */ interface CodexAppServerProvider extends ProviderV4 { (modelId: CodexModelId, settings?: CodexAppServerSettings): LanguageModelV4; languageModel(modelId: CodexModelId, settings?: CodexAppServerSettings): LanguageModelV4; chat(modelId: CodexModelId, settings?: CodexAppServerSettings): LanguageModelV4; embeddingModel(modelId: string): never; imageModel(modelId: string): never; close(): Promise<void>; dispose(): Promise<void>; listModels(modelProviders?: string[]): Promise<CodexAppServerModelListResult>; } /** * Creates a Codex app-server provider instance. * * The provider maintains a shared JSON-RPC client process and can be reused * across many model calls. Always call `provider.close()` (or `dispose()`) * when finished. * * @example * ```ts * const provider = createCodexAppServer({ * defaultSettings: { minCodexVersion: '0.156.0' }, * }); * * try { * const model = provider('gpt-6-astra'); * // use with generateText / streamText / generateObject * } finally { * await provider.close(); * } * ``` */ declare function createCodexAppServer(options?: CodexAppServerProviderSettings): CodexAppServerProvider; declare const codexAppServer: CodexAppServerProvider; interface ListModelsOptions { codexPath?: string; env?: Record<string, string>; cwd?: string; minCodexVersion?: string; modelProviders?: string[]; connectionTimeoutMs?: number; requestTimeoutMs?: number; } interface ListModelsResult { models: ModelInfo[]; defaultModel?: ModelInfo; nextCursor?: string | null; } declare function listModels(options?: ListModelsOptions): Promise<ListModelsResult>; /** * Default minimum Codex CLI version accepted by the app-server client. * Tracks the validated support baseline (Codex CLI 0.156.x); override with * `minCodexVersion` to accept older CLIs. */ declare const DEFAULT_MIN_CODEX_VERSION = "0.156.0"; interface ExecLanguageModelOptions { id: CodexModelId; settings?: CodexExecSettings; } declare class ExecLanguageModel implements LanguageModelV4 { readonly specificationVersion: "v4"; readonly provider = "codex-cli"; readonly supportedUrls: {}; readonly modelId: string; readonly settings: CodexExecSettings; private logger; private sessionId?; private readonly deprecationWarningsEmitted; constructor(options: ExecLanguageModelOptions); private warnDeprecatedOnce; private mergeSettings; private getItemType; private buildArgs; /** * Apply MCP server settings as `-c` config overrides. * * Returns environment variables that must be set on the spawned codex * process. Inline HTTP `bearerToken` secrets are routed through the child * environment (via `bearer_token_env_var`) instead of argv, because command * lines are readable by any local process (`ps`, /proc/<pid>/cmdline). */ private applyMcpSettings; /** * Pick a child-env variable name to carry an inline MCP bearer token, * avoiding collisions between server names that normalize identically * (e.g. 'foo-bar' and 'foo_bar'). */ private allocateBearerTokenEnvVar; private addConfigOverride; /** * Serialize a config override value into a CLI-safe string. */ private serializeConfigValue; private parseExperimentalJsonEvent; private extractUsage; private getToolName; private buildToolInputPayload; private buildToolResultPayload; private emitToolInvocation; private emitToolResult; private handleSpawnError; doGenerate(options: Parameters<LanguageModelV4['doGenerate']>[0]): Promise<Awaited<ReturnType<LanguageModelV4['doGenerate']>>>; doStream(options: Parameters<LanguageModelV4['doStream']>[0]): Promise<Awaited<ReturnType<LanguageModelV4['doStream']>>>; } declare class UnsupportedFeatureError extends UnsupportedFunctionalityError { readonly feature: string; readonly minCodexVersion?: string; readonly serverVersion?: string; constructor({ feature, minCodexVersion, serverVersion, message, }: { feature: string; minCodexVersion?: string; serverVersion?: string; message?: string; }); } declare function isAuthenticationError(err: unknown): boolean; declare function isUnsupportedFeatureError(err: unknown): err is UnsupportedFeatureError; export { type AppServerApprovalGranular, type AppServerApprovalPolicy, type AppServerApprovalReject, type AppServerSandboxPolicy, type AppServerThreadMode, type AppServerUserInput, type ApprovalMode, CODEX_REASONING_EFFORTS, CODEX_SERVICE_TIERS, type CodexAppServerModelListResult, type CodexAppServerProvider, type CodexAppServerProviderOptions, type CodexAppServerProviderSettings, type CodexAppServerRequestHandlers, type CodexAppServerSession, type CodexAppServerSettings, ExecLanguageModel as CodexCliLanguageModel, type CodexExecProvider as CodexCliProvider, type CodexCliProviderOptions, type CodexCliProviderSettings, type CodexCliSettings, type CodexErrorInfo, type CodexExecProvider, type CodexExecProviderOptions, type CodexExecProviderSettings, type CodexExecSettings, type CodexModelId, DEFAULT_MIN_CODEX_VERSION, type ErrorNotification, ExecLanguageModel, type ItemCompletedNotification, type ItemStartedNotification, type JsonRpcError, type JsonRpcErrorResponse, type JsonRpcId, type JsonRpcMessage, type JsonRpcNotification, type JsonRpcRequest, type JsonRpcResponse, type ListModelsOptions, type ListModelsResult, type LocalMcpServer, type LocalMcpServerOptions, type LocalTool, type LocalToolDefinition, type Logger, type ModelInfo, type ModelServiceTier, type ModelVerbosity, type ReasoningEffort, type ReasoningSummary, type ReasoningSummaryFormat, type SandboxMode, type SdkMcpServer, type SdkMcpServerOptions, type ServiceTier, type Thread, type ThreadItem, type ThreadResumeParams, type ThreadResumeResponse, type ThreadStartParams, type ThreadStartResponse, type ThreadStartedNotification, type Turn, type TurnCompletedNotification, type TurnError, type TurnInterruptParams, type TurnInterruptResponse, type TurnStartParams, type TurnStartResponse, type TurnStartedNotification, UnsupportedFeatureError, type UserInput, codexAppServer, codexExec as codexCli, codexExec, createCodexAppServer, createCodexExec as createCodexCli, createCodexExec, createLocalMcpServer, createSdkMcpServer, isAuthenticationError, isUnsupportedFeatureError, listModels, tool };