all notable changes to this project. dates are ISO format (YYYY-MM-DD).
- beginner operations toolkit: added
codex-help,codex-setup(withwizardmode + fallback),codex-doctor(fixmode), andcodex-nextfor guided onboarding and recovery. - account metadata commands: added
codex-tagandcodex-note, pluscodex-listtag filtering. - interactive account pickers:
codex-switch,codex-label, andcodex-removenow support optional index with interactive selection in compatible terminals. - backup/import safety controls:
codex-exportnow supports auto timestamped backup paths;codex-importaddsdryRunpreview and automatic pre-import backup on apply. - beginner safe mode config: new
beginnerSafeModeconfig key andCODEX_AUTH_BEGINNER_SAFE_MODEenv override for conservative retry behavior. - startup preflight summary: one-time startup health summary with recommended next action.
- account storage schema: V3 account metadata now includes optional
accountTagsandaccountNote. - docs refresh for operational flows: README + docs portal/development guides updated to reflect beginner commands, safe mode, interactive picker behavior, and backup/import safeguards.
- test matrix expansion: coverage now includes beginner UI helpers, safe-fix diagnostics edge cases, tag/note command behavior, and timestamped backup/import preview utilities.
- dependency security baseline: refreshed lockfile dependency graph via
npm audit fixto remove all known high/moderate advisories in the audited tree.
- non-interactive command guidance: optional-index commands provide explicit usage guidance when interactive menus are unavailable.
- doctor safe-fix edge path:
codex-doctor fixnow reports a clear non-crashing message when no eligible account is available for auto-switch. - first-time import flow:
codex-importno longer fails withNo accounts to exportwhen storage is empty; pre-import backup is skipped cleanly in zero-account setups. - oauth callback host alignment: authorization redirect now uses
http://127.0.0.1:1455/auth/callbackto match the loopback server binding and avoidlocalhostresolver drift. - oauth success-page resilience: callback server now falls back to a built-in success HTML page when
oauth-success.htmlis unavailable, preventing hard startup failure. - oauth poll contract hardening:
waitForCode(state)now verifies the captured callback state before returning code, matching the declared interface contract. - hybrid account selection eligibility: token-bucket depletion is now enforced during hybrid selection/current-account reuse, preventing premature request failures when other accounts remain eligible.
- organization/account identity matching hardening: org-scoped matching and collision pruning now enforce accountId-aware compatibility to preserve distinct same-org workspace identities.
- id-token organization binding source strictness: id-token candidate org binding now prioritizes
idToken['https://api.openai.com/auth'].organizations[0].id.
- organization-scoped account preservation: org-different variants sharing a refresh token now preserve distinct identity entries during storage collision resolution.
- no-org duplicate collapse alignment: fallback no-org duplicates now collapse consistently across storage, authorize, and prune operations.
- active-index remap stability: index remapping during collision pruning/dedupe maintains stable active-index selection after account deduplication.
- workspace-aware account persistence: oauth workspace candidates are preserved as distinct account entries to keep per-workspace routing stable across multi-account sessions.
- organization identity reconciliation: account restoration now preserves organization/workspace identity across token refresh and flagged-account recovery paths.
- verify-flagged restore identity loss: flagged-account restore no longer drops
organizationIdwhen anaccountIdalready exists.
- documentation alignment with current runtime structure: refreshed README and docs portal/architecture guides to reflect native-vs-legacy request transforms, workspace-aware identity behavior, and current preset/test counts.
- tool-call compatibility with current OpenCode runtime: default request handling now preserves native OpenCode payload/tool definitions, avoiding bridge-side alias rewrites that could trigger invalid tool-call schemas.
- bridge/tool-name drift failures: Codex bridge instructions now anchor on the runtime-provided tool manifest and explicitly avoid translating/inventing tool names.
- request transform mode control: added
requestTransformMode(nativedefault,legacyopt-in) plusCODEX_AUTH_REQUEST_TRANSFORM_MODE=legacyfor compatibility fallback. - legacy codex-mode scope: Codex compatibility rewrites and bridge prompt shaping are now legacy-mode behavior; native mode keeps host request shape unchanged.
- tool mapping conflicts in codex bridge/remap prompts: removed contradictory guidance that treated
patchas forbidden and aligned instructions soapply_patchintent maps topatch(preferred) oreditfor targeted replacements. - OpenCode codex prompt source brittleness: prompt fetch now retries across multiple upstream source URLs instead of relying on a single path that could return 404.
- prompt fetch configurability: added
OPENCODE_CODEX_PROMPT_URLoverride support and source-aware cache metadata so ETag conditional requests stay bound to the same source. - regression coverage + docs wording: updated prompt assertions/tests for the new
patch+editpolicy and refreshed architecture documentation text to match.
- gpt-5.3-codex-spark normalization + routing: added internal model mapping/family support for
gpt-5.3-codex-sparkand Spark reasoning variants. - generic unsupported-model fallback engine: entitlement rejections now support configurable per-model fallback chains via
fallbackOnUnsupportedCodexModelandunsupportedCodexFallbackChain.
- unsupported-model policy defaults: introduced
unsupportedCodexPolicy(strict/fallback) with strict mode as default; legacyfallbackOnUnsupportedCodexModelnow maps to policy behavior. - entitlement handling flow: on unsupported-model errors, plugin now tries remaining accounts/workspaces before model fallback, improving Spark entitlement discovery across multi-account setups.
- fast-session reasoning summary: fast mode now uses
reasoning.summary = "auto"(invalid/legacy summary values sanitize toauto). - legacy fallback compatibility:
fallbackToGpt52OnUnsupportedGpt53/CODEX_AUTH_FALLBACK_GPT53_TO_GPT52now act as a legacy edge toggle inside the generic fallback flow. - documentation refresh: README, configuration, getting-started, troubleshooting, and config template docs now describe strict/fallback controls, Spark entitlement gating, and optional manual Spark template additions.
- provider-prefixed model config resolution:
openai/<model>ids now correctly resolve to their base model config instead of falling back to global defaults. - codex variant option merging: variant suffixes like
-xhighnow applymodels.<base>.variants.<variant>options during request transformation.
- workspace candidate selection hardened: OAuth workspace auto-selection now prefers org defaults, id-token-selected workspace IDs, and non-personal org candidates before falling back to token-derived personal IDs.
- business workspace routing: explicit org/manual workspace bindings are now preserved at request time and no longer overwritten by token
chatgpt_account_idvalues. - gpt-5.3-codex on Business accounts: fixed a dual-workspace path where requests could be routed to personal/free workspace IDs and fail with unsupported-model errors.
- auth login interaction redesigned:
opencode auth loginnow defaults to the Codex-style dashboard flow (actions/accounts/danger zone) instead of the legacy add/fresh-only prompt. - styled codex tool output default:
codex-list,codex-status,codex-health,codex-switch,codex-remove,codex-refresh,codex-export, andcodex-importnow default to the new Codex TUI formatting; scripts parsing legacy plain output should update or setcodexTuiV2: false.
- codex tui runtime controls: new config + env options for UI behavior:
codexTuiV2,codexTuiColorProfile,codexTuiGlyphMode,CODEX_TUI_V2,CODEX_TUI_COLOR_PROFILE, andCODEX_TUI_GLYPHS. - full account dashboard actions: interactive login now supports add/check/deep-check/verify-flagged/start-fresh, plus account-level actions (enable/disable, refresh, delete).
- dedicated flagged storage: introduced
openai-codex-flagged-accounts.jsonwith automatic migration from legacyopenai-codex-blocked-accounts.json. - ui architecture + coverage: added shared terminal UI runtime/theme/format modules and parity documentation (
TUI_PARITY_CHECKLIST.md) with focused tests.
- disabled account safety: disabled accounts are now excluded from active/current selection and rotation paths.
- enabled-flag migration:
enabledaccount state now survives v1->v3 storage migration and persists reliably across save/load cycles.
- gpt-5.3 fallback default: fallback from
gpt-5.3-codextogpt-5.2-codexon ChatGPT entitlement rejection is now enabled by default for all users. - strict-mode opt-out: strict behavior is now opt-out via
fallbackToGpt52OnUnsupportedGpt53: falseorCODEX_AUTH_FALLBACK_GPT53_TO_GPT52=0.
- unsupported-model handling: normalized the upstream 400 (
"not supported when using Codex with a ChatGPT account") to a clear entitlement-style error instead of generic bad-request handling.
- fast session mode: optional low-latency tuning (
fastSession) withhybrid/alwaysstrategies and configurable history window (fastSessionMaxInputItems).
- prompt caching: codex + opencode bridge prompts now use stale-while-revalidate + in-memory caching; startup prewarms instruction caches to reduce first-turn latency.
- request parsing: fetch pipeline now normalizes
Requestinputs and supports non-string bodies (Uint8Array/ArrayBuffer/Blob) without failing request transformations.
- trivial-turn overhead: in fast session mode, trivial one-liners can omit tool definitions and compact instructions to reduce roundtrip time.
- gpt-5.3-codex model support: added end-to-end normalization and routing for
gpt-5.3-codexwithlow,medium,high, andxhighvariants. - new codex family key: account rotation/storage now tracks
gpt-5.3-codexindependently inactiveIndexByFamily.
- reasoning defaults:
gpt-5.3-codexnow defaults toxhigheffort (matching the current codex-family behavior), andnone/minimalare normalized to supported codex levels. - prompt fetch/cache mapping: prompt family detection now recognizes
gpt-5.3-codex; cache files are keyed togpt-5.3-codex-instructions.md. - config templates + docs refreshed: modern/legacy config examples and model reference docs now advertise
gpt-5.3-codexinstead ofgpt-5.2-codex.
- runtime metrics tool: added
codex-metricsto inspect live request/error/latency counters for the current plugin process. - 401 diagnostics payload: normalized 401 errors now include
diagnostics(for examplerequestId,cfRay,correlationId,threadId) to speed up debugging. - stream watchdog controls: new
fetchTimeoutMsandstreamStallTimeoutMsconfig options (and env overrides) for upstream timeout tuning.
- request correlation: each upstream fetch now sets a correlation id, reuses
CODEX_THREAD_ID/prompt_cache_keywhen available, and clears scope after each request. - plan-mode tool gating:
request_user_inputis automatically stripped from tool definitions when collaboration mode is Default (kept in Plan mode). - safety prompt hardening: bridge/remap prompts now explicitly block destructive git commands unless the user asks for them.
- gpt-5.2-codex default effort: default reasoning now prefers
xhighwhen no explicit effort/variant is provided. - gitignore hygiene: local planning/release scratch artifacts are now ignored to keep working trees clean.
- non-stream SSE hangs: non-streaming SSE parsing now aborts stalled reads instead of waiting indefinitely.
- per-project storage location: project-scoped account files now live under
~/.opencode/projects/<project-key>/openai-codex-accounts.jsoninstead of writing into<project>/.opencode/.
- legacy migration: when the new project-scoped path is empty, the plugin now auto-migrates legacy
<project>/.opencode/openai-codex-accounts.jsondata on first load.
- Empty response retry - Automatically retries when the API returns empty/malformed responses. Configurable via
emptyResponseMaxRetries(default: 2) andemptyResponseRetryDelayMs(default: 1000ms) - PID offset for parallel agents - When multiple OpenCode instances run in parallel, each process now gets a deterministic offset for account selection, reducing contention. Enable with
pidOffsetEnabled: true
{
"emptyResponseMaxRetries": 2,
"emptyResponseRetryDelayMs": 1000,
"pidOffsetEnabled": false
}-
Environment variables:
-
CODEX_AUTH_EMPTY_RESPONSE_MAX_RETRIES -
CODEX_AUTH_EMPTY_RESPONSE_RETRY_DELAY_MS -
CODEX_AUTH_PID_OFFSET_ENABLED -
Test coverage - 1516 tests across 49 files (up from 1498)
- PID offset formula - Fixed bug where all accounts received the same offset (now uses
account.index * 0.131 + pidBonusfor unique distribution) - Empty response detection - Hardened
isEmptyResponse()to correctly identify empty choice objects ([{}]) and whitespace-only content as empty - Test mocks - Fixed
index.test.tsmocks forcreateLoggerand new config getters (55 tests were failing)
- npm publish status: not published on npm (tag/release only).
- Test coverage - Up to 89% coverage (1498 tests)
- Code quality - Various improvements from audit
- Account persistence fix - Accounts were being saved to the wrong location when
perProjectAccountswas enabled (default). The issue was thatsetStoragePath()only ran in the loader, but authorize runs before that. So accounts got written to the global path, then the loader looked in the per-project path and found nothing. Both OAuth methods (browser and manual URL paste) now init storage path before saving. (#19)
- TUI crash on workspace prompt - Removed redundant workspace selection prompt (auto-selects default now). Added
isNonInteractiveMode()to detect TUI/Desktop environments. (#17) - Web UI validation error - Added validate function to manual OAuth flow for proper error messages instead of
[object Object].
-
Audit logging - Rotating file audit log with structured entries
-
Auth rate limiting - Token bucket rate limiting (5 req/min/account)
-
Proactive token refresh - Refreshes tokens 5 minutes before expiry
-
Zod schemas - Runtime validation as single source of truth
-
Tests: 580 → 631 (+51)
-
All passing on Windows with
--pool=forks
- Business plan workspace fix - Fixed the "usage not included" errors some Business plan users were hitting. Turns out we were sending a stale stored accountId instead of pulling the fresh one from the token - problematic when you've got multiple workspaces. (#17, h/t @alanzchen for the detailed trace)
- Persistence errors actually visible now - Storage failures used to fail silently unless you had debug mode on. Now you get a proper error toast with actionable hints (antivirus exclusions on Windows, chmod suggestions on Unix). (#19)
- Atomic writes for account storage - Switched to temp file + rename to avoid corrupted state if a write gets interrupted mid-flight.
- Fixed a reader lock leak - The SSE response handler wasn't releasing its lock in the finally block. Small thing but could cause issues over time.
- Debug logging for rotation - Added some visibility into which account gets picked and why during rotation.
- tool rename: all
openai-accounts-*tools renamed to shortercodex-*prefix:openai-accounts→codex-listopenai-accounts-switch→codex-switchopenai-accounts-status→codex-statusopenai-accounts-health→codex-healthopenai-accounts-refresh→codex-refreshopenai-accounts-remove→codex-remove
- codex-export: export all accounts to a portable JSON file for backup or migration
- codex-import: import accounts from a JSON file, merges with existing accounts (skips duplicates)
- windows account persistence: fixed silent failure when saving accounts on Windows. errors are now logged at WARN level with storage path in message, and a toast notification appears if persistence fails.
-
This plugin provides 6 built-in tools for managing your OpenAI accounts. Just ask the agent or type the tool name directly.
-
| Tool | What It Does | Example Prompt |
-
|------|--------------|----------------|
-
|
openai-accounts| List all accounts | "list my accounts" | -
|
openai-accounts-switch| Switch active account | "switch to account 2" | -
|
openai-accounts-status| Show rate limits & health | "show account status" | -
|
openai-accounts-health| Validate tokens (read-only) | "check account health" | -
|
openai-accounts-refresh| Refresh & save tokens | "refresh my tokens" | -
|
openai-accounts-remove| Remove an account | "remove account 3" |
- Zod validation error - Fixed crash when calling
openai-accounts-statuswith no accounts configured
- Subdirectory detection - Per-project accounts now work from subdirectories. The plugin walks up the directory tree to find the project root (identified by
.git,package.json,pyproject.toml, etc.) - Live countdown timer - Rate limit waits now show a live countdown that updates every 5 seconds:
Waiting for rate limit reset (2m 35s remaining) - Auto-remove on auth failure - Accounts are automatically removed after 3 consecutive auth failures, with a notification explaining what happened. No more manual cleanup of dead accounts.
- openai-accounts-refresh tool - Manually refresh all OAuth tokens to verify they're still valid
- per-project accounts: each project gets its own account storage now. no more conflicts when working across different repos with different chatgpt accounts. auto-detects project directories (looks for .git, package.json, etc). falls back to global storage if you're not in a project folder.
- configurable toast duration: rate limit notifications stick around longer now (5s default). set
toastDurationMsin config if you want them longer/shorter. - account removal tool: new
openai-accounts-removetool to delete accounts by index. finally. - token masking in logs: all tokens, api keys, and bearer headers are now masked in debug logs. no more accidentally leaking creds.
- account limit bumped to 20: was 10, now 20. add more accounts if you need them.
- per-project accounts default on:
perProjectAccountsdefaults totruenow. disable withperProjectAccounts: falsein config if you want the old global behavior.
- token refresh race condition: added
tokenRotationMapto prevent concurrent refresh requests from stepping on each other. - rate limit retry jitter: 20% jitter on retry delays to prevent thundering herd.
- apply_patch infinite loop: removed apply_patch references from codex bridge that caused loops in some edge cases.
new options in ~/.opencode/openai-codex-auth-config.json:
{
"perProjectAccounts": true,
"toastDurationMs": 5000
}env vars:
CODEX_AUTH_PER_PROJECT_ACCOUNTS=1- enable per-project accountsCODEX_AUTH_TOAST_DURATION_MS=8000- set toast duration in ms
- business/team workspace selection: detect multiple workspace account IDs from oauth tokens and prompt for the correct one.
- prevent refresh/hydration from overwriting selected workspace ids (org/manual choices remain stable).
- persist workspace labels and sources for clearer account listings.
CODEX_AUTH_ACCOUNT_IDoverride to force a specific workspace id (non-interactive login).- troubleshooting guidance for "usage not included in your plan".
- tui auth gating: non-tty/ui auth attempts now return a clear instruction to run
opencode auth loginin a terminal shell. - error-mapping simplification: consolidated entitlement/rate-limit mapping in fetch helpers for a single handling path.
-
When your ChatGPT subscription didn't include Codex access, the plugin kept rotating through all accounts and retrying forever because it thought it was a temporary rate limit.
-
You get an immediate, clear error: "This model is not included in your ChatGPT subscription."
- Account error handling - Fixes infinite retry loop when account doesn't have access to Codex models.
usage_not_includederrors now return 403 Forbidden instead of being treated as rate limits. Clear error message explaining the subscription issue. Prevents pointless account rotation for non-recoverable errors. (#16, thanks @rainmeter33-jpg!)
- TUI auth flow disabled - We now strictly enforce using
opencode auth loginin the terminal for authentication. The UI-based 'Connect' flow is disabled with a clear message to prevent issues with non-interactive environments.
- Strict tool schema validation - Added filtering of required fields, flattening enums for compatibility with strict models like Claude/Gemini
- Manual login fixed - Parsing of OAuth URLs with fragments (
#code=) is fixed - Account switching - Manual selection is now strictly prioritized over rotation logic
- apply_patch enabled - The bridge prompt now allows
apply_patch
- Strict schema validation - Ported robust tool cleaning logic from
antigravity-auth. Automatically normalizes tool definitions to prevent errors with strict models (like Claude or Gemini):- Filters out
requiredfields that are not defined inproperties - Flattens
anyOfschemas withconstvalues into standardenumarrays - Converts nullable array types into single types with a description note
- Injects placeholder properties for empty object parameters
- Filters out
- Enabled apply_patch - Updated the Codex bridge prompt to allow the
apply_patchtool
- Manual login fixed - The plugin now correctly parses OAuth redirect URLs that use fragments (e.g.,
#code=...). Previously, it only looked for query parameters, which caused manual copy-paste logins to fail with a redirection error. - Account switching logic - Changed account selection logic to strictly respect your manual choice. Before this fix, the hybrid rotation algorithm would sometimes override your selection based on account health or token scores.
- TUI integration - Implemented the missing event handler for the TUI. When you click an account in the interface, it now triggers the
openai.account.selectevent, saves the new active index to disk, and shows a confirmation toast. - Removed API key option - Removed the 'API Key' authentication method from the list because this plugin is designed for OAuth only.
- Auth prompts moved to TUI - Avoids readline input conflicts
- Error payload normalization - Improves rate-limit handling and rotation
- npm publish status: not published on npm (tag/release only).
- When
opencode auth logincalled the authorize function,inputswasundefined. The code had a conditional check that only entered the multi-account while loop ifinputsexisted with keys. This caused only single-account flow to run.
-
Multi-account flow always runs - authorize() now always uses multi-account flow regardless of inputs parameter. (#12)
-
Removed the conditional check so multi-account flow always runs, allowing users to add multiple ChatGPT accounts.
breaking: package renamed from opencode-openai-codex-auth-multi to oc-chatgpt-multi-auth
- package renamed to bypass opencode's plugin blocking. opencode skips any plugin with
opencode-openai-codex-authin the name. the new nameoc-chatgpt-multi-authworks correctly. - updated all documentation, configs, and references to use new package name.
- added
multiAccountflag check in loader to coexist with opencode's built-in auth.
- removed debug console.log statements from loader.
- plugin now properly detects when it should handle auth vs deferring to built-in.
update your ~/.config/opencode/opencode.json:
{
"plugin": ["oc-chatgpt-multi-auth@latest"]
}- fix node esm plugin load by importing tool from
@opencode-ai/plugin/tooland ensuring runtime dependency is installed. - correct package metadata (repository links, update-check package name) and add troubleshooting guidance for plugin install/load.
- npm package line: published under
opencode-openai-codex-auth-multi(legacy package), notoc-chatgpt-multi-auth.
feature release: full session recovery system ported from opencode-antigravity-auth.
- session recovery system: automatic recovery from common api errors that would previously crash sessions:
tool_result_missing: handles interrupted tool executions (esc during tool run)thinking_block_order: fixes corrupted thinking blocks in message historythinking_disabled_violation: strips thinking blocks when switching to non-thinking models
- new recovery module (
lib/recovery/):types.ts- type definitions for stored messages, parts, and recoveryconstants.ts- storage paths (xdg-compliant) and type setsstorage.ts- filesystem operations for reading/writing opencode session dataindex.ts- module re-exports
- main recovery logic (
lib/recovery.ts):detectErrorType()- identifies recoverable error patterns from api responsesisRecoverableError()- quick check for recovery eligibilitycreateSessionRecoveryHook()- creates hook for session-level error recovery- toast notifications during recovery attempts
- new configuration options:
sessionRecovery(default:true) - enable/disable session recoveryautoResume(default:true) - auto-resume session after thinking block recovery- environment variables:
CODEX_AUTH_SESSION_RECOVERY,CODEX_AUTH_AUTO_RESUME
- 26 new unit tests for recovery system
- account label format: changed from
Account N (email)toN. emailfor cleaner display - error response handling:
handleErrorResponse()now returnserrorBodyfor recovery detection - enhanced error logging with recoverable error detection in fetch flow
- npm package line: published under
opencode-openai-codex-auth-multi(legacy package), notoc-chatgpt-multi-auth.
feature release: context overflow handling and missing tool result injection.
- context overflow handler: gracefully handles "prompt too long" / context length exceeded errors:
- returns synthetic sse response with helpful instructions instead of raw 400 error
- suggests
/compact,/clear, or/undocommands to reduce context size - prevents opencode session from getting locked on context overflow
- new module:
lib/context-overflow.ts
- missing tool result injection: automatically handles cancelled tool calls (esc mid-execution):
- detects orphaned
function_callitems (calls without matching outputs) - injects synthetic output:
"Operation cancelled by user" - prevents "missing tool_result" api errors when user cancels mid-tool
- new function:
injectMissingToolOutputs()inlib/request/helpers/input-utils.ts
- detects orphaned
- 34 new unit tests for context overflow and tool injection
- npm package line: published under
opencode-openai-codex-auth-multi(legacy package), notoc-chatgpt-multi-auth.
- strict tool validation: automatically cleans tool schemas for compatibility with strict models (claude, gemini)
- auto-update notifications: get notified when a new version is available
- 22 model presets: full variant system with reasoning levels (none/low/medium/high/xhigh)
- health-aware account rotation with automatic failover
- hybrid selection prefers healthy accounts with available tokens
- npm package line: published under
opencode-openai-codex-auth-multi(legacy package), notoc-chatgpt-multi-auth.
- health scoring: tracks success/failure per account
- token bucket: prevents hitting rate limits
- always retries when all accounts are rate-limited (waits for reset)
new retry options:
retryAllAccountsRateLimited(default:true)retryAllAccountsMaxWaitMs(default:0= unlimited)retryAllAccountsMaxRetries(default:Infinity)
- npm publish status: not published on npm (tag/release only).
- openai-accounts-status --json - Scriptable status output with email/ID labels
-
Account labels - Now prefer email and show ID suffix when available; list/status outputs are columnized for readability
-
Email normalization - Stored account emails are trimmed/lowercased when present
-
@opencode-ai plugin/sdk 1.1.34
-
hono 4.11.5
-
vitest 4.0.18
-
@types/node 25.0.10
-
@typescript-eslint 8.53.1
-
@andremxmx for reporting the multi-account ID issue (#4)
- npm package line: published under
opencode-openai-codex-auth-multi(legacy package), notoc-chatgpt-multi-auth.