-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
Expand file tree
/
Copy pathmain.go
More file actions
333 lines (295 loc) · 9.56 KB
/
Copy pathmain.go
File metadata and controls
333 lines (295 loc) · 9.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Command fetch_codex_models connects to the Codex API using stored auth
// credentials and saves the dynamically fetched Codex client model catalog to a
// JSON file for inspection or offline use.
//
// Usage:
//
// go run ./cmd/fetch_codex_models [flags]
//
// Flags:
//
// --auths-dir <path> Directory containing auth JSON files (default: config auth-dir)
// --config <path> Config file path (default: "config.yaml")
// --output <path> Output JSON file path (default: "codex_models.json")
// --client-version <ver> Codex client_version query value (default: "0.133.0")
// --pretty Pretty-print the output JSON (default: true)
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
codexauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/codex"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
sdkauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
log "github.com/sirupsen/logrus"
)
const (
codexModelsBaseURL = "https://chatgpt.com/backend-api/codex"
codexModelsPath = "/models"
defaultClientVersion = "0.133.0"
defaultCodexUserAgent = "codex_cli_rs/0.133.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9"
defaultCodexOriginator = "codex_cli_rs"
accessTokenRefreshLeeway = 30 * time.Second
)
func init() {
logging.SetupBaseLogger()
log.SetLevel(log.InfoLevel)
}
func main() {
var authsDir string
var configPath string
var outputPath string
var clientVersion string
var pretty bool
flag.StringVar(&authsDir, "auths-dir", "", "Directory containing auth JSON files (overrides config auth-dir)")
flag.StringVar(&configPath, "config", "", "Configure File Path")
flag.StringVar(&outputPath, "output", "codex_models.json", "Output JSON file path")
flag.StringVar(&clientVersion, "client-version", defaultClientVersion, "Codex client_version query value")
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
flag.Parse()
authsDirOverridden := false
flag.Visit(func(f *flag.Flag) {
if f.Name == "auths-dir" {
authsDirOverridden = true
}
})
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
os.Exit(1)
}
if strings.TrimSpace(configPath) == "" {
configPath = filepath.Join(wd, "config.yaml")
}
cfg, err := config.LoadConfigOptional(configPath, false)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to load config file %s: %v\n", configPath, err)
os.Exit(1)
}
if cfg == nil {
cfg = &config.Config{}
}
if !authsDirOverridden {
authsDir = cfg.AuthDir
} else if strings.TrimSpace(authsDir) != "" && !strings.HasPrefix(strings.TrimSpace(authsDir), "~") && !filepath.IsAbs(authsDir) {
authsDir = filepath.Join(wd, authsDir)
}
if authsDir, err = util.ResolveAuthDir(authsDir); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to resolve auth directory: %v\n", err)
os.Exit(1)
}
if !filepath.IsAbs(outputPath) {
outputPath = filepath.Join(wd, outputPath)
}
fmt.Printf("Scanning auth files in: %s\n", authsDir)
fileStore := sdkauth.NewFileTokenStore()
fileStore.SetBaseDir(authsDir)
ctx := context.Background()
auths, err := fileStore.List(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
os.Exit(1)
}
if len(auths) == 0 {
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
os.Exit(1)
}
chosen := findCodexAuth(auths)
if chosen == nil {
fmt.Fprintf(os.Stderr, "error: no enabled codex auth found in %s\n", authsDir)
os.Exit(1)
}
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
accessToken, refreshed, err := ensureAccessToken(ctx, fileStore, chosen)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to prepare codex access token: %v\n", err)
os.Exit(1)
}
if refreshed {
fmt.Println("Refreshed Codex access token.")
}
fmt.Println("Fetching Codex model list from upstream...")
raw, count, err := fetchModels(ctx, chosen, accessToken, clientVersion)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to fetch codex models: %v\n", err)
os.Exit(1)
}
fmt.Printf("Fetched %d models.\n", count)
if pretty {
raw, err = prettyJSON(raw)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to format JSON: %v\n", err)
os.Exit(1)
}
}
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
os.Exit(1)
}
fmt.Printf("Model list saved to: %s\n", outputPath)
}
func findCodexAuth(auths []*coreauth.Auth) *coreauth.Auth {
for _, auth := range auths {
if auth == nil || auth.Disabled {
continue
}
if !strings.EqualFold(strings.TrimSpace(auth.Provider), "codex") {
continue
}
if metaStringValue(auth.Metadata, "access_token") == "" && metaStringValue(auth.Metadata, "refresh_token") == "" {
continue
}
return auth
}
return nil
}
func ensureAccessToken(ctx context.Context, store *sdkauth.FileTokenStore, auth *coreauth.Auth) (string, bool, error) {
accessToken := metaStringValue(auth.Metadata, "access_token")
if accessToken != "" {
if expiresAt, ok := auth.ExpirationTime(); !ok || time.Now().Add(accessTokenRefreshLeeway).Before(expiresAt) {
return accessToken, false, nil
}
}
refreshToken := metaStringValue(auth.Metadata, "refresh_token")
if refreshToken == "" {
if accessToken != "" {
return accessToken, false, nil
}
return "", false, fmt.Errorf("missing access_token and refresh_token")
}
svc := codexauth.NewCodexAuthWithProxyURL(nil, auth.ProxyURL)
tokenData, errRefresh := svc.RefreshTokensWithRetry(ctx, refreshToken, 3, auth.ID)
if errRefresh != nil {
return "", false, errRefresh
}
if strings.TrimSpace(tokenData.AccessToken) == "" {
return "", false, fmt.Errorf("refresh response did not include access_token")
}
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
auth.Metadata["id_token"] = tokenData.IDToken
auth.Metadata["access_token"] = tokenData.AccessToken
if tokenData.RefreshToken != "" {
auth.Metadata["refresh_token"] = tokenData.RefreshToken
}
if tokenData.AccountID != "" {
auth.Metadata["account_id"] = tokenData.AccountID
}
if tokenData.Email != "" {
auth.Metadata["email"] = tokenData.Email
}
auth.Metadata["expired"] = tokenData.Expire
auth.Metadata["type"] = "codex"
auth.Metadata["last_refresh"] = time.Now().Format(time.RFC3339)
if _, errSave := store.Save(ctx, auth); errSave != nil {
return "", false, fmt.Errorf("failed to save refreshed auth: %w", errSave)
}
return tokenData.AccessToken, true, nil
}
func fetchModels(ctx context.Context, auth *coreauth.Auth, accessToken, clientVersion string) ([]byte, int, error) {
modelsURL, errURL := codexModelsURL(clientVersion)
if errURL != nil {
return nil, 0, errURL
}
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodGet, modelsURL, nil)
if errReq != nil {
return nil, 0, errReq
}
httpReq.Close = true
httpReq.Header.Set("Accept", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
httpReq.Header.Set("Originator", defaultCodexOriginator)
httpReq.Header.Set("User-Agent", defaultCodexUserAgent)
if accountID := metaStringValue(auth.Metadata, "account_id"); accountID != "" {
httpReq.Header.Set("Chatgpt-Account-Id", accountID)
}
if auth != nil {
util.ApplyCustomHeadersFromAttrs(httpReq, auth.Attributes)
}
httpClient := &http.Client{}
if auth != nil {
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
httpClient.Transport = transport
}
}
httpResp, errDo := httpClient.Do(httpReq)
if errDo != nil {
return nil, 0, errDo
}
bodyBytes, errRead := io.ReadAll(httpResp.Body)
if errClose := httpResp.Body.Close(); errClose != nil && errRead == nil {
errRead = errClose
}
if errRead != nil {
return nil, 0, errRead
}
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
return nil, 0, fmt.Errorf("models request failed with status %d: %s", httpResp.StatusCode, strings.TrimSpace(string(bodyBytes)))
}
count, errCount := countModels(bodyBytes)
if errCount != nil {
return nil, 0, errCount
}
return bodyBytes, count, nil
}
func codexModelsURL(clientVersion string) (string, error) {
u, err := url.Parse(codexModelsBaseURL + codexModelsPath)
if err != nil {
return "", err
}
if strings.TrimSpace(clientVersion) != "" {
q := u.Query()
q.Set("client_version", strings.TrimSpace(clientVersion))
u.RawQuery = q.Encode()
}
return u.String(), nil
}
func countModels(raw []byte) (int, error) {
var payload struct {
Models []map[string]any `json:"models"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
return 0, fmt.Errorf("failed to parse response JSON: %w", err)
}
if payload.Models == nil {
return 0, fmt.Errorf("response JSON does not contain models array")
}
return len(payload.Models), nil
}
func prettyJSON(raw []byte) ([]byte, error) {
var buf bytes.Buffer
if err := json.Indent(&buf, raw, "", " "); err != nil {
return nil, err
}
buf.WriteByte('\n')
return buf.Bytes(), nil
}
func metaStringValue(m map[string]any, key string) string {
if m == nil {
return ""
}
v, ok := m[key]
if !ok {
return ""
}
switch val := v.(type) {
case string:
return strings.TrimSpace(val)
default:
return ""
}
}