-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodex-model.sh
More file actions
executable file
·198 lines (179 loc) · 6.89 KB
/
Copy pathcodex-model.sh
File metadata and controls
executable file
·198 lines (179 loc) · 6.89 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
#!/usr/bin/env bash
# codex-model-switch — toggle the OpenAI Codex CLI/App between a LOCAL model
# (Ollama / any OpenAI-compatible provider) and the NATIVE cloud model.
#
# https://github.com/cnvipstar/codex-model-switch MIT License
#
# Usage:
# codex-model Interactive menu (lists installed local + cloud models)
# codex-model local [MODEL] Switch to a local provider model (default: $CODEX_MODEL_DEFAULT_LOCAL)
# codex-model native [MODEL] Switch back to Codex native cloud (default: $CODEX_MODEL_DEFAULT_NATIVE)
# codex-model status Show the current mode
# codex-model -h | --help Show this help
#
# Only the top-level keys model / model_provider / oss_provider in config.toml are rewritten;
# everything else (projects, MCP servers, plugins, desktop settings, …) is preserved untouched.
# Every switch writes atomically and keeps a timestamped backup next to config.toml.
set -euo pipefail
CONFIG="${CODEX_HOME:-$HOME/.codex}/config.toml"
CODEX_DIR="$(dirname "$CONFIG")"
LOCAL_API_BASE="${CODEX_MODEL_LOCAL_API:-http://localhost:11434/v1}" # OpenAI-compatible endpoint
PROVIDER_ID="${CODEX_MODEL_PROVIDER_ID:-ollama}" # value written to model_provider
OSS_PROVIDER="${CODEX_MODEL_OSS_PROVIDER:-ollama}" # value written to oss_provider
DEFAULT_LOCAL="${CODEX_MODEL_DEFAULT_LOCAL:-gpt-oss:20b}"
DEFAULT_NATIVE="${CODEX_MODEL_DEFAULT_NATIVE:-gpt-5.5}"
die(){ echo "❌ $*" >&2; exit 1; }
usage(){
awk 'NR==1{next} /^#/{sub(/^# ?/,""); print; next} {exit}' "$0"
}
[ -f "$CONFIG" ] || die "config.toml not found at: $CONFIG (set CODEX_HOME if it lives elsewhere)"
# ── List local models from the OpenAI-compatible /models endpoint (works for Ollama & LM Studio) ──
list_local_models(){
curl -sf "$LOCAL_API_BASE/models" 2>/dev/null \
| python3 -c "import sys,json;[print(x.get('id','')) for x in json.load(sys.stdin).get('data',[])]" 2>/dev/null \
|| true
}
# ── Show current mode ──
show_status(){
python3 - "$CONFIG" <<'PY'
import sys, re
lines = open(sys.argv[1], encoding='utf-8').read().split('\n')
top = []
for l in lines:
if re.match(r'\s*\[', l): break
top.append(l)
top = '\n'.join(top)
def g(k):
m = re.search(rf'(?m)^\s*{k}\s*=\s*"([^"]*)"', top)
return m.group(1) if m else None
model, prov = g('model'), g('model_provider')
if prov:
print(f"current: 🖥 LOCAL (model_provider={prov}, model={model})")
else:
print(f"current: ☁️ NATIVE (cloud, model={model})")
PY
}
# ── Apply a switch: apply_switch <local|native> <model> ──
apply_switch(){
local MODE="$1" MODEL="$2"
if [ "$MODE" = "local" ]; then
local models
models="$(list_local_models)"
if [ -z "$models" ]; then
echo "⚠️ Local endpoint not reachable at $LOCAL_API_BASE — Codex won't be able to connect after switching."
elif ! printf '%s\n' "$models" | grep -qxF "$MODEL"; then
echo "⚠️ Model '$MODEL' not found at $LOCAL_API_BASE. Pull/load it first (e.g. 'ollama pull $MODEL') or check the name."
fi
fi
local bak="$CONFIG.bak-codex-model-$(date +%Y%m%d-%H%M%S)"
cp "$CONFIG" "$bak"
python3 - "$CONFIG" "$MODE" "$MODEL" "$PROVIDER_ID" "$OSS_PROVIDER" <<'PY'
import sys, re, os
path, mode, model, provider_id, oss_provider = sys.argv[1:6]
lines = open(path, encoding='utf-8').read().split('\n')
first = len(lines)
for i, l in enumerate(lines):
if re.match(r'\s*\[', l):
first = i; break
top, rest = lines[:first], lines[first:]
# drop any existing top-level model / model_provider / oss_provider
top = [l for l in top if not re.match(r'\s*(model|model_provider|oss_provider)\s*=', l)]
new = [f'model = "{model}"']
if mode == 'local':
new += [f'model_provider = "{provider_id}"', f'oss_provider = "{oss_provider}"']
out = '\n'.join(new + top + rest)
with open(path + '.tmp', 'w', encoding='utf-8') as f:
f.write(out)
os.replace(path + '.tmp', path)
PY
echo "✅ switched"
show_status
echo "📦 backup: $bak"
if pgrep -f "Codex.app" >/dev/null 2>&1; then
echo "🔁 Codex App is running — restart it (or open a new conversation) for the change to take effect."
else
echo "🔁 Takes effect next time Codex starts / on a new conversation."
fi
}
# ── Interactive menu ──
interactive_menu(){
echo "════════════ Codex model switch ════════════"
show_status
echo
local -a names modes
names=(); modes=()
echo "── 🖥 Local ($LOCAL_API_BASE) ──"
local local_list; local_list="$(list_local_models)"
if [ -n "$local_list" ]; then
while IFS= read -r m; do
[ -z "$m" ] && continue
names+=("$m"); modes+=("local")
printf " %2d) %s\n" "${#names[@]}" "$m"
done <<< "$local_list"
else
echo " (endpoint unreachable — start your local server, or use 'm' below)"
fi
echo "── ☁️ Codex native (cloud) ──"
local native_list
native_list="$(python3 - "$CODEX_DIR/models_cache.json" <<'PY' 2>/dev/null || true
import sys, json
try:
d = json.load(open(sys.argv[1], encoding='utf-8'))
except Exception:
sys.exit(0)
found = set()
def walk(o):
if isinstance(o, dict):
for k, v in o.items():
if k in ('id', 'slug') and isinstance(v, str) and v.startswith('gpt-'):
found.add(v)
walk(v)
elif isinstance(o, list):
for v in o: walk(v)
walk(d)
for m in sorted(found): print(m)
PY
)"
[ -z "${native_list:-}" ] && native_list=$'gpt-5.5\ngpt-5.4\ngpt-5.4-mini'
while IFS= read -r m; do
[ -z "$m" ] && continue
names+=("$m"); modes+=("native")
printf " %2d) %s\n" "${#names[@]}" "$m"
done <<< "$native_list"
echo " ───────────────"
echo " m) ✍️ enter a model name manually"
echo " q) cancel"
echo
printf "Select a number: "
local choice; read -r choice
case "$choice" in
""|q|Q) echo "cancelled, no changes."; exit 0;;
m|M)
printf "model name: "; local mm; read -r mm
[ -z "$mm" ] && { echo "nothing entered, cancelled."; exit 0; }
printf "type [1=local / 2=native cloud]: "; local mt; read -r mt
case "$mt" in
1) apply_switch local "$mm";;
2) apply_switch native "$mm";;
*) die "invalid type: $mt";;
esac
;;
*[!0-9]*) die "invalid input: $choice";;
*)
local idx=$((choice-1))
[ "$choice" -ge 1 ] 2>/dev/null && [ -n "${names[$idx]:-}" ] || die "number out of range: $choice"
apply_switch "${modes[$idx]}" "${names[$idx]}"
;;
esac
}
# ── Entry point ──
cmd="${1:-MENU}"
arg="${2:-}"
case "$cmd" in
MENU) interactive_menu;;
status) show_status;;
local) apply_switch local "${arg:-$DEFAULT_LOCAL}";;
native) apply_switch native "${arg:-$DEFAULT_NATIVE}";;
-h|--help|help) usage;;
*) die "unknown command: $cmd (use: no-args = menu | local | native | status | --help)";;
esac