opencode icon indicating copy to clipboard operation
opencode copied to clipboard

Add OpenAI auth login like claude

Open heymaaz opened this issue 1 year ago • 126 comments

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

heymaaz avatar Aug 07 '25 19:08 heymaaz

Waiting for same thing @thdxr

leoisadev1 avatar Aug 07 '25 20:08 leoisadev1

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

ben-vargas avatar Aug 07 '25 21:08 ben-vargas

ill look into it

thdxr avatar Aug 07 '25 21:08 thdxr

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.

mmun avatar Aug 08 '25 05:08 mmun

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

Ronuhz avatar Aug 08 '25 07:08 Ronuhz

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

RodriMora avatar Aug 08 '25 10:08 RodriMora

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.

heymaaz avatar Aug 08 '25 10:08 heymaaz

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).

Waishnav avatar Aug 08 '25 12:08 Waishnav

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"}

ben-vargas avatar Aug 08 '25 13:08 ben-vargas

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.

ben-vargas avatar Aug 08 '25 14:08 ben-vargas

@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.

mateuszmazurek avatar Aug 08 '25 15:08 mateuszmazurek

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.

Securiteru avatar Aug 08 '25 15:08 Securiteru

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

Image

Securiteru avatar Aug 08 '25 15:08 Securiteru

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

Allmight97 avatar Aug 08 '25 16:08 Allmight97

Anyone got word if the Codex limits got fixed?

leoisadev1 avatar Aug 08 '25 16:08 leoisadev1

https://github.com/sst/opencode/pull/1722

If somebody want's to take this draft PR further, I've made oauth login working. Please feel free to dive deeper, and make it more robust to codex's login working in opencode

Waishnav avatar Aug 08 '25 17:08 Waishnav

How about including gemini cli too?

nikhilmaddirala avatar Aug 08 '25 22:08 nikhilmaddirala

Google doesn't really offer plans like codex and openai where you pay. I am pretty sure it will go against their TOS.

heymaaz avatar Aug 08 '25 23:08 heymaaz

@heymaaz - Google does, it's just not that compelling. Gemini Code Assist Standard includes "1500 requests" but what they don't tell you is not all of those requests can be gemini-2.5-pro; from my experience it works out to 20-50 tool-calls/requests per prompt and I get cutoff at 500-800 "requests" per day. That equates to 14 to 20 prompts per day... it's a subscription at $24-30/mo depending on annual contract or monthly.

So they have it, it just isn't compelling. But regardless, they shouldn't really care if you burn your 20 prompts in gemini-cli or opencode - both are same inference cost, and the API endpoints enforce the limit not the client. So I'd put Google in the same boat as Anthropic and OpenAI as far as "should they care"... now whether they do or not is another question because the other part of that equation is getting people hooked on the client (i.e. claude code) so they don't jump ship on next weekly frontier model leapfrog.

ben-vargas avatar Aug 08 '25 23:08 ben-vargas

Ahh ok that makes sense. Last I checked they were giving free requests for google sso login and only had api pricing for vertex and ai studio.

heymaaz avatar Aug 08 '25 23:08 heymaaz