-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2320 lines (2129 loc) · 98.3 KB
/
Copy pathserver.js
File metadata and controls
2320 lines (2129 loc) · 98.3 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require("express");
const fs = require("fs");
const path = require("path");
const os = require("os");
const { createProxyMiddleware, fixRequestBody } = require("http-proxy-middleware");
const app = express();
const PORT = process.env.PORT ? Number(process.env.PORT) : 3777;
// Paths
const CODEX_DIR = path.join(os.homedir(), ".codex");
const CONFIG_PATH = process.env.CONFIG_PATH || path.join(CODEX_DIR, "config.toml");
const MODELS_CACHE_PATH = process.env.MODELS_CACHE_PATH || path.join(CODEX_DIR, "models_cache.json");
const BACKUP_DIR = path.join(CODEX_DIR, "Backup");
const PROVIDERS_PATH = process.env.PROVIDERS_PATH || path.join(__dirname, "providers.json");
const AUTH_PATH = process.env.AUTH_PATH || path.join(CODEX_DIR, "auth.json");
// Preserved ChatGPT OAuth credentials. Native GPT passthrough needs Codex in
// apikey mode (so custom providers route through the proxy), but that mode
// hides the ChatGPT login — so before switching we stash the OAuth tokens here
// and the proxy uses them to reach chatgpt.com. Gitignored (contains tokens).
const AUTH_CHATGPT_PATH = process.env.AUTH_CHATGPT_PATH || path.join(__dirname, "auth.chatgpt.json");
// Our merged model catalog. Codex reads this file via the `model_catalog_json`
// config key, which is how the custom models appear in the native picker
// (same mechanism codex-router uses). It is derived data — regenerated from
// the native cache + providers — so it is gitignored.
const MERGED_CATALOG_PATH = process.env.MERGED_CATALOG_PATH || path.join(__dirname, "merged-models.json");
const NATIVE_ALIASES_PATH = process.env.NATIVE_ALIASES_PATH || path.join(__dirname, "native-aliases.json");
const MANAGED_START = "# BEGIN codex-switcher-managed";
const MANAGED_END = "# END codex-switcher-managed";
const MANAGED_PROVIDER_START = "# BEGIN codex-switcher-provider-managed";
const MANAGED_PROVIDER_END = "# END codex-switcher-provider-managed";
// Desktop builds often hide namespaced external slugs in the picker. Publish
// external models under native-looking slots and keep a private alias map for
// routing the selected slot back to provider/model.
function readNativeAliases() {
try {
if (!fs.existsSync(NATIVE_ALIASES_PATH)) return {};
const parsed = JSON.parse(fs.readFileSync(NATIVE_ALIASES_PATH, "utf-8"));
return parsed && parsed.aliases && typeof parsed.aliases === "object" ? parsed.aliases : {};
} catch { return {}; }
}
function writeNativeAliases(aliases) {
fs.writeFileSync(NATIVE_ALIASES_PATH, JSON.stringify({ version: 1, aliases }, null, 2), "utf-8");
}
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static(path.join(__dirname, "public")));
// ── File logger ────────────────────────────────────────────────────────────
// Mirrors console output to logs/proxy.log so the request/stream flow can be
// inspected after the fact (the terminal window isn't always visible). Never
// logs Authorization headers or api keys — only request shape and flow events.
const LOG_DIR = process.env.LOG_DIR || path.join(__dirname, "logs");
const LOG_PATH = path.join(LOG_DIR, "proxy.log");
const LOG_MAX_BYTES = 5 * 1024 * 1024; // rotate at ~5 MB
// How long the upstream may go without sending a single byte before we give up
// on it. Free-tier providers sometimes accept the connection, queue the request
// and then never respond — without this the translation loop waits forever and
// Codex sits on a dead turn with nothing in the log.
const UPSTREAM_IDLE_MS = process.env.UPSTREAM_IDLE_MS ? Number(process.env.UPSTREAM_IDLE_MS) : 120000;
// While upstream is quiet we still send SSE comment heartbeats downstream, so
// Codex's own idle timer never fires on a slow-but-alive provider.
const HEARTBEAT_MS = process.env.HEARTBEAT_MS ? Number(process.env.HEARTBEAT_MS) : 10000;
// ── Upstream rate limiting & retry ──────────────────────────────────────────
// Free-tier providers (e.g. Baseten) cap request rate (e.g. 120 req/min).
// Codex fires many concurrent turns, so we (a) pace outgoing requests with a
// token bucket so we never exceed the provider's rate, and (b) retry with
// backoff when a 429/5xx still slips through — instead of immediately bouncing
// a 502 back to Codex, which only triggers another flood of retries.
//
// The rate is per-provider: each provider in providers.json may declare
// `rateLimitPerMin` (and optionally `rateBurst`). When left empty, the bucket
// runs in AUTO mode — it starts unthrottled and learns the provider's real
// limit from 429 response headers (Retry-After / X-RateLimit-*), so you never
// have to hardcode a limit per provider.
const UPSTREAM_RATE_PER_MIN = process.env.UPSTREAM_RATE_PER_MIN ? Number(process.env.UPSTREAM_RATE_PER_MIN) : 100;
const UPSTREAM_RATE_BURST = process.env.UPSTREAM_RATE_BURST ? Number(process.env.UPSTREAM_RATE_BURST) : 5;
const UPSTREAM_RETRY_MAX = process.env.UPSTREAM_RETRY_MAX ? Number(process.env.UPSTREAM_RETRY_MAX) : 3;
const UPSTREAM_RETRY_BASE_MS = process.env.UPSTREAM_RETRY_BASE_MS ? Number(process.env.UPSTREAM_RETRY_BASE_MS) : 1000;
const UPSTREAM_RETRY_MAX_MS = process.env.UPSTREAM_RETRY_MAX_MS ? Number(process.env.UPSTREAM_RETRY_MAX_MS) : 8000;
// How many times to retry an upstream that returns 200 OK but with NO content
// (no text, no tool calls). Some providers occasionally emit a degenerate
// empty stream — like OpenRouter, we treat that as a transient failure and
// retry instead of silently handing Codex an empty turn.
const UPSTREAM_EMPTY_RETRY_MAX = process.env.UPSTREAM_EMPTY_RETRY_MAX ? Number(process.env.UPSTREAM_EMPTY_RETRY_MAX) : 3;
// Token bucket: refills continuously, allows a small burst, and queues callers
// when the bucket is empty so we never exceed the provider's request rate.
// In "auto" mode (rateLimitPerMin empty) we start unthrottled and learn the
// provider's real limit from 429 response headers, so the user never has to
// hardcode a limit per provider.
class TokenBucket {
constructor(ratePerMin, burst, auto = false) {
this.auto = auto;
this.ratePerMin = ratePerMin;
this.ratePerSec = ratePerMin / 60;
this.burst = burst;
this.tokens = burst;
this.last = Date.now();
}
_refill() {
const now = Date.now();
this.tokens = Math.min(this.burst, this.tokens + ((now - this.last) / 1000) * this.ratePerSec);
this.last = now;
}
// Resolve once a token is available and consume it. In auto mode with no
// detected limit yet, we do not throttle.
async take() {
if (this.auto && !Number.isFinite(this.ratePerSec)) return;
while (this.tokens < 1) {
this._refill();
if (this.tokens < 1) await new Promise((r) => setTimeout(r, 50));
}
this.tokens -= 1;
}
// Learn the provider's real limit from a 429 response's headers. Returns the
// suggested wait (ms) from Retry-After, or null if none.
applyRateLimit(headers) {
if (!this.auto) return null;
const h = (k) => headers[k] || headers[k.toLowerCase()];
let waitMs = null;
const ra = h("retry-after");
if (ra) {
const n = Number(ra);
if (Number.isFinite(n)) waitMs = n * 1000;
else { const t = Date.parse(ra); if (!Number.isNaN(t)) waitMs = Math.max(0, t - Date.now()); }
}
const limit = Number(h("x-ratelimit-limit"));
const reset = Number(h("x-ratelimit-reset"));
if (Number.isFinite(limit) && limit > 0) {
let windowSec = 60;
if (Number.isFinite(reset) && reset > 0 && reset < 3600) windowSec = reset;
this.ratePerMin = Math.max(1, Math.round((limit / windowSec) * 60));
this.ratePerSec = this.ratePerMin / 60;
this.burst = Math.max(1, Math.round(this.ratePerMin / 20));
this.tokens = Math.min(this.tokens, this.burst);
this.last = Date.now();
}
return waitMs;
}
}
// One bucket per provider id, rebuilt only if the provider's *raw* rate/burst
// config changes at runtime (so a learned auto limit is not discarded).
const bucketsByProvider = new Map();
function bucketFor(provider) {
const rawRate = provider.rateLimitPerMin;
const rawBurst = provider.rateBurst;
const existing = bucketsByProvider.get(provider.id);
if (existing && existing.rawRate === rawRate && existing.rawBurst === rawBurst) return existing;
const auto = rawRate == null || rawRate === "" || String(rawRate).toLowerCase() === "auto";
const rate = auto ? Infinity : (Number(rawRate) > 0 ? Number(rawRate) : UPSTREAM_RATE_PER_MIN);
const burst = (rawBurst == null || rawBurst === "")
? Math.max(1, Number.isFinite(rate) ? Math.round(rate / 20) : 5)
: (Number(rawBurst) > 0 ? Number(rawBurst) : UPSTREAM_RATE_BURST);
const b = new TokenBucket(rate, burst, auto);
b.rawRate = rawRate;
b.rawBurst = rawBurst;
bucketsByProvider.set(provider.id, b);
return b;
}
// Statuses worth retrying: rate limit + transient server errors.
function isRetryableStatus(status) {
return status === 429 || status === 502 || status === 503 || status === 504;
}
// ── Agent behavior guidance ────────────────────────────────────────────────
// Swapped models often skip straight to firing shell commands with no preamble,
// unlike the official Codex agent which narrates and reads the relevant files
// first. We inject this guidance into the system prompt so swapped models mimic
// that workflow. Override with AGENT_GUIDANCE="" (disable) or your own text.
const AGENT_GUIDANCE = process.env.AGENT_GUIDANCE || [
"You are an autonomous coding agent working in a project directory.",
"Work deliberately and efficiently. Follow these rules:",
"1. NARRATE FIRST: before every tool call, write a short text line explaining what you are about to do and why. Never fire a command silently.",
"2. READ ONCE: read each file you need exactly once. Do NOT re-read the same file or overlapping line ranges repeatedly — that wastes commands. If you already saw a range, do not fetch it again.",
"3. SEARCH, DON'T DUMP: use targeted searches (rg/grep for specific symbols or patterns) instead of dumping entire large files. Only read the specific line ranges you actually need.",
"4. PLAN BEFORE EXPLORING: first form a clear plan of which files/functions are relevant, then read only those. Avoid broad, repeated scans of the whole codebase.",
"5. AVOID REDUNDANCY: do not repeat the same or near-identical command. If a command did not help, reason about why before running a different one.",
"6. Be deliberate and careful — avoid destructive or irreversible actions without explaining them first.",
"7. Keep the user informed of what you are doing at each step."
].join("\n");
function ensureLogDir() {
try { if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true }); } catch (e) {}
}
ensureLogDir();
function log(tag, msg) {
const line = `[${new Date().toISOString()}] [${tag}] ${msg}\n`;
try {
// Rotate: keep one .old backup so the file never grows without bound.
if (fs.existsSync(LOG_PATH) && fs.statSync(LOG_PATH).size > LOG_MAX_BYTES) {
try { fs.renameSync(LOG_PATH, LOG_PATH + ".old"); } catch (e) {}
}
fs.appendFileSync(LOG_PATH, line);
} catch (e) { /* logging must never crash the request */ }
process.stdout.write(line);
}
// Logger middleware
app.use((req, res, next) => {
log("HTTP", `${req.method} ${req.originalUrl}`);
next();
});
// ── Helpers ──────────────────────────────────────────────────────────────────
function readConfigToml() {
const raw = fs.readFileSync(CONFIG_PATH, "utf-8");
return raw;
}
function parseTopLevelValues(raw) {
const lines = raw.split("\n");
const result = {
model: "",
model_reasoning_effort: "",
service_tier: "",
api_base_url: "",
api_key: "",
model_provider: "",
openai_base_url: "",
chatgpt_base_url: "",
};
// TOML puts all top-level keys before the first `[section]` header. Keys
// inside a section (e.g. `[agents.subagent] model = "..."`) must NOT be
// treated as the top-level value — otherwise a later section's `model`
// silently overrides the real one and the picker shows the wrong model.
let inSection = false;
for (const line of lines) {
const trimmed = line.trim();
if (/^\[.*\]$/.test(trimmed)) {
inSection = true;
continue;
}
if (inSection) continue;
const modelMatch = line.match(
/^model\s*=\s*"([^"]+)"/
);
if (modelMatch) {
result.model = modelMatch[1];
}
const providerMatch = line.match(
/^model_provider\s*=\s*"([^"]+)"/
);
if (providerMatch) {
result.model_provider = providerMatch[1];
}
const baseOverrideMatch = line.match(
/^openai_base_url\s*=\s*"([^"]+)"/
);
if (baseOverrideMatch) {
result.openai_base_url = baseOverrideMatch[1];
}
const chatgptMatch = line.match(
/^chatgpt_base_url\s*=\s*"([^"]+)"/
);
if (chatgptMatch) {
result.chatgpt_base_url = chatgptMatch[1];
}
const reasoningMatch = line.match(
/^model_reasoning_effort\s*=\s*"([^"]+)"/
);
if (reasoningMatch) {
result.model_reasoning_effort = reasoningMatch[1];
}
const tierMatch = line.match(
/^service_tier\s*=\s*"([^"]+)"/
);
if (tierMatch) {
result.service_tier = tierMatch[1];
}
const baseUrlMatch = line.match(
/^api_base_url\s*=\s*"([^"]+)"/
);
if (baseUrlMatch) {
result.api_base_url = baseUrlMatch[1];
}
const apiKeyMatch = line.match(
/^api_key\s*=\s*"([^"]+)"/
);
if (apiKeyMatch) {
result.api_key = apiKeyMatch[1];
}
}
return result;
}
function updateConfigValue(raw, key, value) {
const regex = new RegExp(`^(${key}\\s*=\\s*)"[^"]*"`, "m");
if (regex.test(raw)) {
return raw.replace(regex, `$1"${value}"`);
}
// If key doesn't exist, add it at the top (after existing top-level keys)
const lines = raw.split("\n");
// Find the last top-level key=value line before any section
let insertIndex = 0;
for (let i = 0; i < lines.length; i++) {
if (/^\s*\[/.test(lines[i])) break;
if (/^\w+\s*=/.test(lines[i])) insertIndex = i + 1;
}
lines.splice(insertIndex, 0, `${key} = "${value}"`);
return lines.join("\n");
}
function maskUserPath(filePath) {
return filePath.replace(os.homedir(), path.join(path.dirname(os.homedir()), "XXXXX"));
}
function createBackup() {
if (!fs.existsSync(BACKUP_DIR)) {
fs.mkdirSync(BACKUP_DIR, { recursive: true });
}
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const backupPath = path.join(BACKUP_DIR, `config_${timestamp}.toml`);
fs.copyFileSync(CONFIG_PATH, backupPath);
// Keep only last 20 backups
const backups = fs
.readdirSync(BACKUP_DIR)
.filter((f) => f.startsWith("config_") && f.endsWith(".toml"))
.sort();
while (backups.length > 20) {
fs.unlinkSync(path.join(BACKUP_DIR, backups.shift()));
}
return backupPath;
}
function loadProviders() {
try {
if (fs.existsSync(PROVIDERS_PATH)) {
return JSON.parse(fs.readFileSync(PROVIDERS_PATH, "utf-8"));
}
} catch (err) {}
return { providers: [], activeProviderId: null };
}
function saveProviders(data) {
fs.writeFileSync(PROVIDERS_PATH, JSON.stringify(data, null, 2), "utf-8");
}
// ── Model registry & routing ────────────────────────────────────────────────
// With the proxy always on, every request Codex sends (custom AND native GPT
// models) arrives here. We route by the requested model:
// - "providerKey/modelId" → the owning custom provider (chat-completions path)
// - a native GPT model → ChatGPT passthrough (Responses API, like codex-router)
// The provider key is a slugified, unique provider name so the picker shows
// unambiguous ids even when two providers share a model id (e.g. bynara and
// Rift both serving "gpt-5.6-luna").
const INJECTED_TAG = "__switcher_injected";
function slugify(s) {
return String(s || "")
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
// Stable, unique key for a provider, used as the model-id namespace prefix.
function providerKeyFor(provider, allProviders) {
const base = slugify(provider.name) || String(provider.id);
const clash = (allProviders || []).some(
(p) => p.id !== provider.id && (slugify(p.name) || String(p.id)) === base
);
return clash ? `${base}-${String(provider.id).slice(0, 6)}` : base;
}
// Read the native (non-injected) model slugs from the cache.
function readNativeModelSlugs() {
const { data } = readModelsCache();
if (!data || !Array.isArray(data.models)) return new Set();
return new Set(
data.models
.filter((m) => m && m[INJECTED_TAG] !== true && m.slug)
.map((m) => m.slug)
);
}
// Resolve a requested model to a route:
// { type: "custom", provider, modelId } → chat-completions translation
// { type: "native", modelId } → ChatGPT passthrough
// { type: "ambiguous", providers } → un-namespaced id owned by 2+ providers
// null → unknown model
function resolveModelRoute(model) {
if (!model) return null;
const data = loadProviders();
const enabled = data.providers.filter((p) => p.enabled !== false);
// 1. Namespaced custom id: "providerKey/modelId"
const slash = model.indexOf("/");
if (slash > 0) {
const key = model.slice(0, slash);
const modelId = model.slice(slash + 1);
const provider = enabled.find((p) => providerKeyFor(p, data.providers) === key);
if (provider && (provider.models || []).includes(modelId)) {
return { type: "custom", provider, modelId };
}
}
// 2. Native GPT model (not owned by any provider).
if (readNativeModelSlugs().has(model)) {
return { type: "native", modelId: model };
}
// 3. Legacy un-namespaced custom id — only unambiguous if one provider owns it.
const owners = enabled.filter((p) => (p.models || []).includes(model));
if (owners.length === 1) {
return { type: "custom", provider: owners[0], modelId: model };
}
if (owners.length > 1) {
return { type: "ambiguous", providers: owners };
}
return null;
}
// ── Model cache injection ──────────────────────────────────────────────────
// Codex populates its native model picker from `models_cache.json`. To make a
// custom (user-input) provider's models show up in that picker — right next to
// the native GPT models, exactly like codex-router does — we inject synthetic
// model entries into the cache. The injected entries are tagged with
// `__switcher_injected: true` and a `model_provider` pointing at our local
// `customProvider` so Codex routes them through our proxy.
//
// Everything here is reversible: `ejectProviderModels` removes only the entries
// we added (matched by the tag), leaving the real cached models untouched.
// Build a synthetic cache entry for one model id of an enabled provider. The
// slug is namespaced with the provider key so the picker is unambiguous even
// when two providers share a model id. The entry spreads a native model
// template so it carries every field the App expects — the App drops catalog
// entries that are missing required metadata (context_window, input_modalities,
// model_messages, tool_mode, multi_agent_version, ...). No `model_provider`
// field: routing is via `openai_base_url`, and a model_provider made the App
// group the models under "Custom Provider".
function buildInjectedModel(modelId, provider, providerKey, template) {
const base = template ? { ...template } : {};
const slug = `${providerKey}/${modelId}`;
return {
...base,
slug,
display_name: slug,
description: `Custom provider: ${provider.name || provider.id}`,
default_reasoning_level: "medium",
supported_reasoning_levels: [
{ effort: "low", description: "Fast responses with lighter reasoning" },
{ effort: "medium", description: "Balances speed and reasoning depth for everyday tasks" },
{ effort: "high", description: "Greater reasoning depth for complex problems" },
{ effort: "xhigh", description: "Extra high reasoning depth for complex problems" },
],
shell_type: "shell_command",
visibility: "list",
supported_in_api: true,
priority: 1,
tool_mode: "code_mode_only",
// Match codex-router's routedModel shape instead of inheriting native-only
// capability flags that can make the App silently filter this entry.
max_context_window: base.context_window,
effective_context_window_percent: 95,
auto_compact_token_limit: base.auto_compact_token_limit || null,
use_responses_lite: false,
multi_agent_version: "v1",
service_tiers: [],
default_service_tier: null,
availability_nux: null,
upgrade: null,
support_verbosity: false,
default_verbosity: null,
// No provider_id: Codex hides entries whose provider_id doesn't match
// any [model_providers.*] table. Routing is via openai_base_url.
[INJECTED_TAG]: true,
};
}
// Read the cache safely, returning { data, raw } (data is {} if unreadable).
function readModelsCache() {
try {
if (fs.existsSync(MODELS_CACHE_PATH)) {
const raw = fs.readFileSync(MODELS_CACHE_PATH, "utf-8");
return { data: JSON.parse(raw), raw };
}
} catch (err) {}
return { data: null, raw: null };
}
// Write the cache with stable 2-space indentation. Codex rewrites this file
// with its own formatter, so we just keep it valid JSON — no need to match its
// exact layout; the next Codex refresh would reformat anyway. We only mark our
// injected entries so we can find and remove them later.
function writeModelsCache(data) {
fs.writeFileSync(MODELS_CACHE_PATH, JSON.stringify(data, null, 2), "utf-8");
}
// Remove any previously-injected entries (idempotent).
function ejectProviderModels() {
const { data } = readModelsCache();
if (!data || !Array.isArray(data.models)) return;
const before = data.models.length;
data.models = data.models.filter((m) => !(m && m[INJECTED_TAG] === true));
if (data.models.length !== before) {
writeModelsCache(data);
}
}
// Remove stale injected entries and (re)inject every enabled provider's models.
// Also regenerates the merged catalog file that Codex reads via
// `model_catalog_json` (the mechanism that actually puts custom models in the
// native picker — same as codex-router).
function injectAllProviders() {
const data = loadProviders();
const enabled = data.providers.filter((p) => p.enabled !== false);
const { data: cache } = readModelsCache();
const base = cache && Array.isArray(cache.models) ? cache : { models: [] };
// Use the most complete native model as the template for injected entries so
// they carry the full field set the App requires (same as the merged catalog).
const native = (cache && Array.isArray(cache.models) ? cache.models : [])
.filter((m) => m && m[INJECTED_TAG] !== true);
const template = pickTemplate(native);
// Drop old injected entries first so re-injecting never duplicates.
base.models = base.models.filter((m) => !(m && m[INJECTED_TAG] === true));
for (const provider of enabled) {
const key = providerKeyFor(provider, data.providers);
const ids = Array.isArray(provider.models) ? provider.models : [];
for (const id of ids) {
if (!id) continue;
// Don't duplicate an entry that already exists for this exact id.
if (base.models.some((m) => m && m.slug === `${key}/${id}` && m[INJECTED_TAG] !== true)) continue;
base.models.push(buildInjectedModel(id, provider, key, template));
}
}
writeModelsCache(base);
writeMergedCatalog();
}
function refreshProviderCatalog() {
if (passthroughActive()) {
injectAllProviders();
return;
}
// Keep native mode isolated from synthetic provider entries and catalogs.
ejectProviderModels();
try {
if (fs.existsSync(MERGED_CATALOG_PATH)) fs.unlinkSync(MERGED_CATALOG_PATH);
} catch (e) {}
}
// Pick a stable native template for synthetic entries — prefer gpt-5.5 (the
// model codex-router uses), then the first listed native model, then any.
function pickTemplate(nativeModels) {
const clean = (nativeModels || []).filter(m => m && m[INJECTED_TAG] !== true);
return (
clean.find(m => m.slug === "gpt-5.5") ||
clean.find(m => m.visibility === "list") ||
clean[0] ||
null
);
}
// ── Merged catalog (model_catalog_json) ─────────────────────────────────────
// Codex reads the picker from the file pointed to by `model_catalog_json`.
// We build that file from the native cache plus every enabled provider's
// models. Custom entries carry explicit routedModel-like metadata so the App
// does not silently filter them. provider_id and __switcher_injected are
// stripped — Codex hides entries that carry provider-owned fields when no
// matching [model_providers.*] table exists.
function buildCatalogEntry(modelId, provider, providerKey, template) {
const base = template ? { ...template } : {};
delete base[INJECTED_TAG];
delete base.provider_id;
const slug = `${providerKey}/${modelId}`;
return {
...base,
slug,
display_name: slug,
description: `Custom provider: ${provider.name || provider.id}`,
priority: 1,
visibility: "list",
supported_in_api: true,
default_reasoning_level: "medium",
supported_reasoning_levels: [
{ effort: "low", description: "Fast responses with lighter reasoning" },
{ effort: "medium", description: "Balances speed and reasoning depth for everyday tasks" },
{ effort: "high", description: "Greater reasoning depth for complex problems" },
{ effort: "xhigh", description: "Extra high reasoning depth for complex problems" },
],
context_window: base.context_window || 128000,
max_context_window: base.context_window || 128000,
effective_context_window_percent: 95,
auto_compact_token_limit: base.auto_compact_token_limit || null,
input_modalities: base.input_modalities || ["text"],
comp_hash: base.comp_hash || undefined,
tool_mode: base.tool_mode || "code_mode_only",
shell_type: "shell_command",
additional_speed_tiers: [],
service_tiers: [],
default_service_tier: null,
availability_nux: null,
upgrade: null,
support_verbosity: false,
default_verbosity: null,
supports_reasoning_summaries: false,
default_reasoning_summary: "none",
supports_search_tool: false,
supports_image_detail_original: false,
use_responses_lite: false,
apply_patch_tool_type: "freeform",
multi_agent_version: "v1",
};
}
// Windows Codex Desktop may only show native-looking model IDs when the
// account is using the local proxy session. Publish up to five external models
// through five native slots and route those slots via native-aliases.json.
function buildMergedCatalog() {
const { data: cache } = readModelsCache();
const native = cache && Array.isArray(cache.models)
? cache.models.filter(m => m && m[INJECTED_TAG] !== true && m.slug)
: [];
const template = pickTemplate(native);
const data = loadProviders();
const enabled = data.providers.filter((p) => p.enabled !== false);
const external = [];
for (const provider of enabled) {
const key = providerKeyFor(provider, data.providers);
for (const id of (provider.models || [])) {
if (id) external.push({ provider, key, id, canonical: `${key}/${id}` });
}
}
const maxSlots = 5;
const slots = native.filter(m => m.visibility === "list").slice(0, maxSlots);
const aliases = {};
const models = [];
for (const m of native) {
if (m.slug && m.visibility !== "hide") models.push(m);
}
for (let i = 0; i < Math.min(maxSlots, external.length, slots.length); i++) {
const source = external[i];
const slot = slots[i];
const routed = buildCatalogEntry(source.id, source.provider, source.key, template);
const index = models.findIndex(m => m.slug === slot.slug);
if (index < 0) continue;
aliases[slot.slug] = source.canonical;
models[index] = {
...routed,
slug: slot.slug,
display_name: `${source.provider.name || source.provider.id} / ${source.id}`,
priority: slot.priority,
};
}
writeNativeAliases(aliases);
return { models: models.slice(0, maxSlots) };
}
// Write the merged catalog file and return its absolute path.
function writeMergedCatalog() {
fs.writeFileSync(MERGED_CATALOG_PATH, JSON.stringify(buildMergedCatalog(), null, 2), "utf-8");
return MERGED_CATALOG_PATH;
}
function removeConfigValue(raw, key) {
const regex = new RegExp(`^${key}\\s*=\\s*"[^"]*"\\n?`, "m");
return raw.replace(regex, "");
}
// ── API Routes ───────────────────────────────────────────────────────────────
// GET current config
app.get("/api/config", (req, res) => {
try {
const raw = readConfigToml();
const config = parseTopLevelValues(raw);
// Report auth state so the dashboard can warn when native passthrough
// won't work: it needs a preserved ChatGPT login (side file or chatgpt mode).
let authMode = "unknown";
try {
if (fs.existsSync(AUTH_PATH)) {
const auth = JSON.parse(fs.readFileSync(AUTH_PATH, "utf-8"));
authMode = auth.auth_mode || (auth.tokens ? "chatgpt" : "unknown");
}
} catch (e) {}
const hasChatGptAuth = Boolean(readChatGptTokens());
res.json({
success: true,
config,
authMode,
hasChatGptAuth,
configPath: maskUserPath(CONFIG_PATH),
});
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// POST update config
app.post("/api/config", (req, res) => {
try {
const { model, model_reasoning_effort, service_tier } = req.body;
// Create backup first
const backupPath = createBackup();
let raw = readConfigToml();
if (model) {
raw = updateConfigValue(raw, "model", model);
}
if (model_reasoning_effort) {
raw = updateConfigValue(
raw,
"model_reasoning_effort",
model_reasoning_effort
);
}
if (service_tier) {
raw = updateConfigValue(raw, "service_tier", service_tier);
}
if (typeof req.body.api_base_url === 'string') {
if (req.body.api_base_url === '') {
raw = removeConfigValue(raw, 'api_base_url');
} else {
raw = updateConfigValue(raw, "api_base_url", req.body.api_base_url);
}
}
if (typeof req.body.api_key === 'string') {
if (req.body.api_key === '') {
raw = removeConfigValue(raw, 'api_key');
} else {
raw = updateConfigValue(raw, "api_key", req.body.api_key);
}
}
fs.writeFileSync(CONFIG_PATH, raw, "utf-8");
const updated = parseTopLevelValues(raw);
res.json({
success: true,
config: updated,
backup: path.basename(backupPath),
});
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// GET available models — from the merged catalog when passthrough is active
// (native + custom), else from the native cache.
app.get("/api/models", (req, res) => {
try {
const source = passthroughActive() && fs.existsSync(MERGED_CATALOG_PATH)
? MERGED_CATALOG_PATH
: MODELS_CACHE_PATH;
const raw = fs.readFileSync(source, "utf-8");
const data = JSON.parse(raw);
const models = (data.models || []).map((m) => ({
slug: m.slug,
display_name: m.display_name,
description: m.description || "",
default_reasoning_level: m.default_reasoning_level || "medium",
supported_reasoning_levels: m.supported_reasoning_levels || [],
}));
res.json({ success: true, models });
} catch (err) {
res.json({ success: true, models: [] });
}
});
// GET backups list
app.get("/api/backups", (req, res) => {
try {
if (!fs.existsSync(BACKUP_DIR)) {
return res.json({ success: true, backups: [] });
}
const backups = fs
.readdirSync(BACKUP_DIR)
.filter((f) => f.startsWith("config_") && f.endsWith(".toml"))
.sort()
.reverse()
.slice(0, 10)
.map((f) => ({
name: f,
date: f
.replace("config_", "")
.replace(".toml", "")
.replace(/-/g, (m, i) => (i < 16 ? (i === 10 ? "T" : ":") : ".")),
}));
res.json({ success: true, backups });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// POST restore backup
app.post("/api/restore", (req, res) => {
try {
const { name } = req.body;
const backupPath = path.join(BACKUP_DIR, name);
if (!fs.existsSync(backupPath)) {
return res.status(404).json({ success: false, error: "Backup not found" });
}
// Backup current before restoring
createBackup();
fs.copyFileSync(backupPath, CONFIG_PATH);
const raw = readConfigToml();
const config = parseTopLevelValues(raw);
res.json({ success: true, config });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// ── Custom Providers ─────────────────────────────────────────────────────────
// GET all custom providers
app.get("/api/providers", (req, res) => {
try {
const data = loadProviders();
res.json({ success: true, ...data });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// POST add/update a provider
app.post("/api/providers", (req, res) => {
try {
const { id, name, baseUrl, apiKey, models, rateLimitPerMin, rateBurst, enabled } = req.body;
const data = loadProviders();
const rateLimit = rateLimitPerMin != null && rateLimitPerMin !== "" ? Number(rateLimitPerMin) : undefined;
const burst = rateBurst != null && rateBurst !== "" ? Number(rateBurst) : undefined;
if (id) {
// Update existing
const idx = data.providers.findIndex(p => p.id === id);
if (idx !== -1) {
const updated = {
...data.providers[idx],
name, baseUrl, apiKey,
models: models || [],
};
// Empty rate limit/burst means AUTO: remove the field so the proxy
// auto-detects the provider's real limit instead of keeping a stale value.
if (rateLimit !== undefined) updated.rateLimitPerMin = rateLimit;
else delete updated.rateLimitPerMin;
if (burst !== undefined) updated.rateBurst = burst;
else delete updated.rateBurst;
if (typeof enabled === "boolean") updated.enabled = enabled;
data.providers[idx] = updated;
}
} else {
// Add new
const newProvider = {
id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
name,
baseUrl,
apiKey,
models: models || [],
enabled: enabled !== false,
...(rateLimit !== undefined ? { rateLimitPerMin: rateLimit } : {}),
...(burst !== undefined ? { rateBurst: burst } : {}),
};
data.providers.push(newProvider);
}
saveProviders(data);
// Reflect the new enabled set in the picker immediately when passthrough is active.
refreshProviderCatalog();
res.json({ success: true, ...data });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// DELETE a provider
app.delete("/api/providers/:id", (req, res) => {
try {
const data = loadProviders();
data.providers = data.providers.filter(p => p.id !== req.params.id);
if (data.activeProviderId === req.params.id) {
data.activeProviderId = null;
}
saveProviders(data);
// Rebuild the picker without the deleted provider's models when active.
refreshProviderCatalog();
res.json({ success: true, ...data });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// ── Passthrough mode ────────────────────────────────────────────────────────
// The proxy is always-on: config.toml points `model_provider` at our local
// proxy, and the proxy routes each request by model (custom provider model →
// that provider; native GPT model → ChatGPT). Enabling passthrough writes that
// config and injects every enabled provider's models into the picker; disabling
// it restores the native config and ejects the injected models.
//
// AUTH: this Codex build ignores custom-provider routing while in ChatGPT mode
// (it stays on chatgpt.com). So enabling passthrough switches auth.json to
// apikey mode — the proven way to force all model traffic through the proxy —
// and stashes the ChatGPT OAuth tokens in AUTH_CHATGPT_PATH first. The proxy
// uses those stashed tokens for native GPT passthrough. Disabling passthrough
// restores the ChatGPT auth so the user stays logged in.
// If auth.json currently holds ChatGPT OAuth tokens, preserve them to the side
// file before we switch to apikey mode.
function preserveChatGptAuth() {
try {
if (!fs.existsSync(AUTH_PATH)) return;
const auth = JSON.parse(fs.readFileSync(AUTH_PATH, "utf-8"));
if (auth.auth_mode === "chatgpt" || auth.tokens) {
fs.writeFileSync(AUTH_CHATGPT_PATH, JSON.stringify(auth, null, 2), "utf-8");
log("AUTH", "preserved ChatGPT OAuth credentials for native passthrough");
}
} catch (err) {
log("AUTH", `preserve failed: ${err.message}`);
}
}
// Restore the preserved ChatGPT auth (used when passthrough is disabled).
function restoreChatGptAuth() {
try {
if (fs.existsSync(AUTH_CHATGPT_PATH)) {
fs.copyFileSync(AUTH_CHATGPT_PATH, AUTH_PATH);
log("AUTH", "restored ChatGPT OAuth credentials");
}
} catch (err) {
log("AUTH", `restore failed: ${err.message}`);
}
}
// Read ChatGPT OAuth tokens for native passthrough: from the preserved side
// file first (apikey mode active), else from auth.json if it is chatgpt mode.
function readChatGptTokens() {
const candidates = [AUTH_CHATGPT_PATH, AUTH_PATH];
for (const p of candidates) {
try {
if (!fs.existsSync(p)) continue;
const auth = JSON.parse(fs.readFileSync(p, "utf-8"));
if (auth.tokens && auth.tokens.access_token) {
return { accessToken: auth.tokens.access_token, accountId: auth.tokens.account_id };
}
} catch (e) {}
}
return null;
}
// ── Managed config helpers ────────────────────────────────────────────────────
// We wrap managed root keys (openai_base_url, model_catalog_json) and the
// managed provider table [model_providers.codex-router] in comment markers so
// we can remove only our own sections on disable, never touching the user's
// native model_provider, chatgpt_base_url, model, or auth settings.
function removeManagedRoot(raw, key) {
// Remove a managed key=value line that sits between our markers.
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`\n?${MANAGED_START}[\\s\\S]*?^${escaped}\\s*=\\s*"[^"]*"[\\s\\S]*?${MANAGED_END}`, "m");
return raw.replace(regex, match => {
// Keep the markers but strip just the key=value line.
return match.replace(new RegExp(`^\\s*${escaped}\\s*=\\s*"[^"]*"\\n?`, "m"), "");
});
}
function hasManagedProviderBlock(raw) {
return raw.includes(MANAGED_PROVIDER_START) && raw.includes(MANAGED_PROVIDER_END);
}
function removeManagedProviderBlock(raw) {
const regex = new RegExp(`\n?${MANAGED_PROVIDER_START}[\s\S]*?${MANAGED_PROVIDER_END}`, "m");
return raw.replace(regex, "");
}
// ── Config apply / remove ─────────────────────────────────────────────────────
function createManagedRootBlock(catalogPath) {
return `${MANAGED_START}\nopenai_base_url = "http://127.0.0.1:${PORT}/v1"\nmodel_catalog_json = "${catalogPath.replace(/\\/g, "\\\\")}"\n${MANAGED_END}`;
}