oc-chatgpt-multi-auth 5.4.2 → 5.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +939 -931
- package/config/README.md +92 -88
- package/config/opencode-legacy.json +5 -5
- package/config/opencode-modern.json +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +368 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/prompts/codex.d.ts +1 -1
- package/dist/lib/prompts/codex.d.ts.map +1 -1
- package/dist/lib/prompts/codex.js +8 -1
- package/dist/lib/prompts/codex.js.map +1 -1
- package/dist/lib/request/helpers/model-map.d.ts +0 -6
- package/dist/lib/request/helpers/model-map.d.ts.map +1 -1
- package/dist/lib/request/helpers/model-map.js +18 -4
- package/dist/lib/request/helpers/model-map.js.map +1 -1
- package/dist/lib/request/request-transformer.d.ts.map +1 -1
- package/dist/lib/request/request-transformer.js +48 -7
- package/dist/lib/request/request-transformer.js.map +1 -1
- package/dist/lib/schemas.d.ts +3 -0
- package/dist/lib/schemas.d.ts.map +1 -1
- package/dist/lib/storage.d.ts +4 -0
- package/dist/lib/storage.d.ts.map +1 -1
- package/dist/lib/storage.js +108 -2
- package/dist/lib/storage.js.map +1 -1
- package/package.json +106 -106
package/config/README.md
CHANGED
|
@@ -1,88 +1,92 @@
|
|
|
1
|
-
# Configuration
|
|
2
|
-
|
|
3
|
-
This directory contains the official OpenCode config templates for the ChatGPT Codex OAuth plugin.
|
|
4
|
-
|
|
5
|
-
## Required: choose the right config file
|
|
6
|
-
|
|
7
|
-
| File | OpenCode version | Description |
|
|
8
|
-
|------|------------------|-------------|
|
|
9
|
-
| [`opencode-modern.json`](./opencode-modern.json) | **v1.0.210+** | Variant-based config: 6 base models with 21 total presets |
|
|
10
|
-
| [`opencode-legacy.json`](./opencode-legacy.json) | **v1.0.209 and below** | Legacy explicit entries: 21 individual model definitions |
|
|
11
|
-
|
|
12
|
-
## Quick pick
|
|
13
|
-
|
|
14
|
-
If your OpenCode version is v1.0.210 or newer:
|
|
15
|
-
|
|
16
|
-
```bash
|
|
17
|
-
cp config/opencode-modern.json ~/.config/opencode/opencode.json
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
If your OpenCode version is v1.0.209 or older:
|
|
21
|
-
|
|
22
|
-
```bash
|
|
23
|
-
cp config/opencode-legacy.json ~/.config/opencode/opencode.json
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
Check your version with:
|
|
27
|
-
|
|
28
|
-
```bash
|
|
29
|
-
opencode --version
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
## Why there are two templates
|
|
33
|
-
|
|
34
|
-
OpenCode v1.0.210+ added model `variants`, so one model entry can expose multiple reasoning levels. That keeps modern config much smaller while preserving the same effective presets.
|
|
35
|
-
|
|
36
|
-
Both templates include:
|
|
37
|
-
- GPT-5.4, GPT-5 Codex, GPT-5.1, GPT-5.1 Codex, GPT-5.1 Codex Max, GPT-5.1 Codex Mini
|
|
38
|
-
- Reasoning variants per model family
|
|
39
|
-
- `store: false` and `include: ["reasoning.encrypted_content"]`
|
|
40
|
-
- Context metadata (
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
##
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
- `
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
- `gpt-5.4-pro -> gpt-5.4` (if you
|
|
79
|
-
- `
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
- `gpt-5.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
-
|
|
87
|
-
|
|
88
|
-
|
|
1
|
+
# Configuration
|
|
2
|
+
|
|
3
|
+
This directory contains the official OpenCode config templates for the ChatGPT Codex OAuth plugin.
|
|
4
|
+
|
|
5
|
+
## Required: choose the right config file
|
|
6
|
+
|
|
7
|
+
| File | OpenCode version | Description |
|
|
8
|
+
|------|------------------|-------------|
|
|
9
|
+
| [`opencode-modern.json`](./opencode-modern.json) | **v1.0.210+** | Variant-based config: 6 base models with 21 total presets |
|
|
10
|
+
| [`opencode-legacy.json`](./opencode-legacy.json) | **v1.0.209 and below** | Legacy explicit entries: 21 individual model definitions |
|
|
11
|
+
|
|
12
|
+
## Quick pick
|
|
13
|
+
|
|
14
|
+
If your OpenCode version is v1.0.210 or newer:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
cp config/opencode-modern.json ~/.config/opencode/opencode.json
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
If your OpenCode version is v1.0.209 or older:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
cp config/opencode-legacy.json ~/.config/opencode/opencode.json
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Check your version with:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
opencode --version
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Why there are two templates
|
|
33
|
+
|
|
34
|
+
OpenCode v1.0.210+ added model `variants`, so one model entry can expose multiple reasoning levels. That keeps modern config much smaller while preserving the same effective presets.
|
|
35
|
+
|
|
36
|
+
Both templates include:
|
|
37
|
+
- GPT-5.4, GPT-5 Codex, GPT-5.1, GPT-5.1 Codex, GPT-5.1 Codex Max, GPT-5.1 Codex Mini
|
|
38
|
+
- Reasoning variants per model family
|
|
39
|
+
- `store: false` and `include: ["reasoning.encrypted_content"]`
|
|
40
|
+
- Context metadata (`gpt-5.4*`: 1,000,000 context / 128,000 output; other shipped models: 272,000 / 128,000)
|
|
41
|
+
|
|
42
|
+
If your OpenCode runtime supports global compaction tuning, you can also set:
|
|
43
|
+
- `model_context_window = 1000000`
|
|
44
|
+
- `model_auto_compact_token_limit = 900000`
|
|
45
|
+
|
|
46
|
+
## Spark model note
|
|
47
|
+
|
|
48
|
+
The templates intentionally do **not** include `gpt-5.3-codex-spark` by default. Spark is often entitlement-gated at the account/workspace level, so shipping it by default causes avoidable startup failures for many users.
|
|
49
|
+
|
|
50
|
+
If your workspace is entitled, you can add Spark model IDs manually.
|
|
51
|
+
|
|
52
|
+
## Usage examples
|
|
53
|
+
|
|
54
|
+
Modern template (v1.0.210+):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
opencode run "task" --model=openai/gpt-5.4 --variant=medium
|
|
58
|
+
opencode run "task" --model=openai/gpt-5-codex --variant=high
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Legacy template (v1.0.209 and below):
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
opencode run "task" --model=openai/gpt-5.4-medium
|
|
65
|
+
opencode run "task" --model=openai/gpt-5-codex-high
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Minimal config (advanced)
|
|
69
|
+
|
|
70
|
+
A barebones debug template is available at [`minimal-opencode.json`](./minimal-opencode.json). It omits the full preset catalog.
|
|
71
|
+
|
|
72
|
+
## Unsupported-model behavior
|
|
73
|
+
|
|
74
|
+
Current defaults are strict entitlement handling:
|
|
75
|
+
- `unsupportedCodexPolicy: "strict"` returns entitlement errors directly
|
|
76
|
+
- set `unsupportedCodexPolicy: "fallback"` (or `CODEX_AUTH_UNSUPPORTED_MODEL_POLICY=fallback`) to enable automatic fallback retries
|
|
77
|
+
- `fallbackToGpt52OnUnsupportedGpt53: true` keeps the legacy `gpt-5.3-codex -> gpt-5.2-codex` edge inside fallback mode
|
|
78
|
+
- `gpt-5.4-pro -> gpt-5.4` is included by default in fallback mode (relevant only if you add `gpt-5.4-pro` manually)
|
|
79
|
+
- `unsupportedCodexFallbackChain` lets you override fallback order per model
|
|
80
|
+
|
|
81
|
+
Default fallback chain (when policy is `fallback`):
|
|
82
|
+
- `gpt-5.4-pro -> gpt-5.4` (if you manually select `gpt-5.4-pro`)
|
|
83
|
+
- `gpt-5.3-codex -> gpt-5-codex -> gpt-5.2-codex`
|
|
84
|
+
- `gpt-5.3-codex-spark -> gpt-5-codex -> gpt-5.3-codex -> gpt-5.2-codex` (only relevant if Spark IDs are added manually)
|
|
85
|
+
- `gpt-5.2-codex -> gpt-5-codex`
|
|
86
|
+
- `gpt-5.1-codex -> gpt-5-codex`
|
|
87
|
+
|
|
88
|
+
## Additional docs
|
|
89
|
+
|
|
90
|
+
- Main config reference: [`docs/configuration.md`](../docs/configuration.md)
|
|
91
|
+
- Getting started: [`docs/getting-started.md`](../docs/getting-started.md)
|
|
92
|
+
- Troubleshooting: [`docs/troubleshooting.md`](../docs/troubleshooting.md)
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"gpt-5.4-none": {
|
|
19
19
|
"name": "GPT 5.4 None (OAuth)",
|
|
20
20
|
"limit": {
|
|
21
|
-
"context":
|
|
21
|
+
"context": 1000000,
|
|
22
22
|
"output": 128000
|
|
23
23
|
},
|
|
24
24
|
"modalities": {
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"gpt-5.4-low": {
|
|
44
44
|
"name": "GPT 5.4 Low (OAuth)",
|
|
45
45
|
"limit": {
|
|
46
|
-
"context":
|
|
46
|
+
"context": 1000000,
|
|
47
47
|
"output": 128000
|
|
48
48
|
},
|
|
49
49
|
"modalities": {
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"gpt-5.4-medium": {
|
|
69
69
|
"name": "GPT 5.4 Medium (OAuth)",
|
|
70
70
|
"limit": {
|
|
71
|
-
"context":
|
|
71
|
+
"context": 1000000,
|
|
72
72
|
"output": 128000
|
|
73
73
|
},
|
|
74
74
|
"modalities": {
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
"gpt-5.4-high": {
|
|
94
94
|
"name": "GPT 5.4 High (OAuth)",
|
|
95
95
|
"limit": {
|
|
96
|
-
"context":
|
|
96
|
+
"context": 1000000,
|
|
97
97
|
"output": 128000
|
|
98
98
|
},
|
|
99
99
|
"modalities": {
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
"gpt-5.4-xhigh": {
|
|
119
119
|
"name": "GPT 5.4 Extra High (OAuth)",
|
|
120
120
|
"limit": {
|
|
121
|
-
"context":
|
|
121
|
+
"context": 1000000,
|
|
122
122
|
"output": 128000
|
|
123
123
|
},
|
|
124
124
|
"modalities": {
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,qBAAqB,CAAC;AA+J/D;;;;;;;;;;;;;;;GAeG;AAEH,eAAO,MAAM,iBAAiB,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAGH,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,qBAAqB,CAAC;AA+J/D;;;;;;;;;;;;;;;GAeG;AAEH,eAAO,MAAM,iBAAiB,EAAE,MA6rL/B,CAAC;AAEF,eAAO,MAAM,gBAAgB,QAAoB,CAAC;AAElD,eAAe,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1407,7 +1407,7 @@ export const OpenAIOAuthPlugin = async ({ client }) => {
|
|
|
1407
1407
|
const originalUrl = extractRequestUrl(input);
|
|
1408
1408
|
const url = rewriteUrlForCodex(originalUrl);
|
|
1409
1409
|
// Step 3: Transform request body with model-specific Codex instructions
|
|
1410
|
-
// Instructions are fetched per model family (codex-max, codex, gpt-5.
|
|
1410
|
+
// Instructions are fetched per model family (codex-max, codex, gpt-5.4, etc.)
|
|
1411
1411
|
// Capture original stream value before transformation
|
|
1412
1412
|
// generateText() sends no stream field, streamText() sends stream=true
|
|
1413
1413
|
const normalizeRequestInit = async (requestInput, requestInit) => {
|
|
@@ -1473,7 +1473,7 @@ export const OpenAIOAuthPlugin = async ({ client }) => {
|
|
|
1473
1473
|
let transformedBody = transformation?.body;
|
|
1474
1474
|
const promptCacheKey = transformedBody?.prompt_cache_key;
|
|
1475
1475
|
let model = transformedBody?.model;
|
|
1476
|
-
let modelFamily = model ? getModelFamily(model) : "gpt-5.
|
|
1476
|
+
let modelFamily = model ? getModelFamily(model) : "gpt-5.4";
|
|
1477
1477
|
let quotaKey = model ? `${modelFamily}:${model}` : modelFamily;
|
|
1478
1478
|
const threadIdCandidate = (process.env.CODEX_THREAD_ID ?? promptCacheKey ?? "")
|
|
1479
1479
|
.toString()
|
|
@@ -3215,6 +3215,372 @@ export const OpenAIOAuthPlugin = async ({ client }) => {
|
|
|
3215
3215
|
return lines.join("\n");
|
|
3216
3216
|
},
|
|
3217
3217
|
}),
|
|
3218
|
+
"codex-limits": tool({
|
|
3219
|
+
description: "Show live 5-hour and weekly Codex usage limits for all accounts.",
|
|
3220
|
+
args: {},
|
|
3221
|
+
async execute() {
|
|
3222
|
+
const ui = resolveUiRuntime();
|
|
3223
|
+
const storage = await loadAccounts();
|
|
3224
|
+
if (!storage || storage.accounts.length === 0) {
|
|
3225
|
+
if (ui.v2Enabled) {
|
|
3226
|
+
return [
|
|
3227
|
+
...formatUiHeader(ui, "Codex limits"),
|
|
3228
|
+
"",
|
|
3229
|
+
formatUiItem(ui, "No accounts configured.", "warning"),
|
|
3230
|
+
formatUiItem(ui, "Run: opencode auth login", "accent"),
|
|
3231
|
+
].join("\n");
|
|
3232
|
+
}
|
|
3233
|
+
return "No Codex accounts configured. Run: opencode auth login";
|
|
3234
|
+
}
|
|
3235
|
+
const formatWindowLabel = (windowMinutes) => {
|
|
3236
|
+
if (!windowMinutes || !Number.isFinite(windowMinutes) || windowMinutes <= 0) {
|
|
3237
|
+
return "quota";
|
|
3238
|
+
}
|
|
3239
|
+
if (windowMinutes % 1440 === 0)
|
|
3240
|
+
return `${windowMinutes / 1440}d`;
|
|
3241
|
+
if (windowMinutes % 60 === 0)
|
|
3242
|
+
return `${windowMinutes / 60}h`;
|
|
3243
|
+
return `${windowMinutes}m`;
|
|
3244
|
+
};
|
|
3245
|
+
const formatReset = (resetAtMs) => {
|
|
3246
|
+
if (!resetAtMs || !Number.isFinite(resetAtMs) || resetAtMs <= 0)
|
|
3247
|
+
return undefined;
|
|
3248
|
+
const date = new Date(resetAtMs);
|
|
3249
|
+
if (!Number.isFinite(date.getTime()))
|
|
3250
|
+
return undefined;
|
|
3251
|
+
const now = new Date();
|
|
3252
|
+
const sameDay = now.getFullYear() === date.getFullYear() &&
|
|
3253
|
+
now.getMonth() === date.getMonth() &&
|
|
3254
|
+
now.getDate() === date.getDate();
|
|
3255
|
+
const time = date.toLocaleTimeString(undefined, {
|
|
3256
|
+
hour: "2-digit",
|
|
3257
|
+
minute: "2-digit",
|
|
3258
|
+
hour12: false,
|
|
3259
|
+
});
|
|
3260
|
+
if (sameDay)
|
|
3261
|
+
return time;
|
|
3262
|
+
const day = date.toLocaleDateString(undefined, { month: "short", day: "2-digit" });
|
|
3263
|
+
return `${time} on ${day}`;
|
|
3264
|
+
};
|
|
3265
|
+
const mapWindow = (window) => {
|
|
3266
|
+
if (!window)
|
|
3267
|
+
return {};
|
|
3268
|
+
return {
|
|
3269
|
+
usedPercent: typeof window.used_percent === "number" && Number.isFinite(window.used_percent)
|
|
3270
|
+
? window.used_percent
|
|
3271
|
+
: undefined,
|
|
3272
|
+
windowMinutes: typeof window.limit_window_seconds === "number" && Number.isFinite(window.limit_window_seconds)
|
|
3273
|
+
? Math.max(1, Math.ceil(window.limit_window_seconds / 60))
|
|
3274
|
+
: undefined,
|
|
3275
|
+
resetAtMs: typeof window.reset_at === "number" && window.reset_at > 0
|
|
3276
|
+
? window.reset_at * 1000
|
|
3277
|
+
: typeof window.reset_after_seconds === "number" && window.reset_after_seconds > 0
|
|
3278
|
+
? Date.now() + window.reset_after_seconds * 1000
|
|
3279
|
+
: undefined,
|
|
3280
|
+
};
|
|
3281
|
+
};
|
|
3282
|
+
const formatLimitTitle = (windowMinutes, fallback = "quota") => {
|
|
3283
|
+
if (windowMinutes === 300)
|
|
3284
|
+
return "5h limit";
|
|
3285
|
+
if (windowMinutes === 10080)
|
|
3286
|
+
return "Weekly limit";
|
|
3287
|
+
if (fallback !== "quota")
|
|
3288
|
+
return fallback;
|
|
3289
|
+
return `${formatWindowLabel(windowMinutes)} limit`;
|
|
3290
|
+
};
|
|
3291
|
+
const formatLimitSummary = (window) => {
|
|
3292
|
+
const used = window.usedPercent;
|
|
3293
|
+
const left = typeof used === "number" && Number.isFinite(used)
|
|
3294
|
+
? Math.max(0, Math.min(100, Math.round(100 - used)))
|
|
3295
|
+
: undefined;
|
|
3296
|
+
const reset = formatReset(window.resetAtMs);
|
|
3297
|
+
if (left !== undefined && reset)
|
|
3298
|
+
return `${left}% left (resets ${reset})`;
|
|
3299
|
+
if (left !== undefined)
|
|
3300
|
+
return `${left}% left`;
|
|
3301
|
+
if (reset)
|
|
3302
|
+
return `resets ${reset}`;
|
|
3303
|
+
return "unavailable";
|
|
3304
|
+
};
|
|
3305
|
+
const formatCredits = (credits) => {
|
|
3306
|
+
if (!credits)
|
|
3307
|
+
return undefined;
|
|
3308
|
+
if (credits.unlimited)
|
|
3309
|
+
return "unlimited";
|
|
3310
|
+
if (typeof credits.balance === "string" && credits.balance.trim()) {
|
|
3311
|
+
return credits.balance.trim();
|
|
3312
|
+
}
|
|
3313
|
+
if (credits.has_credits)
|
|
3314
|
+
return "available";
|
|
3315
|
+
return undefined;
|
|
3316
|
+
};
|
|
3317
|
+
const formatExtraName = (name) => {
|
|
3318
|
+
if (!name)
|
|
3319
|
+
return "Additional limit";
|
|
3320
|
+
if (name === "code_review_rate_limit")
|
|
3321
|
+
return "Code review";
|
|
3322
|
+
return name.replace(/[_-]+/g, " ").replace(/\b\w/g, (match) => match.toUpperCase());
|
|
3323
|
+
};
|
|
3324
|
+
const sanitizeUsageErrorMessage = (status, bodyText) => {
|
|
3325
|
+
const normalized = bodyText.replace(/\s+/g, " ").trim();
|
|
3326
|
+
const redacted = normalized
|
|
3327
|
+
.replace(/Bearer\s+\S+/gi, "Bearer [redacted]")
|
|
3328
|
+
.replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted-token]")
|
|
3329
|
+
.replace(/\bsk-[A-Za-z0-9][A-Za-z0-9._:-]{19,}\b/gi, "[redacted-token]")
|
|
3330
|
+
.replace(/\b[a-f0-9]{40,}\b/gi, "[redacted-token]");
|
|
3331
|
+
return redacted ? `HTTP ${status}: ${redacted.slice(0, 200)}` : `HTTP ${status}`;
|
|
3332
|
+
};
|
|
3333
|
+
const isAbortError = (error) => (error instanceof Error && error.name === "AbortError") ||
|
|
3334
|
+
(typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError");
|
|
3335
|
+
const applyRefreshedCredentials = (target, result) => {
|
|
3336
|
+
target.refreshToken = result.refresh;
|
|
3337
|
+
target.accessToken = result.access;
|
|
3338
|
+
target.expiresAt = result.expires;
|
|
3339
|
+
};
|
|
3340
|
+
const usageErrorBodyMaxChars = 4096;
|
|
3341
|
+
const persistRefreshedCredentials = async (params) => {
|
|
3342
|
+
return await withAccountStorageTransaction(async (current, persist) => {
|
|
3343
|
+
const latestStorage = current ??
|
|
3344
|
+
{
|
|
3345
|
+
version: 3,
|
|
3346
|
+
accounts: [],
|
|
3347
|
+
activeIndex: 0,
|
|
3348
|
+
activeIndexByFamily: {},
|
|
3349
|
+
};
|
|
3350
|
+
const uniqueMatch = (matches) => matches.length === 1 ? matches[0] : undefined;
|
|
3351
|
+
let updated = false;
|
|
3352
|
+
if (params.previousRefreshToken) {
|
|
3353
|
+
for (const storedAccount of latestStorage.accounts) {
|
|
3354
|
+
if (storedAccount.refreshToken === params.previousRefreshToken) {
|
|
3355
|
+
applyRefreshedCredentials(storedAccount, params.refreshResult);
|
|
3356
|
+
updated = true;
|
|
3357
|
+
}
|
|
3358
|
+
}
|
|
3359
|
+
}
|
|
3360
|
+
if (!updated) {
|
|
3361
|
+
const normalizedOrganizationId = params.organizationId?.trim() ?? "";
|
|
3362
|
+
const normalizedEmail = params.email?.trim().toLowerCase();
|
|
3363
|
+
const orgScopedMatches = params.accountId
|
|
3364
|
+
? latestStorage.accounts.filter((storedAccount) => storedAccount.accountId === params.accountId &&
|
|
3365
|
+
(storedAccount.organizationId?.trim() ?? "") === normalizedOrganizationId)
|
|
3366
|
+
: [];
|
|
3367
|
+
const accountIdMatches = params.accountId
|
|
3368
|
+
? latestStorage.accounts.filter((storedAccount) => storedAccount.accountId === params.accountId)
|
|
3369
|
+
: [];
|
|
3370
|
+
const emailMatches = normalizedEmail && !params.accountId
|
|
3371
|
+
? latestStorage.accounts.filter((storedAccount) => storedAccount.email?.trim().toLowerCase() === normalizedEmail)
|
|
3372
|
+
: [];
|
|
3373
|
+
const fallbackTarget = uniqueMatch(orgScopedMatches) ??
|
|
3374
|
+
uniqueMatch(accountIdMatches) ??
|
|
3375
|
+
uniqueMatch(emailMatches);
|
|
3376
|
+
if (fallbackTarget) {
|
|
3377
|
+
applyRefreshedCredentials(fallbackTarget, params.refreshResult);
|
|
3378
|
+
updated = true;
|
|
3379
|
+
}
|
|
3380
|
+
}
|
|
3381
|
+
if (updated) {
|
|
3382
|
+
await persist(latestStorage);
|
|
3383
|
+
}
|
|
3384
|
+
if (!updated) {
|
|
3385
|
+
logWarn(`[${PLUGIN_NAME}] persistRefreshedCredentials could not find a matching stored account. Refreshed credentials remain in-memory for this invocation only.`, {
|
|
3386
|
+
accountId: params.accountId,
|
|
3387
|
+
organizationId: params.organizationId,
|
|
3388
|
+
});
|
|
3389
|
+
}
|
|
3390
|
+
return updated;
|
|
3391
|
+
});
|
|
3392
|
+
};
|
|
3393
|
+
const usageFetchTimeoutMs = getFetchTimeoutMs(loadPluginConfig());
|
|
3394
|
+
const fetchUsage = async (params) => {
|
|
3395
|
+
const headers = createCodexHeaders(undefined, params.accountId, params.accessToken, {
|
|
3396
|
+
organizationId: params.organizationId,
|
|
3397
|
+
});
|
|
3398
|
+
headers.set("accept", "application/json");
|
|
3399
|
+
const controller = new AbortController();
|
|
3400
|
+
const timeout = setTimeout(() => controller.abort(), usageFetchTimeoutMs);
|
|
3401
|
+
try {
|
|
3402
|
+
const response = await fetch(`${CODEX_BASE_URL}/wham/usage`, {
|
|
3403
|
+
method: "GET",
|
|
3404
|
+
headers,
|
|
3405
|
+
signal: controller.signal,
|
|
3406
|
+
});
|
|
3407
|
+
if (!response.ok) {
|
|
3408
|
+
let bodyText = "";
|
|
3409
|
+
try {
|
|
3410
|
+
bodyText = (await response.text()).slice(0, usageErrorBodyMaxChars);
|
|
3411
|
+
}
|
|
3412
|
+
catch (error) {
|
|
3413
|
+
if (isAbortError(error) || controller.signal.aborted) {
|
|
3414
|
+
throw new Error("Usage request timed out");
|
|
3415
|
+
}
|
|
3416
|
+
throw error;
|
|
3417
|
+
}
|
|
3418
|
+
if (controller.signal.aborted) {
|
|
3419
|
+
throw new Error("Usage request timed out");
|
|
3420
|
+
}
|
|
3421
|
+
throw new Error(sanitizeUsageErrorMessage(response.status, bodyText));
|
|
3422
|
+
}
|
|
3423
|
+
return (await response.json());
|
|
3424
|
+
}
|
|
3425
|
+
catch (error) {
|
|
3426
|
+
if (isAbortError(error)) {
|
|
3427
|
+
throw new Error("Usage request timed out");
|
|
3428
|
+
}
|
|
3429
|
+
throw error;
|
|
3430
|
+
}
|
|
3431
|
+
finally {
|
|
3432
|
+
clearTimeout(timeout);
|
|
3433
|
+
}
|
|
3434
|
+
};
|
|
3435
|
+
// Deduplicate accounts by refreshToken (same credential = same limits)
|
|
3436
|
+
const seenTokens = new Set();
|
|
3437
|
+
const uniqueIndices = [];
|
|
3438
|
+
for (let i = 0; i < storage.accounts.length; i++) {
|
|
3439
|
+
const acct = storage.accounts[i];
|
|
3440
|
+
if (!acct)
|
|
3441
|
+
continue;
|
|
3442
|
+
const refreshToken = typeof acct.refreshToken === "string" ? acct.refreshToken.trim() : "";
|
|
3443
|
+
if (refreshToken && seenTokens.has(refreshToken))
|
|
3444
|
+
continue;
|
|
3445
|
+
if (refreshToken)
|
|
3446
|
+
seenTokens.add(refreshToken);
|
|
3447
|
+
uniqueIndices.push(i);
|
|
3448
|
+
}
|
|
3449
|
+
const lines = ui.v2Enabled
|
|
3450
|
+
? [...formatUiHeader(ui, "Codex limits"), ""]
|
|
3451
|
+
: [`Codex limits (${uniqueIndices.length} account${uniqueIndices.length === 1 ? "" : "s"}):`, ""];
|
|
3452
|
+
const activeIndex = resolveActiveIndex(storage, "codex");
|
|
3453
|
+
const activeRefreshToken = typeof activeIndex === "number" && activeIndex >= 0 && activeIndex < storage.accounts.length
|
|
3454
|
+
? storage.accounts[activeIndex]?.refreshToken?.trim() || undefined
|
|
3455
|
+
: undefined;
|
|
3456
|
+
let storageChanged = false;
|
|
3457
|
+
for (const i of uniqueIndices) {
|
|
3458
|
+
const account = storage.accounts[i];
|
|
3459
|
+
if (!account)
|
|
3460
|
+
continue;
|
|
3461
|
+
const sharesActiveCredential = !!activeRefreshToken && account.refreshToken === activeRefreshToken;
|
|
3462
|
+
const displayIndex = sharesActiveCredential && typeof activeIndex === "number" ? activeIndex : i;
|
|
3463
|
+
const displayAccount = storage.accounts[displayIndex];
|
|
3464
|
+
if (sharesActiveCredential && !displayAccount) {
|
|
3465
|
+
logWarn(`[${PLUGIN_NAME}] active account entry missing for index ${displayIndex}, falling back to account ${i}`);
|
|
3466
|
+
}
|
|
3467
|
+
const effectiveDisplayAccount = displayAccount ?? account;
|
|
3468
|
+
const label = formatCommandAccountLabel(effectiveDisplayAccount, displayIndex);
|
|
3469
|
+
const isActive = i === activeIndex || sharesActiveCredential;
|
|
3470
|
+
const activeSuffix = isActive ? (ui.v2Enabled ? ` ${formatUiBadge(ui, "active", "accent")}` : " [active]") : "";
|
|
3471
|
+
try {
|
|
3472
|
+
let accessToken = account.accessToken;
|
|
3473
|
+
if (typeof accessToken !== "string" ||
|
|
3474
|
+
!accessToken ||
|
|
3475
|
+
typeof account.expiresAt !== "number" ||
|
|
3476
|
+
account.expiresAt <= Date.now() + 30_000) {
|
|
3477
|
+
const previousRefreshToken = account.refreshToken;
|
|
3478
|
+
if (!previousRefreshToken) {
|
|
3479
|
+
throw new Error("Cannot refresh: account has no refresh token");
|
|
3480
|
+
}
|
|
3481
|
+
const refreshResult = await queuedRefresh(previousRefreshToken);
|
|
3482
|
+
if (refreshResult.type !== "success") {
|
|
3483
|
+
throw new Error(refreshResult.message ?? refreshResult.reason);
|
|
3484
|
+
}
|
|
3485
|
+
let refreshedCount = 0;
|
|
3486
|
+
for (const storedAccount of storage.accounts) {
|
|
3487
|
+
if (!storedAccount)
|
|
3488
|
+
continue;
|
|
3489
|
+
if (storedAccount.refreshToken === previousRefreshToken) {
|
|
3490
|
+
applyRefreshedCredentials(storedAccount, refreshResult);
|
|
3491
|
+
refreshedCount += 1;
|
|
3492
|
+
}
|
|
3493
|
+
}
|
|
3494
|
+
if (refreshedCount === 0) {
|
|
3495
|
+
applyRefreshedCredentials(account, refreshResult);
|
|
3496
|
+
}
|
|
3497
|
+
const persistedRefresh = await persistRefreshedCredentials({
|
|
3498
|
+
previousRefreshToken,
|
|
3499
|
+
accountId: account.accountId,
|
|
3500
|
+
organizationId: account.organizationId,
|
|
3501
|
+
email: account.email,
|
|
3502
|
+
refreshResult,
|
|
3503
|
+
});
|
|
3504
|
+
accessToken = refreshResult.access;
|
|
3505
|
+
storageChanged = storageChanged || persistedRefresh;
|
|
3506
|
+
}
|
|
3507
|
+
const effectiveAccount = sharesActiveCredential ? effectiveDisplayAccount : account;
|
|
3508
|
+
const accountId = effectiveAccount.accountId ?? extractAccountId(accessToken);
|
|
3509
|
+
if (!accountId) {
|
|
3510
|
+
throw new Error("Missing account id");
|
|
3511
|
+
}
|
|
3512
|
+
const payload = await fetchUsage({
|
|
3513
|
+
accountId,
|
|
3514
|
+
accessToken,
|
|
3515
|
+
organizationId: effectiveAccount.organizationId,
|
|
3516
|
+
});
|
|
3517
|
+
const primary = mapWindow(payload.rate_limit?.primary_window ?? null);
|
|
3518
|
+
const secondary = mapWindow(payload.rate_limit?.secondary_window ?? null);
|
|
3519
|
+
const codeReviewRateLimit = payload.code_review_rate_limit ??
|
|
3520
|
+
payload.additional_rate_limits?.find((entry) => entry.limit_name === "code_review_rate_limit")?.rate_limit ??
|
|
3521
|
+
null;
|
|
3522
|
+
const codeReview = mapWindow(codeReviewRateLimit?.primary_window ?? null);
|
|
3523
|
+
const credits = formatCredits(payload.credits ?? null);
|
|
3524
|
+
const additionalLimits = (payload.additional_rate_limits ?? []).filter((entry) => entry.limit_name !== "code_review_rate_limit");
|
|
3525
|
+
if (ui.v2Enabled) {
|
|
3526
|
+
lines.push(formatUiItem(ui, `${label}${activeSuffix}`));
|
|
3527
|
+
lines.push(` ${formatUiKeyValue(ui, formatLimitTitle(primary.windowMinutes), formatLimitSummary(primary), "muted")}`);
|
|
3528
|
+
lines.push(` ${formatUiKeyValue(ui, formatLimitTitle(secondary.windowMinutes), formatLimitSummary(secondary), "muted")}`);
|
|
3529
|
+
if (codeReview.windowMinutes || typeof codeReview.usedPercent === "number" || codeReview.resetAtMs) {
|
|
3530
|
+
lines.push(` ${formatUiKeyValue(ui, "Code review", formatLimitSummary(codeReview), "muted")}`);
|
|
3531
|
+
}
|
|
3532
|
+
for (const limit of additionalLimits) {
|
|
3533
|
+
const extraWindow = mapWindow(limit.rate_limit?.primary_window ?? null);
|
|
3534
|
+
lines.push(` ${formatUiKeyValue(ui, formatExtraName(limit.limit_name ?? limit.metered_feature), formatLimitSummary(extraWindow), "muted")}`);
|
|
3535
|
+
}
|
|
3536
|
+
if (payload.plan_type) {
|
|
3537
|
+
lines.push(` ${formatUiKeyValue(ui, "Plan", payload.plan_type, "muted")}`);
|
|
3538
|
+
}
|
|
3539
|
+
if (credits) {
|
|
3540
|
+
lines.push(` ${formatUiKeyValue(ui, "Credits", credits, "muted")}`);
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
else {
|
|
3544
|
+
lines.push(`${label}${activeSuffix}:`);
|
|
3545
|
+
lines.push(` ${formatLimitTitle(primary.windowMinutes)}: ${formatLimitSummary(primary)}`);
|
|
3546
|
+
lines.push(` ${formatLimitTitle(secondary.windowMinutes)}: ${formatLimitSummary(secondary)}`);
|
|
3547
|
+
if (codeReview.windowMinutes || typeof codeReview.usedPercent === "number" || codeReview.resetAtMs) {
|
|
3548
|
+
lines.push(` Code review: ${formatLimitSummary(codeReview)}`);
|
|
3549
|
+
}
|
|
3550
|
+
for (const limit of additionalLimits) {
|
|
3551
|
+
const extraWindow = mapWindow(limit.rate_limit?.primary_window ?? null);
|
|
3552
|
+
lines.push(` ${formatExtraName(limit.limit_name ?? limit.metered_feature)}: ${formatLimitSummary(extraWindow)}`);
|
|
3553
|
+
}
|
|
3554
|
+
if (payload.plan_type) {
|
|
3555
|
+
lines.push(` Plan: ${payload.plan_type}`);
|
|
3556
|
+
}
|
|
3557
|
+
if (credits) {
|
|
3558
|
+
lines.push(` Credits: ${credits}`);
|
|
3559
|
+
}
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
catch (error) {
|
|
3563
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3564
|
+
if (ui.v2Enabled) {
|
|
3565
|
+
lines.push(formatUiItem(ui, `${label}${activeSuffix}`));
|
|
3566
|
+
lines.push(` ${formatUiKeyValue(ui, "Error", message.slice(0, 160), "danger")}`);
|
|
3567
|
+
}
|
|
3568
|
+
else {
|
|
3569
|
+
lines.push(`${label}${activeSuffix}:`);
|
|
3570
|
+
lines.push(` Error: ${message.slice(0, 160)}`);
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
lines.push("");
|
|
3574
|
+
}
|
|
3575
|
+
if (storageChanged) {
|
|
3576
|
+
invalidateAccountManagerCache();
|
|
3577
|
+
}
|
|
3578
|
+
while (lines.length > 0 && lines[lines.length - 1] === "") {
|
|
3579
|
+
lines.pop();
|
|
3580
|
+
}
|
|
3581
|
+
return lines.join("\n");
|
|
3582
|
+
},
|
|
3583
|
+
}),
|
|
3218
3584
|
"codex-metrics": tool({
|
|
3219
3585
|
description: "Show runtime request metrics for this plugin process.",
|
|
3220
3586
|
args: {},
|