@yansigit/opencodex 2.32.0 → 2.33.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 (108) hide show
  1. package/README.md +2 -2
  2. package/gui/dist/assets/index-DKLr4LTE.js +102 -0
  3. package/gui/dist/assets/index-DrSQdTRd.css +1 -0
  4. package/gui/dist/index.html +2 -2
  5. package/package.json +6 -5
  6. package/src/adapters/anthropic.ts +20 -6
  7. package/src/adapters/azure.ts +20 -4
  8. package/src/adapters/base.ts +3 -1
  9. package/src/adapters/command-code.ts +40 -7
  10. package/src/adapters/cursor/live-transport.ts +1 -1
  11. package/src/adapters/cursor/protobuf-events.ts +158 -7
  12. package/src/adapters/cursor/protobuf-request.ts +33 -15
  13. package/src/adapters/cursor/request-builder.ts +4 -3
  14. package/src/adapters/cursor/tool-definitions.ts +27 -1
  15. package/src/adapters/cursor/types.ts +4 -3
  16. package/src/adapters/cursor.ts +9 -0
  17. package/src/adapters/google-antigravity-replay.ts +2 -2
  18. package/src/adapters/google-antigravity-wire.ts +7 -0
  19. package/src/adapters/google-errors.ts +6 -2
  20. package/src/adapters/google-http.ts +30 -7
  21. package/src/adapters/google-truncation.ts +5 -0
  22. package/src/adapters/google-wire-compiler.ts +38 -6
  23. package/src/adapters/google.ts +148 -26
  24. package/src/adapters/kiro-tools.ts +20 -9
  25. package/src/adapters/openai-chat.ts +9 -0
  26. package/src/adapters/openai-responses.ts +1 -1
  27. package/src/bridge.ts +112 -9
  28. package/src/claude/context-windows.ts +16 -9
  29. package/src/cli/doctor.ts +2 -2
  30. package/src/cli/index.ts +9 -2
  31. package/src/cli/provider.ts +6 -0
  32. package/src/cli/status.ts +23 -0
  33. package/src/codex/auth-api.ts +4 -2
  34. package/src/codex/autostart-health.ts +16 -0
  35. package/src/codex/catalog/aggregation.ts +12 -12
  36. package/src/codex/catalog/effort.ts +18 -3
  37. package/src/codex/catalog/metadata.ts +27 -1
  38. package/src/codex/catalog/model-metadata.ts +39 -12
  39. package/src/codex/catalog/parsing.ts +38 -27
  40. package/src/codex/catalog/provider-fetch.ts +198 -133
  41. package/src/codex/catalog/sync.ts +1 -1
  42. package/src/codex/convergence.ts +5 -0
  43. package/src/codex/shim.ts +56 -3
  44. package/src/config/provider-validation.ts +37 -0
  45. package/src/config.ts +78 -2
  46. package/src/generated/compatibility-version.json +120 -96
  47. package/src/images/loop.ts +37 -6
  48. package/src/lib/azure-identity.ts +154 -0
  49. package/src/lib/debug.ts +42 -0
  50. package/src/lib/errors.ts +14 -0
  51. package/src/lib/provider-outbound.ts +45 -33
  52. package/src/lib/provider-tls-profile.ts +309 -0
  53. package/src/lib/proxy-env.ts +49 -0
  54. package/src/lib/redact.ts +10 -1
  55. package/src/oauth/antigravity-routing.ts +282 -236
  56. package/src/oauth/callback-server.ts +22 -2
  57. package/src/oauth/command-code.ts +5 -16
  58. package/src/oauth/google-antigravity.ts +42 -5
  59. package/src/oauth/index.ts +15 -3
  60. package/src/oauth/kimi.ts +9 -1
  61. package/src/oauth/open-browser-choice.ts +26 -0
  62. package/src/oauth/store.ts +6 -0
  63. package/src/providers/antigravity-quota.ts +3 -1
  64. package/src/providers/api-keys.ts +2 -1
  65. package/src/providers/auto-compact-budget.ts +65 -0
  66. package/src/providers/derive.ts +4 -0
  67. package/src/providers/key-failover.ts +5 -1
  68. package/src/providers/openai-tiers.ts +5 -0
  69. package/src/providers/provider-id-rewrite.ts +1 -0
  70. package/src/providers/quota.ts +59 -13
  71. package/src/providers/registry.ts +3 -1
  72. package/src/providers/request-pacing.ts +33 -6
  73. package/src/providers/xai-transport.ts +21 -0
  74. package/src/responses/google-provider-options.ts +36 -0
  75. package/src/responses/namespace-tool-compat.ts +84 -4
  76. package/src/responses/parser.ts +11 -0
  77. package/src/responses/provider-opaque-metadata.ts +3 -3
  78. package/src/responses/schema.ts +37 -0
  79. package/src/responses/state.ts +94 -4
  80. package/src/router.ts +8 -2
  81. package/src/server/auth-cors.ts +28 -0
  82. package/src/server/images.ts +19 -35
  83. package/src/server/management/agent-settings-routes.ts +205 -15
  84. package/src/server/management/combo-routes.ts +6 -0
  85. package/src/server/management/config-routes.ts +31 -5
  86. package/src/server/management/model-rows.ts +4 -0
  87. package/src/server/management/oauth-account-routes.ts +25 -4
  88. package/src/server/management/provider-routes.ts +113 -15
  89. package/src/server/management/routing-profile-routes.ts +3 -0
  90. package/src/server/request-log.ts +21 -0
  91. package/src/server/responses/agent-task-recovery.ts +1 -1
  92. package/src/server/responses/compact.ts +30 -1
  93. package/src/server/responses/core.ts +359 -153
  94. package/src/server/responses/empty-completion-guard.ts +35 -6
  95. package/src/server/responses/fetch-helpers.ts +18 -5
  96. package/src/server/responses/v2-native-parent-override.ts +59 -0
  97. package/src/server/responses/ws-upstream.ts +75 -2
  98. package/src/server/responses-undeclared-tool-guard.ts +90 -8
  99. package/src/service.ts +1 -1
  100. package/src/types/config.ts +16 -1
  101. package/src/types/provider.ts +16 -0
  102. package/src/types/request.ts +28 -0
  103. package/src/types/tools.ts +27 -0
  104. package/src/types.ts +6 -0
  105. package/src/web-search/gemini-executor.ts +6 -4
  106. package/src/web-search/loop.ts +42 -6
  107. package/gui/dist/assets/index-BG43zwVe.js +0 -102
  108. package/gui/dist/assets/index-CiSI-jrP.css +0 -1
@@ -4,6 +4,27 @@ import { resolveGithubCopilotTransport } from "./github-copilot-transport";
4
4
 
5
5
  export const XAI_GROK_CLI_BASE_URL = "https://cli-chat-proxy.grok.com/v1";
6
6
 
7
+ /** The two hosts that serve xAI's Responses API: the public API and the Grok CLI proxy. */
8
+ const XAI_RESPONSES_HOSTS = new Set(["api.x.ai", "cli-chat-proxy.grok.com"]);
9
+
10
+ /**
11
+ * True when this provider's Responses traffic terminates at xAI itself.
12
+ *
13
+ * Probed 2026-08-22 one field per request: the two hosts accept and refuse exactly the same
14
+ * web_search fields, so they are one dialect rather than two. Matching is exact-host over
15
+ * https, which keeps lookalikes (`api.x.ai.evil.test`) and nonstandard ports out.
16
+ */
17
+ export function isXaiResponsesDestination(provider: Pick<OcxProviderConfig, "baseUrl">): boolean {
18
+ try {
19
+ const url = new URL(provider.baseUrl);
20
+ return url.protocol === "https:"
21
+ && XAI_RESPONSES_HOSTS.has(url.hostname.toLowerCase())
22
+ && (url.port === "" || url.port === "443");
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+
7
28
  export const XAI_GROK_COMPATIBILITY = {
8
29
  version: "0.2.93",
9
30
  userAgent: "opencodex-grok/0.2.93",
@@ -0,0 +1,36 @@
1
+ import { effectiveGoogleMode } from "../providers/registry";
2
+ import type { OcxParsedRequest, OcxProviderConfig } from "../types";
3
+
4
+ const AI_STUDIO_CACHED_CONTENT = /^cachedContents\/[^/?#\s]+$/;
5
+ const VERTEX_CACHED_CONTENT = /^projects\/[^/?#\s]+\/locations\/[^/?#\s]+\/cachedContents\/[^/?#\s]+$/;
6
+
7
+ export function googleProviderOptionsRouteError(
8
+ parsed: Pick<OcxParsedRequest, "options">,
9
+ route: {
10
+ providerName: string;
11
+ provider: OcxProviderConfig;
12
+ adapterName: string;
13
+ },
14
+ ): string | undefined {
15
+ if (!parsed.options.providerOptions?.google) return undefined;
16
+ const mode = effectiveGoogleMode(route.providerName, route.provider);
17
+ if (mode === "cloud-code-assist") {
18
+ return "provider_options.google is not supported on Google Cloud Code Assist routes";
19
+ }
20
+ if (route.adapterName !== "google" || (mode !== "ai-studio" && mode !== "vertex")) {
21
+ return "provider_options.google is supported only on Google AI Studio or Vertex routes";
22
+ }
23
+ if (mode === "ai-studio") {
24
+ const cachedContent = parsed.options.providerOptions.google.cachedContent;
25
+ if (cachedContent && VERTEX_CACHED_CONTENT.test(cachedContent)) {
26
+ return "provider_options.google.cached_content must use cachedContents/{id} on Google AI Studio routes";
27
+ }
28
+ }
29
+ if (mode === "vertex") {
30
+ const cachedContent = parsed.options.providerOptions.google.cachedContent;
31
+ if (cachedContent && AI_STUDIO_CACHED_CONTENT.test(cachedContent)) {
32
+ return "provider_options.google.cached_content must use projects/{project}/locations/{location}/cachedContents/{id} on Vertex routes";
33
+ }
34
+ }
35
+ return undefined;
36
+ }
@@ -4,6 +4,14 @@ import { collectResponsesToolGroups } from "./tool-groups";
4
4
  export interface RoutedNamespaceToolIdentity {
5
5
  namespace: string;
6
6
  name: string;
7
+ /**
8
+ * The kind the tool was DECLARED as. Restoration and `tool_choice` matching both
9
+ * need it: a wire name identifies which tool, not which kind of call may carry it,
10
+ * so without this a tool declared `function` could be selected by a `custom`
11
+ * selector and come back as a `custom_tool_call` — the same name/kind mismatch
12
+ * that motivated narrowing the alias map in the first place.
13
+ */
14
+ kind: "function" | "custom";
7
15
  }
8
16
 
9
17
  export type RoutedNamespaceToolAliases = ReadonlyMap<string, RoutedNamespaceToolIdentity>;
@@ -138,7 +146,10 @@ function buildRewritePlan(groups: readonly unknown[][]): NamespaceRewritePlan {
138
146
  addSelector(selectors, `${parsed.namespace}.${childName}`, wireName);
139
147
  addSelector(selectors, childName, wireName);
140
148
  if (parsed.namespace !== BUILTIN_FUNCTIONS_NAMESPACE) {
141
- aliases.set(wireName, { namespace: parsed.namespace, name: childName });
149
+ // A child declared `custom` stays custom; everything else lowers to a
150
+ // function, which is how `buildTools` flattens it upstream.
151
+ const kind = child.type === "custom" ? "custom" : "function";
152
+ aliases.set(wireName, { namespace: parsed.namespace, name: childName, kind });
142
153
  }
143
154
  }
144
155
  }
@@ -206,18 +217,34 @@ function rewriteToolList(
206
217
  * the failure this layer exists to prevent, and this layer's own response restoration is what put
207
218
  * the key on the item.
208
219
  */
220
+ /**
221
+ * A selector's `namespace` is either absent — meaning "unqualified, resolve the bare
222
+ * name" — or a string naming the group. A present-but-non-string value is neither, and
223
+ * a malformed selector must not authorize anything: not through the unqualified
224
+ * fallback, and not by happening to carry an already-flattened wire name, which would
225
+ * otherwise match the alias map exactly and arm it anyway.
226
+ */
227
+ function hasMalformedNamespace(value: Record<string, unknown>): boolean {
228
+ return "namespace" in value && typeof value.namespace !== "string";
229
+ }
230
+
209
231
  function rewriteNamedSelector(
210
232
  value: unknown,
211
233
  plan: NamespaceRewritePlan,
212
234
  bareFallback: boolean,
213
235
  ): unknown {
214
236
  if (!isPlainObject(value) || typeof value.name !== "string") return value;
215
- if (typeof value.namespace !== "string") {
237
+ // Malformed: hand it back untouched so no rewrite occurs. Authorization rejects it
238
+ // separately — returning it unchanged is not by itself enough, because the name it
239
+ // carries may already BE a wire name.
240
+ if (hasMalformedNamespace(value)) return value;
241
+ const namespace = value.namespace;
242
+ if (typeof namespace !== "string") {
216
243
  if (!bareFallback) return value;
217
244
  const wireName = plan.selectors.get(value.name) ?? undefined;
218
245
  return wireName === undefined || wireName === value.name ? value : { ...value, name: wireName };
219
246
  }
220
- const { namespace, ...rest } = value;
247
+ const { namespace: _dropped, ...rest } = value;
221
248
  const wireName = plan.identities.get(loweredIdentity(namespace, value.name))
222
249
  ?? loweredWireName(namespace, value.name);
223
250
  return { ...rest, name: wireName };
@@ -239,6 +266,59 @@ function rewriteToolChoice(value: unknown, plan: NamespaceRewritePlan): unknown
239
266
  return changed ? { ...value, tools } : value;
240
267
  }
241
268
 
269
+ /**
270
+ * Keep response restoration inside the caller's per-turn tool authorization boundary. The
271
+ * upstream sees every flattened declaration even when `tool_choice` narrows the tools it may call,
272
+ * so its output cannot be trusted merely because a wire name appeared in that catalog.
273
+ */
274
+ function authorizedAliases(
275
+ aliases: Map<string, RoutedNamespaceToolIdentity>,
276
+ toolChoice: unknown,
277
+ ): Map<string, RoutedNamespaceToolIdentity> {
278
+ if (toolChoice === undefined || toolChoice === "auto" || toolChoice === "required") return aliases;
279
+ if (toolChoice === "none" || !isPlainObject(toolChoice)) return new Map();
280
+
281
+ // name -> the kind the selector claimed. A selector authorizes a tool only when it
282
+ // names it AND agrees about what kind of tool it is.
283
+ let authorized: Map<string, "function" | "custom">;
284
+ if (
285
+ (toolChoice.type === "function" || toolChoice.type === "custom")
286
+ && typeof toolChoice.name === "string"
287
+ ) {
288
+ // A malformed namespace makes the whole selector untrustworthy, even when its
289
+ // name is already a flattened wire name that would match the alias map exactly.
290
+ if (hasMalformedNamespace(toolChoice)) return new Map();
291
+ authorized = new Map([[toolChoice.name, toolChoice.type]]);
292
+ } else if (toolChoice.type === "allowed_tools" && Array.isArray(toolChoice.tools)) {
293
+ authorized = new Map();
294
+ for (const tool of toolChoice.tools) {
295
+ // Match the top-level branch above: only a function/custom selector can
296
+ // authorize a client namespace call. `allowed_tools` entries are typed
297
+ // `{type: string}` by the schema, so the accepted set is open-ended and
298
+ // an allowlist is the only closure that also covers kinds added later.
299
+ // Without this, `{type: "file_search", name: "<wire-name>"}` keeps the
300
+ // alias, and an upstream `function_call` carrying that name is restored
301
+ // into a namespace call the caller never permitted.
302
+ if (!isPlainObject(tool)) continue;
303
+ if (tool.type !== "function" && tool.type !== "custom") continue;
304
+ if (typeof tool.name !== "string") continue;
305
+ if (hasMalformedNamespace(tool)) continue;
306
+ authorized.set(tool.name, tool.type);
307
+ }
308
+ } else {
309
+ // An explicit selector for another tool kind does not authorize a client namespace call.
310
+ return new Map();
311
+ }
312
+
313
+ // The kind must agree too. A wire name says WHICH tool, not what kind of call may
314
+ // carry it, so a `custom` selector naming a tool declared `function` is the same
315
+ // name/kind mismatch as a `file_search` selector naming it — narrower, but the
316
+ // same class, and `allowed_tools[].type` accepts any string so both are reachable.
317
+ return new Map(
318
+ [...aliases].filter(([wireName, identity]) => authorized.get(wireName) === identity.kind),
319
+ );
320
+ }
321
+
242
322
  function rewriteInputItem(item: unknown, plan: NamespaceRewritePlan, emitted: Set<string>): unknown {
243
323
  if (!isPlainObject(item)) return item;
244
324
  if (item.type === "additional_tools" && Array.isArray(item.tools)) {
@@ -292,7 +372,7 @@ export function rewriteRoutedNamespaceToolsForUpstream(body: unknown): {
292
372
  ...(input !== body.input ? { input } : {}),
293
373
  ...(toolChoice !== body.tool_choice ? { tool_choice: toolChoice } : {}),
294
374
  },
295
- aliases: plan.aliases,
375
+ aliases: authorizedAliases(plan.aliases, toolChoice),
296
376
  };
297
377
  }
298
378
 
@@ -781,6 +781,17 @@ export function parseRequest(
781
781
  if (data.frequency_penalty !== undefined) options.frequencyPenalty = data.frequency_penalty;
782
782
  if (data.service_tier !== undefined) options.serviceTier = data.service_tier;
783
783
  if (data.prompt_cache_key !== undefined) options.promptCacheKey = data.prompt_cache_key;
784
+ if (data.provider_options?.google) {
785
+ const google = data.provider_options.google;
786
+ options.providerOptions = {
787
+ google: {
788
+ ...(google.thinking_budget !== undefined ? { thinkingBudget: google.thinking_budget } : {}),
789
+ ...(google.include_thoughts !== undefined ? { includeThoughts: google.include_thoughts } : {}),
790
+ ...(google.safety_settings !== undefined ? { safetySettings: google.safety_settings } : {}),
791
+ ...(google.cached_content !== undefined ? { cachedContent: google.cached_content } : {}),
792
+ },
793
+ };
794
+ }
784
795
 
785
796
  // Stash the hosted web_search config (if Codex enabled it) so the proxy can run searches via the
786
797
  // gpt-mini sidecar for routed providers. buildTools still drops the hosted tool; the sidecar path
@@ -24,11 +24,11 @@ function isObj(value: unknown): value is Record<string, unknown> {
24
24
  }
25
25
 
26
26
  /**
27
- * Same ceiling the Antigravity replay cache already enforces on a stored signature. An opaque
28
- * token this large is not a real signature, and accepting it would let a caller push unbounded
27
+ * Ceiling on stored thought signatures. Accommodates deep thinking models (e.g. Gemini 3.7
28
+ * Flash up to 64k tokens of reasoning, whose signatures can exceed 100 KiB) while bounding
29
29
  * state through history replay.
30
30
  */
31
- const MAX_SIGNATURE_BYTES = 64 * 1024;
31
+ const MAX_SIGNATURE_BYTES = 1024 * 1024;
32
32
 
33
33
  export function isCarryableSignature(value: unknown): value is string {
34
34
  if (typeof value !== "string" || value.length === 0) return false;
@@ -134,6 +134,42 @@ export const reasoningConfigSchema = z.object({
134
134
  summary: z.enum(["auto", "concise", "detailed", "none"]).optional(),
135
135
  });
136
136
 
137
+ const googleSafetyCategorySchema = z.enum([
138
+ "HARM_CATEGORY_HATE_SPEECH",
139
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
140
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
141
+ "HARM_CATEGORY_HARASSMENT",
142
+ "HARM_CATEGORY_CIVIC_INTEGRITY",
143
+ "HARM_CATEGORY_JAILBREAK",
144
+ ]);
145
+ const googleSafetyThresholdSchema = z.enum([
146
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
147
+ "BLOCK_LOW_AND_ABOVE",
148
+ "BLOCK_MEDIUM_AND_ABOVE",
149
+ "BLOCK_ONLY_HIGH",
150
+ "BLOCK_NONE",
151
+ "OFF",
152
+ ]);
153
+ const googleSafetySettingSchema = z.object({
154
+ category: googleSafetyCategorySchema,
155
+ threshold: googleSafetyThresholdSchema,
156
+ }).strict();
157
+ const googleProviderOptionsSchema = z.object({
158
+ thinking_budget: z.number().safe().int().gte(-1).optional(),
159
+ include_thoughts: z.boolean().optional(),
160
+ safety_settings: z.array(googleSafetySettingSchema).max(16).superRefine((settings, ctx) => {
161
+ const categories = new Set(settings.map(setting => setting.category));
162
+ if (categories.size !== settings.length) {
163
+ ctx.addIssue({ code: "custom", message: "safety_settings categories must be unique" });
164
+ }
165
+ }).optional(),
166
+ cached_content: z.string().regex(
167
+ /^(?:cachedContents\/[^/?#\s]+|projects\/[^/?#\s]+\/locations\/[^/?#\s]+\/cachedContents\/[^/?#\s]+)$/,
168
+ "cached_content must be a valid Google cached content resource name",
169
+ ).optional(),
170
+ }).strict();
171
+ const providerOptionsSchema = z.object({ google: googleProviderOptionsSchema.optional() }).strict();
172
+
137
173
  export const stopSchema = z.union([z.string(), z.array(z.string()), z.null()]);
138
174
 
139
175
  export const responsesRequestSchema = z.object({
@@ -162,4 +198,5 @@ export const responsesRequestSchema = z.object({
162
198
  prompt: z.unknown().optional(),
163
199
  text: z.unknown().optional(),
164
200
  truncation: z.unknown().optional(),
201
+ provider_options: providerOptionsSchema.optional(),
165
202
  });
@@ -18,6 +18,12 @@ import {
18
18
  const MAX_STORED_RESPONSES = 1_000;
19
19
  const RESPONSE_TTL_MS = 60 * 60 * 1_000;
20
20
  const SNAPSHOT_DEBOUNCE_MS = 2_000;
21
+ /** Snapshot size below which the debounce stays at its base value. */
22
+ const SNAPSHOT_DEBOUNCE_SCALE_FROM_BYTES = 1 * 1024 * 1024;
23
+ /** Ceiling for the stretched debounce. Continuation state is only read after a
24
+ * restart, and a graceful shutdown flushes, so the exposure a longer debounce adds
25
+ * is bounded by a hard kill — paid against rewriting the whole snapshot every 2 s. */
26
+ const SNAPSHOT_DEBOUNCE_MAX_MS = 30_000;
21
27
  /** In-memory high-water byte cap across all entries. Forced store:false retention (kiro/cursor
22
28
  * continuation chains) stores the full expanded input each turn — ~quadratic bytes per chain —
23
29
  * so a count cap alone cannot bound memory. Oldest-first eviction applies past this mark. */
@@ -90,6 +96,43 @@ let oldestResidentId: string | undefined;
90
96
  let oldestResidentAt: number | null = null;
91
97
  let byteCapOverride: number | null = null;
92
98
  let stateRevision = 0;
99
+ /** Byte length and digest of the last snapshot actually written, for the
100
+ * identical-payload skip and the size-scaled debounce. The payload itself is not
101
+ * retained: at the 24 MiB bound that would double the snapshot's memory cost. */
102
+ let lastSnapshotBytes = 0;
103
+ let lastSnapshotDigest: string | null = null;
104
+ // The resolved file the digest above describes. Keeping it means a config-dir
105
+ // change or a retargeted symlink is a miss rather than a false "unchanged".
106
+ let lastSnapshotTarget: string | null = null;
107
+
108
+ /**
109
+ * Is the snapshot on disk still byte-for-byte what we last wrote?
110
+ *
111
+ * The cached digest proves what this process wrote, not what is there now. Size is
112
+ * checked first so the common mismatch costs a `stat`, and the content comparison
113
+ * only runs when the size already agrees. Any read failure answers "no" and the
114
+ * caller rewrites — the safe direction.
115
+ */
116
+ async function snapshotOnDiskMatches(path: string, payload: string, payloadBytes: number): Promise<boolean> {
117
+ try {
118
+ const file = Bun.file(path);
119
+ if (file.size !== payloadBytes) return false;
120
+ if (await file.text() !== payload) return false;
121
+ // Content matching is not the whole invariant. This file holds persisted request
122
+ // and response bodies, and `atomicWriteFileAsync` writes it owner-only; the
123
+ // unconditional rewrite used to restore that on every mutation. Skipping without
124
+ // checking would let a broadened mode persist indefinitely, so treat a widened
125
+ // file as "does not match" and let the caller rewrite it through the hardening
126
+ // path. POSIX only — Windows ACLs are re-applied by that same write path.
127
+ if (process.platform !== "win32") {
128
+ const mode = statSync(path).mode & 0o777;
129
+ if (mode !== 0o600) return false;
130
+ }
131
+ return true;
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
93
136
  const spillCounters = { writes: 0, writeFailures: 0, readFailures: 0 };
94
137
  /**
95
138
  * Admission-boundary observability (test-visible). directSpills: oversized
@@ -788,9 +831,38 @@ async function writeBoundedSnapshot(path: string): Promise<SnapshotWriteOutcome>
788
831
  entries.push(persistEntry);
789
832
  }
790
833
  entries.reverse();
791
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
792
- try { chmodSync(dirname(path), 0o700); } catch { /* best-effort (e.g. Windows) */ }
793
- await atomicWriteFileAsync(path, JSON.stringify({ version: 2, states: entries }));
834
+ const payload = JSON.stringify({ version: 2, states: entries });
835
+ const payloadBytes = Buffer.byteLength(payload, "utf8");
836
+ const payloadDigest = Bun.hash(payload).toString(36);
837
+ // A mutation does not always change what gets persisted: entries past the
838
+ // per-entry or total byte bound are dropped from the selection, and spill
839
+ // demotion moves bytes out of it. Re-writing a byte-identical 24 MiB file
840
+ // buys nothing, so compare first — but the cached digest describes what THIS
841
+ // process last wrote, which is not the same claim as "that is what is on disk
842
+ // now". A second proxy sharing the home, or anything that rewrites the file
843
+ // in place, leaves the digest describing bytes that are gone. Before every
844
+ // release-of-a-write, the previous behaviour rewrote unconditionally and so
845
+ // repaired that silently; skipping without checking would turn a repaired
846
+ // snapshot into a lost one at the next restart.
847
+ //
848
+ // Verify against the file itself, keyed to the resolved target so a retargeted
849
+ // symlink is also a miss. Reading back a matching-size file costs far less
850
+ // than the atomic replace it avoids, and only happens when the digest already
851
+ // matched — the amplification this fixes is the repeated WRITE, not the read.
852
+ const unchanged = lastSnapshotDigest !== null
853
+ && payloadDigest === lastSnapshotDigest
854
+ && payloadBytes === lastSnapshotBytes
855
+ && lastSnapshotTarget === resolveWriteTarget(path)
856
+ && existsSync(path)
857
+ && await snapshotOnDiskMatches(path, payload, payloadBytes);
858
+ if (!unchanged) {
859
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
860
+ try { chmodSync(dirname(path), 0o700); } catch { /* best-effort (e.g. Windows) */ }
861
+ await atomicWriteFileAsync(path, payload);
862
+ lastSnapshotDigest = payloadDigest;
863
+ lastSnapshotBytes = payloadBytes;
864
+ lastSnapshotTarget = resolveWriteTarget(path);
865
+ }
794
866
  persistAttemptHookForTests?.();
795
867
  if (revision === stateRevision) return "stable";
796
868
  }
@@ -809,11 +881,26 @@ function drainPendingSpillUnlinks(): void {
809
881
  }
810
882
  }
811
883
 
884
+ /**
885
+ * Debounce scaled by the size of the last snapshot written.
886
+ *
887
+ * The whole snapshot is re-serialized and atomically replaced on every flush, so at
888
+ * the 24 MiB bound a fixed 2 s debounce is up to ~12 MB/s of write amplification for
889
+ * state nothing reads until the next start (#2460). Small snapshots keep the base
890
+ * cadence; the stretch is linear in size and clamped, so the write rate is roughly
891
+ * flat instead of growing with the file.
892
+ */
893
+ function snapshotDebounceMs(): number {
894
+ if (lastSnapshotBytes <= SNAPSHOT_DEBOUNCE_SCALE_FROM_BYTES) return SNAPSHOT_DEBOUNCE_MS;
895
+ const scaled = Math.round(SNAPSHOT_DEBOUNCE_MS * (lastSnapshotBytes / SNAPSHOT_DEBOUNCE_SCALE_FROM_BYTES));
896
+ return Math.min(scaled, SNAPSHOT_DEBOUNCE_MAX_MS);
897
+ }
898
+
812
899
  function schedulePersistAt(path: string, replace = false): void {
813
900
  if (persistTimer && !replace) return;
814
901
  if (persistTimer) clearTimeout(persistTimer);
815
902
  pendingPersistPath = path;
816
- persistTimer = setTimeout(() => { void persistNow(path); }, SNAPSHOT_DEBOUNCE_MS);
903
+ persistTimer = setTimeout(() => { void persistNow(path); }, snapshotDebounceMs());
817
904
  (persistTimer as { unref?: () => void }).unref?.();
818
905
  }
819
906
 
@@ -1418,6 +1505,9 @@ export function clearResponseStateMemoryForTests(): void {
1418
1505
  replayScopeMismatchDrops = 0;
1419
1506
  replayOverlapSkips = 0;
1420
1507
  persistAttemptHookForTests = null;
1508
+ lastSnapshotBytes = 0;
1509
+ lastSnapshotDigest = null;
1510
+ lastSnapshotTarget = null;
1421
1511
  loaded = false;
1422
1512
  }
1423
1513
 
package/src/router.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  } from "./combos";
10
10
  import type { NormalizedComboConfig } from "./combos/types";
11
11
  import { hasOwnProvider } from "./config/provider-name";
12
+ import { isAzureIdentityProvider } from "./config/provider-validation";
12
13
  import { resolveEnvValue } from "./config";
13
14
  import { assertProviderDestinationAllowed } from "./lib/destination-policy";
14
15
  import { redactSecretString, redactUrlForLog } from "./lib/redact";
@@ -271,10 +272,15 @@ export function routedProviderConfig(providerName: string, provider: OcxProvider
271
272
  const registryEntry = PROVIDER_REGISTRY.find(entry => entry.id === providerName);
272
273
  if (!registryEntry || !providerMatchesRegistryTransportWithStaticGuards(providerName, provider)) {
273
274
  assertProviderDestinationAllowed(providerName, provider);
274
- return { ...provider, apiKey: usableResolvedApiKey(provider.apiKey) };
275
+ return {
276
+ ...provider,
277
+ apiKey: usableResolvedApiKey(provider.apiKey),
278
+ ...(isAzureIdentityProvider(provider) ? { liveModels: false } : {}),
279
+ };
275
280
  }
276
281
  const resolvedApiKey = usableResolvedApiKey(provider.apiKey);
277
- const staticModelCatalog = !providerSupportsLiveModelDiscovery(providerName, provider);
282
+ const staticModelCatalog = isAzureIdentityProvider(provider)
283
+ || !providerSupportsLiveModelDiscovery(providerName, provider);
278
284
  const repairLegacyMimoFreeAuth = providerName === "mimo-free"
279
285
  && staticModelCatalog
280
286
  && (provider.authMode === undefined || provider.authMode === "local");
@@ -10,6 +10,7 @@ import {
10
10
  } from "../config";
11
11
  import {
12
12
  apiKeyTransportConfigError,
13
+ azureCredentialConfigError,
13
14
  booleanRecordConfigError,
14
15
  modelAdapterRecordConfigError,
15
16
  nonBlankStringArrayConfigError,
@@ -19,6 +20,7 @@ import {
19
20
  providerHeadersConfigError,
20
21
  reasoningSummaryDeliveryRecordConfigError,
21
22
  upstreamHttpVersionConfigError,
23
+ isAzureIdentityProvider,
22
24
  } from "../config/provider-validation";
23
25
  import { providerDestinationConfigError } from "../lib/destination-policy";
24
26
  import { redactSecretString } from "../lib/redact";
@@ -26,8 +28,10 @@ import { effectiveGoogleMode, getProviderRegistryEntry, providerCodexAccountMode
26
28
  import { providerConfigSeed } from "../providers/derive";
27
29
  import type { OcxConfig, OcxProviderConfig } from "../types";
28
30
  import { openRouterRoutingConfigError } from "../providers/openrouter-routing";
31
+ import { modelAutoCompactTokenLimitsConfigError } from "../providers/auto-compact-budget";
29
32
  import { googleVertexLocationConfigError } from "../providers/google-vertex-location";
30
33
  import { xaiResponsesOptInState } from "../providers/xai-responses-opt-in";
34
+ import { antigravityOAuthDestinationConfigError, getProviderTlsProfileStatus, providerTlsProfileConfigError } from "../lib/provider-tls-profile";
31
35
 
32
36
  let _corsOrigin = "http://localhost:10100";
33
37
  export function setCorsOrigin(port: number): void { _corsOrigin = `http://localhost:${port}`; }
@@ -565,6 +569,8 @@ export function providerManagementConfigError(name: unknown, provider: unknown):
565
569
  if (contextOverlayError) return contextOverlayError;
566
570
  delete canonicalCandidate.contextWindow;
567
571
  delete canonicalCandidate.modelContextWindows;
572
+ // User-owned soft compaction policy; it does not alter the canonical transport seed.
573
+ delete canonicalCandidate.modelAutoCompactTokenLimits;
568
574
  const canonical = seed && sameCanonicalProviderSeed(canonicalCandidate, seed);
569
575
  if (!canonical) {
570
576
  return `provider ${name} must equal the canonical built-in provider seed`;
@@ -573,6 +579,12 @@ export function providerManagementConfigError(name: unknown, provider: unknown):
573
579
  return `provider ${name} must not include codexAccountMode`;
574
580
  }
575
581
  const typed = provider as unknown as OcxProviderConfig;
582
+ const tlsProfileError = providerTlsProfileConfigError(name, typed);
583
+ if (tlsProfileError) {
584
+ return `provider ${JSON.stringify(redactSecretString(name))} ${tlsProfileError}`;
585
+ }
586
+ const antigravityError = antigravityOAuthDestinationConfigError(name, typed);
587
+ if (antigravityError) return `provider ${name} ${antigravityError}`;
576
588
  const baseUrlError = providerBaseUrlConfigError(typed.baseUrl);
577
589
  if (baseUrlError) return `provider ${name} ${baseUrlError}`;
578
590
  if (effectiveGoogleMode(name, typed) === "vertex" && typed.location !== undefined) {
@@ -605,8 +617,17 @@ export function providerManagementConfigError(name: unknown, provider: unknown):
605
617
  }
606
618
  const apiKeyTransportError = apiKeyTransportConfigError(typed);
607
619
  if (apiKeyTransportError) return `provider ${name} ${apiKeyTransportError}`;
620
+ const azureCredentialError = azureCredentialConfigError(raw);
621
+ if (azureCredentialError) return `provider ${JSON.stringify(redactSecretString(name))} ${azureCredentialError}`;
608
622
  const maxInputError = positiveIntegerRecordConfigError(raw.modelMaxInputTokens, "modelMaxInputTokens");
609
623
  if (maxInputError) return `provider ${name} ${maxInputError}`;
624
+ const autoCompactError = modelAutoCompactTokenLimitsConfigError(
625
+ raw.modelAutoCompactTokenLimits,
626
+ { requireNativeIds: name === "openai" },
627
+ );
628
+ if (autoCompactError) {
629
+ return `provider ${JSON.stringify(redactSecretString(name))} ${autoCompactError}`;
630
+ }
610
631
  const reasoningSummariesError = booleanRecordConfigError(raw.modelSupportsReasoningSummaries, "modelSupportsReasoningSummaries");
611
632
  if (reasoningSummariesError) return `provider ${name} ${reasoningSummariesError}`;
612
633
  const reasoningSummaryDeliveryError = reasoningSummaryDeliveryRecordConfigError(
@@ -689,6 +710,7 @@ export function safeConfigDTO(config: OcxConfig): unknown {
689
710
  adapter: provider.adapter,
690
711
  baseUrl: publicProviderBaseUrl(provider.baseUrl),
691
712
  hasApiKey: !!provider.apiKey,
713
+ hasAzureCredential: isAzureIdentityProvider(provider),
692
714
  hasHeaders: !!provider.headers && Object.keys(provider.headers).length > 0,
693
715
  };
694
716
  if (name === "xai") {
@@ -704,9 +726,11 @@ export function safeConfigDTO(config: OcxConfig): unknown {
704
726
  "freeTier",
705
727
  "liveModels",
706
728
  "requestPacing",
729
+ "tlsProfile",
707
730
  "models",
708
731
  "contextWindow",
709
732
  "modelContextWindows",
733
+ "modelAutoCompactTokenLimits",
710
734
  "defaultMaxOutputTokens",
711
735
  "modelMaxOutputTokens",
712
736
  "openRouterRouting",
@@ -728,6 +752,7 @@ export function safeConfigDTO(config: OcxConfig): unknown {
728
752
  ] as const) {
729
753
  copyIfDefined(dto, provider, key);
730
754
  }
755
+ dto.tlsProfileStatus = provider.tlsProfile === undefined ? "disabled" : getProviderTlsProfileStatus(name, provider);
731
756
  const modelCosts = sanitizeModelCostsForDisplay(provider.modelCosts);
732
757
  if (modelCosts) dto.modelCosts = modelCosts;
733
758
  // Resolve the note by DESTINATION, not by name. A preset saved under a custom name is
@@ -748,6 +773,9 @@ export function safeConfigDTO(config: OcxConfig): unknown {
748
773
  defaultProvider: config.defaultProvider,
749
774
  codexAutoStart: codexAutoStartEnabled(config),
750
775
  websockets: config.websockets,
776
+ // The GUI's browser-open toggle reads and writes this; absent means the
777
+ // historical auto-open behavior.
778
+ oauthOpenBrowser: config.oauthOpenBrowser !== false,
751
779
  providers,
752
780
  };
753
781
  }
@@ -33,7 +33,9 @@ import { readJsonRequestBody } from "./request-decompress";
33
33
  import { ForwardAdmissionCredentialError, validateForwardAdmissionCredential } from "./auth-cors";
34
34
  import type { RequestLogContext } from "./request-log";
35
35
  import { codexLogAccountId, decodeRequestErrorResponse } from "./responses";
36
- import { getValidAccessToken, getOAuthCredentialProjectId } from "../oauth/index";
36
+ import { getValidAccessToken, getOAuthCredentialProjectId, getValidAccessTokenSnapshot, type OAuthAccessSnapshot } from "../oauth/index";
37
+ import { isCanonicalAntigravityUrl, providerTlsFetch } from "../lib/provider-tls-profile";
38
+ import { redactErrorMessage } from "../lib/redact";
37
39
  import { safeAntigravityHttpErrorMessage } from "../adapters/google-errors";
38
40
  import { sanitizeUpstreamErrorText } from "../adapters/upstream-http-error";
39
41
  import { ANTIGRAVITY_REQUEST_UA } from "../adapters/google-antigravity-wire";
@@ -156,6 +158,9 @@ async function tryCcaImageGeneration(
156
158
  if (endpoint !== "generations") return undefined;
157
159
  const provider = config.providers?.["google-antigravity"];
158
160
  if (!provider || provider.disabled) return undefined;
161
+ if (provider.baseUrl && !isCanonicalAntigravityUrl(provider.baseUrl)) {
162
+ return formatErrorResponse(400, "invalid_request_error", "google-antigravity requires a canonical destination");
163
+ }
159
164
 
160
165
  const prompt = (body as { prompt?: unknown })?.prompt;
161
166
  if (typeof prompt !== "string" || !prompt.trim()) {
@@ -174,36 +179,25 @@ async function tryCcaImageGeneration(
174
179
  // OAuth token refresh and project discovery, not just the upstream fetch.
175
180
  const timeoutMs = config.images?.timeoutMs ?? IMAGES_UPSTREAM_TIMEOUT_MS;
176
181
  const linkedSignal = signalWithTimeout(timeoutMs, signal);
177
- let token: string;
182
+ let snapshot: OAuthAccessSnapshot;
178
183
  try {
179
- // Race the OAuth refresh against the deadline signal. getValidAccessToken
180
- // chains through 4 layers (resolveAccessSnapshotForAccount →
181
- // refreshAndPersistAccessToken → refreshGenericAccountWithLock →
182
- // def.refresh()) that do HTTP calls without accepting a signal. Rather than
183
- // threading signal through the entire chain, race the whole call against
184
- // linkedSignal: when the signal aborts we stop awaiting and surface the
185
- // cancellation immediately instead of hanging on the refresh HTTP call.
186
- token = await abortableRace(getValidAccessToken("google-antigravity"), linkedSignal.signal);
184
+ snapshot = await abortableRace(getValidAccessTokenSnapshot("google-antigravity"), linkedSignal.signal);
187
185
  } catch (err) {
188
186
  linkedSignal.cleanup();
189
- // abortableRace rejects immediately when the signal fires, so client
190
- // cancellation and deadline expiry surface here. Parent abort propagates
191
- // into the linked signal, so check parent first (499) before the linked
192
- // signal (504).
193
187
  if (signal.aborted) {
194
188
  return formatErrorResponse(499, "client_closed_request", "CCA image request canceled by client");
195
189
  }
196
190
  if (linkedSignal.signal.aborted) {
197
191
  return formatErrorResponse(504, "upstream_error", "CCA image generation timed out during authentication");
198
192
  }
199
- // Missing/revoked credential → 401 (re-login required); transient refresh/network → 502.
200
193
  const errName = err instanceof Error ? err.name : "";
201
194
  if (errName === "OAuthLoginRequiredError") {
202
195
  return formatErrorResponse(401, "invalid_request_error", "Google Antigravity login required: run 'ocx login google-antigravity'");
203
196
  }
204
197
  return formatErrorResponse(502, "upstream_error", "CCA image generation failed: OAuth token refresh failed");
205
198
  }
206
- const project = getOAuthCredentialProjectId("google-antigravity");
199
+ const token = snapshot.accessToken;
200
+ const project = snapshot.projectId;
207
201
  if (!project) {
208
202
  linkedSignal.cleanup();
209
203
  return formatErrorResponse(
@@ -234,10 +228,8 @@ async function tryCcaImageGeneration(
234
228
  let upstream: Response | undefined;
235
229
  try {
236
230
  try {
237
- // Image generation is a paid, non-idempotent POST. A transport failure is
238
- // ambiguous: the upstream may have accepted the request before the
239
- // connection failed, so never replay it on a peer host.
240
- upstream = await fetch(`${baseUrl}/v1internal:generateContent`, {
231
+ const executor = providerTlsFetch("google-antigravity", provider, globalThis.fetch);
232
+ upstream = await executor(`${baseUrl}/v1internal:generateContent`, {
241
233
  method: "POST",
242
234
  headers: {
243
235
  "Content-Type": "application/json",
@@ -249,23 +241,15 @@ async function tryCcaImageGeneration(
249
241
  });
250
242
  } catch (err) {
251
243
  if (signal.aborted) return formatErrorResponse(499, "client_closed_request", "CCA image request canceled by client");
244
+ const rawMsg = err instanceof Error ? err.message : String(err);
245
+ const safeMsg = redactErrorMessage(sanitizeUpstreamErrorText(rawMsg));
252
246
  if (err instanceof Error && err.name === "TimeoutError") {
253
- return ccaAmbiguousImageTransportError("upstream request timed out");
247
+ return formatErrorResponse(504, "upstream_error", `CCA image generation timed out: ${safeMsg}`);
254
248
  }
255
- // Network/DNS/runtime errors may embed the request URL or headers verbatim
256
- // (e.g. "fetch failed: https://…/v1internal:generateContent"). The token
257
- // lives in an Authorization header, not in the URL, but sanitize defensively
258
- // so no upstream-rejected credential or query param can reach the client,
259
- // and strip the internal base URL host from the surfaced message.
260
- // 400, not 5xx: the POST is paid and non-idempotent. Codex retries every
261
- // 5xx up to 5 attempts, which would duplicate generation after an ambiguous
262
- // transport failure (the upstream may already have accepted the request).
263
- const rawMsg = err instanceof Error ? err.message : String(err);
264
- const safeMsg = sanitizeUpstreamErrorText(rawMsg).replace(
265
- /https?:\/\/[^\s"'<>]+/gi,
266
- "[upstream-url]",
267
- );
268
- return ccaAmbiguousImageTransportError(safeMsg);
249
+ if (provider.tlsProfile === "antigravity-browser") {
250
+ return formatErrorResponse(502, "upstream_error", `CCA image generation failed: ${safeMsg}`);
251
+ }
252
+ return ccaAmbiguousImageTransportError(safeMsg.replace(/https?:\/\/[^\s"'<>]+/gi, "[upstream-url]"));
269
253
  }
270
254
 
271
255
  // Stream the upstream body with a bounded reader so an oversized or malicious