{"id":31805364,"url":"https://github.com/ben-vargas/ai-sdk-provider-codex-cli","last_synced_at":"2026-01-02T04:51:35.592Z","repository":{"id":310605994,"uuid":"1040491291","full_name":"ben-vargas/ai-sdk-provider-codex-cli","owner":"ben-vargas","description":"Vercel AI SDK community provider for Codex CLI - Use Plus/Pro Subscription via spawn of Codex CLI.","archived":false,"fork":false,"pushed_at":"2025-10-06T21:40:34.000Z","size":206,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-10T10:24:59.174Z","etag":null,"topics":["ai","ai-sdk","chatgpt","codex","codex-cli","gpt-5","openai"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ben-vargas.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-19T04:15:52.000Z","updated_at":"2025-10-06T17:46:26.000Z","dependencies_parsed_at":"2025-08-19T06:50:44.046Z","dependency_job_id":"b6c9815b-4b45-4785-a90c-7c68e057db60","html_url":"https://github.com/ben-vargas/ai-sdk-provider-codex-cli","commit_stats":null,"previous_names":["ben-vargas/ai-sdk-provider-codex-cli"],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/ben-vargas/ai-sdk-provider-codex-cli","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ben-vargas%2Fai-sdk-provider-codex-cli","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ben-vargas%2Fai-sdk-provider-codex-cli/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ben-vargas%2Fai-sdk-provider-codex-cli/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ben-vargas%2Fai-sdk-provider-codex-cli/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ben-vargas","download_url":"https://codeload.github.com/ben-vargas/ai-sdk-provider-codex-cli/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ben-vargas%2Fai-sdk-provider-codex-cli/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279005940,"owners_count":26084004,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-11T02:00:06.511Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","ai-sdk","chatgpt","codex","codex-cli","gpt-5","openai"],"created_at":"2025-10-11T02:49:27.097Z","updated_at":"2026-01-02T04:51:35.573Z","avatar_url":"https://github.com/ben-vargas.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AI SDK Provider for Codex CLI\n\n[![npm version](https://img.shields.io/npm/v/ai-sdk-provider-codex-cli.svg)](https://www.npmjs.com/package/ai-sdk-provider-codex-cli)\n[![npm downloads](https://img.shields.io/npm/dm/ai-sdk-provider-codex-cli.svg)](https://www.npmjs.com/package/ai-sdk-provider-codex-cli)\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n![Node \u003e= 18](https://img.shields.io/badge/node-%3E%3D18-43853d?logo=node.js\u0026logoColor=white)\n![AI SDK v6](https://img.shields.io/badge/AI%20SDK-v6-000?logo=vercel\u0026logoColor=white)\n![Modules: ESM + CJS](https://img.shields.io/badge/modules-ESM%20%2B%20CJS-3178c6)\n![TypeScript](https://img.shields.io/badge/TypeScript-blue)\n[![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/ben-vargas/ai-sdk-provider-codex-cli/issues)\n[![Latest Release](https://img.shields.io/github/v/release/ben-vargas/ai-sdk-provider-codex-cli?display_name=tag)](https://github.com/ben-vargas/ai-sdk-provider-codex-cli/releases/latest)\n\nA community provider for Vercel AI SDK v6 that uses OpenAI's Codex CLI (non‑interactive `codex exec`) to talk to GPT‑5.1 / GPT‑5.2 class models (`gpt-5.1`, `gpt-5.2`, the Codex-specific `gpt-5.1-codex` / `gpt-5.2-codex`, the flagship `*-codex-max`, and the lightweight `*-codex-mini` slugs) with your ChatGPT Plus/Pro subscription. The provider spawns the Codex CLI process, parses its JSONL output, and adapts it to the AI SDK LanguageModelV3 interface. Legacy GPT-5 / GPT-5-codex slugs remain compatible for existing workflows.\n\n- Works with `generateText`, `streamText`, and `generateObject` (native JSON Schema support via `--output-schema`)\n- Uses ChatGPT OAuth from `codex login` (tokens in `~/.codex/auth.json`) or `OPENAI_API_KEY`\n- Node-only (spawns a local process); supports CI and local dev\n- **v1.0.0**: AI SDK v6 stable migration with LanguageModelV3 interface\n- **v0.5.0**: Adds comprehensive logging system with verbose mode and custom logger support\n- **v0.3.0**: Adds comprehensive tool streaming support for monitoring autonomous tool execution\n\n## Version Compatibility\n\n| Provider Version | AI SDK Version | NPM Tag     | NPM Installation                                      |\n| ---------------- | -------------- | ----------- | ----------------------------------------------------- |\n| 1.x.x            | v6             | `latest`    | `npm i ai-sdk-provider-codex-cli ai@^6.0.0`           |\n| 0.x.x            | v5             | `ai-sdk-v5` | `npm i ai-sdk-provider-codex-cli@ai-sdk-v5 ai@^5.0.0` |\n\n## Installation\n\n### For AI SDK v6 (default)\n\n1. Install and authenticate Codex CLI\n\n```bash\nnpm i -g @openai/codex\ncodex login   # or set OPENAI_API_KEY\n```\n\n2. Install provider and AI SDK v6\n\n```bash\nnpm i ai ai-sdk-provider-codex-cli\n```\n\n### For AI SDK v5\n\n```bash\nnpm i ai@^5.0.0 ai-sdk-provider-codex-cli@ai-sdk-v5\n```\n\n\u003e **⚠️ Codex CLI Version**: Requires Codex CLI **\u003e= 0.42.0** for `--experimental-json` and `--output-schema` support. **\u003e= 0.60.0 recommended** for `gpt-5.1-codex-max` and `xhigh` reasoning effort. If you supply your own Codex CLI (global install or custom `codexPath`/`allowNpx`), check it with `codex --version` and upgrade if needed. The optional dependency `@openai/codex` in this package pulls a compatible version automatically.\n\u003e\n\u003e ```bash\n\u003e npm i -g @openai/codex@latest\n\u003e ```\n\n## Quick Start\n\nText generation\n\n```js\nimport { generateText } from 'ai';\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\nconst model = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  skipGitRepoCheck: true,\n  approvalMode: 'on-failure',\n  sandboxMode: 'workspace-write',\n});\n\nconst { text } = await generateText({\n  model,\n  prompt: 'Reply with a single word: hello.',\n});\nconsole.log(text);\n```\n\nStreaming\n\n```js\nimport { streamText } from 'ai';\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\n// The provider works with both `gpt-5.1` and `gpt-5.1-codex`; use the latter for\n// the Codex CLI specific slug. Legacy `gpt-5` slugs still work if you need them.\nconst { textStream } = await streamText({\n  model: codexCli('gpt-5.1-codex', { allowNpx: true, skipGitRepoCheck: true }),\n  prompt: 'Write two short lines of encouragement.',\n});\nfor await (const chunk of textStream) process.stdout.write(chunk);\n```\n\nObject generation (Zod)\n\n```js\nimport { generateObject } from 'ai';\nimport { z } from 'zod';\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\nconst schema = z.object({ name: z.string(), age: z.number().int() });\nconst { object } = await generateObject({\n  model: codexCli('gpt-5.1-codex', { allowNpx: true, skipGitRepoCheck: true }),\n  schema,\n  prompt: 'Generate a small user profile.',\n});\nconsole.log(object);\n```\n\n## Features\n\n- AI SDK v6 compatible (LanguageModelV3)\n- Streaming and non‑streaming\n- **Configurable logging** (v0.5.0+) - Verbose mode, custom loggers, or silent operation\n- **Tool streaming support** (v0.3.0+) - Monitor autonomous tool execution in real-time\n- **Native JSON Schema support** via `--output-schema` (API-enforced with `strict: true`)\n- JSON object generation with Zod schemas (100-200 fewer tokens per request vs prompt engineering)\n- Safe defaults for non‑interactive automation (`on-failure`, `workspace-write`, `--skip-git-repo-check`)\n- Fallback to `npx @openai/codex` when not on PATH (`allowNpx`)\n- Usage tracking from experimental JSON event format\n- **Image support** - Pass images to vision-capable models via `--image` flag\n\n### Image Support\n\nThe provider supports multimodal (image) inputs for vision-capable models:\n\n```js\nimport { generateText } from 'ai';\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\nimport { readFileSync } from 'fs';\n\nconst model = codexCli('gpt-5.1-codex', { allowNpx: true, skipGitRepoCheck: true });\nconst imageBuffer = readFileSync('./screenshot.png');\n\nconst { text } = await generateText({\n  model,\n  messages: [\n    {\n      role: 'user',\n      content: [\n        { type: 'text', text: 'What do you see in this image?' },\n        { type: 'image', image: imageBuffer, mimeType: 'image/png' },\n      ],\n    },\n  ],\n});\nconsole.log(text);\n```\n\n**Supported image formats:**\n\n- Base64 data URL (`data:image/png;base64,...`)\n- Base64 string (without data URL prefix)\n- `Buffer` / `Uint8Array` / `ArrayBuffer`\n\n**Not supported:**\n\n- HTTP/HTTPS URLs (images must be provided as binary data)\n\nImages are written to temporary files and passed to Codex CLI via the `--image` flag. Temp files are automatically cleaned up after the request completes.\n\nSee [examples/image-support.mjs](examples/image-support.mjs) for a complete working example.\n\n### Tool Streaming (v0.3.0+)\n\nThe provider supports comprehensive tool streaming, enabling real-time monitoring of Codex CLI's autonomous tool execution:\n\n```js\nimport { streamText } from 'ai';\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\nconst result = await streamText({\n  model: codexCli('gpt-5.1-codex', { allowNpx: true, skipGitRepoCheck: true }),\n  prompt: 'List files and count lines in the largest one',\n});\n\nfor await (const part of result.fullStream) {\n  if (part.type === 'tool-call') {\n    console.log('🔧 Tool:', part.toolName);\n  }\n  if (part.type === 'tool-result') {\n    console.log('✅ Result:', part.result);\n  }\n}\n```\n\n**What you get:**\n\n- Tool invocation events when Codex starts executing tools (exec, patch, web_search, mcp_tool_call)\n- Tool input tracking with full parameter visibility\n- Tool result events with complete output payloads\n- `providerExecuted: true` on all tool calls (Codex executes autonomously, app doesn't need to)\n\n**Limitation:** Real-time output streaming (`output-delta` events) not yet available. Tool outputs delivered in final `tool-result` event. See `examples/streaming-tool-calls.mjs` and `examples/streaming-multiple-tools.mjs` for usage patterns.\n\n### Logging Configuration (v0.5.0+)\n\nControl logging verbosity and integrate with your observability stack:\n\n```js\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\n// Default: warn/error only (clean production output)\nconst model = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  skipGitRepoCheck: true,\n});\n\n// Verbose mode: enable debug/info logs for troubleshooting\nconst verboseModel = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  skipGitRepoCheck: true,\n  verbose: true, // Shows all log levels\n});\n\n// Custom logger: integrate with Winston, Pino, Datadog, etc.\nconst customModel = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  skipGitRepoCheck: true,\n  verbose: true,\n  logger: {\n    debug: (msg) =\u003e myLogger.debug('Codex:', msg),\n    info: (msg) =\u003e myLogger.info('Codex:', msg),\n    warn: (msg) =\u003e myLogger.warn('Codex:', msg),\n    error: (msg) =\u003e myLogger.error('Codex:', msg),\n  },\n});\n\n// Silent: disable all logging\nconst silentModel = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  skipGitRepoCheck: true,\n  logger: false, // No logs at all\n});\n```\n\n**Log Levels:**\n\n- `debug`: Detailed execution traces (verbose mode only)\n- `info`: General execution flow (verbose mode only)\n- `warn`: Warnings and misconfigurations (always shown)\n- `error`: Errors and failures (always shown)\n\n**Default Logger:** Adds level tags `[DEBUG]`, `[INFO]`, `[WARN]`, `[ERROR]` to console output. Use a custom logger or `logger: false` if you need different formatting.\n\nSee `examples/logging-*.mjs` for complete examples and [docs/ai-sdk-v5/guide.md](docs/ai-sdk-v5/guide.md) for detailed configuration.\n\n### Text Streaming behavior\n\n**Status:** Incremental streaming not currently supported with `--experimental-json` format (expected in future Codex CLI releases)\n\nThe `--experimental-json` output format (introduced Sept 25, 2025) currently only emits `item.completed` events with full text content. Incremental streaming via `item.updated` or delta events is not yet implemented by OpenAI.\n\n**What this means:**\n\n- `streamText()` works functionally but delivers the entire response in a single chunk after generation completes\n- No incremental text deltas—you wait for the full response, then receive it all at once\n- The AI SDK's streaming interface is supported, but actual incremental streaming is not available\n\n**Future support:** The Codex CLI commit (344d4a1d) introducing experimental JSON explicitly notes: \"or other item types like `item.output_delta` when we need streaming\" and states \"more event types and item types to come.\"\n\nWhen OpenAI adds streaming support, this provider will be updated to handle those events and enable true incremental streaming.\n\n## Documentation\n\n- Getting started, configuration, and troubleshooting live in `docs/`:\n  - [docs/ai-sdk-v5/guide.md](docs/ai-sdk-v5/guide.md) – full usage guide and examples\n  - [docs/ai-sdk-v5/configuration.md](docs/ai-sdk-v5/configuration.md) – all settings and how they map to CLI flags\n  - [docs/ai-sdk-v5/troubleshooting.md](docs/ai-sdk-v5/troubleshooting.md) – common issues and fixes\n  - [docs/ai-sdk-v5/limitations.md](docs/ai-sdk-v5/limitations.md) – known constraints and behavior differences\n- See [examples/](examples/) for runnable scripts covering core usage, streaming, permissions/sandboxing, and object generation.\n\n## Authentication\n\n- Preferred: ChatGPT OAuth via `codex login` (stores tokens at `~/.codex/auth.json`)\n- Alternative: export `OPENAI_API_KEY` in the provider’s `env` settings (forwarded to the spawned process)\n\n## Configuration (high level)\n\n- `allowNpx`: If true, falls back to `npx -y @openai/codex` when Codex is not on PATH\n- `cwd`: Working directory for Codex\n- `addDirs`: Extra directories Codex may read/write (repeats `--add-dir`)\n- Autonomy/sandbox:\n  - `fullAuto` (equivalent to `--full-auto`)\n  - `dangerouslyBypassApprovalsAndSandbox` (bypass approvals and sandbox; dangerous)\n  - Otherwise the provider writes `-c approval_policy=...` and `-c sandbox_mode=...` for you; defaults to `on-failure` and `workspace-write`\n- `skipGitRepoCheck`: enable by default for CI/non‑repo contexts\n- `color`: `always` | `never` | `auto`\n- `outputLastMessageFile`: by default the provider sets a temp path and reads it to capture final text reliably\n- Logging (v0.5.0+):\n  - `verbose`: Enable debug/info logs (default: `false` for clean output)\n  - `logger`: Custom logger object or `false` to disable all logging\n\nSee [docs/ai-sdk-v5/configuration.md](docs/ai-sdk-v5/configuration.md) for the full list and examples.\n\n## Model Parameters \u0026 Advanced Options (v0.4.0+)\n\nControl reasoning effort, verbosity, and advanced Codex features at model creation time:\n\n```ts\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\nconst model = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  skipGitRepoCheck: true,\n  addDirs: ['../shared'],\n\n  // Reasoning \u0026 verbosity\n  reasoningEffort: 'medium', // none | minimal | low | medium | high | xhigh (xhigh on codex-max and newer models that expose it)\n  reasoningSummary: 'auto', // auto | detailed (Note: 'concise' and 'none' are rejected by API)\n  reasoningSummaryFormat: 'none', // none | experimental\n  modelVerbosity: 'high', // low | medium | high\n\n  // Advanced features\n  profile: 'production', // adds --profile production\n  oss: false, // adds --oss when true\n  webSearch: true, // maps to -c tools.web_search=true\n\n  // MCP servers (stdio + HTTP/RMCP)\n  rmcpClient: true, // enables HTTP-based MCP clients (features.rmcp_client=true)\n  mcpServers: {\n    local: {\n      transport: 'stdio',\n      command: 'node',\n      args: ['tools/mcp.js'],\n      env: { API_KEY: process.env.MCP_API_KEY ?? '' },\n    },\n    docs: {\n      transport: 'http',\n      url: 'https://mcp.my-org.com',\n      bearerTokenEnvVar: 'MCP_BEARER',\n      httpHeaders: { 'x-tenant': 'acme' },\n    },\n  },\n\n  // Generic overrides (maps to -c key=value)\n  configOverrides: {\n    experimental_resume: '/tmp/session.jsonl',\n    sandbox_workspace_write: { network_access: true },\n  },\n});\n```\n\nNested override objects are flattened to dotted keys (e.g., the example above emits\n`-c sandbox_workspace_write.network_access=true`). Arrays are serialized to JSON strings.\nMCP server env/header objects flatten the same way (e.g., `mcp_servers.docs.http_headers.x-tenant=acme`).\n\n### Per-call overrides via `providerOptions` (v0.4.0+)\n\nOverride these parameters for individual AI SDK calls using the `providerOptions` map. Per-call\nvalues take precedence over constructor defaults while leaving other settings intact.\n\n```ts\nimport { generateText } from 'ai';\nimport { codexCli } from 'ai-sdk-provider-codex-cli';\n\nconst model = codexCli('gpt-5.1-codex', {\n  allowNpx: true,\n  reasoningEffort: 'medium',\n  modelVerbosity: 'medium',\n});\n\nconst response = await generateText({\n  model,\n  prompt: 'Summarize the latest release notes.',\n  providerOptions: {\n    'codex-cli': {\n      reasoningEffort: 'high',\n      reasoningSummary: 'detailed',\n      textVerbosity: 'high', // AI SDK naming; maps to model_verbosity\n      rmcpClient: true,\n      mcpServers: {\n        scratch: {\n          transport: 'stdio',\n          command: 'pnpm',\n          args: ['mcp', 'serve'],\n        },\n      },\n      configOverrides: {\n        experimental_resume: '/tmp/resume.jsonl',\n      },\n    },\n  },\n});\n```\n\n**Precedence:** `providerOptions['codex-cli']` \u003e constructor `CodexCliSettings` \u003e Codex CLI defaults.\n\n## Zod Compatibility\n\n- Peer supports `zod@^3 || ^4`\n- Validation logic normalizes v3/v4 error shapes\n\n## Limitations\n\n- Node ≥ 18, local process only (no Edge)\n- Codex `--experimental-json` mode emits events rather than streaming deltas; streaming typically yields a final chunk. The CLI provides the final assistant text in the `item.completed` event, which this provider reads and emits at the end.\n- Some AI SDK parameters are unsupported by Codex CLI (e.g., temperature/topP/penalties); the provider surfaces warnings and ignores them\n\n### JSON Schema Limitations (v0.2.0+)\n\n**⚠️ Important:** OpenAI strict mode has limitations:\n\n- **Optional fields NOT supported**: All fields must be required (no `.optional()`)\n- **Format validators stripped**: `.email()`, `.url()`, `.uuid()` are removed (use descriptions instead)\n- **Pattern validators stripped**: `.regex()` is removed (use descriptions instead)\n\nSee [LIMITATIONS.md](LIMITATIONS.md) for comprehensive details and migration guidance.\n\n## Disclaimer\n\nThis is a community provider and not an official OpenAI or Vercel product. You are responsible for complying with all applicable terms and ensuring safe usage.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fben-vargas%2Fai-sdk-provider-codex-cli","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fben-vargas%2Fai-sdk-provider-codex-cli","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fben-vargas%2Fai-sdk-provider-codex-cli/lists"}