79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
#!/usr/bin/env python3
|
||
"""PLUS 周额度用尽时,切 Codex 到卡若AI 网关 3102,绕过 OAuth 限额。"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import shutil
|
||
import subprocess
|
||
import time
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
CODEX_HOME = Path.home() / ".codex"
|
||
KARUO_KEY = "kr_jSH3zQPDUKmuNwn_Q931CJgfofuOs5Eg"
|
||
PROVIDER = "karuo_gateway"
|
||
|
||
|
||
def main() -> None:
|
||
cfg = CODEX_HOME / "config.toml"
|
||
auth = CODEX_HOME / "auth.json"
|
||
ts = datetime.now().strftime("%Y%m%d%H%M%S")
|
||
for p in (cfg, auth):
|
||
if p.exists():
|
||
shutil.copy2(p, p.with_name(f"{p.name}.bak.{ts}"))
|
||
|
||
lines = cfg.read_text(encoding="utf-8").splitlines() if cfg.exists() else []
|
||
lines = [l for l in lines if not l.strip().startswith('["/Users/karuo/.persistent-chat-local/ensure-hub.sh"')]
|
||
out, skip = [], False
|
||
for line in lines:
|
||
s = line.strip()
|
||
if s.startswith("model_provider = "):
|
||
continue
|
||
if s.startswith("[model_providers."):
|
||
skip = True
|
||
continue
|
||
if skip:
|
||
if s.startswith("[") and not s.startswith("[model_providers."):
|
||
skip = False
|
||
out.append(line)
|
||
continue
|
||
out.append(line)
|
||
while out and not out[-1].strip():
|
||
out.pop()
|
||
out.extend(
|
||
[
|
||
"",
|
||
f'model_provider = "{PROVIDER}"',
|
||
"",
|
||
f"[model_providers.{PROVIDER}]",
|
||
'name = "卡若AI网关"',
|
||
'base_url = "http://localhost:3102/api/v1"',
|
||
'wire_api = "responses"',
|
||
"requires_openai_auth = false",
|
||
"supports_websockets = false",
|
||
f'experimental_bearer_token = "{KARUO_KEY}"',
|
||
"",
|
||
]
|
||
)
|
||
cfg.write_text("\n".join(out), encoding="utf-8")
|
||
|
||
auth.write_text(
|
||
json.dumps({"auth_mode": "apikey", "OPENAI_API_KEY": KARUO_KEY}, ensure_ascii=False, indent=2)
|
||
+ "\n",
|
||
encoding="utf-8",
|
||
)
|
||
|
||
cli = Path("/Applications/Codex.app/Contents/Resources/codex")
|
||
if cli.exists():
|
||
subprocess.run([str(cli), "logout"], check=False, capture_output=True)
|
||
subprocess.run([str(cli), "login", "--with-api-key"], input=KARUO_KEY.encode(), check=False)
|
||
|
||
subprocess.run(["killall", "Codex"], check=False)
|
||
time.sleep(1.5)
|
||
subprocess.run(["/usr/bin/open", "-a", "Codex"], check=True)
|
||
print("[OK] 已切到卡若AI网关 3102,请 Cmd+Q 后新开对话再试")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|