Skip to content

Add OpenAI auth login like claude #1686

Closed

Description

@heymaaz

OpenAI codex now uses chatgpt subscription like anthropic's claude. This means we don't need OpenAI Key and can utilise the Plus and Pro subscription.

Would be amazing if this can be added to opencode too.

https://x.com/embirico/status/1953526045573059056

https://x.com/embirico/status/1953530935447859635

Activity

  1. leoisadev1 commented on Aug 7, 2025

    @leoisadev1

    Waiting for same thing @thdxr

  2. ben-vargas commented on Aug 7, 2025

    @ben-vargas
    Contributor

    Here to submit the same... thanks @heymaaz for submitting already!

  3. self-assigned this
    on Aug 7, 2025
  4. thdxr commented on Aug 7, 2025

    @thdxr
    Member

    ill look into it

  5. mmun commented on Aug 8, 2025

    @mmun

    I did a bit of digging. The API being hit is

    POST https://chatgpt.com/backend-api/codex/responses
    

    with headers

    authorization: Bearer <your_jwt>
    version: 0.19.0
    openai-beta: responses=experimental
    session_id: <your_session_id>
    chatgpt-account-id: <your_chatgpt_account_id>
    originator: codex_cli_rs
    

    The JWT used is the access token obtained through this OAuth flow: https://github.com/openai/codex/blob/main/codex-rs/login/src/login_with_chatgpt.py.

  6. Ronuhz commented on Aug 8, 2025

    @Ronuhz

    Wanted to ask for the same thing, I'm glad it's getting looked into

  7. RodriMora commented on Aug 8, 2025

    @RodriMora

    Is this OK with the ToS? has anyone looked into it?

  8. heymaaz commented on Aug 8, 2025

    @heymaaz
    Author

    Is this OK with the ToS? has anyone looked into it?

    We already have this in opencode for github copilot and claude subscriptions and there haven't been any issues. If openai in the future doesn't like we can can remove it, but since they are the one controlling the usage by ratelimiting and are getting paid for the subscriptions, I don't think they would ban this, as this would be same as using the codex-cli just instead of the codex client we are using the opencode client. We aren't getting more than what they offer.

  9. Waishnav commented on Aug 8, 2025

    @Waishnav

    I did a bit of digging. The API being hit is

    POST https://chatgpt.com/backend-api/codex/responses
    

    with headers

    authorization: Bearer <your_jwt>
    version: 0.19.0
    openai-beta: responses=experimental
    session_id: <your_session_id>
    chatgpt-account-id: <your_chatgpt_account_id>
    originator: codex_cli_rs
    

    The JWT used is the access token obtained through this OAuth flow: https://github.com/openai/codex/blob/main/codex-rs/login/src/login_with_chatgpt.py.

    I also investigated a bit more into the Codex codebase for its implementation. It turns out OAuth is handled along with the redirect URI http://localhost:1455/auth/callback, and note that their local server is running on port 1455.

    It’s possible they may have a validation check for this redirect URI, so in opencode we may need to run a short-lived server on this port to handle this part. Let’s hope this check is not there, then we can create an auth callback route in our default opencode's server (which is already running on port 4096).

  10. ben-vargas commented on Aug 8, 2025

    @ben-vargas
    Contributor

    I also investigated a bit more into the Codex codebase for its implementation. It turns out OAuth is handled along with the redirect URI http://localhost:1455/auth/callback, and note that their local server is running on port 1455.

    It’s possible they may have a validation check for this redirect URI, so in opencode we may need to run a short-lived server on this port to handle this part. Let’s hope this check is not there, then we can create an auth callback route in our default opencode's server (which is already running on port 4096).

    I've been poking at it on a fork - got it through the OAuth on a remote ssh (headless server) where browser can't be launched. Running the OAuth and using curl on the remote machine to send the return call works fine. So, there's not really anything crazy there - it's returning the OAuth return URL and I can get all my tokens.

    However, I've gotten caught up in the forming of the instructions, there's some kind of extra validation - I've modeled codex headers and bearer correctly to get through the auth checks using the backend-api and role checks, but haven't gotten a successful response yet due to constant invalid instructions. Hoping others are making better progress.

    Request headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer xxxxxxxxxxxxxxxxxx",
      "Accept": "text/event-stream",
      "OpenAI-Beta": "responses=experimental",
      "session_id": "xxxxxxxx-xxxxxx-xxxx-xxxx-xxxxxxxxxxxxxx",
      "originator": "codex_cli_rs",
      "chatgpt-account-id": "xxxxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxx"
    }
    ChatGPT backend API error: 400 {"detail":"Instructions are not valid"}
    
  11. ben-vargas commented on Aug 8, 2025

    @ben-vargas
    Contributor

    I got a successful request accepted, but Claude and GPT-5 are exhausted.

    ChatGPT Backend API Requirements

    This document outlines the exact requirements for making successful requests to the ChatGPT backend API (https://chatgpt.com/backend-api/codex/responses) using OAuth authentication.

    Overview

    The ChatGPT backend API performs strict validation. It expects an exact match with what the official Rust Codex client sends, including specific tools, instructions, and model.

    1. Authentication Requirements

    OAuth Token

    • Location: ~/.codex/auth.json
    • Type: JWT bearer token

    Account ID Extraction

    Extract chatgpt_account_id from the JWT payload:

    const tokenParts = oauth_token.split('.');
    const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString());
    const chatgptAccountId = payload['https://api.openai.com/auth'].chatgpt_account_id;

    2. Required Headers

    {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${oauth_jwt_token}`,
      'Accept': 'text/event-stream',
      'OpenAI-Beta': 'responses=experimental',
      'session_id': crypto.randomUUID(),  // Generate unique UUID v4
      'originator': 'codex_cli_rs',       // MUST be exactly this value
      'chatgpt-account-id': chatgpt_account_id  // Extracted from JWT
    }

    Important: Do NOT include User-Agent header

    3. Model Requirement

    • Required Model: gpt-5
    • Other models (e.g., gpt-4o) will return {"detail":"Unsupported model"} error

    4. Instructions Requirement

    Must use the EXACT instructions from the Rust Codex prompt file:

    • File: /codex/main/codex-rs/core/prompt.md
    • The instructions reference apply_patch and must match the tools being sent
    • Any deviation results in {"detail":"Instructions are not valid"} error

    5. Required Tools Schema

    Must send exactly these two tools with this specific structure:

    Shell Tool

    {
      type: 'function',
      name: 'shell',
      description: 'Runs a shell command and returns its output',
      strict: false,
      parameters: {
        type: 'object',
        properties: {
          command: {
            type: 'array',
            items: { type: 'string' }
          },
          workdir: {
            type: 'string'
          },
          timeout: {
            type: 'number'
          }
        },
        required: ['command'],
        additionalProperties: false
      }
    }

    Update Plan Tool

    {
      type: 'function',
      name: 'update_plan',
      description: `Use the update_plan tool to keep the user updated on the current plan for the task.
    After understanding the user's task, call the update_plan tool with an initial plan. An example of a plan:
    1. Explore the codebase to find relevant files (status: in_progress)
    2. Implement the feature in the XYZ component (status: pending)
    3. Commit changes and make a pull request (status: pending)
    Each step should be a short, 1-sentence description.
    Until all the steps are finished, there should always be exactly one in_progress step in the plan.
    Call the update_plan tool whenever you finish a step, marking the completed step as \`completed\` and marking the next step as \`in_progress\`.
    Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step.
    Sometimes, you may need to change plans in the middle of a task: call \`update_plan\` with the updated plan and make sure to provide an \`explanation\` of the rationale when doing so.
    When all steps are completed, call update_plan one last time with all steps marked as \`completed\`.`,
      strict: false,
      parameters: {
        type: 'object',
        properties: {
          explanation: {
            type: 'string'
          },
          plan: {
            type: 'array',
            description: 'The list of steps',
            items: {
              type: 'object',
              properties: {
                step: { type: 'string' },
                status: { type: 'string' }
              },
              required: ['step', 'status'],
              additionalProperties: false
            }
          }
        },
        required: ['plan'],
        additionalProperties: false
      }
    }

    6. Request Body Structure

    {
      model: 'gpt-5',
      instructions: instructions,  // Full Codex instructions from prompt.md
      input: [{
        type: 'message',
        role: 'user',
        content: [{
          type: 'input_text',
          text: 'user message here'
        }]
      }],
      store: false,
      stream: true,
      include: ['reasoning.encrypted_content'],
      // NO temperature parameter - causes error
      tools: [shell_tool, update_plan_tool],
      tool_choice: 'auto',
      parallel_tool_calls: false
    }

    7. Validation Rules

    The ChatGPT backend API enforces these strict validation rules:

    Originator Matching

    When originator: codex_cli_rs is sent:

    • Instructions MUST match the Rust Codex instructions exactly
    • Tools MUST be shell and update_plan with exact schemas shown above
    • Model MUST be gpt-5

    Tool-Instruction Consistency

    • If instructions mention "apply patches", the shell tool must be present (since apply_patch is a shell command in Codex)
    • Tool names referenced in instructions must match actual tools provided

    Parameter Restrictions

    • temperature parameter is NOT supported (causes {"detail":"Unsupported parameter: temperature"})
    • Tool structure must be flat (properties directly on tool object, not nested under function)

    8. Common Error Messages

    Error Message Cause Solution
    "Instructions are not valid" Instructions don't match expected format for the originator Use exact Codex instructions from prompt.md
    "Unsupported model" Wrong model for the originator Use gpt-5
    "Unsupported parameter: temperature" Temperature parameter included Remove temperature from request
    "Missing required parameter: 'tools[0].name'" Tool structure is wrong Use flat tool structure (not nested)

    9. Testing

    A test script is available at test-mirror-tools.ts that demonstrates a working request with all correct parameters.

    10. Important Notes

    1. Exact Matching Required: The backend performs sophisticated validation. Every aspect must match exactly what the Rust Codex client sends.

    2. Tool Name Incompatibility: If your application uses different tool names (e.g., read_file, edit_file instead of shell), you cannot claim to be codex_cli_rs without causing validation errors.

    3. No Partial Compliance: You cannot mix and match - either send exactly what Codex sends, or don't use the originator: codex_cli_rs header.

    4. Streaming Response: The API returns a streaming response with text/event-stream content type. Parse the SSE (Server-Sent Events) format to extract the response.

    Example Working Request

    See test-mirror-tools.ts for a complete working example that successfully authenticates and receives responses from the ChatGPT backend API.

  12. mateuszmazurek commented on Aug 8, 2025

    @mateuszmazurek

    @ben-vargas take a look at this implementation https://github.com/Securiteru/codex-openai-proxy/blob/main/src/main.rs

    @Securiteru claims in readme that it's "Tested extensively with CLINE VS Code extension" so system prompt and tools are different than ones from original codex_cli_rs 🤔 Or maybe it's some AI-generated readme with ton of hallucinations, I can't try it by myself because I have no Pro/Plus access right now.

  13. Securiteru commented on Aug 8, 2025

    @Securiteru

    Actually it works however, I'm doing it for CLINE and it's being a pain because they use a different standard but the requests themselves do go out and come back, I'll push the latest version soon.

  14. Securiteru commented on Aug 8, 2025

    @Securiteru

    Cline doesn't like something from the context and decided to spam the endpoint.

    Image
  15. Allmight97 commented on Aug 8, 2025

    @Allmight97

    Came here to request the same! Codex is pretty decent and would love to see it in Opencode!

  16. 103 remaining items

  17. chadhs commented on Oct 23, 2025

    @chadhs

    @chadhs - that was built by research/work of folks talking in this thread if you read above 😂

    I skimmed a little too quickly and missed that lol. If that works well i'm curious how far off we are from 1st class support.

  18. ben-vargas commented on Oct 23, 2025

    @ben-vargas
    Contributor
  19. RodriMora commented on Oct 31, 2025

    @RodriMora

    I think this pretty much says that they allow login in with chatgpt account for this types os uses

    https://x.com/thsottiaux/status/1984348422246449310

  20. Kreijstal commented on Nov 6, 2025

    @Kreijstal

    ohhhh so this is not supported yet? :( sad

  21. numman-ali commented on Nov 6, 2025

    @numman-ali

    ohhhh so this is not supported yet? :( sad

    Not officially no, but the plugin I made allows you to use it

    https://github.com/numman-ali/opencode-openai-codex-auth

    The OpenCode team are waiting for official guidance from OpenAI before implementing themselves

  22. RodriMora commented on Nov 13, 2025

    @RodriMora

    I think this pretty much says that they allow login in with chatgpt account for this types os uses

    https://x.com/thsottiaux/status/1984348422246449310

    well, it was deleted...

  23. fatihdogmus commented on Dec 21, 2025

    @fatihdogmus

    are there any plans for this, other than unoffical auth plugin?

  24. carlalexander commented on Dec 21, 2025

    @carlalexander

    They mentioned in an issue that they weren't doing it. Not sure if that's changed. For now, this plugin works:
    https://github.com/jenslys/opencode-gemini-auth

  25. ben-vargas commented on Jan 2, 2026

    @ben-vargas
    Contributor

    (edit: he deleted it) @mathisdev7 what makes you think it's okay to spam your CLI here in opencode repo? Inappropriate.

    For actual opencode users, jenslys plugin is good, but so is this antigravity plugin as it will use BOTH your Antigravity and Gemini CLI quotas (yes, Google provides different quota allocations in Antigravity and Gemini CLI, so if you're not using both, you're missing some available inference).

    So for Google OAuth subscription use, I'm using https://github.com/NoeFabris/opencode-antigravity-auth as my main plugin these days.

    For OpenAI OAuth sub use, @numman-ali is the way: https://github.com/numman-ali/opencode-openai-codex-auth

  26. colesmcintosh commented on Jan 6, 2026

    @colesmcintosh

    Why not support it natively in opencode? Plugin is fine for now but I feel like a native flow would be better for overall stability. I'd love for it to mimic exactly how it's done with a Claude subscription.

  27. jeankvd commented on Jan 10, 2026

    @jeankvd

    This is now supported, can be closed 👍

  28. heymaaz commented on Jan 10, 2026

    @heymaaz
    Author

    Closing this as its now supported 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions