forked from r266-tech/sub2cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsub2cli-inject
More file actions
executable file
·1361 lines (1173 loc) · 46.8 KB
/
Copy pathsub2cli-inject
File metadata and controls
executable file
·1361 lines (1173 loc) · 46.8 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
#!/usr/bin/env python3
"""sub2cli-inject — Codex 渠道切换器 (vendored from r266-tech/codex-provider-macos).
sub2cli 用 add-api 子命令注入 url + apikey 到本机 Codex CLI / Codex App.
单文件 Python, 无第三方依赖, MIT 许可.
"""
from __future__ import annotations
import argparse
import base64
import getpass
import json
import os
import re
import select
import sqlite3
import subprocess
import sys
import termios
import time
import tty
try:
import readline # noqa: F401 启用 input() 的行编辑 (退格/CJK 宽度/Ctrl-U/方向键)
except ImportError:
pass
from pathlib import Path
from urllib import error as urlerror
from urllib import parse as urlparse
from urllib import request as urlrequest
HOME = Path(os.environ.get("CODEX_PROVIDER_HOME", str(Path.home()))).expanduser()
CODEX_HOME = Path(os.environ.get("CODEX_HOME", str(HOME / ".codex"))).expanduser()
APP_SUPPORT = HOME / "Library" / "Application Support"
APP_PROFILE = APP_SUPPORT / "Codex"
AUTH_JSON = CODEX_HOME / "auth.json"
CONFIG_TOML = CODEX_HOME / "config.toml"
STATE_DB = CODEX_HOME / "state_5.sqlite"
SESSION_DIRS = [CODEX_HOME / "sessions", CODEX_HOME / "archived_sessions"]
SLOTS_FILE = CODEX_HOME / "provider-slots.json"
BACKUP_ROOT = CODEX_HOME / "provider-switch-backups"
OAUTH_PROVIDER = "openai"
RELAY_PROVIDER = "OpenAI"
THREAD_PROVIDERS = (OAUTH_PROVIDER, RELAY_PROVIDER)
DEFAULT_MODEL = "gpt-5.5"
DEFAULT_API_BASE_URL = "https://api.openai.com/v1"
APP_VERSION = "0.1.0"
APP_URL = os.environ.get("CODEX_PROVIDER_URL", "https://github.com/r266-tech/codex-provider-macos")
APP_BANNER = r"""
____ _ ____ _ _
/ ___|___ __| | _____ _| _ \ _ __ _____ _(_) __| | ___ _ __
| | / _ \ / _` |/ _ \ \/ / |_) | '__/ _ \ \ / / |/ _` |/ _ \ '__|
| |__| (_) | (_| | __/> <| __/| | | (_) \ V /| | (_| | __/ |
\____\___/ \__,_|\___/_/\_\_| |_| \___/ \_/ |_|\__,_|\___|_|
""".strip("\n")
class ChineseHelpFormatter(argparse.HelpFormatter):
def start_section(self, heading: str | None) -> None:
translations = {
"positional arguments": "命令",
"optional arguments": "选项",
"options": "选项",
}
super().start_section(translations.get(heading, heading))
def fail(message: str, code: int = 2) -> None:
print(f"错误:{message}", file=sys.stderr)
raise SystemExit(code)
def atomic_write_json(path: Path, data: dict, *, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
try:
tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
os.chmod(tmp, mode)
tmp.replace(path)
except Exception:
if tmp.exists() or tmp.is_symlink():
try:
tmp.unlink()
except OSError:
pass
raise
def atomic_write_text(path: Path, text: str, *, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(f"{path.name}.{os.getpid()}.{time.time_ns()}.tmp")
try:
tmp.write_text(text)
os.chmod(tmp, mode)
tmp.replace(path)
except Exception:
if tmp.exists() or tmp.is_symlink():
try:
tmp.unlink()
except OSError:
pass
raise
def atomic_symlink(link_path: Path, target: Path) -> None:
if link_path.exists() and not link_path.is_symlink():
fail(f"{link_path} is a real file/dir, not a symlink. Run init first or move it aside manually.")
link_path.parent.mkdir(parents=True, exist_ok=True)
target.parent.mkdir(parents=True, exist_ok=True)
tmp = link_path.with_name(f"{link_path.name}.{os.getpid()}.{time.time_ns()}.tmp")
if tmp.exists() or tmp.is_symlink():
tmp.unlink()
tmp.symlink_to(target)
os.replace(tmp, link_path)
def symlink_points_to(link_path: Path, target: Path) -> bool:
if not link_path.is_symlink():
return False
try:
return Path(os.readlink(link_path)).expanduser().resolve(strict=False) == target.resolve(strict=False)
except OSError:
return False
def toml_quote(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')
def normalize_base_url(value: str) -> str:
base_url = value.strip().rstrip("/")
if base_url.lower().endswith("/v1"):
base_url = base_url[:-3].rstrip("/")
if not base_url.startswith(("http://", "https://")):
fail(f"base_url must start with http:// or https://: {value!r}")
return base_url
def slot_from_url(base_url: str) -> str:
host = urlparse.urlparse(base_url).hostname or ""
host = host.removeprefix("www.").removeprefix("api.")
slot = host.split(".")[0] if host else ""
if not slot:
fail(f"could not derive a slot name from {base_url!r}; pass --slot")
return validate_slot(slot)
def validate_slot(slot: str) -> str:
slot = slot.strip().lower()
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,30}", slot):
fail(f"invalid slot {slot!r}; use lowercase a-z, 0-9, _ or -, max 31 chars")
return slot
def load_slots(required: bool = True) -> dict:
if not SLOTS_FILE.exists():
if required:
fail(f"{SLOTS_FILE} not found. Run: codex-provider init")
return {"version": 1, "current": None, "app_history_slot": None, "slots": {}}
try:
data = json.loads(SLOTS_FILE.read_text())
except json.JSONDecodeError as exc:
fail(f"{SLOTS_FILE} is invalid JSON: {exc}")
data.setdefault("version", 1)
data.setdefault("slots", {})
return data
def save_slots(data: dict) -> None:
atomic_write_json(SLOTS_FILE, data)
def codex_running() -> bool:
return subprocess.run(["pgrep", "-x", "Codex"], capture_output=True).returncode == 0
def quit_codex(timeout: float = 8.0) -> bool:
if not codex_running():
return False
try:
subprocess.run(
["osascript", "-e", 'tell application id "com.openai.codex" to quit'],
check=False,
timeout=timeout,
capture_output=True,
text=True,
)
except subprocess.TimeoutExpired:
return True
deadline = time.time() + timeout
while time.time() < deadline:
if not codex_running():
return True
time.sleep(0.25)
fail("Codex.app 退出超时。请手动退出 Codex App 后重试。")
return True
def launch_codex() -> None:
subprocess.Popen(["open", "-a", "Codex"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def decode_auth_email(auth_file: Path) -> str | None:
try:
data = json.loads(auth_file.read_text())
token = data.get("tokens", {}).get("id_token", "")
if token.count(".") < 2:
return None
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
return json.loads(base64.urlsafe_b64decode(payload)).get("email")
except Exception:
return None
def cmd_init(slot: str = "local", display: str | None = None, *, quiet: bool = False) -> int:
slot = validate_slot(slot)
data = load_slots(required=False)
if data.get("current") and data.get("slots") and AUTH_JSON.is_symlink() and APP_PROFILE.is_symlink():
if not quiet:
print(f"already initialized: current={data['current']}")
print(f"slots file: {SLOTS_FILE}")
return 0
quit_codex()
CODEX_HOME.mkdir(parents=True, exist_ok=True)
APP_SUPPORT.mkdir(parents=True, exist_ok=True)
auth_slot = CODEX_HOME / f"auth.{slot}.json"
profile_slot = APP_SUPPORT / f"Codex.{slot}"
if AUTH_JSON.is_symlink():
auth_slot = Path(os.readlink(AUTH_JSON)).expanduser()
elif AUTH_JSON.exists():
if auth_slot.exists():
fail(f"{auth_slot} already exists; refusing to overwrite it")
AUTH_JSON.rename(auth_slot)
if APP_PROFILE.is_symlink():
profile_slot = Path(os.readlink(APP_PROFILE)).expanduser()
elif APP_PROFILE.exists():
if profile_slot.exists():
fail(f"{profile_slot} already exists; refusing to overwrite it")
APP_PROFILE.rename(profile_slot)
else:
profile_slot.mkdir(parents=True, exist_ok=True)
atomic_symlink(APP_PROFILE, profile_slot)
if auth_slot.exists() or AUTH_JSON.is_symlink():
atomic_symlink(AUTH_JSON, auth_slot)
email = decode_auth_email(auth_slot) if auth_slot.exists() else None
display_name = display or (f"Codex - {email}" if email else f"Codex - {slot}")
data["slots"][slot] = {
"display_name": display_name,
"mode": "oauth",
"auth_file": str(auth_slot),
"app_profile_dir": str(profile_slot),
}
data["current"] = slot
data["app_history_slot"] = slot
save_slots(data)
if not quiet:
print(f"initialized: {slot}")
print(f" auth: {auth_slot}")
print(f" profile: {profile_slot}")
print(f" slots: {SLOTS_FILE}")
return 0
def ensure_initialized() -> None:
if not SLOTS_FILE.exists():
cmd_init(quiet=True)
def probe_relay(base_url: str, api_key: str, timeout: float = 12.0) -> tuple[bool, str]:
req = urlrequest.Request(
base_url.rstrip("/") + "/v1/models",
headers={
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"User-Agent": "codex-provider-macos/1.0",
},
)
try:
with urlrequest.urlopen(req, timeout=timeout) as resp:
body = resp.read(8192)
parsed = json.loads(body)
if isinstance(parsed, dict) and isinstance(parsed.get("data"), list):
return True, f"/v1/models 可访问({len(parsed['data'])} 个模型)"
return False, "中转有响应,但返回格式不像 OpenAI 兼容接口"
except urlerror.HTTPError as exc:
if exc.code == 401:
return False, "401 Unauthorized - API key 不正确"
if exc.code == 403:
return False, "403 Forbidden - key 权限不足,或中转拒绝当前网络"
if exc.code == 404:
return False, "404 Not Found - base URL 可能不对,通常不要带 /v1"
return False, f"HTTP {exc.code} {exc.reason}"
except urlerror.URLError as exc:
return False, f"无法访问中转:{exc.reason}"
except TimeoutError:
return False, f"{timeout:.0f}s 后超时"
except Exception as exc:
return False, f"{type(exc).__name__}: {exc}"
def write_apikey_auth(path: Path, api_key: str) -> bool:
desired = {"OPENAI_API_KEY": api_key, "auth_mode": "apikey"}
if path.exists():
try:
if json.loads(path.read_text()) == desired:
return False
except (OSError, json.JSONDecodeError):
pass
atomic_write_json(path, desired)
return True
def split_toml_head(text: str) -> tuple[str, str]:
match = re.search(r"(?m)^\s*\[", text)
if not match:
return text, ""
return text[: match.start()], text[match.start() :]
def set_top_level_config(text: str, updates: dict[str, str]) -> str:
head, tail = split_toml_head(text)
keys = "|".join(re.escape(key) for key in updates)
if keys:
head = re.sub(rf'(?m)^\s*({keys})\s*=.*(?:\n)?', "", head)
block = "".join(f'{key} = "{toml_quote(value)}"\n' for key, value in updates.items())
return block + head.lstrip("\n") + tail
def strip_relay_provider_block(text: str) -> str:
return re.sub(
rf"(?ms)^\s*\[model_providers\.{re.escape(RELAY_PROVIDER)}\]\s*\n.*?(?=^\s*\[|\Z)",
"",
text,
flags=re.IGNORECASE,
).rstrip() + "\n"
def patch_config(*, mode: str, model: str, relay_base_url: str | None = None) -> bool:
text = CONFIG_TOML.read_text() if CONFIG_TOML.exists() else ""
provider = RELAY_PROVIDER if mode == "relay" else OAUTH_PROVIDER
new_text = set_top_level_config(
text,
{
"model": model,
"model_provider": provider,
"api_base_url": DEFAULT_API_BASE_URL,
},
)
new_text = strip_relay_provider_block(new_text)
if mode == "relay":
if not relay_base_url:
fail("relay_base_url is required for relay mode")
block = (
f"\n[model_providers.{RELAY_PROVIDER}]\n"
f'name = "{RELAY_PROVIDER}"\n'
f'base_url = "{toml_quote(relay_base_url.rstrip("/"))}"\n'
'wire_api = "responses"\n'
"requires_openai_auth = true\n"
)
new_text = new_text.rstrip() + "\n" + block
if new_text == text:
return False
atomic_write_text(CONFIG_TOML, new_text)
return True
def top_level_value(text: str, key: str) -> str | None:
head, _ = split_toml_head(text)
match = re.search(rf'(?m)^\s*{re.escape(key)}\s*=\s*"([^"]*)"', head)
return match.group(1) if match else None
def relay_block_base_url(text: str) -> str | None:
match = re.search(
rf"(?ms)^\s*\[model_providers\.{re.escape(RELAY_PROVIDER)}\]\s*\n(.*?)(?=^\s*\[|\Z)",
text,
flags=re.IGNORECASE,
)
if not match:
return None
body = match.group(1)
url_match = re.search(r'(?m)^\s*base_url\s*=\s*"([^"]*)"', body)
return url_match.group(1).rstrip("/") if url_match else None
def config_clean_for_slot(cfg: dict) -> bool:
try:
text = CONFIG_TOML.read_text()
except OSError:
return False
mode = cfg.get("mode", "oauth")
expected_provider = RELAY_PROVIDER if mode == "relay" else OAUTH_PROVIDER
expected_model = cfg.get("model", DEFAULT_MODEL)
if top_level_value(text, "model_provider") != expected_provider:
return False
if top_level_value(text, "model") != expected_model:
return False
if top_level_value(text, "api_base_url") != DEFAULT_API_BASE_URL:
return False
relay_url = relay_block_base_url(text)
if mode == "relay":
return relay_url == str(cfg.get("base_url", "")).rstrip("/")
return relay_url is None
def new_backup_dir(label: str) -> Path:
safe = re.sub(r"[^A-Za-z0-9_.-]+", "-", label)
path = BACKUP_ROOT / f"{time.strftime('%Y%m%d-%H%M%S')}-{time.time_ns()}-{safe}"
path.mkdir(parents=True, exist_ok=False)
return path
def backup_state_db(backup_dir: Path) -> Path | None:
if not STATE_DB.exists():
return None
target = backup_dir / STATE_DB.name
with sqlite3.connect(f"file:{STATE_DB}?mode=ro", uri=True, timeout=30) as src:
src.execute("PRAGMA busy_timeout=30000")
with sqlite3.connect(target) as dst:
src.backup(dst)
os.chmod(target, 0o600)
return target
def thread_provider_counts() -> dict[str, int]:
if not STATE_DB.exists():
return {}
try:
with sqlite3.connect(f"file:{STATE_DB}?mode=ro", uri=True, timeout=10) as conn:
conn.execute("PRAGMA busy_timeout=10000")
rows = conn.execute("SELECT model_provider, COUNT(*) FROM threads GROUP BY model_provider").fetchall()
except sqlite3.Error:
return {}
return {str(provider): int(count) for provider, count in rows}
def normalize_state_db(target_provider: str, *, backup_dir: Path | None, dry_run: bool) -> dict:
stats = {"exists": STATE_DB.exists(), "changed": 0, "backup": None, "error": None}
if not STATE_DB.exists():
return stats
try:
with sqlite3.connect(STATE_DB, timeout=30) as conn:
conn.execute("PRAGMA busy_timeout=30000")
pending = conn.execute(
"SELECT COUNT(*) FROM threads WHERE model_provider IN (?, ?) AND model_provider != ?",
(*THREAD_PROVIDERS, target_provider),
).fetchone()[0]
stats["changed"] = int(pending)
if dry_run or pending == 0:
return stats
if backup_dir is not None:
stats["backup"] = str(backup_state_db(backup_dir))
conn.execute("BEGIN IMMEDIATE")
conn.execute(
"UPDATE threads SET model_provider = ? WHERE model_provider IN (?, ?) AND model_provider != ?",
(target_provider, *THREAD_PROVIDERS, target_provider),
)
conn.commit()
except sqlite3.Error as exc:
stats["error"] = f"{type(exc).__name__}: {exc}"
return stats
def extract_rollout_thread_id(line: bytes) -> str | None:
match = re.search(rb'"id":"([^"]+)"', line)
if not match:
return None
try:
return match.group(1).decode("utf-8")
except UnicodeDecodeError:
return None
def rollout_provider_records(path: Path, target_provider: str, *, dry_run: bool) -> list[dict]:
tokens = [(provider, f'"model_provider":"{provider}"'.encode()) for provider in THREAD_PROVIDERS]
records: list[dict] = []
try:
offset = 0
with path.open("rb") as handle:
for line_no, line in enumerate(handle, start=1):
if b'"type":"session_meta"' not in line or b'"model_provider":"' not in line:
offset += len(line)
continue
matches = [(line.find(token), provider, token) for provider, token in tokens]
matches = [(pos, provider, token) for pos, provider, token in matches if pos >= 0]
if not matches:
offset += len(line)
continue
pos, provider, _ = min(matches, key=lambda item: item[0])
if provider != target_provider:
records.append(
{
"path": str(path),
"line": line_no,
"offset": offset + pos + len(b'"model_provider":"'),
"thread_id": extract_rollout_thread_id(line[:4096]),
"from": provider,
"to": target_provider,
}
)
offset += len(line)
except OSError as exc:
return [{"path": str(path), "error": f"{type(exc).__name__}: {exc}"}]
if dry_run or not records:
return records
try:
before = path.stat()
with path.open("r+b") as handle:
for record in records:
provider = str(record["from"])
handle.seek(int(record["offset"]))
current = handle.read(len(provider))
if current != provider.encode():
record["error"] = "provider bytes changed before write"
continue
handle.seek(int(record["offset"]))
handle.write(target_provider.encode())
handle.flush()
os.fsync(handle.fileno())
os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns))
except OSError as exc:
for record in records:
record["error"] = f"{type(exc).__name__}: {exc}"
return records
def normalize_rollouts(target_provider: str, *, backup_dir: Path | None, dry_run: bool) -> dict:
stats = {"scanned": 0, "changed": 0, "errors": 0, "audit": None}
audit_handle = None
try:
if backup_dir is not None and not dry_run:
audit_path = backup_dir / "rollout-provider-changes.jsonl"
audit_handle = audit_path.open("w", encoding="utf-8")
stats["audit"] = str(audit_path)
for root in SESSION_DIRS:
if not root.exists():
continue
for path in root.rglob("rollout-*.jsonl"):
stats["scanned"] += 1
for record in rollout_provider_records(path, target_provider, dry_run=dry_run):
if record.get("error"):
stats["errors"] += 1
else:
stats["changed"] += 1
if audit_handle is not None:
audit_handle.write(json.dumps(record, ensure_ascii=False) + "\n")
finally:
if audit_handle is not None:
audit_handle.close()
return stats
def normalize_sessions(target_provider: str, *, dry_run: bool = False) -> dict:
if target_provider not in THREAD_PROVIDERS:
fail(f"unsupported target provider {target_provider!r}; expected openai or OpenAI")
preview = {
"target_provider": target_provider,
"dry_run": dry_run,
"backup_dir": None,
"state_db": None,
"rollouts": None,
}
backup_dir = None if dry_run else new_backup_dir(f"thread-provider-{target_provider}")
preview["backup_dir"] = str(backup_dir) if backup_dir is not None else None
preview["state_db"] = normalize_state_db(target_provider, backup_dir=backup_dir, dry_run=dry_run)
preview["rollouts"] = normalize_rollouts(target_provider, backup_dir=backup_dir, dry_run=dry_run)
if backup_dir is not None:
atomic_write_json(backup_dir / "manifest.json", preview)
return preview
def normalize_sessions_if_needed(target_provider: str) -> dict:
preview = normalize_sessions(target_provider, dry_run=True)
db_changed = int(preview["state_db"].get("changed", 0))
db_error = preview["state_db"].get("error")
rollouts = preview["rollouts"]
rollout_changed = int(rollouts.get("changed", 0))
rollout_errors = int(rollouts.get("errors", 0))
if db_changed == 0 and not db_error and rollout_changed == 0 and rollout_errors == 0:
preview["dry_run"] = False
preview["backup_dir"] = None
preview["skipped"] = True
return preview
return normalize_sessions(target_provider, dry_run=False)
def sessions_need_normalize(target_provider: str) -> bool:
preview = normalize_sessions(target_provider, dry_run=True)
return bool(
preview["state_db"].get("error")
or int(preview["state_db"].get("changed", 0))
or int(preview["rollouts"].get("changed", 0))
or int(preview["rollouts"].get("errors", 0))
)
def print_session_summary(stats: dict) -> None:
action = "将聚合" if stats.get("dry_run") else "已聚合"
db_stats = stats.get("state_db") or {}
rollout_stats = stats.get("rollouts") or {}
print(
f" 历史 session {action}: provider={stats.get('target_provider')} "
f"(DB 行: {db_stats.get('changed', 0)}, rollout 头: {rollout_stats.get('changed', 0)})"
)
if db_stats.get("error"):
print(f" state DB 错误: {db_stats['error']}")
if rollout_stats.get("errors"):
print(f" rollout 错误: {rollout_stats['errors']}")
if stats.get("backup_dir"):
print(f" 备份: {stats['backup_dir']}")
def resolve_slot(name: str, slots: dict) -> str:
query = name.strip().lower()
if query in slots:
return query
matches = [key for key, cfg in slots.items() if query in key or query in cfg.get("display_name", "").lower()]
if len(matches) == 1:
return matches[0]
if not matches:
fail(f"no slot matches {name!r}. Available: {', '.join(sorted(slots)) or '(none)'}")
fail(f"{name!r} is ambiguous: {', '.join(matches)}")
return query
def history_profile_target(data: dict, target_slot: str) -> Path:
slots = data.get("slots", {})
history_slot = data.get("app_history_slot")
if history_slot in slots:
return Path(slots[history_slot]["app_profile_dir"]).expanduser()
return Path(slots[target_slot]["app_profile_dir"]).expanduser()
def slot_thread_provider(cfg: dict) -> str:
return RELAY_PROVIDER if cfg.get("mode") == "relay" else OAUTH_PROVIDER
def slot_is_clean(data: dict, target_slot: str) -> bool:
cfg = data["slots"][target_slot]
auth_target = Path(cfg["auth_file"]).expanduser()
profile_target = history_profile_target(data, target_slot)
if data.get("current") != target_slot:
return False
if not symlink_points_to(AUTH_JSON, auth_target):
return False
if not symlink_points_to(APP_PROFILE, profile_target):
return False
if cfg.get("mode") == "relay":
api_key = str(cfg.get("api_key") or "")
try:
if json.loads(auth_target.read_text()) != {"OPENAI_API_KEY": api_key, "auth_mode": "apikey"}:
return False
except (OSError, json.JSONDecodeError):
return False
elif not auth_target.exists() or auth_target.stat().st_size < 10:
return False
return config_clean_for_slot(cfg) and not sessions_need_normalize(slot_thread_provider(cfg))
def cmd_switch(name: str, *, no_restart: bool = False) -> int:
ensure_initialized()
data = load_slots()
slots = data.get("slots", {})
target_slot = resolve_slot(name, slots)
cfg = slots[target_slot]
mode = cfg.get("mode", "oauth")
if mode not in ("oauth", "relay"):
fail(f"slot {target_slot!r} has invalid mode {mode!r}")
if slot_is_clean(data, target_slot):
print(f"当前已是:{cfg.get('display_name', target_slot)} ({target_slot}) [{mode}]")
print(" 无需修改;Codex App 未重启")
return 0
if not no_restart:
quit_codex()
auth_target = Path(cfg["auth_file"]).expanduser()
profile_target = history_profile_target(data, target_slot)
auth_target.parent.mkdir(parents=True, exist_ok=True)
profile_target.mkdir(parents=True, exist_ok=True)
if mode == "relay":
api_key = str(cfg.get("api_key") or "").strip()
base_url = str(cfg.get("base_url") or "").strip().rstrip("/")
if not api_key or not base_url:
fail(f"relay slot {target_slot!r} is missing api_key/base_url")
write_apikey_auth(auth_target, api_key)
patch_config(mode="relay", model=cfg.get("model", DEFAULT_MODEL), relay_base_url=base_url)
else:
patch_config(mode="oauth", model=cfg.get("model", DEFAULT_MODEL))
atomic_symlink(AUTH_JSON, auth_target)
atomic_symlink(APP_PROFILE, profile_target)
session_stats = normalize_sessions_if_needed(slot_thread_provider(cfg))
previous = data.get("current")
data["current"] = target_slot
data.setdefault("app_history_slot", target_slot)
save_slots(data)
verb = "已修复当前渠道" if previous == target_slot else "已切换到"
print(f"{verb}:{cfg.get('display_name', target_slot)} ({target_slot}) [{mode}]")
print(f" auth.json -> {auth_target}")
print(f" App profile -> {profile_target}(历史保留)")
if mode == "relay":
print(f" base_url -> {cfg.get('base_url')}")
print(f" model -> {cfg.get('model', DEFAULT_MODEL)}")
elif not auth_target.exists() or auth_target.stat().st_size < 10:
print(f" 尚未登录:请运行 `codex login` 写入 {auth_target}")
print_session_summary(session_stats)
if not no_restart:
launch_codex()
print(" Codex App 已重新打开")
else:
print(" --no-restart:Codex App 未重新打开")
return 0
def cmd_relay(
base_url: str,
api_key: str,
*,
slot: str | None = None,
model: str = DEFAULT_MODEL,
display: str | None = None,
skip_probe: bool = False,
no_switch: bool = False,
no_restart: bool = False,
) -> int:
ensure_initialized()
base_url = normalize_base_url(base_url)
api_key = api_key.strip()
if not api_key:
fail("API key 不能为空")
slot = validate_slot(slot) if slot else slot_from_url(base_url)
if not skip_probe:
ok, message = probe_relay(base_url, api_key)
if not ok:
print(f"中转检查失败:{message}", file=sys.stderr)
print("渠道未保存。请换正确的 URL/key 后重试,或加 --skip-check 跳过检查。", file=sys.stderr)
return 3
print(f"检查通过:{message}")
data = load_slots()
slots = data.setdefault("slots", {})
existing = slots.get(slot)
if existing and existing.get("mode") != "relay":
fail(f"渠道 {slot!r} 已存在,但不是 API 渠道")
slots[slot] = {
"display_name": display or (existing or {}).get("display_name") or f"Codex - {slot} relay",
"mode": "relay",
"auth_file": str(CODEX_HOME / f"auth.{slot}.json"),
"app_profile_dir": str(APP_SUPPORT / f"Codex.{slot}"),
"base_url": base_url,
"model": model,
"api_key": api_key,
}
save_slots(data)
print(f"{'已更新' if existing else '已添加'} API 渠道:{slot}")
print(f" base_url: {base_url}")
print(f" model: {model}")
if no_switch:
print(f" 稍后切换:codex-provider use {slot}")
return 0
return cmd_switch(slot, no_restart=no_restart)
def cmd_oauth(
slot: str,
*,
display: str | None = None,
no_switch: bool = False,
no_restart: bool = False,
) -> int:
ensure_initialized()
slot = validate_slot(slot)
data = load_slots()
slots = data.setdefault("slots", {})
existing = slots.get(slot)
if existing and existing.get("mode") != "oauth":
fail(f"渠道 {slot!r} 已存在,但不是账号渠道")
slots[slot] = {
"display_name": display or (existing or {}).get("display_name") or f"Codex - {slot}",
"mode": "oauth",
"auth_file": str(CODEX_HOME / f"auth.{slot}.json"),
"app_profile_dir": str(APP_SUPPORT / f"Codex.{slot}"),
}
save_slots(data)
print(f"{'已更新' if existing else '已添加'}账号渠道:{slot}")
if no_switch:
print(f" 稍后切换:codex-provider use {slot}")
print(" 切过去后运行:codex login")
return 0
rc = cmd_switch(slot, no_restart=no_restart)
auth_target = Path(slots[slot]["auth_file"]).expanduser()
if not auth_target.exists() or auth_target.stat().st_size < 10:
print(" 下一步:运行 `codex login`,登录这个账号")
return rc
def cmd_list() -> int:
data = load_slots(required=False)
current = data.get("current")
slots = data.get("slots", {})
if not slots:
print("还没有渠道")
print(" 添加 API: codex-provider add-api https://relay.example.com sk-...")
print(" 添加账号: codex-provider add-account work")
return 0
for key, cfg in slots.items():
marker = "*" if key == current else " "
mode = cfg.get("mode", "oauth")
label = cfg.get("display_name", key)
extra = cfg.get("base_url", "") if mode == "relay" else "(账号登录)"
print(f"{marker} {key:<16} [{mode:<5}] {label:<32} {extra}")
return 0
def cmd_status() -> int:
data = load_slots(required=False)
current = data.get("current")
slots = data.get("slots", {})
if not current or current not in slots:
print("当前没有渠道")
print(" 运行:codex-provider")
return 0
cfg = slots[current]
provider = slot_thread_provider(cfg)
print(f"当前渠道:{cfg.get('display_name', current)} ({current}) [{cfg.get('mode', 'oauth')}]")
print(f" 渠道文件: {SLOTS_FILE}")
print(f" auth.json: {'-> ' + os.readlink(AUTH_JSON) if AUTH_JSON.is_symlink() else str(AUTH_JSON)}")
print(f" App profile: {'-> ' + os.readlink(APP_PROFILE) if APP_PROFILE.is_symlink() else str(APP_PROFILE)}")
print(f" App 运行中: {'是' if codex_running() else '否'}")
counts = thread_provider_counts()
if counts:
summary = ", ".join(f"{key}:{value}" for key, value in sorted(counts.items()))
print(f" sessions: {summary}")
preview = normalize_sessions(provider, dry_run=True)
print_session_summary(preview)
if not slot_is_clean(data, current):
print(f" 状态不一致:运行 `codex-provider use {current}` 修复")
return 0
def cmd_remove(slot: str, *, hard: bool = False) -> int:
data = load_slots()
slot = resolve_slot(slot, data.get("slots", {}))
if slot == data.get("current"):
fail(f"{slot!r} is current; switch away before removing it")
cfg = data["slots"].pop(slot)
save_slots(data)
print(f"removed slot: {slot}")
if hard:
auth_path = Path(cfg.get("auth_file", "")).expanduser()
profile_path = Path(cfg.get("app_profile_dir", "")).expanduser()
if auth_path.is_file() or auth_path.is_symlink():
if CODEX_HOME.resolve(strict=False) in auth_path.resolve(strict=False).parents:
auth_path.unlink()
print(f" removed {auth_path}")
if profile_path.exists() and not profile_path.is_symlink():
if APP_SUPPORT.resolve(strict=False) in profile_path.resolve(strict=False).parents:
import shutil
shutil.rmtree(profile_path)
print(f" removed {profile_path}")
return 0
def cmd_normalize_sessions(target: str | None, *, dry_run: bool) -> int:
if target in (None, "", "current"):
data = load_slots()
current = data.get("current")
if not current:
fail("当前没有渠道")
target_provider = slot_thread_provider(data["slots"][current])
elif target in THREAD_PROVIDERS:
target_provider = target
else:
data = load_slots()
slot = resolve_slot(target, data.get("slots", {}))
target_provider = slot_thread_provider(data["slots"][slot])
stats = normalize_sessions(target_provider, dry_run=dry_run)
print_session_summary(stats)
return 1 if stats.get("rollouts", {}).get("errors") else 0
def clear_screen() -> None:
if sys.stdout.isatty():
print("\033[2J\033[H", end="")
def pause() -> None:
if sys.stdin.isatty():
input("\n按 Enter 继续...")
def read_key() -> str:
fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = os.read(fd, 1)
if ch == b"\x1b":
key = ch
while select.select([sys.stdin], [], [], 0.02)[0]:
key += os.read(fd, 1)
if key in (b"\x1b[A", b"\x1b[D"):
return "up"
if key in (b"\x1b[B", b"\x1b[C"):
return "down"
return "back"
if ch in (b"\r", b"\n"):
return "enter"
if ch in (b"q", b"Q", b"\x03"):
return "quit"
if ch in (b"b", b"B", b"\x7f"):
return "back"
if ch in (b"v", b"V"):
return "version"
if ch in (b"m", b"M"):
return "more"
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
return ""
def select_menu(
title: str,
options: list[tuple[str, str]],
*,
subtitle: str | None = None,
branded: bool = False,
) -> str:
if not options:
return "back"
if not (sys.stdin.isatty() and sys.stdout.isatty()):
print(title)
if subtitle:
print(subtitle)
for idx, (label, _) in enumerate(options, start=1):
print(f"{idx}. {label}")
choice = input("> ").strip()
if not choice:
return "back"
try:
return options[int(choice) - 1][1]
except (ValueError, IndexError):
return "back"
selected = 0
while True:
clear_screen()
if branded:
print(APP_BANNER)
print(f" {APP_URL}")
print(f" {title}")
if subtitle:
print(f" {subtitle}")
print("")
else:
print(title)
if subtitle:
print(subtitle)
print("")
for idx, (label, _) in enumerate(options):
marker = "➤" if idx == selected else " "
print(f"{marker} {idx + 1}. {label}")
if branded:
print("\n↑↓ | Enter 确认 | Q 退出")
else:
print("\n↑↓ | Enter 确认 | B 返回 | Q 退出")
key = read_key()
if key == "up":
selected = (selected - 1) % len(options)
elif key == "down":
selected = (selected + 1) % len(options)
elif key == "enter":
return options[selected][1]
elif key in ("back", "quit"):
return key