codex-grok-bridge 1.8.4 → 1.8.6

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,133 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { existsSync } from "node:fs";
4
+ import { mkdtemp, mkdir, writeFile, readFile, readdir, rm } from "node:fs/promises";
5
+ import { randomUUID } from "node:crypto";
6
+ import { tmpdir } from "node:os";
7
+ import path from "node:path";
8
+ import assert from "node:assert/strict";
9
+ import { once } from "node:events";
10
+ import { fileURLToPath } from "node:url";
11
+ import { resolveCodexBinary } from "../src/paths.mjs";
12
+
13
+ async function readRolloutTree(dir) {
14
+ const chunks = [];
15
+ async function walk(current) {
16
+ let entries;
17
+ try {
18
+ entries = await readdir(current, { withFileTypes: true });
19
+ } catch {
20
+ return;
21
+ }
22
+ for (const entry of entries) {
23
+ const full = path.join(current, entry.name);
24
+ if (entry.isDirectory()) await walk(full);
25
+ else if (entry.name.endsWith(".jsonl")) chunks.push(await readFile(full, "utf8"));
26
+ }
27
+ }
28
+ await walk(dir);
29
+ return chunks.join("\n");
30
+ }
31
+
32
+ const bundledCodex = resolveCodexBinary();
33
+ if (!existsSync(bundledCodex)) {
34
+ console.error(`verify:app-server skipped: bundled Codex CLI not found at ${bundledCodex}`);
35
+ console.error("Set CODEX_BINARY, or install Codex (macOS /Applications/Codex.app, Linux /usr/lib/chatgpt/resources/codex, Windows store pointer).");
36
+ process.exit(2);
37
+ }
38
+
39
+ const home = await mkdtemp(path.join(tmpdir(), "codex-provider-verifier-"));
40
+ const child = spawn(
41
+ process.execPath,
42
+ [fileURLToPath(new URL("./codex-wrapper.mjs", import.meta.url)), "app-server"],
43
+ { stdio: ["pipe", "pipe", "ignore"], env: { ...process.env, CODEX_HOME: home } },
44
+ );
45
+ const exited = once(child, "close");
46
+ const pending = new Map();
47
+ let counter = 0;
48
+ const lines = createInterface({ input: child.stdout });
49
+ lines.on("line", (line) => {
50
+ const m = JSON.parse(line);
51
+ if (pending.has(m.id)) {
52
+ pending.get(m.id)(m);
53
+ pending.delete(m.id);
54
+ }
55
+ });
56
+ const request = (method, params) =>
57
+ new Promise((resolve, reject) => {
58
+ const id = ++counter;
59
+ const timer = setTimeout(() => {
60
+ pending.delete(id);
61
+ reject(Error("RPC timeout: " + method));
62
+ }, 30000);
63
+ pending.set(id, (msg) => {
64
+ clearTimeout(timer);
65
+ msg.error ? reject(Error(msg.error.message)) : resolve(msg.result);
66
+ });
67
+ child.stdin.write(JSON.stringify({ id, method, params }) + "\n");
68
+ });
69
+ try {
70
+ await request("initialize", {
71
+ clientInfo: { name: "grok-bridge-verifier", version: "0.2.0" },
72
+ capabilities: { experimentalApi: true },
73
+ });
74
+ child.stdin.write(JSON.stringify({ method: "initialized" }) + "\n");
75
+ const models = await request("model/list", { limit: 100 });
76
+ assert.ok(models.data.some((m) => m.id === "grok-4.7"));
77
+ assert.ok(models.data.some((m) => m.id === "grok-4.6"));
78
+ const gpt = models.data.find((m) => m.id.startsWith("gpt"));
79
+ assert.ok(gpt);
80
+ const threadId = randomUUID();
81
+ const timestamp = new Date().toISOString();
82
+ const sessions = path.join(home, "sessions");
83
+ await mkdir(sessions);
84
+ const rollout = path.join(sessions, `rollout-${timestamp.slice(0, 19).replaceAll(":", "-")}-${threadId}.jsonl`);
85
+ const fixture = [
86
+ { type: "session_meta", payload: { id: threadId, timestamp, cwd: process.cwd(), originator: "provider-verifier", cli_version: "0.153.4", model_provider: "openai", source: "cli" } },
87
+ { type: "response_item", payload: { type: "message", role: "user", content: [{ type: "input_text", text: "Keep this verification history." }] } },
88
+ { type: "response_item", payload: { type: "message", role: "assistant", content: [{ type: "output_text", text: "History fixture; no inference was executed." }] } },
89
+ ].map((item) => JSON.stringify({ timestamp, ...item }) + "\n").join("");
90
+ await writeFile(rollout, fixture, { mode: 0o600 });
91
+ const original = await request("thread/resume", {
92
+ threadId,
93
+ path: rollout,
94
+ model: gpt.model,
95
+ modelProvider: "openai",
96
+ cwd: process.cwd(),
97
+ sandbox: "read-only",
98
+ approvalPolicy: "on-request",
99
+ });
100
+ const transitions = [];
101
+ for (const [model, provider] of [["grok-4.7", "grok_build_cli"], ["grok-4.6", "grok_build_cli"], [gpt.model, "openai"]]) {
102
+ await request("thread/settings/update", { threadId, model });
103
+ const resumed = await request("thread/resume", { threadId, excludeTurns: true });
104
+ assert.equal(resumed.thread.id, threadId);
105
+ assert.equal(resumed.modelProvider, provider);
106
+ assert.equal(resumed.model, model);
107
+ assert.equal(resumed.approvalPolicy, original.approvalPolicy);
108
+ assert.deepEqual(resumed.sandbox, original.sandbox);
109
+ transitions.push({ model: resumed.model, provider: resumed.modelProvider });
110
+ }
111
+ const savedRollout = await readRolloutTree(home);
112
+ assert.match(savedRollout, /Keep this verification history/);
113
+ assert.match(savedRollout, /History fixture; no inference was executed/);
114
+ console.log(JSON.stringify({
115
+ models: models.data.map((m) => m.id),
116
+ transitions,
117
+ sameThread: true,
118
+ permissionsPreserved: true,
119
+ inferenceExecuted: false,
120
+ }));
121
+ } finally {
122
+ child.stdin.end();
123
+ child.kill("SIGTERM");
124
+ const killer = new Promise((resolve) =>
125
+ setTimeout(() => {
126
+ child.kill("SIGKILL");
127
+ resolve();
128
+ }, 5000),
129
+ );
130
+ await Promise.race([exited, killer]);
131
+ lines.close();
132
+ await rm(home, { recursive: true, force: true });
133
+ }
package/src/bridge.mjs CHANGED
@@ -9,7 +9,18 @@ import {
9
9
  runGrok,
10
10
  } from "./cli-inference.mjs";
