### Run Basic App Server Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Executes the basic usage example for the createCodexAppServer provider. ```bash npm run build node examples/app-server/basic-usage.mjs ``` -------------------------------- ### Run Abort App Server Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Executes the abort example for the createCodexAppServer provider. ```bash npm run build node examples/app-server/abort.mjs ``` -------------------------------- ### Run Usage Metadata App Server Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Executes the usage metadata example for the createCodexAppServer provider. ```bash npm run build node examples/app-server/usage-metadata.mjs ``` -------------------------------- ### Run Basic Exec Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Executes the basic usage example for the codexExec provider. ```bash npm run build node examples/exec/basic-usage.mjs ``` -------------------------------- ### Run List Models App Server Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Executes the list models example for the createCodexAppServer provider. ```bash npm run build node examples/app-server/list-models.mjs ``` -------------------------------- ### Validate App-Server Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/app-server/README.md Check the installation and authentication of the Codex CLI, verify the app-server help command, and perform a minimal generation call. This script also runs all app-server examples and validates their output against expectations. ```bash node examples/app-server/check-cli.mjs ``` ```bash npm run validate:examples:app-server ``` -------------------------------- ### Run Raw Chunks App Server Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Executes the raw chunks example for the createCodexAppServer provider. ```bash npm run build node examples/app-server/raw-chunks.mjs ``` -------------------------------- ### Validate App Server Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/README.md Runs the validation script for app server examples. ```bash npm run validate:examples:app-server ``` -------------------------------- ### Build and Run App-Server Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/app-server/README.md Commands to build the project and run various app-server example scripts, including basic usage, conversation history, model listing, session injection, and more. ```bash npm run build node examples/app-server/basic-usage.mjs node examples/app-server/conversation-history.mjs node examples/app-server/list-models.mjs node examples/app-server/session-injection.mjs node examples/app-server/local-mcp-tool.mjs node examples/app-server/abort.mjs node examples/app-server/raw-chunks.mjs node examples/app-server/usage-metadata.mjs ``` -------------------------------- ### Install AI SDK v5 and Provider Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/README.md Installs the AI SDK version 5 and the corresponding provider package. ```bash npm i ai@^5.0.0 ai-sdk-provider-codex-cli@ai-sdk-v5 ``` -------------------------------- ### Example SdkMcpServerOptions Configurations Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Illustrates how to configure SdkMcpServerOptions. The first example uses a cacheKey for persistent model reuse, while the second omits it for per-request instances. ```typescript const sdkServer: SdkMcpServerOptions = { name: 'shared-tools', tools: commonTools, cacheKey: 'my-org-shared-tools', // Reused across calls }; const sdkServer2: SdkMcpServerOptions = { name: 'request-tools', tools: requestSpecificTools, // No cacheKey = new instance per request }; ``` -------------------------------- ### Run Streaming Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/exec/README.md Executes the streaming example for `codex exec`. This demonstrates how to handle streaming output from the `codex exec` process. ```bash node examples/exec/streaming.mjs ``` -------------------------------- ### McpServerStdio Configuration Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Example of configuring an MCP server using stdio transport. This is useful for local process execution. ```typescript const mcpServer: McpServerStdio = { transport: 'stdio', command: 'node', args: ['tools/mcp.js'], env: { API_KEY: 'sk-...' }, cwd: '/workspace', }; ``` -------------------------------- ### Example Codex App Server Provider Creation Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md An example showing how to create a Codex App Server instance using `createCodexAppServer` with specified default settings. ```typescript const provider = createCodexAppServer({ defaultSettings: { minCodexVersion: '0.130.0', personality: 'pragmatic', autoApprove: false, }, }); ``` -------------------------------- ### McpServerHttp Configuration Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Example of configuring an MCP server using HTTP transport. Suitable for remote or local HTTP-based servers. ```typescript const mcpServer: McpServerHttp = { transport: 'http', url: 'https://mcp.example.com', bearerToken: 'token-123', httpHeaders: { 'x-tenant': 'acme' }, }; ``` -------------------------------- ### Example AppServer Request Handlers Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Provides an example of how to implement partial request handlers for an app server. This snippet demonstrates handling command execution and file change approvals. ```typescript const handlers: Partial = { onCommandExecutionApproval: async (request) => { console.log(`Execute: ${request.params.command}`); return { approved: true }; }, onFileChangeApproval: async (request) => { console.log(`Change file: ${request.params.filePath}`); return { approved: true }; }, }; ``` -------------------------------- ### Install Codex CLI and AI SDK v6 Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/README.md Installs the Codex CLI globally and the AI SDK with the provider for version 6. ```bash npm i -g @openai/codex codex login # or set OPENAI_API_KEY ``` ```bash npm i ai ai-sdk-provider-codex-cli ``` -------------------------------- ### Example Codex App Server Configuration Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md An example demonstrating how to set `CodexAppServerSettings` with specific values for personality, effort, timeouts, and a session creation callback. ```typescript const settings: CodexAppServerSettings = { personality: 'pragmatic', effort: 'medium', summary: 'detailed', approvalPolicy: 'on-failure', sandboxPolicy: { type: 'workspaceWrite', networkAccess: true }, baseInstructions: 'Be concise.', autoApprove: false, connectionTimeoutMs: 10000, minCodexVersion: '0.130.0', threadMode: 'persistent', onSessionCreated: (session) => { console.log(`Thread: ${session.threadId}`); }, }; ``` -------------------------------- ### createLocalMcpServer Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/README.md Starts an HTTP MCP server for managing AI model interactions locally. ```APIDOC ## createLocalMcpServer(options) ### Description Starts a local HTTP server that implements the Multi-Call Protocol (MCP). This server can be used to manage AI model interactions and tool definitions within a local environment. ### Method `createLocalMcpServer` ### Parameters #### Options - **options** (LocalMcpServerOptions) - Required - Options for configuring and starting the local MCP server. ``` -------------------------------- ### Schema for Guiding Model with Descriptions (Workaround) Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/LIMITATIONS.md This example uses descriptions within a Zod schema to guide the model on expected formats for fields like email, website, and UUID, as direct format/pattern validation is removed during schema sanitization. ```typescript const schema = z.object({ email: z.string().describe('Valid email address'), website: z.string().describe('Full URL starting with https://'), id: z.string().describe('UUID v4 format'), }); ``` -------------------------------- ### AppServerUserInput Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-session.md Demonstrates creating instances of `AppServerUserInput` for text, remote images, and local images, and injecting them into a session. ```typescript const textInput: AppServerUserInput = { type: 'text', text: 'Continue with more examples.', }; const remoteImageInput: AppServerUserInput = { type: 'image', imageUrl: 'https://example.com/chart.png', }; const localImageInput: AppServerUserInput = { type: 'localImage', path: '/home/user/diagram.png', }; await session.injectMessage([textInput, remoteImageInput]); ``` -------------------------------- ### Create a Local MCP Server with `createLocalMcpServer()` Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Starts an HTTP server for local tool execution using the MCP protocol. Configure the server with a name, an array of tools, and optional port and host settings. The server URL and bearer token are provided upon startup. ```typescript import { createLocalMcpServer, tool } from 'ai-sdk-provider-codex-cli'; import { z } from 'zod'; const tools = [ tool({ name: 'greet', description: 'Greet a person', parameters: z.object({ name: z.string() }), execute: async (params) => `Hello, ${params.name}!`, }), ]; const server = await createLocalMcpServer({ name: 'my-tools', tools, port: 3000, }); console.log(`Server running at: ${server.url}`); console.log(`Bearer token: ${server.config.bearerToken}`); // Use with codexExec or codexAppServer const model = codexExec('gpt-5.5', { mcpServers: { local: { transport: 'http', url: server.url, bearerToken: server.config.bearerToken, }, }, }); // Later: stop the server await server.stop(); ``` -------------------------------- ### createLocalMcpServer(options) Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Starts an HTTP server implementing the MCP protocol for local tool execution. This server can be used to expose defined tools to the Codex CLI. ```APIDOC ## createLocalMcpServer(options) ### Description Starts an HTTP server implementing the MCP protocol for local tool execution. This server can be used to expose defined tools to the Codex CLI. ### Signature ```typescript async function createLocalMcpServer( options: LocalMcpServerOptions, ): Promise ``` ### Parameters #### Path Parameters - **options** (LocalMcpServerOptions) - Required - Server configuration - **options.name** (string) - Required - Server name (used in MCP handshake) - **options.tools** (LocalTool[]) - Required - Array of tools to expose - **options.port** (number) - Optional - HTTP port; `0` = auto-assign - **options.host** (string) - Optional - Bind address (loopback only by default) - **options.allowNonLoopbackHost** (boolean) - Optional - Allow non-loopback hosts (unsafe) ### Returns `Promise` — Server instance with URL and stop method. ### Throws - `Error` — If host is non-loopback and `allowNonLoopbackHost` is false ### Request Example ```typescript import { createLocalMcpServer, tool } from 'ai-sdk-provider-codex-cli'; import { z } from 'zod'; const tools = [ tool({ name: 'greet', description: 'Greet a person', parameters: z.object({ name: z.string() }), execute: async (params) => `Hello, ${params.name}!`, }), ]; const server = await createLocalMcpServer({ name: 'my-tools', tools, port: 3000, }); console.log(`Server running at: ${server.url}`); console.log(`Bearer token: ${server.config.bearerToken}`); // Use with codexExec or codexAppServer const model = codexExec('gpt-5.5', { mcpServers: { local: { transport: 'http', url: server.url, bearerToken: server.config.bearerToken, }, }, }); // Later: stop the server await server.stop(); ``` ``` -------------------------------- ### CodexExecProviderSettings Factory Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Shows how to create a Codex execution provider with default settings applied to all subsequent models. ```typescript const provider = createCodexExec({ defaultSettings: { allowNpx: true, skipGitRepoCheck: true, reasoningEffort: 'medium', }, }); ``` -------------------------------- ### LocalMcpServerOptions Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Configuration options for starting a local MCP HTTP server. This includes server name, the tools to expose, and network binding details. ```APIDOC ## LocalMcpServerOptions ### Description Configuration for starting a local MCP HTTP server. ### Signature ```typescript interface LocalMcpServerOptions { name: string; tools: LocalTool[]; port?: number; host?: string; allowNonLoopbackHost?: boolean; } ``` ### Fields | Field | Type | Default | Description | |-------|------|---------|-------------| | `name` | `string` | — | Server name (used in MCP protocol handshake) | | `tools` | `LocalTool[]` | — | Array of tools to expose | | `port` | `number` | `0` | Port number; `0` = auto-assign available port | | `host` | `string` | `127.0.0.1` | Bind address (loopback by default for security) | | `allowNonLoopbackHost` | `boolean` | `false` | Allow binding to non-loopback addresses | ### Example ```typescript const options: LocalMcpServerOptions = { name: 'analytics', tools: analyticsTools, // Assuming analyticsTools is defined elsewhere port: 3001, host: '127.0.0.1', // Loopback only allowNonLoopbackHost: false, }; // Assuming createLocalMcpServer is imported // const server = await createLocalMcpServer(options); ``` ``` -------------------------------- ### Instantiate AppServerLanguageModel Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-provider.md Example of how to instantiate the AppServerLanguageModel. Ensure you have an AppServerRpcClient instance and provide the model ID and settings. ```typescript import { AppServerLanguageModel } from 'ai-sdk-provider-codex-cli'; const model = new AppServerLanguageModel({ id: 'gpt-5.5', settings: { personality: 'pragmatic' }, client: rpcClient, // AppServerRpcClient instance }); ``` -------------------------------- ### Custom Logger Implementation Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Provides an example of implementing the Logger interface for custom logging output. This logger is then passed to `codexExec` to control logging behavior. ```typescript import { codexExec } from 'ai-sdk-provider-codex-cli'; const customLogger: Logger = { debug: (msg) => console.log(`[DEBUG] ${msg}`), info: (msg) => console.log(`[INFO] ${msg}`), warn: (msg) => console.warn(`[WARN] ${msg}`), error: (msg) => console.error(`[ERROR] ${msg}`), }; const model = codexExec('gpt-5.5', { logger: customLogger, verbose: true, }); ``` -------------------------------- ### CodexExecSettings Configuration Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Demonstrates how to configure `CodexExecSettings` for exec mode, specifying paths, security options, and model configurations. ```typescript const settings: CodexExecSettings = { codexPath: '/usr/local/bin/codex', allowNpx: true, skipGitRepoCheck: true, approvalMode: 'on-failure', sandboxMode: 'workspace-write', reasoningEffort: 'high', modelVerbosity: 'high', addDirs: ['../shared'], mcpServers: { local: { transport: 'stdio', command: 'node', args: ['tools/mcp.js'], }, }, }; ``` -------------------------------- ### Create an SDK MCP Server with `createSdkMcpServer()` Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Wraps a local MCP server for SDK provider configurations, enabling lifecycle management and optional persistent caching. This is useful for integrating tools into SDK provider setups, with an option to use a `cacheKey` for reusing model configurations. ```typescript import { codexExec, createSdkMcpServer, tool } from 'ai-sdk-provider-codex-cli'; import { z } from 'zod'; const dbServer = createSdkMcpServer({ name: 'database', tools: [ tool({ name: 'query_users', description: 'Query users from database', parameters: z.object({ filter: z.string().optional(), }), execute: async (params) => { // Query database return []; }, }), ], cacheKey: 'my-app-db-server', // Optional: reuse across calls }); const model = codexExec('gpt-5.5', { mcpServers: { database: dbServer, }, }); ``` -------------------------------- ### Backward Compatibility (Deprecated) Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/README.md Provides aliases for AI SDK v5 functions, with a link to a migration guide. ```APIDOC ## Backward Compatibility (Deprecated) ### Description Deprecated AI SDK v5 aliases. ### Aliases - `codexCli` → `codexExec` - `createCodexCli` → `createCodexExec` ### Resources - Migration guide available at `api-reference/backward-compat.md`. ``` -------------------------------- ### createSdkMcpServer(options) Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Wraps a local MCP server for use in SDK provider configurations, with lifecycle management and optional persistent caching. This function is used to create MCP servers that can be integrated into SDK provider setups. ```APIDOC ## createSdkMcpServer(options) ### Description Wraps a local MCP server for use in SDK provider configurations, with lifecycle management and optional persistent caching. This function is used to create MCP servers that can be integrated into SDK provider setups. ### Signature ```typescript function createSdkMcpServer(options: SdkMcpServerOptions): SdkMcpServer ``` ### Parameters #### Path Parameters - **options** (SdkMcpServerOptions) - Required - Server factory configuration - **options.name** (string) - Required - Unique server name - **options.tools** (LocalTool[]) - Required - Array of tools to expose - **options.port** (number) - Optional - HTTP port; `0` = auto-assign - **options.host** (string) - Optional - Bind address - **options.allowNonLoopbackHost** (boolean) - Optional - Allow non-loopback hosts - **options.cacheKey** (string) - Optional - Stable key for persistent model reuse; omit for per-call servers ### Returns `SdkMcpServer` — Special marker object for SDK-level MCP server management. ### Request Example ```typescript import { codexExec, createSdkMcpServer, tool } from 'ai-sdk-provider-codex-cli'; import { z } from 'zod'; const dbServer = createSdkMcpServer({ name: 'database', tools: [ tool({ name: 'query_users', description: 'Query users from database', parameters: z.object({ filter: z.string().optional(), }), execute: async (params) => { // Query database return []; }, }), ], cacheKey: 'my-app-db-server', // Optional: reuse across calls }); const model = codexExec('gpt-5.5', { mcpServers: { database: dbServer, }, }); ``` ``` -------------------------------- ### ApprovalMode Usage Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Demonstrates setting the `approvalMode` option for `codexExec`. The default `'on-failure'` is safe for CI, while `'never'` allows fully autonomous execution with caution. ```typescript const model = codexExec('gpt-5.5', { approvalMode: 'on-failure', // Default safe mode }); const autoApprovedModel = codexExec('gpt-5.5', { approvalMode: 'never', // Fully autonomous (use with caution) }); ``` -------------------------------- ### Nested Object Configuration Overrides Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/configuration.md Demonstrates how nested objects in config overrides are flattened into dotted keys for command-line arguments. Shows examples for network access and writable roots. ```typescript configOverrides: { sandbox_workspace_write: { network_access: true, writable_roots: ['/output'], }, } // Emits: // -c sandbox_workspace_write.network_access=true // -c sandbox_workspace_write.writable_roots=["/output"] ``` -------------------------------- ### Exec Mode Text Streaming with Options Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/streaming-and-advanced.md This example demonstrates text streaming in 'Exec Mode' with specific options for the Codex CLI provider, such as allowing npx and skipping Git repository checks. The full response is received as a single chunk. ```typescript import { streamText } from 'ai'; import { codexExec } from 'ai-sdk-provider-codex-cli'; const { textStream } = await streamText({ model: codexExec('gpt-5.5', { allowNpx: true, skipGitRepoCheck: true }), prompt: 'Write a function to calculate factorial.', }); for await (const chunk of textStream) { // In exec mode: receives full response as one chunk after execution process.stdout.write(chunk); } ``` -------------------------------- ### Handle Invalid Settings in Codex Exec Creation Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/exec-provider.md This example shows that invalid settings provided during the creation of the Codex exec provider will result in an error. Validate `defaultSettings` before creating the provider. ```typescript const provider = createCodexExec({ defaultSettings: { sandboxMode: 'invalid' }, // Throws Error with message }); ``` -------------------------------- ### Check CLI Installation and Authentication Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/exec/README.md Validates the `codex` CLI installation and authentication status. This is a useful check before running other `codex exec` commands. ```bash node examples/exec/check-cli.mjs ``` -------------------------------- ### Handle LoadAPIKeyError Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/errors.md Catch `LoadAPIKeyError` to inform the user about authentication failures and guide them to log in. ```typescript import { isAuthenticationError } from 'ai-sdk-provider-codex-cli'; try { const { text } = await generateText({ model: codexExec('gpt-5.5'), prompt: 'Hello', }); } catch (error) { if (isAuthenticationError(error)) { console.error('Codex CLI authentication failed. Run: codex login'); } } ``` -------------------------------- ### Setting up a Local MCP Server for Development Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Creates a local MCP server for development purposes and configures a Codex model to use it via HTTP, including the bearer token. ```typescript const server = await createLocalMcpServer({ name: 'dev-tools', tools: [myTool], }); const model = codexExec('gpt-5.5', { mcpServers: { dev: { transport: 'http', url: server.url, bearerToken: server.config.bearerToken, }, }, }); ``` -------------------------------- ### Image Support with Codex Exec Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/README.md Demonstrates how to use local image files as input for vision-capable models with the `codexExec` provider. Ensure the image file exists at the specified path. ```javascript import { generateText } from 'ai'; import { codexExec } from 'ai-sdk-provider-codex-cli'; import { readFileSync } from 'fs'; const model = codexExec('gpt-5.5', { allowNpx: true, skipGitRepoCheck: true }); const imageBuffer = readFileSync('./screenshot.png'); const { text } = await generateText({ model, messages: [ { role: 'user', content: [ { type: 'text', text: 'What do you see in this image?' }, { type: 'image', image: imageBuffer, mimeType: 'image/png' }, ], }, ], }); console.log(text); ``` -------------------------------- ### Initialize Codex App Server Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/configuration.md Instantiate the Codex App Server with default settings. Further configuration can be applied via constructor options. ```typescript const provider = createCodexAppServer({ defaultSettings: { /* ... */ } }); ``` -------------------------------- ### SandboxMode Usage Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Illustrates configuring `sandboxMode` for `codexExec`. `'workspace-write'` is the default for development, while `'read-only'` offers the highest security. ```typescript const model = codexExec('gpt-5.5', { sandboxMode: 'workspace-write', // Default for dev }); const readOnlyModel = codexExec('gpt-5.5', { sandboxMode: 'read-only', // Safest mode }); ``` -------------------------------- ### Configure local MCP server options Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Set up the configuration for a local MCP HTTP server, including its name, the tools it will expose, and optional network settings like port, host, and whether to allow non-loopback hosts. The 'analyticsTools' array should contain your defined LocalTool objects. ```typescript const options: LocalMcpServerOptions = { name: 'analytics', tools: analyticsTools, port: 3001, host: '127.0.0.1', // Loopback only allowNonLoopbackHost: false, }; const server = await createLocalMcpServer(options); ``` -------------------------------- ### Disable Logging Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Shows how to disable all logging output by passing `logger: false` to `codexExec`. This is useful for silent execution. ```typescript const silentModel = codexExec('gpt-5.5', { logger: false }); ``` -------------------------------- ### Create and Use Codex App Server Provider Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-provider.md Instantiate the provider, list available models, create a language model with specific settings, and ensure the provider is closed when done. ```typescript const provider = createCodexAppServer(); // List available models const { models, defaultModel } = await provider.listModels(); console.log('Default:', defaultModel.modelId); // Create and use a model const model = provider('gpt-5.5', { personality: 'pragmatic' }); // Always close when done await provider.close(); ``` -------------------------------- ### createCodexAppServer Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-provider.md Creates a new app-server provider instance with optional default settings. The provider maintains a shared client pool and must be closed when done. ```APIDOC ## createCodexAppServer(options) ### Description Creates a new app-server provider instance with optional default settings. The provider maintains a shared client pool and must be closed when done. ### Signature ```typescript function createCodexAppServer( options: CodexAppServerProviderSettings = {}, ): CodexAppServerProvider ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **options** (`CodexAppServerProviderSettings`) - Optional - `{}` - Provider configuration with optional `defaultSettings` ### Request Example ```typescript import { createCodexAppServer } from 'ai-sdk-provider-codex-cli'; import { generateText } from 'ai'; const provider = createCodexAppServer({ defaultSettings: { minCodexVersion: '0.130.0', autoApprove: false, personality: 'pragmatic', }, }); try { const { text } = await generateText({ model: provider('gpt-5.5'), prompt: 'Hello, Codex!', }); console.log(text); } finally { await provider.close(); } ``` ### Response #### Success Response `CodexAppServerProvider` — A provider object callable as a function, with lifecycle methods `close()` and `listModels()`. #### Response Example * None provided in source. ### Throws - `Error` — If `defaultSettings` validation fails ``` -------------------------------- ### ReasoningEffort Usage Examples Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Shows how to set `reasoningEffort` for `codexExec`. `'high'` is suitable for complex problems, while `'low'` provides quicker responses. ```typescript const model = codexExec('gpt-5.5', { reasoningEffort: 'high', // Deep reasoning for complex tasks }); const fastModel = codexExec('gpt-5.5', { reasoningEffort: 'low', // Quick responses }); ``` -------------------------------- ### CodexModelId Usage Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Demonstrates how to assign known and custom model IDs to the CodexModelId type. The `(string & {})` allows any string for custom models. ```typescript const modelId: CodexModelId = 'gpt-5.5'; // Known model const customModel: CodexModelId = 'custom-model-v1'; // Custom model allowed ``` -------------------------------- ### Configure Sandbox Policies with String Shorthand Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/configuration.md Apply sandbox policies using a simple string shorthand for both exec and app server modes. This is the quickest way to set common security configurations. ```typescript // Exec mode const model = codexExec('gpt-5.5', { sandboxMode: 'workspace-write', }); // App server mode const model = provider('gpt-5.5', { sandboxPolicy: 'workspace-write', }); ``` -------------------------------- ### Stateful Threads with Codex App-Server Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/README.md Enables stateful conversations by starting a persistent thread and passing its `threadId` across calls. The `threadId` is available in `providerMetadata`. ```javascript import { generateText } from 'ai'; import { createCodexAppServer } from 'ai-sdk-provider-codex-cli'; const provider = createCodexAppServer(); const first = await generateText({ model: provider('gpt-5.5'), prompt: 'Start a migration checklist.', providerOptions: { 'codex-app-server': { threadMode: 'persistent' }, }, }); const threadId = first.providerMetadata?.['codex-app-server']?.threadId; const second = await generateText({ model: provider('gpt-5.5'), prompt: 'Continue from step 2.', providerOptions: { 'codex-app-server': { threadId }, }, }); await provider.close(); ``` -------------------------------- ### Create Codex App Server Instance Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-provider.md Creates a new app-server provider instance with optional default settings. The provider must be closed when done. Use this for custom configurations. ```typescript import { createCodexAppServer } from 'ai-sdk-provider-codex-cli'; import { generateText } from 'ai'; const provider = createCodexAppServer({ defaultSettings: { minCodexVersion: '0.130.0', autoApprove: false, personality: 'pragmatic', }, }); try { const { text } = await generateText({ model: provider('gpt-5.5'), prompt: 'Hello, Codex!', }); console.log(text); } finally { await provider.close(); } ``` -------------------------------- ### List Models and Display Results Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/list-models.md Call `listModels` without options to get all available models and display their IDs, providers, and the default model if set. ```typescript const result = await listModels(); console.log(`Found ${result.models.length} models`); result.models.forEach(m => { console.log(` ${m.modelId} (${m.provider})`); }); if (result.defaultModel) { console.log(`Default: ${result.defaultModel.modelId}`); } ``` -------------------------------- ### App Server with Custom Approval Handlers Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/configuration.md Configure an app server with custom handlers for command execution and file change approvals. Rejects dangerous commands and protects config files. ```typescript import { createCodexAppServer } from 'ai-sdk-provider-codex-cli'; const provider = createCodexAppServer({ defaultSettings: { autoApprove: false, serverRequests: { onCommandExecutionApproval: async (request) => { const { command } = request.params; if (command.includes('rm') || command.includes('chmod')) { return { approved: false }; // Reject dangerous commands } return { approved: true }; // Auto-approve safe ones }, onFileChangeApproval: async (request) => { const { filePath } = request.params; if (filePath.startsWith('.env') || filePath.includes('config')) { return { approved: false }; // Protect config files } return { approved: true }; }, }, }, }); ``` -------------------------------- ### Resolve Codex CLI Not Found Error Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/errors.md Provides solutions for the 'Codex CLI Not Found' error, including installation, explicit path configuration, or using `allowNpx`. ```typescript // 1. Install Codex CLI // npm i -g @openai/codex // 2. Or explicitly provide path const model = codexExec('gpt-5.5', { codexPath: '/opt/homebrew/bin/codex', }); // 3. Or use `allowNpx` to fall back to npx const model = codexExec('gpt-5.5', { allowNpx: true, // Falls back to npx @openai/codex }); ``` -------------------------------- ### Configure Codex App Server Provider Settings Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Use `CodexAppServerProviderSettings` to define factory options for `createCodexAppServer()`, including default server settings. ```typescript interface CodexAppServerProviderSettings { defaultSettings?: CodexAppServerSettings; } ``` -------------------------------- ### MCP Tools API Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/README.md Define and expose Model Context Protocol tools. Includes functions for creating tools, starting MCP servers, and type guarding. ```APIDOC ## MCP Tools API ### Description Define and expose Model Context Protocol tools. ### Functions - `tool(definition)`: Create tool from Zod schema. - `createLocalMcpServer(options)`: Start HTTP MCP server. - `createSdkMcpServer(options)`: SDK-managed server with lifecycle. - `isSdkMcpServer(value)`: Type guard. ``` -------------------------------- ### Create Codex Exec Provider Instance Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/exec-provider.md Use `createCodexExec` to instantiate a provider with optional default settings. This is useful for configuring provider-wide options like `allowNpx`, `skipGitRepoCheck`, `approvalMode`, and `sandboxMode`. ```typescript import { createCodexExec } from 'ai-sdk-provider-codex-cli'; const provider = createCodexExec({ defaultSettings: { allowNpx: true, skipGitRepoCheck: true, approvalMode: 'on-failure', sandboxMode: 'workspace-write', }, }); const model = provider('gpt-5.5'); ``` -------------------------------- ### createCodexExec Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/exec-provider.md Creates a new exec provider instance with optional default settings. This provider can then be used to instantiate language models. ```APIDOC ## createCodexExec(options) ### Description Creates a new exec provider instance with optional default settings. This provider can then be used to instantiate language models. ### Signature ```typescript function createCodexExec(options: CodexExecProviderSettings = {}): CodexExecProvider ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **options** (`CodexExecProviderSettings`) - Optional - Provider configuration with optional `defaultSettings` ### Request Example ```typescript import { createCodexExec } from 'ai-sdk-provider-codex-cli'; const provider = createCodexExec({ defaultSettings: { allowNpx: true, skipGitRepoCheck: true, approvalMode: 'on-failure', sandboxMode: 'workspace-write', }, }); const model = provider('gpt-5.5'); ``` ### Response #### Success Response (200) * **CodexExecProvider** (`CodexExecProvider`) - A provider object that can be called as a function to create language models. #### Response Example ```json { "example": "provider object" } ``` ``` -------------------------------- ### Close Provider Example Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/examples/app-server/README.md Always close the provider when finished to prevent child 'codex app-server' processes from running longer than expected. This pattern ensures proper resource management. ```javascript const provider = createCodexAppServer(); try { // calls... } finally { await provider.close(); } ``` -------------------------------- ### Tool Streaming with Codex Exec Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/README.md Illustrates how to stream text and monitor autonomous tool execution in real-time using the `codexExec` provider. This is useful for observing the steps Codex CLI takes when executing tools. ```javascript import { streamText } from 'ai'; import { codexExec } from 'ai-sdk-provider-codex-cli'; const result = await streamText({ model: codexExec('gpt-5.5', { allowNpx: true, skipGitRepoCheck: true }), prompt: 'List files and count lines in the largest one', }); for await (const part of result.fullStream) { if (part.type === 'tool-call') { console.log('🔧 Tool:', part.toolName); } if (part.type === 'tool-result') { console.log('✅ Result:', part.result); } } ``` -------------------------------- ### CodexAppServerProviderSettings Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/types.md Factory options for `createCodexAppServer()`. This interface allows setting default configurations for the Codex App Server when it is created. ```APIDOC ## CodexAppServerProviderSettings ### Description Factory options for `createCodexAppServer()`. This interface allows setting default configurations for the Codex App Server when it is created. ### Fields - **defaultSettings** (`CodexAppServerSettings`): Optional default settings to apply to the app server. ### Example ```typescript const provider = createCodexAppServer({ defaultSettings: { minCodexVersion: '0.130.0', personality: 'pragmatic', autoApprove: false, }, }); ``` ``` -------------------------------- ### Stream Structured Objects with Progress Tracking Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/streaming-and-advanced.md Generate structured objects with progress tracking using `streamObject`. This example demonstrates how to define a Zod schema and stream partial objects as they are generated. ```typescript import { streamObject } from 'ai'; import { z } from 'zod'; const schema = z.object({ title: z.string(), sections: z.array( z.object({ heading: z.string(), content: z.string(), }) ), }); const { partialObjectStream } = await streamObject({ model: provider('gpt-5.5'), schema, prompt: 'Create an article outline on AI', }); for await (const partialObject of partialObjectStream) { console.log('Partial:', JSON.stringify(partialObject, null, 2)); } ``` -------------------------------- ### createSdkMcpServer Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/README.md Creates an MCP server managed by the SDK, allowing for programmatic control over AI model interactions. ```APIDOC ## createSdkMcpServer(options) ### Description Creates an MCP server instance that is managed by the SDK. This provides a way to programmatically control and interact with AI models through the MCP interface. ### Method `createSdkMcpServer` ### Parameters #### Options - **options** (SdkMcpServerOptions) - Required - Options for configuring the SDK-managed MCP server. ``` -------------------------------- ### Persistent Thread with Injection Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-session.md This example shows how to create a persistent thread for a session and then continue the conversation in the same thread, injecting a message after a delay. It uses `generateText` and `streamText` and requires the `threadMode: 'persistent'` option. ```typescript const provider = createCodexAppServer(); // First request with persistent thread const response1 = await generateText({ model: provider('gpt-5.5'), prompt: 'Create an outline for a blog post on AI.', providerOptions: { 'codex-app-server': { threadMode: 'persistent', onSessionCreated: (session) => { console.log(`Thread: ${session.threadId}`); }, }, }, }); // Continue in same thread with injection capability const response2 = await streamText({ model: provider('gpt-5.5'), prompt: 'Expand section 2 with more examples.', providerOptions: { 'codex-app-server': { threadId: response1.providerMetadata?.['codex-app-server']?.threadId, onSessionCreated: async (session) => { setTimeout(async () => { if (session.isActive()) { await session.injectMessage('Include code examples.'); } }, 1000); }, }, }, }); await provider.close(); ``` -------------------------------- ### Stream Text with Codex App-Server Provider Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/README.md Uses the `createCodexAppServer` provider for persistent processes. Configure default settings like `minCodexVersion`, `autoApprove`, and `personality`. ```javascript import { streamText } from 'ai'; import { createCodexAppServer } from 'ai-sdk-provider-codex-cli'; const provider = createCodexAppServer({ defaultSettings: { minCodexVersion: '0.130.0', autoApprove: false, personality: 'pragmatic', }, }); const { textStream } = await streamText({ model: provider('gpt-5.5'), prompt: 'Write two short lines of encouragement.', }); for await (const chunk of textStream) process.stdout.write(chunk); await provider.close(); ``` -------------------------------- ### Configuring an SDK MCP Server for Provider-Level Use Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Sets up an SDK MCP server for shared tools and integrates it into a Codex application server's default settings for provider-level requests. ```typescript const sdkServer = createSdkMcpServer({ name: 'shared', tools: sharedTools, cacheKey: 'org-shared-tools', }); const provider = createCodexAppServer({ defaultSettings: { mcpServers: { shared: sdkServer, }, }, }); ``` -------------------------------- ### Handle Stale Thread Error After Server Restart Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-provider.md This example illustrates the error message received when a persistent thread becomes invalid after a server restart. The message suggests creating a new thread. ```typescript // After server restart, prior threadId becomes invalid // Error: Thread '...' not found after server restart. Create a new thread by omitting threadId. ``` -------------------------------- ### Zod Schema with All Required Fields (Works) Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/LIMITATIONS.md This example shows a valid Zod schema where all fields are required, which is necessary to avoid API errors when using OpenAI's strict mode with `--output-schema`. ```typescript const schema = z.object({ name: z.string(), age: z.number(), email: z.string(), // ✅ All fields required }); ``` -------------------------------- ### App Server with MCP Tools Configuration Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/configuration.md Configure an app server to use MCP (Multi-Command Protocol) tools, defining a database tool for querying. Integrates with Codex. ```typescript import { createCodexAppServer, createSdkMcpServer, tool } from 'ai-sdk-provider-codex-cli'; import { z } from 'zod'; const dbTools = createSdkMcpServer({ name: 'database', tools: [ tool({ name: 'query', description: 'Query database', parameters: z.object({ sql: z.string() }), execute: async (params) => { // Query database return []; }, }), ], cacheKey: 'org-db-server', }); const provider = createCodexAppServer({ defaultSettings: { mcpServers: { database: dbTools, }, }, }); ``` -------------------------------- ### Handle Authentication and Unsupported Feature Errors Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/README.md Use the provided helper functions to check for specific error types from the Codex CLI. This is useful for guiding users on how to resolve authentication issues or informing them about feature compatibility. ```typescript import { isAuthenticationError, isUnsupportedFeatureError } from 'ai-sdk-provider-codex-cli'; try { // ... generate text } catch (error) { if (isAuthenticationError(error)) { console.error('Run: codex login'); } else if (isUnsupportedFeatureError(error)) { console.error(`Requires Codex >= ${error.minCodexVersion}`); } } ``` -------------------------------- ### SdkMcpServerOptions Interface Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/mcp-tools.md Configuration options for creating an SDK-managed MCP server. This interface defines the structure for server name, tools, port, host, and caching behavior. ```APIDOC ## SdkMcpServerOptions ### Description Configuration for creating an SDK-managed MCP server. ### Fields - **name** (string) - Required - Server name (used in MCP handshake) - **tools** (LocalTool[]) - Required - Array of tools to expose - **port** (number) - Optional - HTTP port; `0` = auto-assign - **host** (string) - Optional - Bind address (loopback by default) - **allowNonLoopbackHost** (boolean) - Optional - Allow non-loopback hosts - **cacheKey** (string) - Optional - Optional stable key for persistent model reuse (omit for per-call servers) ### Example ```typescript const sdkServer: SdkMcpServerOptions = { name: 'shared-tools', tools: commonTools, cacheKey: 'my-org-shared-tools', // Reused across calls }; const sdkServer2: SdkMcpServerOptions = { name: 'request-tools', tools: requestSpecificTools, // No cacheKey = new instance per request }; ``` ``` -------------------------------- ### Zod Schema with Optional Field (Causes API Error) Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/LIMITATIONS.md This example demonstrates a Zod schema that will cause an API error because it includes an optional field, which is not supported by OpenAI's strict mode when using `--output-schema`. ```typescript const schema = z.object({ name: z.string(), age: z.number(), email: z.string().optional(), // ❌ Will cause API error }); ``` -------------------------------- ### Use Default Codex App Server Instance Source: https://github.com/ben-vargas/ai-sdk-provider-codex-cli/blob/main/_autodocs/api-reference/app-server-provider.md Uses the default instance of the app-server provider, which is pre-instantiated without any default settings. Remember to close the provider when finished. ```typescript import { codexAppServer } from 'ai-sdk-provider-codex-cli'; const model = codexAppServer('gpt-5.5'); // ... use with AI SDK await codexAppServer.close(); ```