@bitkyc08/opencodex 2.95.0 → 2.96.0

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.
Files changed (62) hide show
  1. package/gui/dist/assets/{App-8yedBkhm.js → App-bwugJRKn.js} +18 -18
  2. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-BOPQyDbH.js} +1 -1
  3. package/gui/dist/assets/{index-D7DCm5eQ.js → index-ebuVUtB7.js} +2 -2
  4. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-6HsrHQAy.js} +1 -1
  5. package/gui/dist/index.html +1 -1
  6. package/package.json +1 -1
  7. package/src/adapters/ollama-native.ts +10 -6
  8. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  9. package/src/adapters/openai-responses/passthrough.ts +3 -4
  10. package/src/adapters/openai-responses/transport.ts +17 -26
  11. package/src/adapters/qoder/adapter.ts +1 -1
  12. package/src/adapters/qoder/image-input.ts +5 -2
  13. package/src/cli/agent.ts +44 -15
  14. package/src/cli/capabilities-agents-routing.ts +9 -0
  15. package/src/cli/ensure-desired-integrations.ts +4 -3
  16. package/src/cli/index.ts +4 -1
  17. package/src/cli/message-command.ts +2 -1
  18. package/src/cli/message-mcp-command.ts +29 -0
  19. package/src/cli/registry.ts +1 -1
  20. package/src/codex/account-store.ts +1 -0
  21. package/src/codex/auth-context-provider.ts +15 -0
  22. package/src/codex/auth-context.ts +10 -19
  23. package/src/codex/forward-transport-headers.ts +33 -33
  24. package/src/codex/installation-id.ts +72 -0
  25. package/src/generated/compatibility-version.json +83 -47
  26. package/src/grok/sync.ts +10 -1
  27. package/src/lib/windows-secret-acl.ts +2 -2
  28. package/src/messaging/mcp-queue-rpc.ts +102 -0
  29. package/src/messaging/mcp-queue-server.ts +42 -0
  30. package/src/messaging/mcp-queue-tools.ts +39 -0
  31. package/src/oauth/anthropic-identity.ts +2 -6
  32. package/src/oauth/index.ts +5 -0
  33. package/src/providers/anthropic-subscription.ts +25 -0
  34. package/src/providers/claude-cli-usage.ts +15 -67
  35. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  36. package/src/providers/quota/anthropic-usage-windows.ts +55 -0
  37. package/src/responses/parser-tools.ts +1 -0
  38. package/src/responses/schema.ts +5 -2
  39. package/src/server/audio-dictation.ts +3 -0
  40. package/src/server/audio-live.ts +8 -2
  41. package/src/server/audio-upstream.ts +2 -0
  42. package/src/server/claude-messages.ts +6 -3
  43. package/src/server/context-history.ts +9 -6
  44. package/src/server/images.ts +14 -5
  45. package/src/server/index/live-sideband.ts +16 -2
  46. package/src/server/index/serve-options.ts +1 -0
  47. package/src/server/index/websocket-handler.ts +1 -1
  48. package/src/server/live.ts +30 -5
  49. package/src/server/responses/adapter-dispatch.ts +5 -0
  50. package/src/server/responses/codex-auth-error.ts +4 -0
  51. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  52. package/src/server/responses/compact.ts +37 -19
  53. package/src/server/responses/core-codex-account.ts +17 -6
  54. package/src/server/responses/core-combo.ts +12 -8
  55. package/src/server/responses/core-normalize.ts +7 -1
  56. package/src/server/responses/passthrough-build-error.ts +36 -0
  57. package/src/server/responses/passthrough-dispatch.ts +7 -22
  58. package/src/server/responses/request-sidecar-auth.ts +3 -1
  59. package/src/server/search.ts +13 -4
  60. package/src/server/ws-bridge.ts +5 -2
  61. package/src/vision/describe.ts +4 -7
  62. package/src/web-search/executor.ts +4 -7
@@ -26,6 +26,15 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
26
26
  "queued means submitted, not processed. unknown must not be replayed; no automatic retry, daemon start or thread resume.",
27
27
  "Exit 0: queued; 1: not sent; 3: unknown; 64: invalid usage. No Claude transport, native lifecycle mutation or skill installation."],
28
28
  },