11
11
  import { emitProxySse, readRelayProxySse } from "./proxy.mjs";
12
- import { videoCallsFromParts, videoToolOutput } from "./videogen.mjs";
12
+ import {
13
+ addUsage,
14
+ applyVideoHandoff,
15
+ noteVideoHandoff,
16
+ ordinaryFunctionCalls,
17
+ retainedInputItems,
18
+ stampUsage,
19
+ stripVideoToolEvents,
20
+ usageFromParts,
21
+ videoCallsFromParts,
22
+ videoToolOutput,
23
+ } from "./videogen.mjs";
13
24
  import { forwardImagine } from "./imagine.mjs";
14
25
  import { attachSidebandUpgrade, forwardRealtime } from "./realtime.mjs";
15
26
  import {
@@ -37,37 +48,67 @@ export { MODEL_INFO };
37
48
  const VIDEO_FOLLOW_UPS = 2;
38
49
 
39
50
  async function relayWithVideo(options, output, map, usageBox, onClientByte) {
40
- let body = options.body;
51
+ const handoffKey = options.sessionId || options.convId || "default";
52
+ let body = {
53
+ ...options.body,
54
+ input: applyVideoHandoff(handoffKey, options.body?.input),
55
+ };
56
+ let totalUsage = {};
41
57
  for (let step = 0; step <= VIDEO_FOLLOW_UPS; step += 1) {
42
58
  const parts = await readRelayProxySse({ ...options, body }, output);
59
+ totalUsage = addUsage(totalUsage, usageFromParts(parts));
43
60
  const calls =
44
61
  process.env.GROK_BRIDGE_VIDEO_GEN === "off" ? [] : videoCallsFromParts(parts);
45
62
  if (!calls.length || step === VIDEO_FOLLOW_UPS) {
46
- await emitProxySse(parts, output, map, usageBox, onClientByte);
63
+ const visible = calls.length ? stripVideoToolEvents(parts) : parts;
64
+ await emitProxySse(stampUsage(visible, totalUsage), output, map, usageBox, onClientByte);
47
65
  return;
48
66
  }
49
67
  // The videos API poll can sit for minutes. Keepalive is safe here: this
50
68
  // upstream reply is finished, and nothing has been written to Codex yet.
51
69
  onClientByte();
52
- const additions = [];
70
+ const videos = [];
53
71
  for (const call of calls) {
54
- const toolOutput = await videoToolOutput(call, options.video);
55
- additions.push(
72
+ videos.push({
73
+ name: call.name,
74
+ call_id: call.call_id,
75
+ arguments: call.arguments,
76
+ output: await videoToolOutput(call, options.video),
77
+ });
78
+ }
79
+ const ordinary = ordinaryFunctionCalls(parts);
80
+ if (ordinary.length) {
81
+ noteVideoHandoff(handoffKey, {
82
+ waiting: ordinary.map((call) => call.call_id).filter(Boolean),
83
+ videos,
84
+ });
85
+ await emitProxySse(
86
+ stampUsage(stripVideoToolEvents(parts), totalUsage),
87
+ output,
88
+ map,
89
+ usageBox,
90
+ onClientByte,
91
+ );
92
+ return;
93
+ }
94
+ const additions = [
95
+ ...retainedInputItems(parts),
96
+ ...videos.flatMap((video) => [
56
97
  {
57
98
  type: "function_call",
58
- name: call.name,
59
- call_id: call.call_id,
60
- arguments: call.arguments,
99
+ name: video.name,
100
+ call_id: video.call_id,
101
+ arguments: video.arguments,
61
102
  },
62
103
  {
63
104
  type: "function_call_output",
64
- name: call.name,
65
- call_id: call.call_id,
66
- output: toolOutput,
105
+ name: video.name,
106
+ call_id: video.call_id,
107
+ output: video.output,
67
108
  },
68
- );
69
- }
70
- body = { ...body, input: [...body.input, ...additions] };
109
+ ]),
110
+ ];
111
+ body = { ...body, input: [...(body.input ?? []), ...additions] };
71
112
  }
72
113
  }
