Skip to content

Commit 5f35121

Browse files
author
jun
committed
fix(codex): inject experimental_realtime_ws_base_url so desktop voice sideband joins through the proxy
Since openai/codex 438c9e98d (#35830) the WebRTC voice sideband dials https://api.openai.com/v1/live/{callId} directly with the app's own login, while the call was created through the proxy under a Pool account. Two accounts, one call: the join returns 404 ("realtime websocket handshake failed"). Design B injection now writes a marker-owned root experimental_realtime_ws_base_url with the same loopback value as openai_base_url; the key is journaled on its own so a user-owned override that equals the proxy URL is never stripped, and an app-reserialized config (comments dropped) is still recognized as ours on re-inject and restore.
1 parent e6a7375 commit 5f35121

5 files changed

Lines changed: 322 additions & 9 deletions

File tree

‎src/codex/inject.ts‎

Lines changed: 104 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
import {
3333
markJournalInjectedState,
3434
journaledInjectedOpenaiBaseUrl,
35+
journaledInjectedRealtimeWsBaseUrl,
3536
journaledInjectedCatalogPath,
3637
removeJournal,
3738
restoreJournalState,
@@ -49,9 +50,11 @@ import {
4950
} from "./history-job";
5051
import {
5152
OCX_SECTION_MARKER,
53+
REALTIME_WS_BASE_URL_KEY,
5254
hasInjectedCodexRouting,
5355
hasInjectedOpenaiBaseUrl,
5456
isRootOpenaiBaseUrlLine,
57+
isRootRealtimeWsBaseUrlLine,
5558
providerTableStart,
5659
providerTableString,
5760
rootTomlString,
@@ -346,6 +349,20 @@ function buildOpenaiBaseUrlLineForTarget(target: CodexRoutingTarget): string {
346349
return `openai_base_url = ${tomlString(target.baseUrl)}`;
347350
}
348351

352+
/**
353+
* Realtime sideband override (codex-rs `experimental_realtime_ws_base_url`), written with the
354+
* SAME value as `openai_base_url`. Desktop voice creates its WebRTC call through the proxy
355+
* (`POST /v1/live`, answered under the Pool account the proxy selects) but, since openai/codex
356+
* 438c9e98d (#35830), joins the sideband at `wss://api.openai.com/v1/live/{callId}` with the
357+
* app's own login unless this key redirects it. Two accounts, one call: the join 404s. Pointing
358+
* the key at the proxy sends the join through `GET /v1/live/{callId}` (src/server/live.ts),
359+
* where the same Pool account is reused. codex-rs turns `http` into `ws` and appends
360+
* `/live/{callId}` itself; the value must stay the canonical `/v1` root.
361+
*/
362+
export function buildRealtimeWsBaseUrlLine(target: CodexRoutingTarget): string {
363+
return `${REALTIME_WS_BASE_URL_KEY} = ${tomlString(target.baseUrl)}`;
364+
}
365+
349366
/**
350367
* Design B root-key injection: place `OCX_SECTION_MARKER` + `openai_base_url` at the document
351368
* ROOT (before the first table header). Idempotent: an existing marker-owned line is rewritten
@@ -427,10 +444,56 @@ function setRootOpenaiBaseUrlForTarget(
427444
return { content: lines.join("\n"), keptUserBaseUrl: false };
428445
}
429446

447+
/**
448+
* True when line `index` is inside the marker-owned root block: the line right after the
449+
* marker, or the line right after a marker-owned `openai_base_url`. One marker owns both
450+
* routing keys so the "exactly one marker" invariant the rest of injection relies on holds.
451+
*/
452+
function markerOwnedRootLine(lines: string[], index: number): boolean {
453+
if (index > 0 && lines[index - 1].includes(OCX_SECTION_MARKER)) return true;
454+
return index > 1
455+
&& isRootOpenaiBaseUrlLine(lines[index - 1])
456+
&& lines[index - 2].includes(OCX_SECTION_MARKER);
457+
}
458+
459+
/**
460+
* Companion to `setRootOpenaiBaseUrlForTarget` for the realtime sideband override. Same
461+
* ownership rule: a marker-owned line is rewritten in place, a user's own line (not in the
462+
* marker block) is kept and nothing is injected. Placement: directly after the marker-owned
463+
* `openai_base_url` so the marker owns both keys as one block. Only ever called on the
464+
* Design B (loopback) path right after the routing override was written — the legacy
465+
* provider-table form needs the admission-token header, which the sideband cannot carry.
466+
*/
467+
export function setRootRealtimeWsBaseUrl(
468+
content: string,
469+
target: CodexRoutingTarget,
470+
): { content: string; keptUserRealtimeWsBaseUrl: boolean } {
471+
const lines = content.split("\n");
472+
const firstTable = lines.findIndex((line) => /^\s*\[/.test(line));
473+
const rootEnd = firstTable === -1 ? lines.length : firstTable;
474+
const key = buildRealtimeWsBaseUrlLine(validateCodexRoutingTarget(target));
475+
for (let index = 0; index < rootEnd; index += 1) {
476+
if (!isRootRealtimeWsBaseUrlLine(lines[index])) continue;
477+
if (!markerOwnedRootLine(lines, index)) return { content, keptUserRealtimeWsBaseUrl: true };
478+
lines[index] = key;
479+
return { content: lines.join("\n"), keptUserRealtimeWsBaseUrl: false };
480+
}
481+
for (let index = 0; index < rootEnd; index += 1) {
482+
if (!isRootOpenaiBaseUrlLine(lines[index])) continue;
483+
if (!(index > 0 && lines[index - 1].includes(OCX_SECTION_MARKER))) continue;
484+
lines.splice(index + 1, 0, key);
485+
return { content: lines.join("\n"), keptUserRealtimeWsBaseUrl: false };
486+
}
487+
// No marker-owned routing override to attach to: the override has no owner, so inject nothing.
488+
return { content, keptUserRealtimeWsBaseUrl: false };
489+
}
490+
430491
/**
431492
* Remove the marker-owned root `openai_base_url` (marker line + the key line right after it).
432493
* A user's own root override (no marker) survives; an orphaned marker with no key line after
433494
* it is dropped too so repeated strip/inject cycles cannot accumulate marker comments.
495+
* The `experimental_realtime_ws_base_url` companion directly under that pair is part of the
496+
* same owned block and goes with it.
434497
*/
435498
export function stripInjectedOpenaiBaseUrl(content: string): string {
436499
const lines = content.split("\n");
@@ -442,6 +505,7 @@ export function stripInjectedOpenaiBaseUrl(content: string): string {
442505
if (i + 1 < rootEnd && isRootOpenaiBaseUrlLine(lines[i + 1])) {
443506
drop.add(i);
444507
drop.add(i + 1);
508+
if (i + 2 < rootEnd && isRootRealtimeWsBaseUrlLine(lines[i + 2])) drop.add(i + 2);
445509
} else if (i + 1 >= rootEnd || lines[i + 1].trim() === "") {
446510
drop.add(i); // orphaned marker at root
447511
}
@@ -959,6 +1023,7 @@ export async function injectCodexConfig(
9591023
// Provider-table form: non-loopback admission (legacy) or the authless Desktop opt-in (#1107).
9601024
const legacyMode = usesProviderTable(routingTarget);
9611025
let keptUserBaseUrl = false;
1026+
let keptUserRealtimeWsBaseUrl = false;
9621027
if (legacyMode) {
9631028
// Legacy (non-loopback) injection: the built-in openai provider cannot carry the
9641029
// x-opencodex-api-key env header, so keep the opencodex provider table + root re-tag.
@@ -975,9 +1040,24 @@ export async function injectCodexConfig(
9751040
// Design B (loopback): a single root override; codex keeps its native `openai` provider id
9761041
// so thread history is never remapped. Any legacy form was already stripped above.
9771042
content = stripInjectedOpenaiBaseUrl(content); // normalize before idempotent re-insert
1043+
// #1798: after a Codex app rewrite the marker is gone but the values we recorded writing
1044+
// are still ours. Consume them by value so re-inject does not mistake our own routing
1045+
// for a user override (and then journal it as not-ours, making it unrestorable).
1046+
content = stripJournaledOpenaiBaseUrl(
1047+
content,
1048+
journaledInjectedOpenaiBaseUrl(),
1049+
journaledInjectedRealtimeWsBaseUrl(),
1050+
);
9781051
const result = setRootOpenaiBaseUrlForTarget(content, routingTarget);
9791052
content = result.content;
9801053
keptUserBaseUrl = result.keptUserBaseUrl;
1054+
// Voice sideband override rides on the routing override: same value, same ownership rule,
1055+
// and never when the user owns the routing line (we inject nothing in that case).
1056+
if (!keptUserBaseUrl) {
1057+
const realtime = setRootRealtimeWsBaseUrl(content, routingTarget);
1058+
content = realtime.content;
1059+
keptUserRealtimeWsBaseUrl = realtime.keptUserRealtimeWsBaseUrl;
1060+
}
9811061
}
9821062

9831063
const desiredSubagentDefaults = configuredManagedSubagentDefaults(config);
@@ -1091,8 +1171,18 @@ export async function injectCodexConfig(
10911171
}
10921172

10931173
const applyNativeArtifacts = (): void => {
1174+
// #1798 again: a Codex app rewrite keeps values and drops the ownership comments, so
1175+
// marker evidence alone would classify our own routed config as the user's native
1176+
// baseline and replace the real original snapshot. Value evidence from the journal
1177+
// (the URLs the last injection recorded writing) blocks that misclassification.
1178+
const journaledBaseUrl = journaledInjectedOpenaiBaseUrl();
1179+
const journaledRealtimeWsBaseUrl = journaledInjectedRealtimeWsBaseUrl();
1180+
const looksInjectedByValue =
1181+
(journaledBaseUrl !== null && rootTomlString(rawContent, "openai_base_url") === journaledBaseUrl)
1182+
|| (journaledRealtimeWsBaseUrl !== null
1183+
&& rootTomlString(rawContent, REALTIME_WS_BASE_URL_KEY) === journaledRealtimeWsBaseUrl);
10941184
writeJournal({
1095-
currentStateIsNative: !hasInjectedCodexRouting(rawContent),
1185+
currentStateIsNative: !hasInjectedCodexRouting(rawContent) && !looksInjectedByValue,
10961186
configContent: baselineContent,
10971187
owner: options.journalOwner,
10981188
});
@@ -1103,6 +1193,11 @@ export async function injectCodexConfig(
11031193
injectedOpenaiBaseUrl: legacyMode || keptUserBaseUrl
11041194
? null
11051195
: rootTomlString(content, "openai_base_url"),
1196+
// The sideband override is ours only when we wrote it this pass (never in legacy mode,
1197+
// never when the user owns either key).
1198+
injectedRealtimeWsBaseUrl: legacyMode || keptUserBaseUrl || keptUserRealtimeWsBaseUrl
1199+
? null
1200+
: rootTomlString(content, REALTIME_WS_BASE_URL_KEY),
11061201
// This is the catalog artifact selected for this injection, even when config.toml
11071202
// already points at that path and therefore needs no textual rewrite.
11081203
injectedCatalogPath: catalogPath,
@@ -1301,7 +1396,7 @@ export async function injectCodexConfig(
13011396
? `Injected opencodex as default provider into Codex config (authless Desktop mode: requires_openai_auth = false).\n`
13021397
: legacyMode
13031398
? `Injected opencodex as default provider into Codex config.\n`
1304-
: `Pointed Codex's built-in openai provider at the opencodex proxy (openai_base_url).\n`;
1399+
: `Pointed Codex's built-in openai provider at the opencodex proxy (openai_base_url + realtime sideband override).\n`;
13051400
return {
13061401
success: true,
13071402
...(nativeSubagentDefaultsWarning ? { nativeSubagentDefaultsWarning } : {}),
@@ -1388,6 +1483,7 @@ interface StripOpencodexConfigResult {
13881483
function stripOpencodexConfigResult(
13891484
content: string,
13901485
journaledBaseUrl: string | null = null,
1486+
journaledRealtimeWsBaseUrl: string | null = null,
13911487
): StripOpencodexConfigResult {
13921488
let out = content;
13931489
const hadRootOcxProvider =
@@ -1398,7 +1494,7 @@ function stripOpencodexConfigResult(
13981494
const hadInjectedBaseUrl = hasInjectedOpenaiBaseUrl(out)
13991495
|| (journaledBaseUrl !== null && rootTomlString(out, "openai_base_url") === journaledBaseUrl);
14001496
out = stripInjectedOpenaiBaseUrl(out); // before removeOcxSection — it keys on the marker line too
1401-
out = stripJournaledOpenaiBaseUrl(out, journaledBaseUrl);
1497+
out = stripJournaledOpenaiBaseUrl(out, journaledBaseUrl, journaledRealtimeWsBaseUrl);
14021498
if (hasOcxProviderTable(out)) {
14031499
out = removeOcxSection(out);
14041500
}
@@ -1453,9 +1549,12 @@ export function removeCodexConfig(
14531549
// Read the recorded injection once: the strip below consumes it, and so does the
14541550
// ownership verdict, which must agree with what was actually removed.
14551551
const journaledBaseUrl = journaledInjectedOpenaiBaseUrl();
1552+
const journaledRealtimeWsBaseUrl = journaledInjectedRealtimeWsBaseUrl();
14561553
const had = hasOpencodexRouting(content)
1457-
|| (journaledBaseUrl !== null && rootTomlString(content, "openai_base_url") === journaledBaseUrl);
1458-
const stripped = stripOpencodexConfigResult(content, journaledBaseUrl);
1554+
|| (journaledBaseUrl !== null && rootTomlString(content, "openai_base_url") === journaledBaseUrl)
1555+
|| (journaledRealtimeWsBaseUrl !== null
1556+
&& rootTomlString(content, REALTIME_WS_BASE_URL_KEY) === journaledRealtimeWsBaseUrl);
1557+
const stripped = stripOpencodexConfigResult(content, journaledBaseUrl, journaledRealtimeWsBaseUrl);
14591558
if (had || stripped.content !== content) {
14601559
atomicWriteFile(CODEX_CONFIG_PATH, applyEol(stripped.content, eol));
14611560
}

‎src/codex/injected-marker.ts‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,20 @@ export function isRootOpenaiBaseUrlLine(line: string): boolean {
1515
return /^\s*openai_base_url\s*=/.test(line);
1616
}
1717

18+
/**
19+
* codex-rs root key that redirects the realtime sideband WebSocket (WebRTC voice
20+
* join + standalone realtime WS) without touching ordinary provider HTTP. Since
21+
* openai/codex 438c9e98d (#35830) the sideband ignores the provider base URL and
22+
* dials `https://api.openai.com/v1` unless this key is set, so a Pool-routed
23+
* call-create and a directly-joined sideband end up on different accounts (404).
24+
* Injected next to `openai_base_url` with the same value.
25+
*/
26+
export const REALTIME_WS_BASE_URL_KEY = "experimental_realtime_ws_base_url";
27+
28+
export function isRootRealtimeWsBaseUrlLine(line: string): boolean {
29+
return /^\s*experimental_realtime_ws_base_url\s*=/.test(line);
30+
}
31+
1832
export function tomlStringPattern(key: string): RegExp {
1933
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2034
const keyToken = `(?:${escaped}|"${escaped}"|'${escaped}')`;
@@ -65,16 +79,28 @@ export function providerTableString(content: string, provider: string, key: stri
6579
* EXACT value match against what we recorded writing: a user gateway we never wrote
6680
* cannot match, so restore can never delete a URL that was not ours.
6781
*/
68-
export function stripJournaledOpenaiBaseUrl(content: string, injectedUrl: string | null): string {
69-
if (!injectedUrl) return content;
82+
export function stripJournaledOpenaiBaseUrl(
83+
content: string,
84+
injectedUrl: string | null,
85+
injectedRealtimeWsUrl: string | null = null,
86+
): string {
87+
if (!injectedUrl && !injectedRealtimeWsUrl) return content;
7088
const lines = content.split(String.fromCharCode(10));
7189
const firstTable = lines.findIndex(l => /^\s*\[/.test(l));
7290
const rootEnd = firstTable === -1 ? lines.length : firstTable;
7391
const drop = new Set<number>();
7492
for (let i = 0; i < rootEnd; i++) {
7593
const line = lines[i]!;
76-
if (!isRootOpenaiBaseUrlLine(line)) continue;
77-
if (rootTomlString(line, "openai_base_url") !== injectedUrl) continue;
94+
// Each key is matched against ITS OWN recorded value. The realtime override is
95+
// journaled separately so a user-owned override that happens to equal the proxy
96+
// URL is never mistaken for ours.
97+
if (isRootOpenaiBaseUrlLine(line)) {
98+
if (!injectedUrl || rootTomlString(line, "openai_base_url") !== injectedUrl) continue;
99+
} else if (isRootRealtimeWsBaseUrlLine(line)) {
100+
if (!injectedRealtimeWsUrl || rootTomlString(line, REALTIME_WS_BASE_URL_KEY) !== injectedRealtimeWsUrl) continue;
101+
} else {
102+
continue;
103+
}
78104
drop.add(i);
79105
// Take an ownership marker directly above it too, so repeated cycles cannot
80106
// accumulate orphaned comments.

‎src/codex/journal.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ interface Journal {
3535
* and it is what lets restore tell OUR loopback URL apart from a gateway the user set.
3636
*/
3737
injectedOpenaiBaseUrl?: string | null;
38+
/**
39+
* The root `experimental_realtime_ws_base_url` this injection wrote, when it wrote one.
40+
* Recorded on its own rather than inferred from `injectedOpenaiBaseUrl`: a user can own a
41+
* realtime override whose value happens to equal the proxy URL, and restore must not treat
42+
* that as ours. Null when the key was preserved or not injected.
43+
*/
44+
injectedRealtimeWsBaseUrl?: string | null;
3845
/**
3946
* The catalog path this injection actually wrote to.
4047
*
@@ -119,6 +126,7 @@ export function writeJournal(options: WriteJournalOptions = {}): void {
119126

120127
export interface InjectedJournalOwnership {
121128
injectedOpenaiBaseUrl: string | null;
129+
injectedRealtimeWsBaseUrl: string | null;
122130
injectedCatalogPath: string | null;
123131
}
124132

@@ -140,6 +148,7 @@ export function markJournalInjectedState(
140148
// Only the caller knows which values it actually owns. Deriving these from the final TOML
141149
// would mistake a preserved user override for injected routing.
142150
journal.injectedOpenaiBaseUrl = ownership.injectedOpenaiBaseUrl;
151+
journal.injectedRealtimeWsBaseUrl = ownership.injectedRealtimeWsBaseUrl;
143152
journal.injectedCatalogPath = ownership.injectedCatalogPath;
144153
atomicWriteFile(JOURNAL_PATH, JSON.stringify(journal));
145154
}
@@ -156,6 +165,11 @@ export function journaledInjectedOpenaiBaseUrl(): string | null {
156165
return readJournal()?.injectedOpenaiBaseUrl ?? null;
157166
}
158167

168+
/** The root `experimental_realtime_ws_base_url` the last injection wrote, or null. */
169+
export function journaledInjectedRealtimeWsBaseUrl(): string | null {
170+
return readJournal()?.injectedRealtimeWsBaseUrl ?? null;
171+
}
172+
159173
/** The catalog path the last injection wrote to, or null when none was recorded. */
160174
export function journaledInjectedCatalogPath(): string | null {
161175
return readJournal()?.injectedCatalogPath ?? null;

0 commit comments

Comments
 (0)