29
+ {
30
+ command: ["message", "mcp"], usage: "ocx message mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home>",
31
+ summary: "Serve opt-in MCP tools for stored Codex metadata and queued text delivery over stdio.",
32
+ routes: [], mutates: true, json: "none",
33
+ flags: [{ name: "--codex", value: "string", required: true, summary: "Explicit local Codex CLI executable." },
34
+ { name: "--codex-home", value: "string", required: true, summary: "Explicit existing Codex home; no creation or login." }],
35
+ details: ["macOS/Linux only. No proxy/control socket required. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged.",
36
+ "Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. No daemon start, thread resume, steer, automatic replies or registration."],
37
+ },
29
38
  {
30
39
  command: ["advisor"],
31
40
  summary: "Inspect and configure the advisor sidecar (expert consultation for routed workers).",
@@ -48,7 +48,7 @@ export interface EnsureDesiredIntegrationsDeps {
48
48
  syncGrokConfig: (
49
49
  port: number,
50
50
  config: OcxConfig,
51
- opts?: { hostname?: string; probeHostname?: string },
51
+ opts?: { hostname?: string; probeHostname?: string; admit?: () => boolean },
52
52
  ) => Promise<GrokInjectResult>;
53
53
  removeDesktop3pStandardPivot: typeof removeDesktop3pStandardPivot;
54
54
  removeDesktopFirstParty?: typeof removeDesktopFirstParty;
@@ -67,7 +67,7 @@ export interface EnsureDesiredIntegrationsDeps {
67
67
  async function defaultSyncGrokConfig(
68
68
  port: number,
69
69
  config: OcxConfig,
70
- opts: { hostname?: string; probeHostname?: string } = {},
70
+ opts: { hostname?: string; probeHostname?: string; admit?: () => boolean } = {},
71
71
  ): Promise<GrokInjectResult> {
72
72
  const { syncGrokConfig } = await import("../grok/sync");
73
73
  return syncGrokConfig(port, config, opts);
@@ -133,7 +133,8 @@ export async function ensureGrokFenceMatchesDesired(
133
133
  port,
134
134
  config,
135
135
  { ...(hostname !== undefined ? { hostname } : {}),
136
- ...(opts.probeHostname !== undefined ? { probeHostname: opts.probeHostname } : {}) },
136
+ ...(opts.probeHostname !== undefined ? { probeHostname: opts.probeHostname } : {}),
137
+ admit: () => shouldSyncGrokOnStart(deps.loadConfig()) },
137
138
  );
138
139
  if (g.changed) log(" + Grok Build config updated (~/.grok/config.toml)");
139
140
  else if (!g.ok) error(`⚠️ ${g.message}`);
package/src/cli/index.ts CHANGED
@@ -781,7 +781,10 @@ async function handleStart(options: { block?: boolean } = {}) {
781
781
  // one restart, because the toggle removed the fence and start wrote it back.
782
782
  if (shouldSyncGrokOnStart(config)) try {
783
783
  const { syncGrokConfig } = await import("../grok/sync");
784
- const r = await syncGrokConfig(port, config, config.hostname ? { hostname: config.hostname } : {});
784
+ const r = await syncGrokConfig(port, config, {
785
+ ...(config.hostname ? { hostname: config.hostname } : {}),
786
+ admit: () => !shuttingDown && !cleaned && shouldSyncGrokOnStart(loadConfig()),
787
+ });
785
788
  if (r.changed) console.log(" + Grok Build config updated (~/.grok/config.toml)");
786
789
  else if (!r.ok) console.error(`⚠️ ${r.message}`);
787
790
  } catch (err) {
@@ -7,11 +7,12 @@ import { terminalSafeText } from "./runtime-api";
7
7
 
8
8
  /** Run one local messaging operation after pure syntax validation, then release owned resources. */
9
9
  export async function runMessageCommand(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): Promise<number> {
10
+ if (argv[0] === "mcp") return (await import("./message-mcp-command")).runMessageMcpCommand(argv.slice(1));
10
11
  const remote = parseRemoteMessageArgs(argv);
11
12
  if (remote) return (await import("./message-remote-command")).runRemoteMessageCommand(remote, env);
12
13
  const args = parseMessageArgs(argv);
13
14
  if (!args) {
14
- console.error("Usage: ocx message sessions [--host <peer>] [--json] | send (--thread <uuid> | --name <exact-name>) --stdin [--host <peer>] [--kind request|response|notification] [--in-reply-to <uuid>] [--json] | enable [--port <port>] | disable | status | hosts <probe|add|list|remove|abandon|allow-inbound|deny-inbound> | serve [--host <peer>]...");
15
+ console.error("Usage: ocx message sessions [--host <peer>] [--json] | send (--thread <uuid> | --name <exact-name>) --stdin [--host <peer>] [--kind request|response|notification] [--in-reply-to <uuid>] [--json] | mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home> | enable [--port <port>] | disable | status | hosts <probe|add|list|remove|abandon|allow-inbound|deny-inbound> | serve [--host <peer>]...");
15
16
  return 64;
16
17
  }
17
18
  const controller = new AbortController();
@@ -0,0 +1,29 @@
1
+ import { isAbsolute } from "node:path";
2
+ import type { QueueMcpOptions } from "../messaging/mcp-queue-rpc";
3
+
4
+ /** Validate all syntax before importing the MCP host or resolving any executable/home. */
5
+ export function parseQueueMcpArgs(argv: readonly string[]): QueueMcpOptions | null {
6
+ if (argv.length !== 4) return null;
7
+ const values: Record<string, string> = {};
8
+ for (let i = 0; i < argv.length; i += 2) {
9
+ const flag = argv[i]!, value = argv[i + 1]!;
10
+ if (!["--codex", "--codex-home"].includes(flag) || values[flag] !== undefined
11
+ || !value || !isAbsolute(value) || /[\x00-\x1f]/.test(value)) return null;
12
+ values[flag] = value;
13
+ }
14
+ return values["--codex"] && values["--codex-home"] ? { codex: values["--codex"], codexHome: values["--codex-home"] } : null;
15
+ }
16
+
17
+ export async function runMessageMcpCommand(argv: readonly string[]): Promise<number> {
18
+ const options = parseQueueMcpArgs(argv);
19
+ if (!options) {
20
+ console.error("Usage: ocx message mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home>");
21
+ return 64;
22
+ }
23
+ if (process.platform === "win32") {
24
+ console.error("Queue MCP currently supports macOS and Linux only.");
25
+ return 1;
26
+ }
27
+ try { await (await import("../messaging/mcp-queue-server")).serveQueueMcp(options); return 0; }
28
+ catch { console.error("Queue MCP could not serve the stdio connection."); return 1; }
29
+ }
@@ -18,7 +18,7 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
18
18
  },
19
19
  {
20
20
  name: "message",
21
- usage: "ocx message <sessions|send|enable|disable|status|hosts|serve> [options]",
21
+ usage: "ocx message <sessions|send|mcp|enable|disable|status|hosts|serve> [options]",
22
22
  summary: "Discover loaded Codex sessions and queue messages locally or through explicit SSH peers.",
23
23
  details: ["Remote listeners/tunnels require explicit foreground serve; no daemon start. queued is submission, not processing; never replay an unknown send."],
24
24
  },
@@ -92,6 +92,7 @@ function isCredential(value: unknown): value is CodexAccountCredentials {
92
92
  && typeof value.refreshToken === "string"
93
93
  && typeof value.expiresAt === "number"
94
94
  && typeof value.chatgptAccountId === "string"
95
+ && value.chatgptAccountId.trim().length > 0
95
96
  && (hasNoSource || hasCompleteSource);
96
97
  }
97
98
 
@@ -0,0 +1,15 @@
1
+ import type { OcxProviderConfig } from "../types";
2
+
3
+ export type OcxRuntimeProviderConfig = OcxProviderConfig & {
4
+ _codexAccountOverride?: { accessToken: string; chatgptAccountId: string; kind?: "pool" | "main-pool" };
5
+ _codexAccountRequired?: boolean;
6
+ };
7
+
8
+ export function stripCodexRuntimeProviderFields(provider: OcxProviderConfig): OcxProviderConfig {
9
+ const {
10
+ _codexAccountOverride: _override,
11
+ _codexAccountRequired: _required,
12
+ ...safeProvider
13
+ } = provider as OcxRuntimeProviderConfig;
14
+ return safeProvider;
15
+ }
@@ -1,3 +1,6 @@
1
+ import type { OcxRuntimeProviderConfig } from "./auth-context-provider";
2
+ export type { OcxRuntimeProviderConfig } from "./auth-context-provider";
3
+ export { stripCodexRuntimeProviderFields } from "./auth-context-provider";
1
4
  import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt, poolCreditRecoveryNeeded, poolContextCreditRecoveryNeeded, poolCreditRecoveryRetryAt } from "./pool-credit-policy";
2
5
  import { hasSpendableCodexCredits } from "./quota-types";
3
6
  import { nextQuotaQueryDelay } from "./quota-query-backoff";
@@ -378,11 +381,6 @@ export function releaseCodexAuthContextProbeLease(ctx: CodexAuthContext | undefi
378
381
  else releaseCodexQuotaProbeLease(ctx.accountId!, leaseId);
379
382
  }
380
383
 
381
- export type OcxRuntimeProviderConfig = OcxProviderConfig & {
382
- _codexAccountOverride?: { accessToken: string; chatgptAccountId: string };
383
- _codexAccountRequired?: boolean;
384
- };
385
-
386
384
  export class CodexAuthContextError extends Error {
387
385
  accountId: string;
388
386
 
@@ -1795,6 +1793,7 @@ export function applyCodexAuthContextToProvider(
1795
1793
  _codexAccountOverride: {
1796
1794
  accessToken: ctx.accessToken,
1797
1795
  chatgptAccountId: ctx.chatgptAccountId,
1796
+ kind: ctx.kind,
1798
1797
  },
1799
1798
  _codexAccountRequired: true,
1800
1799
  };
@@ -1840,14 +1839,15 @@ export function materializeCodexUpstreamAuth(
1840
1839
  const selected = new Headers();
1841
1840
  for (const name of FORWARD_HEADERS) {
1842
1841
  const value = headers.get(name);
1843
- if (value) selected.set(name, value);
1842
+ if (value || (value !== null && (name === "x-codex-installation-id" || name === "x-codex-turn-metadata"))) selected.set(name, value);
1844
1843
  }
1845
1844
  if (ctx.kind === "pool" || ctx.kind === "main-pool") {
1846
1845
  assertCodexAccountValidationReady(ctx.accountId);
1847
1846
  if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, options.config), poolContextCreditRecoveryNeeded(ctx, options.config), ctx.quotaScope);
1848
1847
  selected.set("authorization", `Bearer ${ctx.accessToken}`);
1849
1848
  selected.set("chatgpt-account-id", ctx.chatgptAccountId);
1850
- isolateCodexPoolAccountHeaders(selected, ctx.chatgptAccountId);
1849
+ if (ctx.kind === "pool") isolateCodexPoolAccountHeaders(selected, ctx.chatgptAccountId);
1850
+ else selected.delete("x-oai-attestation");
1851
1851
  if (ctx.kind === "main-pool") {
1852
1852
  ctx.mainQuotaWriter = observeSelectedMainCredential(ctx, ctx.mainQuotaWriter);
1853
1853
  assertMainAccountPolicy(options.config);
@@ -1878,7 +1878,7 @@ export function materializeCodexUpstreamAuth(
1878
1878
  selected.delete("chatgpt-account-id");
1879
1879
  selected.set("authorization", `Bearer ${stored.accessToken}`);
1880
1880
  if (stored.chatgptAccountId) selected.set("chatgpt-account-id", stored.chatgptAccountId);
1881
- isolateCodexPoolAccountHeaders(selected, stored.chatgptAccountId ?? "");
1881
+ selected.delete("x-oai-attestation");
1882
1882
  observeSelectedMainCredential(stored, writer);
1883
1883
  assertMainAccountPolicy(options.config);
1884
1884
  assertMaterializedReserve(selected, ctx, options);
@@ -1949,7 +1949,7 @@ export async function materializeCodexUpstreamAuthAsync(
1949
1949
  const selected = new Headers();
1950
1950
  for (const name of FORWARD_HEADERS) {
1951
1951
  const value = headers.get(name);
1952
- if (value) selected.set(name, value);
1952
+ if (value || (value !== null && (name === "x-codex-installation-id" || name === "x-codex-turn-metadata"))) selected.set(name, value);
1953
1953
  }
1954
1954
  if (options.config !== undefined && isMainAccountHardLockEnabled(options.config)) {
1955
1955
  reconcileMainCodexAccountRuntimeState();
@@ -1963,7 +1963,7 @@ export async function materializeCodexUpstreamAuthAsync(
1963
1963
  selected.delete("chatgpt-account-id");
1964
1964
  selected.set("authorization", `Bearer ${stored.accessToken}`);
1965
1965
  if (stored.chatgptAccountId) selected.set("chatgpt-account-id", stored.chatgptAccountId);
1966
- isolateCodexPoolAccountHeaders(selected, stored.chatgptAccountId ?? "");
1966
+ selected.delete("x-oai-attestation");
1967
1967
  observeSelectedMainCredential(stored, writer);
1968
1968
  assertMainAccountPolicy(options.config);
1969
1969
  // An opt-in enabled during token refresh must not turn a proof-less context into Reserve.
@@ -1988,12 +1988,3 @@ export function isCodexAuthContextUsable(ctx: CodexAuthContext, config: OcxConfi
1988
1988
  if (ctx.kind === "main-pool") return isCodexAccountUsable(config, ctx.accountId);
1989
1989
  return isCodexAccountUsable(config, ctx.accountId) && isCodexAccountGenerationLive(ctx.accountId, ctx.generation);
1990
1990
  }
1991
-
1992
- export function stripCodexRuntimeProviderFields(provider: OcxProviderConfig): OcxProviderConfig {
1993
- const {
1994
- _codexAccountOverride: _override,
1995
- _codexAccountRequired: _required,
1996
- ...safeProvider
1997
- } = provider as OcxRuntimeProviderConfig;
1998
- return safeProvider;
1999
- }
@@ -1,4 +1,4 @@
1
- import { createHmac } from "node:crypto";
1
+ import { CodexInstallationIdUnavailableError, codexInstallationIdForAccount } from "./installation-id";
2
2
 
3
3
  /** Native request metadata shared by the HTTP adapter and WS preparation. */
4
4
  export const CODEX_RESPONSES_LITE_HEADER = "x-openai-internal-codex-responses-lite";
@@ -9,40 +9,27 @@ export const CODEX_TURN_METADATA_HEADER = "x-codex-turn-metadata";
9
9
  export const CODEX_TURN_STATE_HEADER = "x-codex-turn-state";
10
10
  export const CODEX_ATTESTATION_HEADER = "x-oai-attestation";
11
11
 
12
+ // Caller credentials are forwarded only to the canonical Codex destination, never by capability.
13
+ export const FORWARD_HEADERS = [
14
+ "authorization", "chatgpt-account-id", "openai-beta", "originator", "session_id", "session-id",
15
+ "thread-id", "x-client-request-id", "x-codex-beta-features", "x-codex-installation-id",
16
+ "x-codex-parent-thread-id", "x-codex-turn-metadata", "x-codex-turn-state", "x-codex-window-id",
17
+ "x-oai-attestation", "x-openai-subagent", "x-responsesapi-include-timing-metrics", "version", CODEX_RESPONSES_LITE_HEADER,
18
+ ];
19
+
12
20
  const MAX_ROUTING_MODEL_BYTES = 256;
13
21
  const MAX_ROUTING_TIER_BYTES = 64;
14
- const INSTALL_BODY_KEY = "opencodex-codex-pool-install-body-v1";
15
- const INSTALL_TAG_KEY = "opencodex-codex-pool-install-tag-v1";
16
- const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
22
  const MAX_TURN_METADATA_BYTES = 32 * 1024;
18
23
 
19
- function accountTagForUuidPrefix(account: string, prefix20Hex: string): string {
20
- return createHmac("sha256", INSTALL_TAG_KEY).update(`${account}\0${prefix20Hex.toLowerCase()}`).digest("hex").slice(0, 12);
21
- }
22
-
23
- /**
24
- * Deterministic, idempotent RFC 4122 v4 UUID isolated per (chatgptAccountId, callerInstallationId).
25
- * Calling it twice with the same chatgptAccountId returns the identical UUID without double-hashing.
26
- */
27
- export function deriveCodexAccountInstallationId(chatgptAccountId: string, callerInstallationId: string): string {
28
- const account = chatgptAccountId.trim();
29
- const raw = callerInstallationId.trim();
30
- if (!account || !raw) return callerInstallationId;
31
- if (UUID_V4_RE.test(raw)) {
32
- const hex = raw.replace(/-/g, "").toLowerCase();
33
- if (hex.slice(20, 32) === accountTagForUuidPrefix(account, hex.slice(0, 20))) {
34
- return raw.toLowerCase();
35
- }
36
- }
37
- const h = createHmac("sha256", INSTALL_BODY_KEY).update(`${account}\0${raw}`).digest("hex");
38
- const variant = ((Number.parseInt(h[16]!, 16) & 0x3) | 0x8).toString(16);
39
- const prefix20 = `${h.slice(0, 8)}${h.slice(8, 12)}4${h.slice(13, 16)}${variant}${h.slice(17, 20)}`;
40
- const node12 = accountTagForUuidPrefix(account, prefix20);
41
- return `${prefix20.slice(0, 8)}-${prefix20.slice(8, 12)}-${prefix20.slice(12, 16)}-${prefix20.slice(16, 20)}-${node12}`;
24
+ /** Compatibility export: caller values never contribute to the selected account identity. */
25
+ export function deriveCodexAccountInstallationId(chatgptAccountId: string, _callerInstallationId: string): string {
26
+ return codexInstallationIdForAccount(chatgptAccountId);
42
27
  }
43
28
 
44
29
  export function rewriteTurnMetadataInstallationId(rawMetadata: string, chatgptAccountId: string): string {
45
- if (!chatgptAccountId.trim() || Buffer.byteLength(rawMetadata, "utf8") > MAX_TURN_METADATA_BYTES) return rawMetadata;
30
+ if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
31
+ // A size bound must refuse the Pool send, never bypass identity projection.
32
+ if (Buffer.byteLength(rawMetadata, "utf8") > MAX_TURN_METADATA_BYTES) throw new CodexInstallationIdUnavailableError();
46
33
  let parsed: unknown;
47
34
  try { parsed = JSON.parse(rawMetadata); } catch { return rawMetadata; }
48
35
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return rawMetadata;
@@ -54,10 +41,10 @@ export function rewriteTurnMetadataInstallationId(rawMetadata: string, chatgptAc
54
41
  }
55
42
 
56
43
  export function isolateCodexPoolAccountHeaders(headers: Headers, chatgptAccountId: string): void {
44
+ if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
57
45
  headers.delete(CODEX_ATTESTATION_HEADER);
58
- if (!chatgptAccountId.trim()) return;
59
46
  const installId = headers.get(CODEX_INSTALLATION_ID_HEADER);
60
- if (installId && installId.trim()) {
47
+ if (installId !== null) {
61
48
  headers.set(CODEX_INSTALLATION_ID_HEADER, deriveCodexAccountInstallationId(chatgptAccountId, installId));
62
49
  }
63
50
  const turnMeta = headers.get(CODEX_TURN_METADATA_HEADER);
@@ -67,15 +54,17 @@ export function isolateCodexPoolAccountHeaders(headers: Headers, chatgptAccountI
67
54
  }
68
55
 
69
56
  export function isolateCodexPoolClientMetadata(body: unknown, chatgptAccountId: string | undefined): unknown {
70
- if (!chatgptAccountId?.trim() || !body || typeof body !== "object" || Array.isArray(body)) return body;
57
+ if (chatgptAccountId === undefined) return body;
58
+ if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
59
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
71
60
  const record = body as Record<string, unknown>;
72
61
  const cm = record.client_metadata;
73
62
  if (!cm || typeof cm !== "object" || Array.isArray(cm)) return body;
74
63
  const meta = cm as Record<string, unknown>;
75
64
  let nextMeta: Record<string, unknown> | undefined;
76
65
  const rawInstallId = meta[CODEX_INSTALLATION_ID_HEADER];
77
- if (typeof rawInstallId === "string" && rawInstallId.trim()) {
78
- const nextId = deriveCodexAccountInstallationId(chatgptAccountId, rawInstallId);
66
+ if (Object.hasOwn(meta, CODEX_INSTALLATION_ID_HEADER)) {
67
+ const nextId = codexInstallationIdForAccount(chatgptAccountId);
79
68
  if (nextId !== rawInstallId) nextMeta = { ...meta, [CODEX_INSTALLATION_ID_HEADER]: nextId };
80
69
  }
81
70
  const rawTurnMeta = (nextMeta ?? meta)[CODEX_TURN_METADATA_HEADER];
@@ -103,3 +92,14 @@ export function applyCodexRoutingHint(headers: Headers, body: unknown): void {
103
92
  headers.set(CODEX_ROUTING_HINT_HEADER,
104
93
  `model=${record.model}${tier === undefined ? "" : `;tier=${tier}`}`);
105
94
  }
95
+
96
+ /** Selected identity is authoritative after provider-header merges, including deletions. */
97
+ export function mergeCodexSelectedHeaders(configured: HeadersInit | undefined, selected: Headers): Headers {
98
+ const headers = new Headers(configured);
99
+ for (const name of [CODEX_INSTALLATION_ID_HEADER, CODEX_TURN_METADATA_HEADER, CODEX_ATTESTATION_HEADER]) headers.delete(name);
100
+ for (const name of FORWARD_HEADERS) {
101
+ const value = selected.get(name);
102
+ if (value !== null) headers.set(name, value);
103
+ }
104
+ return headers;
105
+ }
@@ -0,0 +1,72 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { getConfigDir } from "../config/paths";
5
+ import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
6
+ import { hardenSecretDir, hardenSecretPath } from "../lib/windows-secret-acl";
7
+
8
+ const SECRET_BYTES = 32;
9
+ const DOMAIN = "opencodex-codex-installation-id-v1\0";
10
+
11
+ /** Sanitized, retryable refusal: neither a path nor a credential belongs in its cause. */
12
+ export class CodexInstallationIdUnavailableError extends Error {
13
+ constructor() {
14
+ super("Codex installation identity unavailable");
15
+ this.name = "CodexInstallationIdUnavailableError";
16
+ }
17
+ }
18
+
19
+ function readSecret(path: string): Buffer {
20
+ // Refuse links and non-files; never rotate an unreadable or corrupt persisted secret.
21
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
22
+ try {
23
+ const stat = fstatSync(fd);
24
+ if (!stat.isFile() || stat.size !== SECRET_BYTES) throw new CodexInstallationIdUnavailableError();
25
+ if (process.platform !== "win32") fchmodSync(fd, 0o600);
26
+ hardenSecretPath(path, { required: true });
27
+ const bytes = readFileSync(fd);
28
+ if (bytes.length !== SECRET_BYTES) throw new CodexInstallationIdUnavailableError();
29
+ return bytes;
30
+ } finally { closeSync(fd); }
31
+ }
32
+
33
+ function installationSecret(dir: string): Buffer {
34
+ assertNotRealHomeUnderTest(dir);
35
+ // Each secret file gets its own required, inheritance-protected DACL before reading or
36
+ // writing bytes. Optional parent/sibling hardening cannot admit or refuse this file.
37
+ const path = join(dir, "codex-installation-secret");
38
+ try { return readSecret(path); } catch (error) {
39
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
40
+ }
41
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
42
+ // Make new files private at creation: Windows ignores POSIX mode 0600.
43
+ hardenSecretDir(dir, { required: true });
44
+ // Publish complete bytes without replacing another process's winning secret.
45
+ const temporary = join(dir, `.codex-installation-secret-${randomBytes(16).toString("hex")}`);
46
+ const fd = openSync(temporary, "wx", 0o600);
47
+ try {
48
+ try {
49
+ hardenSecretPath(temporary, { required: true });
50
+ writeFileSync(fd, randomBytes(SECRET_BYTES));
51
+ fsyncSync(fd);
52
+ } finally { closeSync(fd); }
53
+ try { linkSync(temporary, path); } catch (error) {
54
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
55
+ }
56
+ return readSecret(path);
57
+ } finally { unlinkSync(temporary); }
58
+ }
59
+
60
+ /** Stable per upstream account and local installation, independent of bearer/caller identity. */
61
+ export function codexInstallationIdForAccount(accountKey: string, configDir = getConfigDir()): string {
62
+ try {
63
+ const account = accountKey.trim();
64
+ if (!account) throw new CodexInstallationIdUnavailableError();
65
+ const bytes = createHmac("sha256", installationSecret(configDir)).update(DOMAIN).update(account).digest().subarray(0, 16);
66
+ // RFC 9562 §5.4 layout; pseudorandom HMAC bits replace per-request randomness.
67
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;
68
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
69
+ const hex = bytes.toString("hex");
70
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
71
+ } catch { throw new CodexInstallationIdUnavailableError(); }
72
+ }