73
114
 
@@ -312,6 +353,7 @@ export function createBridgeServer(options = {}) {
312
353
  let acquired = false;
313
354
  let queuedMs = 0;
314
355
  let cacheUsage = null;
356
+ const usageBox = {};
315
357
  try {
316
358
  await slots.acquire(controller.signal);
317
359
  acquired = true;
@@ -363,7 +405,6 @@ export function createBridgeServer(options = {}) {
363
405
  const { request, map, projected } = toProxyRequest(sanitizeImages(body));
364
406
  if (convId) request.prompt_cache_key = convId;
365
407
  request.input = prefixes.reuse(convId, projected);
366
- const usageBox = {};
367
408
  try {
368
409
  await relayWithVideo(
369
410
  {
@@ -403,7 +444,8 @@ export function createBridgeServer(options = {}) {
403
444
  }
404
445
  }
405
446
  diagnostics.record({
406
- event: "turn_ok",
447
+ event: usageBox.upstreamFailed ? "turn_failed" : "turn_ok",
448
+ ...(usageBox.upstreamFailed ? { kind: "upstream_status" } : {}),
407
449
  ...shape,
408
450
  ...(cacheUsage ?? {}),
409
451
  queuedMs,
@@ -11,7 +11,7 @@ export const MAX_LOG_BYTES = 4 * 1024 * 1024;
11
11
  // Values that must never reach disk, matched structurally rather than by name,
12
12
  // because the field a token arrives in is not stable.
13
13
  const SECRET_PATTERNS = [
14
- [/Bearer\s+[A-Za-z0-9._~+/-]+=*/g, "Bearer [redacted]"],
14
+ [/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi, "Bearer [redacted]"],
15
15
  [/eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g, "[jwt]"],
16
16
  [/sk-[A-Za-z0-9_-]{16,}/g, "[key]"],
17
17
  [/xai-[A-Za-z0-9_-]{16,}/g, "[key]"],
package/src/errors.mjs CHANGED
@@ -29,6 +29,7 @@ const MESSAGES = Object.freeze({
29
29
  "Grok closed the connection before finishing. Retry.",
30
30
  [BRIDGE_ERROR.UPSTREAM_PROTOCOL]:
31
31
  "Grok sent a malformed response. Retry.",
32
+ [BRIDGE_ERROR.UPSTREAM_STATUS]: "Grok returned an error status. Retry.",
32
33
  [BRIDGE_ERROR.PAYLOAD]: "Grok rejected the request payload",
33
34
  [BRIDGE_ERROR.INTERNAL]: "Grok bridge failed to process the turn",
34
35
  });
@@ -62,6 +63,11 @@ function* chain(error, depth = 0) {
62
63
  export function classifyBridgeError(error, context = {}) {
63
64
  for (const link of chain(error)) {
64
65
  const code = typeof link.code === "string" ? link.code : "";
66
+ if (link.name === "GrokAuthError") return BRIDGE_ERROR.AUTH;
67
+ const status = Number(link.status);
68
+ if (status === 401 || status === 403) return BRIDGE_ERROR.AUTH;
69
+ if (status === 400 || status === 422) return BRIDGE_ERROR.PAYLOAD;
70
+ if (status === 429 || (status >= 500 && status <= 599)) return BRIDGE_ERROR.UPSTREAM_STATUS;
65
71
  if (link.name === "AbortError" || ABORT_CODES.has(code)) {
66
72
  // The bridge aborts the upstream only when the client hangs up, so an
67
73
  // abort-shaped error means the client left. If the bridge ever aborts for
package/src/imagegen.mjs CHANGED
@@ -15,15 +15,18 @@ export const DEFAULT_IMAGE_DIR = path.join(
15
15
  ".local/share/codex-grok-bridge/generated-images",
16
16
  );
17
17
 
18
- const SIGNATURES = [
19
- [Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), "png"],
20
- [Buffer.from([255, 216, 255]), "jpg"],
21
- [Buffer.from("RIFF", "ascii"), "webp"],
22
- ];
18
+ const PNG_MAGIC = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
23
19
 
24
20
  function extensionFor(bytes) {
25
- for (const [magic, extension] of SIGNATURES)
26
- if (bytes.subarray(0, magic.length).equals(magic)) return extension;
21
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_MAGIC)) return "png";
22
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255)
23
+ return "jpg";
24
+ if (
25
+ bytes.length >= 12 &&
26
+ bytes.toString("ascii", 0, 4) === "RIFF" &&
27
+ bytes.toString("ascii", 8, 12) === "WEBP"
28
+ )
29
+ return "webp";
27
30
  return "bin";
28
31
  }
29
32
 
@@ -62,7 +65,7 @@ export function saveGeneratedImage(item, options = {}) {
62
65
  * colour type: 4 is greyscale+alpha, 6 is RGBA.
63
66
  */
64
67
  export function hasAlphaChannel(bytes) {
65
- const isPng = bytes.subarray(0, 8).equals(SIGNATURES[0][0]);
68
+ const isPng = bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_MAGIC);
66
69
  if (!isPng || bytes.length < 26) return false;
67
70
  const colorType = bytes[25];
68
71
  return colorType === 4 || colorType === 6;
@@ -0,0 +1,367 @@
1
+ // Codex CLI 0.166+ rejects a turn when the thread provider differs from the
2
+ // app-server's configured provider (openai/codex#57840). The desktop wrapper
3
+ // keeps one app-server for both providers, so a switch has to make those two
4
+ // values match before resume or turn/start. The value lives in the user's
5
+ // config.toml for that process only; the baseline is restored on exit.
6
+
7
+ import { randomUUID } from "node:crypto";
8
+ import { constants, existsSync, openSync, closeSync, readFileSync, writeFileSync, mkdirSync, rmSync, statSync, unlinkSync } from "node:fs";
9
+ import { lstat, readFile, rename, rm, writeFile } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { rewriteRolloutProviderText } from "./rollout.mjs";
12
+
13
+ const STATE_DBS = ["state_5.sqlite", "state_4.sqlite"];
14
+
15
+ export function providerMarkerPath(codexHome) {
16
+ return path.join(codexHome, "grok-bridge-provider.json");
17
+ }
18
+
19
+ function processStartedAt(pid) {
20
+ try {
21
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
22
+ const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
23
+ return rest[19] || null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ const PROCESS_OWNER = {
30
+ pid: process.pid,
31
+ token: randomUUID(),
32
+ startedAt: processStartedAt(process.pid),
33
+ };
34
+ let ownerAliveForTests = null;
35
+
36
+ export function setOwnerAliveForTests(fn) {
37
+ ownerAliveForTests = fn;
38
+ }
39
+
40
+ function ownerKey(owner) {
41
+ return owner && Number.isInteger(owner.pid) ? `${owner.pid}:${owner.token ?? ""}` : "";
42
+ }
43
+
44
+ function ownerRecord(owner) {
45
+ const startedAt = owner.startedAt || processStartedAt(owner.pid);
46
+ return {
47
+ pid: owner.pid,
48
+ token: owner.token,
49
+ ...(startedAt ? { startedAt } : {}),
50
+ };
51
+ }
52
+
53
+ function ownerAlive(owner) {
54
+ if (!ownerKey(owner)) return false;
55
+ if (ownerAliveForTests) return ownerAliveForTests(owner);
56
+ if (owner.pid === PROCESS_OWNER.pid && owner.token === PROCESS_OWNER.token) return true;
57
+ const startedAt = processStartedAt(owner.pid);
58
+ if (owner.startedAt) return startedAt === owner.startedAt;
59
+ if (!startedAt) {
60
+ try {
61
+ process.kill(owner.pid, 0);
62
+ return true;
63
+ } catch (error) {
64
+ return error?.code === "EPERM";
65
+ }
66
+ }
67
+ return true;
68
+ }
69
+
70
+ function liveOwners(marker, except) {
71
+ const skip = ownerKey(except);
72
+ const seen = new Set();
73
+ const live = [];
74
+ for (const owner of marker?.owners ?? []) {
75
+ const key = ownerKey(owner);
76
+ if (!key || key === skip || seen.has(key) || !ownerAlive(owner)) continue;
77
+ seen.add(key);
78
+ live.push(ownerRecord(owner));
79
+ }
80
+ return live;
81
+ }
82
+
83
+ function readMarker(codexHome) {
84
+ const markerPath = providerMarkerPath(codexHome);
85
+ if (!existsSync(markerPath)) return null;
86
+ try {
87
+ const marker = JSON.parse(readFileSync(markerPath, "utf8"));
88
+ return marker && typeof marker === "object" ? marker : null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ function writeMarker(codexHome, marker) {
95
+ const markerPath = providerMarkerPath(codexHome);
96
+ const tmp = `${markerPath}.${process.pid}.${randomUUID()}.tmp`;
97
+ writeFileSync(tmp, `${JSON.stringify(marker)}\n`, { mode: 0o600 });
98
+ try {
99
+ rmSync(markerPath, { force: true });
100
+ const fd = openSync(markerPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
101
+ try {
102
+ writeFileSync(fd, `${JSON.stringify(marker)}\n`);
103
+ } finally {
104
+ closeSync(fd);
105
+ }
106
+ } finally {
107
+ rmSync(tmp, { force: true });
108
+ }
109
+ }
110
+
111
+ function withProviderLock(codexHome, fn) {
112
+ mkdirSync(codexHome, { recursive: true, mode: 0o700 });
113
+ const lockPath = path.join(codexHome, "grok-bridge-provider.lock");
114
+ const started = Date.now();
115
+ let fd;
116
+ for (;;) {
117
+ try {
118
+ fd = openSync(lockPath, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR, 0o600);
119
+ break;
120
+ } catch (error) {
121
+ if (error?.code !== "EEXIST") throw error;
122
+ try {
123
+ if (Date.now() - statSync(lockPath).mtimeMs > 2_000) unlinkSync(lockPath);
124
+ } catch {
125
+ // The holder removed it between the stat and the unlink.
126
+ }
127
+ if (Date.now() - started > 5_000) throw new Error("provider baseline lock timed out");
128
+ const until = Date.now() + 15;
129
+ while (Date.now() < until) {
130
+ // The critical section is synchronous, so the wait has to be too.
131
+ }
132
+ }
133
+ }
134
+ try {
135
+ return fn();
136
+ } finally {
137
+ closeSync(fd);
138
+ try {
139
+ unlinkSync(lockPath);
140
+ } catch {
141
+ // A stale-lock recovery may already have removed it.
142
+ }
143
+ }
144
+ }
145
+
146
+ export function readModelProvider(text) {
147
+ let inTable = false;
148
+ for (const line of String(text ?? "").split(/\r?\n/)) {
149
+ if (/^\s*\[/.test(line)) inTable = true;
150
+ if (inTable) continue;
151
+ const match = line.match(/^\s*model_provider\s*=\s*(.*?)\s*(?:#.*)?$/);
152
+ if (!match) continue;
153
+ return unquoteToml(match[1].trim());
154
+ }
155
+ return null;
156
+ }
157
+
158
+ function unquoteToml(value) {
159
+ if (
160
+ (value.startsWith('"') && value.endsWith('"')) ||
161
+ (value.startsWith("'") && value.endsWith("'"))
162
+ ) {
163
+ return value
164
+ .slice(1, -1)
165
+ .replace(/\\n/g, "\n")
166
+ .replace(/\\"/g, '"')
167
+ .replace(/\\'/g, "'")
168
+ .replace(/\\\\/g, "\\");
169
+ }
170
+ return value;
171
+ }
172
+
173
+ export function renderModelProvider(text, provider) {
174
+ const source = String(text ?? "");
175
+ const lines = source.split(/\r?\n/);
176
+ if (lines.at(-1) === "") lines.pop();
177
+ let inTable = false;
178
+ let replaced = false;
179
+ const out = [];
180
+ for (const line of lines) {
181
+ if (/^\s*\[/.test(line)) inTable = true;
182
+ if (!inTable && /^\s*model_provider\s*=/.test(line)) {
183
+ replaced = true;
184
+ if (provider != null) out.push(`model_provider = ${JSON.stringify(provider)}`);
185
+ continue;
186
+ }
187
+ out.push(line);
188
+ }
189
+ if (!replaced && provider != null) {
190
+ let insertAt = 0;
191
+ while (
192
+ insertAt < out.length &&
193
+ (/^\s*$/.test(out[insertAt]) || /^\s*#/.test(out[insertAt]))
194
+ ) {
195
+ insertAt += 1;
196
+ }
197
+ out.splice(insertAt, 0, `model_provider = ${JSON.stringify(provider)}`);
198
+ }
199
+ if (out.length === 0) return "";
200
+ return `${out.join("\n")}\n`;
201
+ }
202
+
203
+ function configPath(codexHome) {
204
+ return path.join(codexHome, "config.toml");
205
+ }
206
+
207
+ export function alignConfiguredProvider(codexHome, provider) {
208
+ if (!codexHome || !provider) return false;
209
+ const file = configPath(codexHome);
210
+ const text = existsSync(file) ? readFileSync(file, "utf8") : "";
211
+ if (readModelProvider(text) === provider) return false;
212
+ const next = renderModelProvider(text, provider);
213
+ mkdirSync(codexHome, { recursive: true, mode: 0o700 });
214
+ writeFileSync(file, next, { mode: 0o600 });
215
+ return true;
216
+ }
217
+
218
+ export function applyModelProvider(codexHome, provider) {
219
+ const file = configPath(codexHome);
220
+ const exists = existsSync(file);
221
+ const text = exists ? readFileSync(file, "utf8") : "";
222
+ const next = renderModelProvider(text, provider);
223
+ if (next === text) return false;
224
+ if (!next && !exists) return false;
225
+ if (!next) {
226
+ rmSync(file, { force: true });
227
+ return true;
228
+ }
229
+ mkdirSync(codexHome, { recursive: true, mode: 0o700 });
230
+ writeFileSync(file, next, exists ? undefined : { mode: 0o600 });
231
+ return true;
232
+ }
233
+
234
+ export function captureProviderBaseline(codexHome, owner = PROCESS_OWNER) {
235
+ return withProviderLock(codexHome, () => {
236
+ const marker = readMarker(codexHome);
237
+ const trusted = marker?.codexHome === codexHome ? marker : null;
238
+ const others = liveOwners(trusted, owner);
239
+ if (others.length) {
240
+ writeMarker(codexHome, {
241
+ codexHome,
242
+ original: trusted.original ?? null,
243
+ owners: [...others, ownerRecord(owner)],
244
+ });
245
+ return trusted.original ?? null;
246
+ }
247
+ if (trusted) applyModelProvider(codexHome, trusted.original ?? null);
248
+ const file = configPath(codexHome);
249
+ const original = existsSync(file) ? readModelProvider(readFileSync(file, "utf8")) : null;
250
+ writeMarker(codexHome, {
251
+ codexHome,
252
+ original,
253
+ owners: [ownerRecord(owner)],
254
+ });
255
+ return original;
256
+ });
257
+ }
258
+
259
+ export function restoreProviderBaseline(codexHome, owner = PROCESS_OWNER) {
260
+ return withProviderLock(codexHome, () => {
261
+ const markerPath = providerMarkerPath(codexHome);
262
+ if (!existsSync(markerPath)) return false;
263
+ const marker = readMarker(codexHome);
264
+ if (!marker || marker.codexHome !== codexHome) {
265
+ rmSync(markerPath, { force: true });
266
+ return true;
267
+ }
268
+ const others = liveOwners(marker, owner);
269
+ if (others.length) {
270
+ writeMarker(codexHome, { ...marker, owners: others });
271
+ return true;
272
+ }
273
+ applyModelProvider(codexHome, marker.original ?? null);
274
+ rmSync(markerPath, { force: true });
275
+ return true;
276
+ });
277
+ }
278
+
279
+ async function updateStateDb(file, threadId, provider, model) {
280
+ let DatabaseSync;
281
+ try {
282
+ ({ DatabaseSync } = await import("node:sqlite"));
283
+ } catch {
284
+ return null;
285
+ }
286
+ let db;
287
+ try {
288
+ db = new DatabaseSync(file, { timeout: 3000 });
289
+ let row;
290
+ try {
291
+ row = db.prepare("SELECT model_provider, rollout_path FROM threads WHERE id = ?").get(threadId);
292
+ } catch {
293
+ row = db.prepare("SELECT model_provider FROM threads WHERE id = ?").get(threadId);
294
+ }
295
+ if (!row) return null;
296
+ if (model != null) {
297
+ try {
298
+ db.prepare("UPDATE threads SET model_provider = ?, model = ? WHERE id = ?").run(
299
+ provider,
300
+ model,
301
+ threadId,
302
+ );
303
+ } catch {
304
+ db.prepare("UPDATE threads SET model_provider = ? WHERE id = ?").run(provider, threadId);
305
+ }
306
+ } else if (row.model_provider !== provider) {
307
+ db.prepare("UPDATE threads SET model_provider = ? WHERE id = ?").run(provider, threadId);
308
+ }
309
+ return row;
310
+ } catch {
311
+ return null;
312
+ } finally {
313
+ try {
314
+ db?.close();
315
+ } catch {
316
+ // The resume path still has the rollout fallback.
317
+ }
318
+ }
319
+ }
320
+
321
+ export async function rewriteSavedModelProvider({
322
+ codexHome,
323
+ threadId,
324
+ rolloutPath,
325
+ provider,
326
+ model,
327
+ }) {
328
+ if (!provider || !threadId) return false;
329
+ let savedPath = rolloutPath;
330
+ let updated = false;
331
+ if (codexHome) {
332
+ for (const name of STATE_DBS) {
333
+ const file = path.join(codexHome, name);
334
+ if (!existsSync(file)) continue;
335
+ const row = await updateStateDb(file, threadId, provider, model);
336
+ if (row) {
337
+ updated = true;
338
+ savedPath = savedPath || row.rollout_path;
339
+ }
340
+ }
341
+ }
342
+ if (savedPath && (await rewriteRolloutModelProvider(savedPath, provider, model))) updated = true;
343
+ return updated;
344
+ }
345
+
346
+ export async function rewriteRolloutModelProvider(file, provider, model) {
347
+ if (typeof file !== "string" || !file || !provider) return false;
348
+ let info;
349
+ try {
350
+ info = await lstat(file);
351
+ } catch {
352
+ return false;
353
+ }
354
+ if (!info.isFile()) return false;
355
+ const first = await readFile(file);
356
+ const next = rewriteRolloutProviderText(first.toString("utf8"), provider, model);
357
+ if (next === first.toString("utf8")) return true;
358
+ const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`;
359
+ await writeFile(tmp, next, { mode: info.mode & 0o777 });
360
+ const again = await readFile(file);
361
+ if (!again.equals(first)) {
362
+ await rm(tmp, { force: true });
363
+ return false;
364
+ }
365
+ await rename(tmp, file);
366
+ return true;
367
+ }