{"id":46705923,"url":"https://github.com/pppp606/cli-agent-openai-adapter","last_synced_at":"2026-03-09T08:11:18.074Z","repository":{"id":324047873,"uuid":"1095666608","full_name":"pppp606/cli-agent-openai-adapter","owner":"pppp606","description":null,"archived":false,"fork":false,"pushed_at":"2025-11-13T13:39:16.000Z","size":26,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-11-13T15:24:45.895Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"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/pppp606.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-13T11:03:12.000Z","updated_at":"2025-11-13T11:03:17.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/pppp606/cli-agent-openai-adapter","commit_stats":null,"previous_names":["pppp606/cli-agent-openai-adapter"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/pppp606/cli-agent-openai-adapter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pppp606%2Fcli-agent-openai-adapter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pppp606%2Fcli-agent-openai-adapter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pppp606%2Fcli-agent-openai-adapter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pppp606%2Fcli-agent-openai-adapter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pppp606","download_url":"https://codeload.github.com/pppp606/cli-agent-openai-adapter/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pppp606%2Fcli-agent-openai-adapter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30287500,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-09T02:57:19.223Z","status":"ssl_error","status_checked_at":"2026-03-09T02:56:26.373Z","response_time":61,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":[],"created_at":"2026-03-09T08:11:17.525Z","updated_at":"2026-03-09T08:11:18.064Z","avatar_url":"https://github.com/pppp606.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# cli-agent-openai-adapter\n\nConvert CLI-based AI agents (Claude Code, etc.) to OpenAI ChatAPI endpoints.\n\n## Overview\n\nThis adapter allows you to use local CLI tools like Claude Code as drop-in replacements for OpenAI's API in your development environment, while keeping the same code structure for production.\n\n**Use Cases:**\n- **Production**: Use OpenAI API (pay per token)\n- **Development**: Use local Claude Code with Haiku model (reduce costs)\n- **Same Code**: Switch between environments using the same API interface (e.g., LangChain's `ChatOpenAI`)\n\n**Default Model:** This adapter uses Claude Haiku by default for cost efficiency during development. You can configure a different model (e.g., Sonnet, Opus) via the `MODEL` environment variable.\n\n## Features\n\n- ✅ OpenAI-compatible API endpoints (`/v1/chat/completions`)\n- ✅ Support for conversation history\n- ✅ Stateless execution (like OpenAI API)\n- ✅ Chat-only mode (tools disabled for safety)\n- ✅ TypeScript with full type definitions\n- 🚧 Claude Code adapter (initial implementation)\n- 🔜 Codex adapter (future)\n- 🔜 Gemini CLI adapter (future)\n\n## Demo\n\nTry the adapter with the minimal, dependency-free web client:\n\n```bash\n# Start the adapter (project root)\nnpm ci\nnpm run build \u0026\u0026 npm start\n\n# Open the client in your browser\n# File path: examples/minimal-web-client/index.html\n```\n\n[→ Minimal Web Client README](examples/minimal-web-client/README.md)\n\n## Installation\n\n```bash\nnpm install -g cli-agent-openai-adapter\n```\n\nOr use directly with npx:\n\n```bash\nnpx cli-agent-openai-adapter\n```\n\n## Prerequisites\n\n- Node.js \u003e= 20.0.0\n- Claude Code CLI installed and accessible in PATH\n\nTo verify Claude Code is installed:\n\n```bash\nclaude --version\n```\n\n## Usage\n\n### Start the Server\n\n```bash\ncli-agent-openai-adapter\n```\n\nBy default, the server starts at `http://localhost:8000`.\n\n### Configuration\n\nConfigure using environment variables:\n\n```bash\nexport ADAPTER_TYPE=claude-code  # Adapter to use\nexport MODEL=haiku                # Claude model to use (default: haiku)\nexport PORT=8000                  # Server port\nexport HOST=localhost             # Server host\nexport RUNTIME_DIR=./runtime      # Runtime directory (optional)\nexport TIMEOUT=30000              # Timeout in milliseconds\nexport DEBUG=true                 # Enable debug mode\n```\n\nOr create a `.env` file (requires `dotenv`).\n\n**Note:** This adapter uses **Haiku** as the default model to reduce costs during development. You can change the model by setting the `MODEL` environment variable to `sonnet` or `opus` if needed.\n\n### Example with LangChain\n\n```typescript\nimport { ChatOpenAI } from \"@langchain/openai\";\n\n// Development environment: via cli-agent-openai-adapter\nconst llmDev = new ChatOpenAI({\n  configuration: {\n    baseURL: \"http://localhost:8000/v1\"\n  },\n  modelName: \"claude-code\",\n  apiKey: \"dummy\" // Not used but required by the SDK\n});\n\n// Production environment: OpenAI API directly\nconst llmProd = new ChatOpenAI({\n  openAIApiKey: process.env.OPENAI_API_KEY,\n  modelName: \"gpt-4\"\n});\n\n// Usage is identical\nconst response = await llmDev.invoke(\"Hello!\");\nconsole.log(response.content);\n```\n\n### Example with OpenAI SDK\n\n```typescript\nimport OpenAI from \"openai\";\n\nconst client = new OpenAI({\n  baseURL: \"http://localhost:8000/v1\",\n  apiKey: \"dummy\" // Not used but required by the SDK\n});\n\nconst response = await client.chat.completions.create({\n  model: \"claude-code\",\n  messages: [\n    { role: \"system\", content: \"You are a helpful assistant.\" },\n    { role: \"user\", content: \"Hello!\" }\n  ]\n});\n\nconsole.log(response.choices[0].message.content);\n```\n\n### Example with Direct HTTP Request\n\n```bash\ncurl -X POST http://localhost:8000/v1/chat/completions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"claude-code\",\n    \"messages\": [\n      {\"role\": \"user\", \"content\": \"Hello!\"}\n    ]\n  }'\n```\n\n## API Endpoints\n\n### POST /v1/chat/completions\n\nOpenAI-compatible chat completions endpoint.\n\n**Request:**\n\n```json\n{\n  \"model\": \"claude-code\",\n  \"messages\": [\n    {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n    {\"role\": \"user\", \"content\": \"Hello\"}\n  ],\n  \"temperature\": 0.7,\n  \"max_tokens\": 1000\n}\n```\n\n**Response:**\n\n```json\n{\n  \"id\": \"chatcmpl-123\",\n  \"object\": \"chat.completion\",\n  \"created\": 1234567890,\n  \"model\": \"claude-code\",\n  \"choices\": [{\n    \"index\": 0,\n    \"message\": {\n      \"role\": \"assistant\",\n      \"content\": \"Hello! How can I help you?\"\n    },\n    \"finish_reason\": \"stop\"\n  }],\n  \"usage\": {\n    \"prompt_tokens\": 10,\n    \"completion_tokens\": 20,\n    \"total_tokens\": 30\n  }\n}\n```\n\n### GET /v1/models\n\nList available models.\n\n**Response:**\n\n```json\n{\n  \"object\": \"list\",\n  \"data\": [\n    {\n      \"id\": \"claude-code\",\n      \"object\": \"model\",\n      \"created\": 1234567890,\n      \"owned_by\": \"cli-agent-openai-adapter\"\n    }\n  ]\n}\n```\n\n### GET /health\n\nHealth check endpoint.\n\n**Response:**\n\n```json\n{\n  \"status\": \"ok\",\n  \"adapter\": \"claude-code\"\n}\n```\n\n## How It Works\n\n### Architecture\n\n1. **Stateless Execution**: Each request executes `claude code --system-prompt \"...\" -p \"...\"` independently\n2. **Conversation History**: Managed by the client (like OpenAI API), sent in the `messages` array\n3. **Chat Mode**: Tools are disabled via `.claude/settings.json` for chat-only behavior\n4. **Output Cleaning**: ANSI codes and progress indicators are removed from CLI output\n\n### Conversation History Handling\n\nThe adapter formats conversation history as JSON and includes it in the prompt:\n\n```\nSystem Prompt: [Your system message] + Context instruction\n\nUser Prompt:\nConversation history:\n[\n  {\"role\": \"user\", \"content\": \"My favorite color is blue\"},\n  {\"role\": \"assistant\", \"content\": \"That's nice!\"}\n]\n\nCurrent user message: What is my favorite color?\n```\n\nThis allows Claude to understand the full context while maintaining stateless execution.\n\n## Error Handling\n\nThe adapter handles various error scenarios:\n\n- **Timeout (30s default)**: Returns HTTP 504 with timeout error\n- **CLI tool not found**: Fails at startup with clear error message\n- **Invalid request**: Returns HTTP 400 with validation error\n- **Execution error**: Returns HTTP 500 with error details\n\n## Troubleshooting\n\n### Claude Code not found\n\n**Error:** `claude-code is not available`\n\n**Solution:** Make sure Claude CLI is installed and accessible:\n\n```bash\n# Check if claude is in PATH\nwhich claude\n\n# Try running claude directly\nclaude --version\n```\n\n### Timeout errors\n\n**Error:** `Claude Code execution timed out`\n\n**Solution:** Increase timeout:\n\n```bash\nexport TIMEOUT=60000  # 60 seconds\n```\n\n### Output contains noise\n\nIf responses contain ANSI codes or progress indicators, please report as an issue with examples.\n\n## Development\n\n### Setup\n\n```bash\ngit clone https://github.com/pppp606/cli-agent-openai-adapter.git\ncd cli-agent-openai-adapter\nnpm install\n```\n\n### Run in Development Mode\n\n```bash\nnpm run dev\n```\n\n### Build\n\n```bash\nnpm run build\n```\n\n### Run Tests\n\n```bash\n# Run all tests\nnpm test\n\n# Run tests in watch mode\nnpm run test:watch\n\n# Run tests with coverage\nnpm run test:coverage\n```\n\nThe project uses Jest for testing with full TypeScript support. All tests are located in `src/__tests__/` directory.\n\n### Project Structure\n\n```\ncli-agent-openai-adapter/\n├── src/\n│   ├── adapters/\n│   │   ├── base.ts           # Abstract base class\n│   │   ├── claude_code.ts    # Claude Code implementation\n│   │   └── factory.ts        # Adapter factory\n│   ├── bin/\n│   │   └── cli.ts            # CLI entry point\n│   ├── server.ts             # Express server\n│   ├── config.ts             # Configuration loader\n│   ├── types.ts              # TypeScript types\n│   └── index.ts              # Main exports\n├── runtime/\n│   └── claude-code/          # Claude Code runtime\n│       └── .claude/\n│           └── settings.json # Tool disable configuration\n├── package.json\n├── tsconfig.json\n└── README.md\n```\n\n## Future Enhancements\n\n- [ ] Support for streaming responses\n- [ ] Support for Codex CLI adapter\n- [ ] Support for Gemini CLI adapter\n- [ ] Configuration file support (.adaprc)\n- [ ] Better token estimation\n- [ ] Conversation history truncation/summarization\n- [ ] Logging and metrics\n- [ ] Docker support\n\n## License and Terms\n\nThis tool is provided under the MIT License.\n\n**Important:** When using Claude Code through this adapter, you must comply with Anthropic's Terms of Service. Please use this tool in accordance with all applicable terms and conditions.\n\n## Contributing\n\nContributions are welcome! Please feel free to submit issues or pull requests.\n\n---\n\n**Note:** This is an early implementation. The actual behavior of Claude Code CLI options may require adjustments. Please test in your environment and report any issues.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpppp606%2Fcli-agent-openai-adapter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpppp606%2Fcli-agent-openai-adapter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpppp606%2Fcli-agent-openai-adapter/lists"}