@bitkyc08/opencodex 1.9.5 → 2.0.1

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.
@@ -1,4 +1,4 @@
1
- import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { atomicWriteFile, websocketsEnabled } from "./config";
@@ -6,6 +6,7 @@ import { CODEX_CONFIG_PATH, CODEX_MODELS_CACHE_PATH, DEFAULT_CATALOG_PATH, readR
6
6
  import { DEFAULT_MODEL_CACHE_TTL_MS, getFreshCached, getStaleCached, setCached } from "./model-cache";
7
7
  import { buildModelsRequest, resolveModelsAuthToken } from "./oauth/index";
8
8
  import type { OcxConfig, OcxProviderConfig } from "./types";
9
+ import { CODEX_REASONING_LEVELS, configuredReasoningEfforts, sanitizeCodexReasoningEfforts } from "./reasoning-effort";
9
10
  import { getJawcodeModelMetadata, getJawcodeModelMetadataCaseInsensitive, listJawcodeModelMetadata, resolveJawcodeProvider } from "./generated/jawcode-model-metadata";
10
11
  import { shouldCaseFoldMetadataModelId } from "./providers/derive";
11
12
 
@@ -33,10 +34,34 @@ export function nativeOpenAiSlugs(): string[] {
33
34
  return live.length > 0 ? live : NATIVE_OPENAI_MODELS;
34
35
  }
35
36
 
36
- export interface CatalogModel { id: string; provider: string; owned_by?: string; }
37
+ export interface CatalogModel { id: string; provider: string; owned_by?: string; reasoningEfforts?: string[]; contextWindow?: number; inputModalities?: string[]; }
37
38
  type RawEntry = Record<string, unknown>;
38
39
  const JAWCODE_CATALOG_AUGMENT_PROVIDERS = new Set(["opencode-go"]);
39
40
 
41
+ /**
42
+ * Image/video GENERATION model families. opencodex routes chat/coding models into Codex; media-
43
+ * generation models (Grok image/video, DALL·E, Imagen, Sora, Veo, …) are useless to a coding agent
44
+ * and must never surface in the dashboard, /v1/models, or the routed catalog. The metadata has no
45
+ * output-modality field, so we classify by id. Extend this list as providers add media models.
46
+ */
47
+ const MEDIA_GEN_FAMILIES = [
48
+ "dall-e", "dalle", "imagen", "sora", "veo", "flux", "kling",
49
+ "seedance", "hailuo", "stable-diffusion", "sdxl", "midjourney",
50
+ ];
51
+ const MEDIA_GEN_ID_RE = new RegExp(
52
+ `(?:^|[/_-])(?:image|video)(?:[/_-]|$)|(?:^|[/_-])(?:${MEDIA_GEN_FAMILIES.join("|")})(?:[/_-]|$|\\d)`,
53
+ "i",
54
+ );
55
+
56
+ /**
57
+ * True when a model id denotes image/video GENERATION (so it should be hidden everywhere). Vision
58
+ * *input* chat models — `grok-2-vision`, `qwen3-vl-*`, `gpt-4o`, `gemini-3-pro-preview` — are
59
+ * intentionally NOT matched: they carry no `image`/`video` id segment and no generation-family token.
60
+ */
61
+ export function isMediaGenerationModelId(id: string): boolean {
62
+ return MEDIA_GEN_ID_RE.test(id);
63
+ }
64
+
40
65
  /** Resolve the `model_catalog_json` path from Codex config.toml, else the default. */
41
66
  export function readCodexCatalogPath(): string {
42
67
  try {
@@ -171,19 +196,42 @@ export function loadCatalogTemplate(): RawEntry | null {
171
196
  }
172
197
 
173
198
  /**
174
- * The reasoning ladder advertised for routed models in Codex's picker: low medium high → xhigh.
175
- * This matches Codex's NATIVE catalog exactly Codex's strict parser rejects an unknown effort like
176
- * `max`, so it must not be advertised here. (Previously routed models were clamped down to
177
- * low/medium/high, which dropped the `xhigh` that Codex does support.)
199
+ * Codex only accepts its native labels in the catalog. Provider-specific wire values (e.g. Z.AI
200
+ * `max`) are mapped at request time by src/reasoning-effort.ts, never advertised directly here.
178
201
  */
179
- const ROUTED_REASONING_LEVELS: { effort: string; description: string }[] = [
180
- { effort: "low", description: "Fast responses with lighter reasoning" },
181
- { effort: "medium", description: "Balances speed and reasoning depth" },
182
- { effort: "high", description: "Greater reasoning depth for complex problems" },
183
- { effort: "xhigh", description: "Extended reasoning for the hardest problems" },
184
- ];
202
+ const ROUTED_REASONING_LEVELS = CODEX_REASONING_LEVELS;
203
+
204
+ function applyCatalogModelMetadata(entry: RawEntry, model?: CatalogModel): void {
205
+ if (!model) return;
206
+ if (typeof model.contextWindow === "number" && model.contextWindow > 0) {
207
+ entry.context_window = model.contextWindow;
208
+ entry.max_context_window = model.contextWindow;
209
+ entry.auto_compact_token_limit = Math.floor(model.contextWindow * 0.9);
210
+ }
211
+ if (Array.isArray(model.inputModalities) && model.inputModalities.length > 0) {
212
+ entry.input_modalities = model.inputModalities;
213
+ }
214
+ }
215
+
216
+ function applyReasoningLevels(entry: RawEntry, effortsOverride?: string[]): void {
217
+ const efforts = sanitizeCodexReasoningEfforts(effortsOverride) ?? ROUTED_REASONING_LEVELS.map(l => l.effort);
218
+ const byEffort = new Map(
219
+ (Array.isArray(entry.supported_reasoning_levels) ? entry.supported_reasoning_levels : [])
220
+ .map((l: { effort?: string }) => [l.effort, l]),
221
+ );
222
+ entry.supported_reasoning_levels = efforts.map(effort => {
223
+ const native = byEffort.get(effort);
224
+ if (native) return native;
225
+ return ROUTED_REASONING_LEVELS.find(l => l.effort === effort) ?? { effort, description: `${effort} reasoning` };
226
+ });
227
+ if (efforts.length === 0) {
228
+ delete entry.default_reasoning_level;
229
+ return;
230
+ }
231
+ entry.default_reasoning_level = efforts.includes("medium") ? "medium" : efforts.includes("high") ? "high" : efforts[0];
232
+ }
185
233
 
186
- function deriveEntry(template: RawEntry | null, slug: string, desc: string, priority: number): RawEntry {
234
+ function deriveEntry(template: RawEntry | null, slug: string, desc: string, priority: number, model?: CatalogModel): RawEntry {
187
235
  if (template) {
188
236
  const e = JSON.parse(JSON.stringify(template)) as RawEntry;
189
237
  e.slug = slug;
@@ -203,28 +251,24 @@ function deriveEntry(template: RawEntry | null, slug: string, desc: string, prio
203
251
  `You are a coding agent powered by the ${modelName} model, served through the opencodex proxy. Do not claim to be GPT-5 or made by OpenAI.`,
204
252
  );
205
253
  }
206
- // Reuse the template's level objects where they exist (correct shape/fields), synthesize the rest.
207
- const byEffort = new Map(
208
- (Array.isArray(e.supported_reasoning_levels) ? e.supported_reasoning_levels : [])
209
- .map((l: { effort?: string }) => [l.effort, l]),
210
- );
211
- e.supported_reasoning_levels = ROUTED_REASONING_LEVELS.map(l => byEffort.get(l.effort) ?? { ...l });
212
- e.default_reasoning_level = "medium";
254
+ applyReasoningLevels(e, model?.reasoningEfforts);
213
255
  normalizeRoutedCatalogEntry(e);
214
256
  applyJawcodeCatalogMetadata(e, slug);
257
+ applyCatalogModelMetadata(e, model);
215
258
  }
216
259
  return ensureStrictCatalogFields(normalizeServiceTiers(e));
217
260
  }
218
261
  // Fallback when no template is available (best-effort; strict parser may need more).
219
262
  const entry: RawEntry = {
220
263
  slug, display_name: slug, description: desc,
221
- default_reasoning_level: "medium",
222
- supported_reasoning_levels: ROUTED_REASONING_LEVELS.map(l => ({ ...l })),
223
264
  shell_type: "shell_command", visibility: "list", supported_in_api: true,
224
265
  priority, base_instructions: "You are a helpful coding assistant.",
225
266
  ...(slug.includes("/") ? { web_search_tool_type: "text_and_image", supports_search_tool: true } : {}),
226
267
  };
268
+ if (slug.includes("/")) applyReasoningLevels(entry, model?.reasoningEfforts);
269
+ else applyReasoningLevels(entry);
227
270
  applyJawcodeCatalogMetadata(entry, slug);
271
+ applyCatalogModelMetadata(entry, model);
228
272
  return ensureStrictCatalogFields(normalizeServiceTiers(entry));
229
273
  }
230
274
 
@@ -247,7 +291,7 @@ export function buildCatalogEntries(template: RawEntry | null, gptSlugs: string[
247
291
  }
248
292
  for (const m of goModels) {
249
293
  const slug = `${m.provider}/${m.id}`;
250
- const e = deriveEntry(template, slug, `Routed via opencodex → ${m.provider} (${m.owned_by ?? m.provider}).`, 5);
294
+ const e = deriveEntry(template, slug, `Routed via opencodex → ${m.provider} (${m.owned_by ?? m.provider}).`, 5, m);
251
295
  if (rank.has(slug)) e.priority = rank.get(slug)!;
252
296
  out.push(e);
253
297
  }
@@ -285,6 +329,61 @@ function readNativeBaseline(): Map<string, number> {
285
329
  return out;
286
330
  }
287
331
 
332
+
333
+ type ProviderModelsApiItem = {
334
+ id: string;
335
+ owned_by?: string;
336
+ max_model_len?: number;
337
+ metadata?: {
338
+ capabilities?: Record<string, unknown>;
339
+ limits?: Record<string, unknown>;
340
+ };
341
+ };
342
+
343
+ function catalogHintsFromProviderConfig(name: string, prov: OcxProviderConfig, id: string): Partial<CatalogModel> {
344
+ void name;
345
+ const reasoningEfforts = configuredReasoningEfforts(prov, id);
346
+ return {
347
+ ...(reasoningEfforts !== undefined ? { reasoningEfforts } : {}),
348
+ };
349
+ }
350
+
351
+ function applyConfigHintsToCachedModels(name: string, prov: OcxProviderConfig, models: CatalogModel[]): CatalogModel[] {
352
+ return models.map(model => ({
353
+ ...catalogHintsFromProviderConfig(name, prov, model.id),
354
+ ...model,
355
+ }));
356
+ }
357
+
358
+ function isGlm52ModelId(id: string): boolean {
359
+ const normalized = id.toLowerCase();
360
+ return normalized === "glm-5.2" || normalized === "glm-5.2[1m]";
361
+ }
362
+
363
+ function catalogHintsFromModelsApiItem(providerName: string, item: ProviderModelsApiItem): Partial<CatalogModel> {
364
+ const capabilities = item.metadata?.capabilities;
365
+ const limits = item.metadata?.limits;
366
+ const contextWindow =
367
+ typeof limits?.max_context_length === "number" ? limits.max_context_length
368
+ : typeof item.max_model_len === "number" ? item.max_model_len
369
+ : undefined;
370
+ const reasoningEfforts = capabilities && typeof capabilities.reasoning_effort === "boolean"
371
+ ? (capabilities.reasoning_effort
372
+ ? ((providerName === "neuralwatt" || providerName === "zai") && isGlm52ModelId(item.id)
373
+ ? ["low", "medium", "high", "xhigh"]
374
+ : ["low", "medium", "high"])
375
+ : [])
376
+ : undefined;
377
+ const inputModalities = capabilities && typeof capabilities.vision === "boolean"
378
+ ? (capabilities.vision ? ["text", "image"] : ["text"])
379
+ : undefined;
380
+ return {
381
+ ...(contextWindow && contextWindow > 0 ? { contextWindow } : {}),
382
+ ...(reasoningEfforts !== undefined ? { reasoningEfforts } : {}),
383
+ ...(inputModalities ? { inputModalities } : {}),
384
+ };
385
+ }
386
+
288
387
  /**
289
388
  * Fetch a provider's `/models` (openai-chat style) with a TTL cache + stale fallback. Skips
290
389
  * forward-auth providers. Fresh cache → no network; live fetch → cache the merged result;
@@ -296,21 +395,35 @@ async function fetchProviderModels(name: string, prov: OcxProviderConfig, ttlMs:
296
395
  const apiKey = await resolveModelsAuthToken(name, prov);
297
396
  if (prov.authMode === "oauth" && !apiKey) return []; // not logged in → skip
298
397
  const fresh = getFreshCached(name, ttlMs);
299
- if (fresh) return fresh; // dedups Codex's frequent /v1/models polling within the TTL
300
- const configured: CatalogModel[] = (prov.models ?? []).map(id => ({ id, provider: name }));
398
+ if (fresh) return applyConfigHintsToCachedModels(name, prov, fresh); // dedups Codex's frequent /v1/models polling within the TTL
399
+ const configured: CatalogModel[] = (prov.models ?? []).map(id => ({
400
+ id,
401
+ provider: name,
402
+ ...catalogHintsFromProviderConfig(name, prov, id),
403
+ }));
301
404
  const { url, headers } = buildModelsRequest(prov, apiKey);
302
405
  try {
303
406
  const res = await fetch(url, { headers, signal: AbortSignal.timeout(8000) });
304
- if (!res.ok) return getStaleCached(name) ?? configured;
305
- const json = await res.json() as { data?: { id: string; owned_by?: string }[] };
306
- const live = (json.data ?? []).map(m => ({ id: m.id, provider: name, owned_by: m.owned_by }));
407
+ if (!res.ok) {
408
+ const stale = getStaleCached(name);
409
+ return stale ? applyConfigHintsToCachedModels(name, prov, stale) : configured;
410
+ }
411
+ const json = await res.json() as { data?: ProviderModelsApiItem[] };
412
+ const live = (json.data ?? []).map(m => ({
413
+ id: m.id,
414
+ provider: name,
415
+ owned_by: m.owned_by,
416
+ ...catalogHintsFromProviderConfig(name, prov, m.id),
417
+ ...catalogHintsFromModelsApiItem(name, m),
418
+ }));
307
419
  const liveIds = new Set(live.map(m => m.id));
308
420
  // Merge explicit config additions (e.g. a model not in the provider's /models, like a new endpoint).
309
421
  const merged = [...live, ...configured.filter(m => !liveIds.has(m.id))];
310
422
  setCached(name, merged);
311
423
  return merged;
312
424
  } catch {
313
- return getStaleCached(name) ?? configured;
425
+ const stale = getStaleCached(name);
426
+ return stale ? applyConfigHintsToCachedModels(name, prov, stale) : configured;
314
427
  }
315
428
  }
316
429
 
@@ -325,12 +438,15 @@ export async function gatherRoutedModels(config: OcxConfig): Promise<CatalogMode
325
438
  const lists = await Promise.all(
326
439
  Object.entries(config.providers).map(([name, prov]) => fetchProviderModels(name, prov, ttlMs)),
327
440
  );
328
- const all = augmentRoutedModelsWithJawcodeMetadata(lists.flat(), Object.keys(config.providers));
441
+ const all = augmentRoutedModelsWithJawcodeMetadata(lists.flat(), Object.keys(config.providers), config.providers)
442
+ // Drop image/video generation models (e.g. Grok image/video) — they are not usable by Codex and
443
+ // must not surface in the dashboard, /v1/models, or the routed catalog. Single choke point.
444
+ .filter(m => !isMediaGenerationModelId(m.id));
329
445
  all.sort((a, b) => (a.provider === b.provider ? a.id.localeCompare(b.id) : a.provider.localeCompare(b.provider)));
330
446
  return all;
331
447
  }
332
448
 
333
- export function augmentRoutedModelsWithJawcodeMetadata(models: CatalogModel[], providerNames: string[]): CatalogModel[] {
449
+ export function augmentRoutedModelsWithJawcodeMetadata(models: CatalogModel[], providerNames: string[], providers?: Record<string, OcxProviderConfig>): CatalogModel[] {
334
450
  const out = [...models];
335
451
  const seen = new Set(out.map(m => `${m.provider}/${m.id}`));
336
452
  for (const provider of providerNames) {
@@ -341,7 +457,7 @@ export function augmentRoutedModelsWithJawcodeMetadata(models: CatalogModel[], p
341
457
  const key = `${provider}/${meta.id}`;
342
458
  if (seen.has(key)) continue;
343
459
  seen.add(key);
344
- out.push({ provider, id: meta.id, owned_by: provider });
460
+ out.push({ provider, id: meta.id, owned_by: provider, ...(providers?.[provider] ? catalogHintsFromProviderConfig(provider, providers[provider], meta.id) : {}) });
345
461
  }
346
462
  }
347
463
  return out;
@@ -444,12 +560,15 @@ export function restoreCodexCatalog(): { removed: number; kept: number; path: st
444
560
  }
445
561
 
446
562
  /**
447
- * Delete Codex's models cache ($CODEX_HOME/models_cache.json) so the next turn re-fetches /v1/models.
448
- * Codex caches the model list for 5 min (DEFAULT_MODEL_CACHE_TTL); invalidating makes catalog edits
449
- * (enable/disable, subagent reorder) apply on the next turn instead of waiting for the TTL.
563
+ * Refresh Codex's models cache ($CODEX_HOME/models_cache.json) from the active catalog.
564
+ * Codex caches the model list for 5 min (DEFAULT_MODEL_CACHE_TTL); copying the injected catalog
565
+ * makes catalog edits (enable/disable, subagent reorder) apply on the next turn instead of waiting.
450
566
  */
451
567
  export function invalidateCodexModelsCache(): void {
452
568
  try {
453
- if (existsSync(CODEX_MODELS_CACHE_PATH)) unlinkSync(CODEX_MODELS_CACHE_PATH);
569
+ const catalogPath = readCodexCatalogPath();
570
+ if (!existsSync(catalogPath)) return;
571
+ const catalog = readFileSync(catalogPath, "utf8");
572
+ atomicWriteFile(CODEX_MODELS_CACHE_PATH, catalog.endsWith("\n") ? catalog : `${catalog}\n`);
454
573
  } catch { /* best-effort */ }
455
574
  }
@@ -0,0 +1,49 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { invalidateCodexModelsCache, syncCatalogModels } from "./codex-catalog";
3
+ import { CODEX_MODELS_CACHE_PATH } from "./codex-paths";
4
+ import { atomicWriteFile } from "./config";
5
+ import type { OcxConfig } from "./types";
6
+
7
+ export interface CodexCatalogRefreshResult {
8
+ added: number;
9
+ path: string;
10
+ catalogExists: boolean;
11
+ cacheSynced: boolean;
12
+ }
13
+
14
+ interface RefreshDeps {
15
+ syncCatalogModels: typeof syncCatalogModels;
16
+ invalidateCodexModelsCache: typeof invalidateCodexModelsCache;
17
+ syncCodexModelsCacheFromCatalog: typeof syncCodexModelsCacheFromCatalog;
18
+ existsSync: typeof existsSync;
19
+ }
20
+
21
+ const defaultDeps: RefreshDeps = {
22
+ syncCatalogModels,
23
+ invalidateCodexModelsCache,
24
+ syncCodexModelsCacheFromCatalog,
25
+ existsSync,
26
+ };
27
+
28
+ export function syncCodexModelsCacheFromCatalog(catalogPath: string): void {
29
+ const content = readFileSync(catalogPath, "utf8");
30
+ atomicWriteFile(CODEX_MODELS_CACHE_PATH, content);
31
+ }
32
+
33
+ /**
34
+ * Rebuild Codex's on-disk model catalog and keep Codex's models cache aligned
35
+ * when a catalog file exists. Codex Desktop can read models_cache.json directly,
36
+ * so deleting a stale cache is not enough: the cache must be replaced with the
37
+ * same catalog content the CLI debug path reads.
38
+ */
39
+ export async function refreshCodexModelCatalog(
40
+ config: OcxConfig,
41
+ deps: RefreshDeps = defaultDeps,
42
+ ): Promise<CodexCatalogRefreshResult> {
43
+ const result = await deps.syncCatalogModels(config);
44
+ const catalogExists = deps.existsSync(result.path);
45
+ if (!catalogExists) return { ...result, catalogExists, cacheSynced: false };
46
+ deps.invalidateCodexModelsCache();
47
+ deps.syncCodexModelsCacheFromCatalog(result.path);
48
+ return { ...result, catalogExists, cacheSynced: true };
49
+ }
@@ -0,0 +1,145 @@
1
+ import { delimiter, dirname, extname, join } from "node:path";
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { getConfigDir } from "./config";
4
+
5
+ const SHIM_MARKER = "opencodex codex autostart shim";
6
+ const STATE_PATH = join(getConfigDir(), "codex-shim.json");
7
+
8
+ interface ShimState {
9
+ platform: NodeJS.Platform;
10
+ wrapperPath: string;
11
+ originalPath: string;
12
+ backupPath: string;
13
+ }
14
+
15
+ function cliEntry(): { bun: string; cli: string } {
16
+ return { bun: process.execPath, cli: join(import.meta.dir, "cli.ts") };
17
+ }
18
+
19
+ function commandNames(name: string): string[] {
20
+ if (process.platform !== "win32") return [name];
21
+ const exts = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD;.PS1").split(";").filter(Boolean);
22
+ return [name, ...exts.flatMap(ext => [`${name}${ext.toLowerCase()}`, `${name}${ext.toUpperCase()}`])];
23
+ }
24
+
25
+ function isShim(path: string): boolean {
26
+ try {
27
+ return readFileSync(path, "utf8").includes(SHIM_MARKER);
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ function findCodexOnPath(): string | null {
34
+ for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
35
+ for (const name of commandNames("codex")) {
36
+ const path = join(dir, name);
37
+ if (!existsSync(path) || isShim(path)) continue;
38
+ try {
39
+ if (!lstatSync(path).isDirectory()) return path;
40
+ } catch {
41
+ continue;
42
+ }
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+
48
+ function backupPathFor(path: string): string {
49
+ const ext = extname(path);
50
+ return ext ? `${path.slice(0, -ext.length)}.opencodex-real${ext}` : `${path}.opencodex-real`;
51
+ }
52
+
53
+ export function buildUnixCodexShim(realCodexPath: string, bunPath: string, cliPath: string): string {
54
+ return `#!/usr/bin/env sh
55
+ # ${SHIM_MARKER}
56
+ if [ -z "$OCX_SHIM_BYPASS" ]; then
57
+ if ! "${bunPath}" "${cliPath}" status 2>/dev/null | grep -q "Proxy running"; then
58
+ mkdir -p "$HOME/.opencodex"
59
+ nohup env OCX_SERVICE=1 "${bunPath}" "${cliPath}" start >> "$HOME/.opencodex/shim.log" 2>&1 &
60
+ i=0
61
+ while [ "$i" -lt 50 ]; do
62
+ if "${bunPath}" "${cliPath}" status 2>/dev/null | grep -q "Proxy running"; then
63
+ break
64
+ fi
65
+ sleep 0.1
66
+ i=$((i + 1))
67
+ done
68
+ fi
69
+ fi
70
+ exec "${realCodexPath}" "$@"
71
+ `;
72
+ }
73
+
74
+ export function buildWindowsCodexShim(realCodexPath: string, bunPath: string, cliPath: string): string {
75
+ return `@echo off\r
76
+ rem ${SHIM_MARKER}\r
77
+ if not "%OCX_SHIM_BYPASS%"=="" goto run_codex\r
78
+ "${bunPath}" "${cliPath}" status 2>nul | findstr /C:"Proxy running" >nul\r
79
+ if %ERRORLEVEL% EQU 0 goto run_codex\r
80
+ if not exist "%USERPROFILE%\\.opencodex" mkdir "%USERPROFILE%\\.opencodex"\r
81
+ start "" /b cmd /c "set OCX_SERVICE=1 && ""${bunPath}"" ""${cliPath}"" start >> ""%USERPROFILE%\\.opencodex\\shim.log"" 2>&1"\r
82
+ for /l %%i in (1,1,50) do (\r
83
+ "${bunPath}" "${cliPath}" status 2>nul | findstr /C:"Proxy running" >nul\r
84
+ if not errorlevel 1 goto run_codex\r
85
+ powershell -NoProfile -Command "Start-Sleep -Milliseconds 100" >nul 2>nul\r
86
+ )\r
87
+ :run_codex\r
88
+ "${realCodexPath}" %*\r
89
+ `;
90
+ }
91
+
92
+ function readState(): ShimState | null {
93
+ try {
94
+ return JSON.parse(readFileSync(STATE_PATH, "utf8")) as ShimState;
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ function writeState(state: ShimState): void {
101
+ if (!existsSync(getConfigDir())) mkdirSync(getConfigDir(), { recursive: true });
102
+ writeFileSync(STATE_PATH, JSON.stringify(state, null, 2) + "\n", "utf8");
103
+ }
104
+
105
+ export function installCodexShim(): { installed: boolean; message: string } {
106
+ const existing = readState();
107
+ if (existing && existsSync(existing.wrapperPath) && existsSync(existing.backupPath)) {
108
+ return { installed: false, message: `Codex autostart shim already installed at ${existing.wrapperPath}.` };
109
+ }
110
+
111
+ const originalPath = findCodexOnPath();
112
+ if (!originalPath) return { installed: false, message: "Could not find a codex executable on PATH." };
113
+
114
+ const backupPath = backupPathFor(originalPath);
115
+ if (existsSync(backupPath)) return { installed: false, message: `Refusing to overwrite existing backup: ${backupPath}` };
116
+
117
+ const { bun, cli } = cliEntry();
118
+ const wrapperPath = process.platform === "win32" ? join(dirname(originalPath), "codex.cmd") : originalPath;
119
+ renameSync(originalPath, backupPath);
120
+ if (process.platform === "win32") {
121
+ writeFileSync(wrapperPath, buildWindowsCodexShim(backupPath, bun, cli), "utf8");
122
+ } else {
123
+ writeFileSync(wrapperPath, buildUnixCodexShim(backupPath, bun, cli), "utf8");
124
+ chmodSync(wrapperPath, 0o755);
125
+ }
126
+ writeState({ platform: process.platform, wrapperPath, originalPath, backupPath });
127
+ return { installed: true, message: `Codex autostart shim installed at ${wrapperPath}. Original saved at ${backupPath}.` };
128
+ }
129
+
130
+ export function uninstallCodexShim(): { removed: boolean; message: string } {
131
+ const state = readState();
132
+ if (!state) return { removed: false, message: "Codex autostart shim is not installed." };
133
+ if (existsSync(state.wrapperPath) && isShim(state.wrapperPath)) unlinkSync(state.wrapperPath);
134
+ if (existsSync(state.backupPath) && !existsSync(state.originalPath)) renameSync(state.backupPath, state.originalPath);
135
+ if (existsSync(STATE_PATH)) unlinkSync(STATE_PATH);
136
+ return { removed: true, message: `Codex autostart shim removed. Restored ${state.originalPath}.` };
137
+ }
138
+
139
+ export function codexShimStatus(): string {
140
+ const state = readState();
141
+ if (!state) return "Codex autostart shim is not installed.";
142
+ const wrapper = existsSync(state.wrapperPath) ? "present" : "missing";
143
+ const backup = existsSync(state.backupPath) ? "present" : "missing";
144
+ return `Codex autostart shim: wrapper ${wrapper} at ${state.wrapperPath}; original backup ${backup} at ${state.backupPath}.`;
145
+ }
package/src/config.ts CHANGED
@@ -3,12 +3,13 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { OcxConfig } from "./types";
5
5
 
6
+ let _atomicSeq = 0;
6
7
  /**
7
8
  * Write a file atomically (temp + rename) so concurrent writers — e.g. `ocx stop` and the
8
9
  * proxy's own shutdown handler both restoring Codex — can never leave a half-written file.
9
10
  */
10
11
  export function atomicWriteFile(path: string, content: string): void {
11
- const tmp = `${path}.ocx.tmp`;
12
+ const tmp = `${path}.ocx.${process.pid}.${++_atomicSeq}.tmp`;
12
13
  writeFileSync(tmp, content, "utf-8");
13
14
  renameSync(tmp, path);
14
15
  }
@@ -121,24 +121,40 @@ export function buildModelsRequest(prov: OcxProviderConfig, apiKey: string | und
121
121
  * Only touches providers that are registry-managed AND still `authMode: "oauth"`, and only the
122
122
  * preset fields (never apiKey/baseUrl/user toggles). Persists + returns true when anything changed.
123
123
  */
124
+ function cloneProviderField(value: unknown): unknown {
125
+ if (Array.isArray(value)) return [...value];
126
+ if (value && typeof value === "object") return JSON.parse(JSON.stringify(value));
127
+ return value;
128
+ }
129
+
130
+ const OAUTH_RECONCILE_FIELDS: (keyof OcxProviderConfig)[] = [
131
+ "models",
132
+ "noReasoningModels",
133
+ "noVisionModels",
134
+ "reasoningEfforts",
135
+ "modelReasoningEfforts",
136
+ "reasoningEffortMap",
137
+ "modelReasoningEffortMap",
138
+ "noTemperatureModels",
139
+ "noTopPModels",
140
+ "noPenaltyModels",
141
+ "autoToolChoiceOnlyModels",
142
+ "preserveReasoningContentModels",
143
+ ];
144
+
124
145
  export function reconcileOAuthProviders(config: OcxConfig): boolean {
125
146
  let changed = false;
126
147
  for (const [name, prov] of Object.entries(config.providers)) {
127
148
  const def = OAUTH_PROVIDERS[name];
128
149
  if (!def || prov.authMode !== "oauth") continue;
129
150
  const preset = def.providerConfig;
130
- if (preset.models && JSON.stringify(prov.models) !== JSON.stringify(preset.models)) {
131
- prov.models = [...preset.models];
132
- changed = true;
133
- }
134
- if (JSON.stringify(prov.noReasoningModels) !== JSON.stringify(preset.noReasoningModels)) {
135
- if (preset.noReasoningModels) prov.noReasoningModels = [...preset.noReasoningModels];
136
- else delete prov.noReasoningModels;
137
- changed = true;
138
- }
139
- if (JSON.stringify(prov.noVisionModels) !== JSON.stringify(preset.noVisionModels)) {
140
- if (preset.noVisionModels) prov.noVisionModels = [...preset.noVisionModels];
141
- else delete prov.noVisionModels;
151
+ for (const field of OAUTH_RECONCILE_FIELDS) {
152
+ if (JSON.stringify(prov[field]) === JSON.stringify(preset[field])) continue;
153
+ if (preset[field] !== undefined) {
154
+ prov[field] = cloneProviderField(preset[field]) as never;
155
+ } else {
156
+ delete prov[field];
157
+ }
142
158
  changed = true;
143
159
  }
144
160
  // Heal a defaultModel that no longer exists in the refreshed list (e.g. a deprecated snapshot).
@@ -20,8 +20,17 @@ export interface KeyLoginProvider {
20
20
  * accept a reasoning param. Copied into the created provider config by `enrichProviderFromCatalog`,
21
21
  * so the classification actually gates the sidecars (matching is tolerant of an Ollama ":size" tag).
22
22
  */
23
+ reasoningEfforts?: string[];
24
+ modelReasoningEfforts?: Record<string, string[]>;
25
+ reasoningEffortMap?: Record<string, string>;
26
+ modelReasoningEffortMap?: Record<string, Record<string, string>>;
23
27
  noVisionModels?: string[];
24
28
  noReasoningModels?: string[];
29
+ noTemperatureModels?: string[];
30
+ noTopPModels?: string[];
31
+ noPenaltyModels?: string[];
32
+ autoToolChoiceOnlyModels?: string[];
33
+ preserveReasoningContentModels?: string[];
25
34
  }
26
35
 
27
36
  export const KEY_LOGIN_PROVIDERS: Record<string, KeyLoginProvider> = deriveKeyLoginMap();
@@ -37,8 +46,26 @@ export function enrichProviderFromCatalog(name: string, prov: OcxProviderConfig)
37
46
  if (!e) return;
38
47
  if (!prov.models && e.models) prov.models = [...e.models];
39
48
  if (!prov.defaultModel && e.defaultModel) prov.defaultModel = e.defaultModel;
49
+ if (!prov.reasoningEfforts && e.reasoningEfforts) prov.reasoningEfforts = [...e.reasoningEfforts];
50
+ if (!prov.modelReasoningEfforts && e.modelReasoningEfforts) prov.modelReasoningEfforts = cloneRecordOfArrays(e.modelReasoningEfforts);
51
+ if (!prov.reasoningEffortMap && e.reasoningEffortMap) prov.reasoningEffortMap = { ...e.reasoningEffortMap };
52
+ if (!prov.modelReasoningEffortMap && e.modelReasoningEffortMap) prov.modelReasoningEffortMap = cloneNestedRecord(e.modelReasoningEffortMap);
40
53
  if (!prov.noVisionModels && e.noVisionModels) prov.noVisionModels = [...e.noVisionModels];
41
54
  if (!prov.noReasoningModels && e.noReasoningModels) prov.noReasoningModels = [...e.noReasoningModels];
55
+ if (!prov.noTemperatureModels && e.noTemperatureModels) prov.noTemperatureModels = [...e.noTemperatureModels];
56
+ if (!prov.noTopPModels && e.noTopPModels) prov.noTopPModels = [...e.noTopPModels];
57
+ if (!prov.noPenaltyModels && e.noPenaltyModels) prov.noPenaltyModels = [...e.noPenaltyModels];
58
+ if (!prov.autoToolChoiceOnlyModels && e.autoToolChoiceOnlyModels) prov.autoToolChoiceOnlyModels = [...e.autoToolChoiceOnlyModels];
59
+ if (!prov.preserveReasoningContentModels && e.preserveReasoningContentModels) prov.preserveReasoningContentModels = [...e.preserveReasoningContentModels];
60
+ }
61
+
62
+
63
+ function cloneRecordOfArrays(input: Record<string, string[]>): Record<string, string[]> {
64
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, [...value]]));
65
+ }
66
+
67
+ function cloneNestedRecord(input: Record<string, Record<string, string>>): Record<string, Record<string, string>> {
68
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, { ...value }]));
42
69
  }
43
70
 
44
71
  export function isKeyLoginProvider(name: string): boolean {