-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsub2cli-inject
More file actions
executable file
·2514 lines (2237 loc) · 93.1 KB
/
sub2cli-inject
File metadata and controls
executable file
·2514 lines (2237 loc) · 93.1 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 errno
import fcntl
import getpass
import json
import os
import re
import select
import shutil
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"
LOCK_FILE = CODEX_HOME / ".sub2cli-inject.lock"
SNAPSHOT_FILENAME = "pre-switch-snapshot.json"
AUTO_ROLLBACK_MARKER = ".auto-rollback-done"
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)
# ==================== File lock ====================
class LockBusy(RuntimeError):
"""Another sub2cli-inject process is holding the lock."""
class Sub2cliLock:
"""Advisory exclusive file lock — prevents concurrent ~/.codex mutations.
Wrap any cmd_switch / cmd_relay / cmd_oauth / cmd_init / cmd_rollback in
`with Sub2cliLock(): ...`. Raises LockBusy if another process holds it.
"""
_depth = 0
def __init__(self, path: Path = LOCK_FILE, *, timeout: float = 0.0) -> None:
self.path = path
self.timeout = timeout
self._fd: int | None = None
self._nested = False
def __enter__(self) -> "Sub2cliLock":
if Sub2cliLock._depth > 0:
Sub2cliLock._depth += 1
self._nested = True
return self
self.path.parent.mkdir(parents=True, exist_ok=True)
self._fd = os.open(str(self.path), os.O_CREAT | os.O_WRONLY, 0o600)
deadline = time.time() + self.timeout if self.timeout > 0 else None
while True:
try:
fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
os.ftruncate(self._fd, 0)
os.write(self._fd, f"pid={os.getpid()} t={int(time.time())}\n".encode())
Sub2cliLock._depth = 1
return self
except OSError as exc:
if exc.errno not in (errno.EAGAIN, errno.EACCES):
os.close(self._fd)
self._fd = None
raise
if deadline is None or time.time() >= deadline:
os.close(self._fd)
self._fd = None
raise LockBusy(
f"another sub2cli-inject is running (lock: {self.path})"
)
time.sleep(0.1)
def __exit__(self, *_exc: object) -> None:
if self._nested:
Sub2cliLock._depth = max(0, Sub2cliLock._depth - 1)
return
Sub2cliLock._depth = 0
if self._fd is not None:
try:
fcntl.flock(self._fd, fcntl.LOCK_UN)
finally:
os.close(self._fd)
self._fd = None
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_write_bytes(path: Path, data: bytes, *, 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_bytes(data)
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:
"""Replace link_path with a symlink to target. Used for APP_PROFILE.
AUTH_JSON is no longer symlinked — codex CLI/App atomic-writes auth.json
when refreshing tokens, which would replace any symlink with a real file
(cat-and-mouse). Use copy_auth_atomic() instead for auth.json.
"""
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)
# ==================== auth.json as a real file (no longer symlinked) ====================
def read_auth_bytes() -> bytes | None:
"""Return AUTH_JSON bytes regardless of whether it's a real file or symlink.
Returns None if AUTH_JSON doesn't exist or can't be read.
"""
if not AUTH_JSON.exists():
return None
try:
return AUTH_JSON.read_bytes()
except OSError:
return None
def copy_auth_atomic(src: Path, *, mode: int = 0o600) -> None:
"""Atomic-write src's content to AUTH_JSON as a real file (replacing any
existing symlink or file). Used by cmd_switch when changing slots.
"""
if not src.exists():
fail(f"slot auth file missing: {src}")
data = src.read_bytes()
AUTH_JSON.parent.mkdir(parents=True, exist_ok=True)
tmp = AUTH_JSON.with_name(f"{AUTH_JSON.name}.{os.getpid()}.{time.time_ns()}.tmp")
try:
tmp.write_bytes(data)
os.chmod(tmp, mode)
os.replace(tmp, AUTH_JSON)
except Exception:
if tmp.exists() or tmp.is_symlink():
try:
tmp.unlink()
except OSError:
pass
raise
def flush_auth_to_slot(slot_auth_file: Path, *, mode: int = 0o600) -> bool:
"""Save current AUTH_JSON content back to its slot's auth_file so that
in-flight OAuth refresh tokens written by codex aren't lost on switch.
Returns True if a flush was performed (content changed), False if no-op.
"""
cur = read_auth_bytes()
if cur is None:
return False
slot_auth_file.parent.mkdir(parents=True, exist_ok=True)
if slot_auth_file.exists():
try:
if slot_auth_file.read_bytes() == cur:
return False
except OSError:
pass
tmp = slot_auth_file.with_name(f"{slot_auth_file.name}.{os.getpid()}.{time.time_ns()}.tmp")
try:
tmp.write_bytes(cur)
os.chmod(tmp, mode)
os.replace(tmp, slot_auth_file)
except Exception:
if tmp.exists() or tmp.is_symlink():
try:
tmp.unlink()
except OSError:
pass
raise
return True
def auth_content_equals(slot_auth_file: Path) -> bool:
"""Check if AUTH_JSON content matches a slot's auth_file content."""
if not AUTH_JSON.exists() or not slot_auth_file.exists():
return False
try:
return AUTH_JSON.read_bytes() == slot_auth_file.read_bytes()
except OSError:
return False
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 path_present(path: Path) -> bool:
return path.exists() or path.is_symlink()
def lexical_abs(path: Path) -> Path:
return Path(os.path.abspath(os.path.expanduser(str(path))))
def path_key(path: Path) -> str:
return str(lexical_abs(path))
def is_within(path: Path, base: Path) -> bool:
try:
lexical_abs(path).relative_to(lexical_abs(base))
return True
except ValueError:
return False
def safe_unlink_file(path: Path) -> bool:
if not path_present(path):
return False
if path.is_dir() and not path.is_symlink():
fail(f"refuse to unlink directory as file: {path}")
path.unlink()
return True
def safe_remove_profile_dir(path: Path) -> bool:
if not path_present(path):
return False
if not is_within(path, APP_SUPPORT):
fail(f"refuse to remove profile outside Application Support: {path}")
if not lexical_abs(path).name.startswith("Codex."):
fail(f"refuse to remove non-slot Codex profile: {path}")
if path.is_symlink() or path.is_file():
path.unlink()
return True
if path.is_dir():
shutil.rmtree(path)
return True
return False
def toml_quote(value: str) -> str:
return json.dumps(str(value), ensure_ascii=False)[1:-1]
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 _migrate_legacy_auth_symlink(*, quiet: bool = False) -> bool:
"""If AUTH_JSON is a legacy symlink (v0.2.0 layout), break it into a real
file in place. Idempotent — safe to call from any cmd_init entry path,
including upgrade users who already have populated slots.
Returns True iff a migration was performed.
"""
if not AUTH_JSON.is_symlink():
return False
legacy_target = Path(os.readlink(AUTH_JSON)).expanduser()
if not legacy_target.is_absolute():
legacy_target = (AUTH_JSON.parent / legacy_target).resolve(strict=False)
if legacy_target.exists():
try:
content = legacy_target.read_bytes()
except OSError:
content = b""
AUTH_JSON.unlink()
if content:
AUTH_JSON.write_bytes(content)
os.chmod(AUTH_JSON, 0o600)
if not quiet:
print(f" ↳ migrated legacy auth.json symlink → real file ({len(content)} bytes)")
else:
AUTH_JSON.unlink()
if not quiet:
print(f" ↳ removed dangling legacy auth.json symlink ({legacy_target} missing)")
return True
def cmd_init(slot: str = "local", display: str | None = None, *, quiet: bool = False) -> int:
if Sub2cliLock._depth == 0:
try:
with Sub2cliLock():
return cmd_init(slot=slot, display=display, quiet=quiet)
except LockBusy as exc:
fail(str(exc), code=4)
slot = validate_slot(slot)
data = load_slots(required=False)
# Idempotent legacy migration: run BEFORE the early-return so upgrade
# users (v0.2.0 layout: slots already populated, auth.json still a symlink)
# get their symlink broken into a real file. Without this, codex's next
# token-refresh atomic-write would replace the symlink anyway — but later
# switches would race the symlink check against codex's writes.
legacy_migrated = _migrate_legacy_auth_symlink(quiet=quiet)
# Already initialized if slots are configured and APP_PROFILE is a symlink.
# AUTH_JSON is now intentionally a real file (no longer symlinked).
if data.get("current") and data.get("slots") 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.exists():
# Real file already (typical post-codex-refresh state). Preserve content
# into auth_slot if absent, then leave AUTH_JSON in place.
if not auth_slot.exists():
auth_slot.parent.mkdir(parents=True, exist_ok=True)
auth_slot.write_bytes(AUTH_JSON.read_bytes())
os.chmod(auth_slot, 0o600)
elif auth_slot.read_bytes() != AUTH_JSON.read_bytes():
# Existing auth_slot differs — keep the newer (AUTH_JSON) so live
# tokens are preserved. Back up the old slot file.
bak = auth_slot.with_suffix(auth_slot.suffix + f".pre-init-{int(time.time())}.bak")
bak.write_bytes(auth_slot.read_bytes())
os.chmod(bak, 0o600)
auth_slot.write_bytes(AUTH_JSON.read_bytes())
os.chmod(auth_slot, 0o600)
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)
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,
backup_dir: Path | None = None,
) -> dict:
"""Normalize sessions DB + rollouts to target_provider. If caller passes a
`backup_dir` (e.g. the switch-level backup), reuse it so a later rollback
finds the state_5.sqlite snapshot and rollout-provider-changes audit
inside the same dir it restores config.toml / auth.json from.
"""
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,
}
if not dry_run and backup_dir is None:
backup_dir = new_backup_dir(f"thread-provider-{target_provider}")
if dry_run:
backup_dir = None # don't write anything in dry-run
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:
# Name the manifest so it doesn't collide with switch_pre_switch's
# other manifest files inside the same backup_dir.
atomic_write_json(backup_dir / "thread-provider-manifest.json", preview)
return preview
def normalize_sessions_if_needed(
target_provider: str,
*,
backup_dir: Path | None = None,
) -> 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, backup_dir=backup_dir)
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]
profile_target = history_profile_target(data, target_slot)
if data.get("current") != target_slot:
return False
if not symlink_points_to(APP_PROFILE, profile_target):
return False
# AUTH_JSON is a real file. For relay we check exact content; for oauth we
# check auth_mode and size (token refresh changes bytes, so we can't compare
# byte-equal with the slot's auth_file).
if cfg.get("mode") == "relay":
api_key = str(cfg.get("api_key") or "")
try:
if json.loads(AUTH_JSON.read_text()) != {"OPENAI_API_KEY": api_key, "auth_mode": "apikey"}:
return False
except (OSError, json.JSONDecodeError):
return False
else:
# OAuth: full token JSON is several KB; API-key JSON is ~120 bytes.
# Catch relay→oauth switch failures (auth.json still holds API-key JSON).
if not AUTH_JSON.exists() or AUTH_JSON.stat().st_size < 1000:
return False
try:
if json.loads(AUTH_JSON.read_text()).get("auth_mode") == "apikey":
return False
except (OSError, json.JSONDecodeError):
return False
return config_clean_for_slot(cfg) and not sessions_need_normalize(slot_thread_provider(cfg))
# ==================== Dry-run plan + snapshot/restore ====================
def collect_slot_auth_paths(data: dict) -> list[Path]:
paths: list[Path] = []
for cfg in (data.get("slots") or {}).values():
raw = str((cfg or {}).get("auth_file") or "").strip()
if raw:
paths.append(Path(raw).expanduser())
return paths
def collect_slot_profile_paths(data: dict) -> list[Path]:
paths: list[Path] = []
for cfg in (data.get("slots") or {}).values():
raw = str((cfg or {}).get("app_profile_dir") or "").strip()
if raw:
paths.append(Path(raw).expanduser())
return paths
def managed_existing_paths(data: dict | None = None) -> list[str]:
paths: list[Path] = [CONFIG_TOML, AUTH_JSON, SLOTS_FILE, APP_PROFILE]
if data:
paths.extend(collect_slot_auth_paths(data))
paths.extend(collect_slot_profile_paths(data))
try:
paths.extend(CODEX_HOME.glob("auth.*.json"))
except OSError:
pass
return sorted({path_key(p) for p in paths if path_present(p)})
def backup_existing_slot_auth_files(backup_dir: Path, data: dict | None = None) -> dict[str, str]:
candidates: list[Path] = []
if data: