codex-safe-switch 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ """Stdlib-only arrow-key picker for the CLI.
2
+
3
+ In a TTY, renders an interactive list (↑/↓ or j/k, enter to pick, q/Esc to quit).
4
+ When stdin/stdout aren't TTYs (pipes, scripts), falls back to a numeric menu so
5
+ the command still composes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import select
12
+ import sys
13
+ from typing import Optional
14
+
15
+
16
+ def is_interactive() -> bool:
17
+ return sys.stdin.isatty() and sys.stdout.isatty()
18
+
19
+
20
+ def _read_key(fd: int) -> str:
21
+ """Read one keystroke from a cbreak/raw fd.
22
+
23
+ Handles three forms of arrow keys:
24
+ - CSI: ESC [ A/B/C/D
25
+ - SS3: ESC O A/B/C/D (iTerm in application-cursor mode, etc.)
26
+ - bare ESC (cancel)
27
+ Returns "" on read errors / non-decodable bytes.
28
+ """
29
+ try:
30
+ first = os.read(fd, 1)
31
+ except OSError:
32
+ return ""
33
+ if first != b"\x1b":
34
+ try:
35
+ return first.decode()
36
+ except UnicodeDecodeError:
37
+ return ""
38
+ # ESC arrived. Drain whatever follows within ~200ms; bare ESC stays bare.
39
+ buf = first
40
+ deadline_passed = False
41
+ while not deadline_passed:
42
+ ready, _, _ = select.select([fd], [], [], 0.2)
43
+ if not ready:
44
+ deadline_passed = True
45
+ break
46
+ try:
47
+ more = os.read(fd, 16)
48
+ except OSError:
49
+ break
50
+ if not more:
51
+ break
52
+ buf += more
53
+ # Once we've grabbed the introducer + final byte we're done.
54
+ if len(buf) >= 3 and buf[1:2] in (b"[", b"O"):
55
+ break
56
+ try:
57
+ return buf.decode()
58
+ except UnicodeDecodeError:
59
+ return ""
60
+
61
+
62
+ def pick(
63
+ items: list[str],
64
+ *,
65
+ active: Optional[str] = None,
66
+ prompt: str = "Pick a profile",
67
+ ) -> Optional[str]:
68
+ if not items:
69
+ return None
70
+ if not is_interactive():
71
+ return _pick_numeric(items, active, prompt)
72
+
73
+ import termios
74
+ import tty
75
+
76
+ idx = items.index(active) if active in items else 0
77
+ rendered_lines = 0
78
+ header = f"{prompt} (↑/↓ to move, enter to switch, q to cancel)"
79
+
80
+ def render(first: bool) -> None:
81
+ nonlocal rendered_lines
82
+ if not first:
83
+ # cursor up to the start of the block we drew last time
84
+ sys.stdout.write(f"\x1b[{rendered_lines}A\r")
85
+ lines = [header, ""]
86
+ for i, item in enumerate(items):
87
+ cursor = "▸" if i == idx else " "
88
+ star = "★" if item == active else " "
89
+ lines.append(f" {cursor} {star} {item}")
90
+ for line in lines:
91
+ sys.stdout.write("\x1b[2K" + line + "\n")
92
+ rendered_lines = len(lines)
93
+ sys.stdout.flush()
94
+
95
+ fd = sys.stdin.fileno()
96
+ old_attrs = termios.tcgetattr(fd)
97
+ sys.stdout.write("\x1b[?25l") # hide cursor
98
+ sys.stdout.flush()
99
+ try:
100
+ tty.setcbreak(fd)
101
+ render(first=True)
102
+ while True:
103
+ ch = _read_key(fd)
104
+ if ch in ("\x1b[A", "\x1bOA", "k"):
105
+ idx = (idx - 1) % len(items)
106
+ render(first=False)
107
+ elif ch in ("\x1b[B", "\x1bOB", "j"):
108
+ idx = (idx + 1) % len(items)
109
+ render(first=False)
110
+ elif ch in ("\r", "\n"):
111
+ return items[idx]
112
+ elif ch in ("q", "\x03", "\x1b"):
113
+ return None
114
+ # any other key (including unrecognized escape sequences) is ignored
115
+ finally:
116
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_attrs)
117
+ sys.stdout.write("\x1b[?25h") # show cursor again
118
+ sys.stdout.flush()
119
+
120
+
121
+ def _pick_numeric(
122
+ items: list[str],
123
+ active: Optional[str],
124
+ prompt: str,
125
+ ) -> Optional[str]:
126
+ print(prompt)
127
+ for i, item in enumerate(items, 1):
128
+ marker = "★" if item == active else " "
129
+ print(f" {i}) {marker} {item}")
130
+ while True:
131
+ try:
132
+ raw = input("number (empty to cancel): ").strip()
133
+ except (EOFError, KeyboardInterrupt):
134
+ print()
135
+ return None
136
+ if not raw:
137
+ return None
138
+ try:
139
+ n = int(raw)
140
+ except ValueError:
141
+ print("not a number")
142
+ continue
143
+ if 1 <= n <= len(items):
144
+ return items[n - 1]
145
+ print(f"out of range (1..{len(items)})")
@@ -0,0 +1,201 @@
1
+ Metadata-Version: 2.4
2
+ Name: codex-safe-switch
3
+ Version: 1.0.0
4
+ Summary: Switch between OpenAI Codex CLI provider configurations (official ChatGPT login, third-party relays, multiple API keys). CLI + Alfred workflow.
5
+ Project-URL: Homepage, https://github.com/kadaliao/codex-safe-switch
6
+ Project-URL: Issues, https://github.com/kadaliao/codex-safe-switch/issues
7
+ Author: kadaliao
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: alfred,cli,codex,openai,profile
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Utilities
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: tomlkit>=0.13
20
+ Description-Content-Type: text/markdown
21
+
22
+ # codex-safe-switch
23
+
24
+ [![PyPI](https://img.shields.io/pypi/v/codex-safe-switch.svg)](https://pypi.org/project/codex-safe-switch/)
25
+ [![CI](https://github.com/kadaliao/codex-safe-switch/actions/workflows/ci.yml/badge.svg)](https://github.com/kadaliao/codex-safe-switch/actions/workflows/ci.yml)
26
+
27
+ 中文 | [English](README.en.md)
28
+
29
+ 一键切换 [OpenAI Codex CLI](https://github.com/openai/codex) 的 provider 配置:官方 ChatGPT 登录、第三方 relay、多组 API key,都可以放进 profile 里。提供命令行工具,并可选配 Alfred workflow。
30
+
31
+ 每个 profile 只接管 `~/.codex/config.toml` 里的 provider 片段(model、`[model_providers.*]`、认证方式)。只有确实需要自己认证文件的 profile 才保存 `auth.json`;使用 `env_key` 的 relay 可以继续依赖环境变量,不覆盖官方 ChatGPT 登录缓存。你的本地状态(trusted projects、plugins、marketplaces、MCP servers、TUI 偏好等)会在切换时保留。
32
+
33
+ ## 安装
34
+
35
+ 需要先安装 [`uv`](https://github.com/astral-sh/uv)。
36
+
37
+ ```bash
38
+ uv tool install codex-safe-switch
39
+ ```
40
+
41
+ 安装后会把 `codex-safe-switch` 放到 `$PATH`(默认是 `~/.local/bin/`)。如果 shell 找不到命令,运行一次:
42
+
43
+ ```bash
44
+ uv tool update-shell
45
+ ```
46
+
47
+ 后续升级和卸载:
48
+
49
+ ```bash
50
+ uv tool upgrade codex-safe-switch
51
+ uv tool uninstall codex-safe-switch
52
+ ```
53
+
54
+ ### 免安装试用
55
+
56
+ ```bash
57
+ uvx --from codex-safe-switch codex-safe-switch ls
58
+ ```
59
+
60
+ `uvx` 会为单次调用解析并缓存临时环境,适合快速试用;如果你要频繁使用,尤其是配合 Alfred,建议用 `uv tool install`。
61
+
62
+ ### 安装开发版
63
+
64
+ 想在 PyPI 发版前使用 GitHub 最新提交,可以直接安装仓库版本:
65
+
66
+ ```bash
67
+ uv tool install git+https://github.com/kadaliao/codex-safe-switch.git
68
+ ```
69
+
70
+ ### Alfred(可选)
71
+
72
+ 执行 `uv tool install` 后,双击 `alfred/codex-safe-switch.alfredworkflow` 导入 Alfred。触发关键词是 `cx`。
73
+
74
+ workflow 默认调用 `$HOME/.local/bin/codex-safe-switch`。如果你的 `uv tool install` 把命令装到了别处,可以用 `uv tool dir --bin` 查看路径,然后修改 workflow plist 里的两个 script block。
75
+
76
+ ## 命令
77
+
78
+ ```text
79
+ codex-safe-switch # 交互式选择器(↑/↓,回车切换,q 取消)
80
+ codex-safe-switch ls # 列出 profiles,★ 表示当前 active
81
+ codex-safe-switch current # 打印当前 active profile
82
+ codex-safe-switch official # 切回官方 OpenAI ChatGPT 登录
83
+ codex-safe-switch openai # `official` 的别名
84
+ codex-safe-switch use [name] # 加载 <name>;不传 name 时进入选择器
85
+ codex-safe-switch save <name> # 把当前 ~/.codex 状态保存成 <name>
86
+ codex-safe-switch show <name> # 打印 <name> 的 provider.toml 和 auth.json key 名
87
+ codex-safe-switch state <name> # 查看/设置 profile 的 session-state 作用域
88
+ codex-safe-switch restart-codex
89
+ # 终止 Codex app/server 进程,让配置立即生效
90
+ codex-safe-switch merge-history --dry-run
91
+ # 预览历史 metadata 修复,不写入文件
92
+ codex-safe-switch doctor-history
93
+ # 只读检查当前历史 provider/model 状态
94
+ codex-safe-switch rm <name> # 删除 profile(不允许删除 active profile)
95
+ codex-safe-switch alfred-list # 输出 Alfred Script Filter JSON
96
+ ```
97
+
98
+ 当 stdin/stdout 不是 TTY(管道、脚本等)时,选择器会自动降级成数字菜单。
99
+
100
+ ## 首次使用
101
+
102
+ 如果 `~/.codex/profiles/` 里还没有 profile,第一次运行 `codex-safe-switch`、`codex-safe-switch ls` 或 Alfred workflow 时,工具会自动导入当前 `~/.codex/config.toml` 的 provider 状态,并按 profile 是否需要自己认证来决定是否保存 `auth.json`。
103
+
104
+ - 官方 ChatGPT 登录会导入成隐藏的 `official` profile。
105
+ - relay/API-key 配置会导入成普通 profile,名字来自 `model_provider`,例如 `relay`。
106
+ - 如果 Codex 还没有配置过,CLI 会提示你先正常配置一次 Codex,或者在手动配置 provider 后运行 `codex-safe-switch save <name>`。
107
+
108
+ 如果需要让 Codex 桌面 app 或 app server 立刻读到新配置,可以使用:
109
+
110
+ ```bash
111
+ codex-safe-switch use <name> --restart-codex
112
+ codex-safe-switch official --restart-codex
113
+ codex-safe-switch restart-codex
114
+ ```
115
+
116
+ `restart-codex` 会终止匹配到的 Codex app/server 进程,并避开 `codex-safe-switch` 自己。
117
+
118
+ ## 官方 OpenAI 快捷入口
119
+
120
+ `codex-safe-switch official` 可以一键切回官方 OpenAI ChatGPT 登录。
121
+
122
+ - 工具会维护隐藏快照:`~/.codex/profiles/.official/`。
123
+ - 第一次从官方登录切换到其他 profile 时,会自动刷新这个官方快照。
124
+ - 如果你更喜欢按 provider 名称输入,也可以用 `codex-safe-switch openai`。
125
+
126
+ ## 默认共享历史
127
+
128
+ 每次执行 `use` / `official` 后,`codex-safe-switch` 都会自动把本地 Codex 历史 metadata 对齐到当前 provider 和 model identity。
129
+
130
+ - 正常切换 profile 时不需要再手动记 `merge-history`。
131
+ - 在 relay profile 和官方 OpenAI 登录之间切换时,历史会继续可见,包括会按 model id 过滤的界面。
132
+ - 如果 `session_index.jsonl` 落后于 SQLite 里的最新 thread,切换时会从 `state_5.sqlite` 补追加索引项,避免移动端历史列表停在旧时间点。
133
+ - 如果本机已经开启过 Codex remote-control,切换时还会顺手检查移动端/桌面远程连接依赖的 managed app-server。遇到旧的 unmanaged unix app-server 占住 socket 时会自动结束旧进程并重试;如果 Desktop 还留着旧 SSH remote proxy,会只停止这些 proxy 进程,让下次连接回到当前 MBP;如果缺少官方 standalone 安装,会打印 `curl -fsSL https://chatgpt.com/codex/install.sh | sh` 这种可执行修复命令。
134
+ - 如果你只想修复 provider,不想覆盖历史里的 model 值,可以继续用 `merge-history --keep-models`。
135
+ - `merge-history --dry-run` 会报告将要更新的 rollout 文件数、行数、SQLite rows,以及会创建的备份路径,但不会写入文件。
136
+ - `doctor-history` 是只读诊断命令,会汇总 active profile、当前 provider/model、session-state 模式、SQLite `threads` 分布、最近线程、计划对齐数量和漂移状态。
137
+
138
+ ## Profile 格式
139
+
140
+ ```text
141
+ ~/.codex/profiles/
142
+ ├── .active # 明文:当前 active profile 名
143
+ ├── .official/
144
+ │ ├── auth.json # 切换时完整复制到 ~/.codex/auth.json
145
+ │ └── provider.toml # 官方登录的 provider 片段
146
+ └── myrelay/
147
+ ├── auth.json # 可选;只有该 profile 自带 API key 或 ChatGPT token 时需要
148
+ └── provider.toml # 只包含 provider 相关字段(见 examples/)
149
+ ```
150
+
151
+ profile 会接管下列顶层 key 和 table;`~/.codex/config.toml` 中其他内容会保留:
152
+
153
+ - `model`, `model_provider`, `model_reasoning_effort`, `model_reasoning_summary`, `model_verbosity`
154
+ - `wire_api`, `disable_response_storage`, `preferred_auth_method`
155
+ - `[model_providers.*]`
156
+
157
+ ## 添加 relay profile
158
+
159
+ 1. 先按正常方式在 `~/.codex/config.toml` 里配置 relay,并确认 `codex` 可以工作。
160
+ 2. 如果 relay 用环境变量提供 key,推荐在 provider 里写 `requires_openai_auth = false` 和 `env_key = "..."`。这种 profile 不需要 `auth.json`,切换时会保留当前的官方 ChatGPT 登录缓存,方便 Codex 远程连接继续使用同一个 ChatGPT 账号。
161
+ 3. 运行 `codex-safe-switch save <name>`,把 provider 片段保存成新 profile。只有 provider 明确需要 OpenAI/ChatGPT auth,或没有声明 `requires_openai_auth = false` 的旧式 API-key 配置,才会保存 `auth.json`。
162
+ 4. 后续用 Alfred 的 `cx` 或 `codex-safe-switch use <name>` 随时切换。
163
+
164
+ `requires_openai_auth = false` 只说明这个 relay profile 不需要接管 `auth.json`。移动端能不能持续同步历史,取决于本机的官方 Codex remote-control/app-server 链路是否健康;这条链路需要官方 standalone install,而不是把 token 复制进每个 profile。
165
+
166
+ 也可以手写 profile 文件,参考 `examples/relay-profile/`。
167
+
168
+ ## 环境变量
169
+
170
+ | 变量 | 默认值 | 用途 |
171
+ | -------------------- | ------------------ | -------------------------- |
172
+ | `CODEX_PROFILE_ROOT` | `~/.codex/profiles` | profiles 存放位置 |
173
+ | `CODEX_HOME` | `~/.codex` | 要写入的 Codex 配置目录 |
174
+
175
+ ## 发布
176
+
177
+ PyPI 包发布在 [`codex-safe-switch`](https://pypi.org/project/codex-safe-switch/)。
178
+
179
+ 当前 GitHub Actions 触发规则:
180
+
181
+ - push 到 `main` 或提交 PR:运行 CI,包含 Python 单测、`uv build`、`twine check`。
182
+ - 推送 `v*` tag:运行 `Publish to PyPI` workflow,校验 tag 版本和 `pyproject.toml` 版本一致后,构建并发布到 PyPI。
183
+ - Alfred workflow:目前没有 GitHub Actions 自动构建;仓库里提交的是现成的 `alfred/codex-safe-switch.alfredworkflow`。
184
+
185
+ 发版步骤:
186
+
187
+ 1. 更新 `pyproject.toml` 里的 `version`。
188
+ 2. 运行 `uv run python -m unittest tests.test_cli` 和 `uv build`。
189
+ 3. 提交版本变更并推送 `main`。
190
+ 4. 创建并推送匹配的 tag:
191
+
192
+ ```bash
193
+ git tag vX.Y.Z
194
+ git push origin vX.Y.Z
195
+ ```
196
+
197
+ `Publish to PyPI` workflow 会验证 tag 版本、运行测试、构建 wheel/sdist、检查分发包并发布到 PyPI。需要手动发布时,也可以使用 `uvx twine upload dist/*`。
198
+
199
+ ## License
200
+
201
+ MIT
@@ -0,0 +1,9 @@
1
+ codex_safe_switch/__init__.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
2
+ codex_safe_switch/_swap.py,sha256=RvYFO-nzjVwD_XS-zb_2CufOQsBi6eTj_LYhngYCHvM,2066
3
+ codex_safe_switch/cli.py,sha256=RkCSRSHUgbasZEpgTWGzhk-GSiUAREaCqNW6pJmiH70,60640
4
+ codex_safe_switch/picker.py,sha256=Z2FYNq4xJIJ1KyupgTMJW80CRXKNLRdIUG8W_1FObG0,4238
5
+ codex_safe_switch-1.0.0.dist-info/METADATA,sha256=3IWVP1cMRL3pLBTGj2Qx749RBoYx2__pXNdqli_zrIo,10373
6
+ codex_safe_switch-1.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
7
+ codex_safe_switch-1.0.0.dist-info/entry_points.txt,sha256=nGhwecww1qSAp2hVB3tQ054CGotKT8apFmSy2XP-e-8,65
8
+ codex_safe_switch-1.0.0.dist-info/licenses/LICENSE,sha256=0xymuUzuZEgUQn-AUMgTQ_HooBpXUqTNslZUxD-Cyuw,1065
9
+ codex_safe_switch-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ codex-safe-switch = codex_safe_switch.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kadaliao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.