@bitkyc08/opencodex 2.100.3 → 2.100.4

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 (181) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-DcpyI78f.js} +20 -19
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-CzjPJprT.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BTIi7e69.js +1 -0
  6. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  7. package/gui/dist/assets/index-DVgU6S3y.js +138 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bn6Y-g3R.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-eYJAyNHM.js} +19 -18
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-xHMYxLkV.js} +1 -1
  11. package/gui/dist/classic/assets/index-DSaVRW4F.js +138 -0
  12. package/gui/dist/classic/assets/quota-summary-DyzHlkFl.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/package.json +2 -2
  18. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  19. package/src/adapters/anthropic.ts +3 -0
  20. package/src/adapters/claude-cli/adapter.ts +1 -0
  21. package/src/adapters/devin/cloud-direct/chat.ts +71 -14
  22. package/src/adapters/google-errors.ts +14 -2
  23. package/src/adapters/qoder/adapter.ts +9 -1
  24. package/src/adapters/zed.ts +4 -2
  25. package/src/claude/desktop-remote-store.ts +60 -10
  26. package/src/cli/account-api.ts +4 -0
  27. package/src/cli/account-auth.ts +30 -2
  28. package/src/cli/account-extended.ts +33 -2
  29. package/src/cli/capabilities-access-remote.ts +3 -3
  30. package/src/cli/capabilities-accounts.ts +3 -3
  31. package/src/cli/capabilities-base.ts +11 -6
  32. package/src/cli/capabilities-observe-system.ts +2 -2
  33. package/src/cli/claude.ts +3 -3
  34. package/src/cli/disconnect-runtime.ts +16 -6
  35. package/src/cli/dispatch.ts +7 -1
  36. package/src/cli/index.ts +2 -2
  37. package/src/cli/link-apply-restart.ts +4 -2
  38. package/src/cli/link-routes.ts +4 -1
  39. package/src/cli/link.ts +5 -4
  40. package/src/cli/preflight-exemptions.ts +3 -0
  41. package/src/cli/registry.ts +5 -2
  42. package/src/cli/resolve.ts +23 -8
  43. package/src/cli/restart-failure.ts +11 -1
  44. package/src/cli/runtime-api.ts +4 -0
  45. package/src/cli/status.ts +4 -1
  46. package/src/cli/system-command.ts +1 -1
  47. package/src/cli/system-restart-client.ts +9 -3
  48. package/src/cli/system-settings-parity.ts +2 -1
  49. package/src/client/connect.ts +63 -9
  50. package/src/client/desktop-refusal.ts +38 -0
  51. package/src/client/lifecycle-lock.ts +29 -4
  52. package/src/client/runtime-restart.ts +27 -15
  53. package/src/client/runtime.ts +4 -2
  54. package/src/client/state.ts +14 -0
  55. package/src/codex/account-pause.ts +4 -0
  56. package/src/codex/account-runtime-state.ts +4 -0
  57. package/src/codex/auth-api/main-account-probe.ts +3 -1
  58. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  59. package/src/codex/auth-context.ts +40 -2
  60. package/src/codex/catalog/build-entries.ts +10 -0
  61. package/src/codex/catalog/derive-entry.ts +7 -0
  62. package/src/codex/catalog/reserve-warn.ts +7 -5
  63. package/src/codex/catalog/reserve.ts +4 -3
  64. package/src/codex/catalog/retained-sync.ts +2 -0
  65. package/src/codex/catalog/routed-defaults.ts +35 -0
  66. package/src/codex/convergence.ts +2 -0
  67. package/src/codex/loopback-target.ts +22 -8
  68. package/src/codex/main-account.ts +88 -29
  69. package/src/codex/native-main-auth-file.ts +14 -0
  70. package/src/codex/native-main-credentials.ts +270 -0
  71. package/src/codex/native-main-owner.ts +3 -0
  72. package/src/codex/native-main-refresh-mode.ts +14 -1
  73. package/src/codex/quota.ts +63 -14
  74. package/src/combos/failover.ts +12 -1
  75. package/src/combos/index.ts +5 -0
  76. package/src/combos/resolve.ts +115 -19
  77. package/src/config/diagnostics.ts +3 -0
  78. package/src/config/live-reconcile.ts +6 -3
  79. package/src/config/load-degrade.ts +2 -0
  80. package/src/config/persisted-mutation.ts +2 -2
  81. package/src/config/persisted-projections.ts +18 -0
  82. package/src/config/process-state.ts +4 -3
  83. package/src/config/reserve-capability.ts +96 -0
  84. package/src/config/schema/config-schema.ts +6 -0
  85. package/src/config/schema/leaf-validators.ts +2 -0
  86. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  87. package/src/config.ts +7 -7
  88. package/src/desktop-update/acquire.ts +202 -0
  89. package/src/desktop-update/cli.ts +168 -0
  90. package/src/desktop-update/drain.ts +40 -0
  91. package/src/desktop-update/headless.ts +285 -0
  92. package/src/desktop-update/image.ts +85 -0
  93. package/src/desktop-update/install.ts +53 -0
  94. package/src/desktop-update/msi.ts +72 -0
  95. package/src/desktop-update/release.ts +128 -0
  96. package/src/desktop-update/runtime.ts +155 -0
  97. package/src/desktop-update/staging.ts +118 -0
  98. package/src/desktop-update/trust.ts +45 -0
  99. package/src/generated/compatibility-version.json +246 -130
  100. package/src/images/fulfill-video.ts +3 -3
  101. package/src/images/loop.ts +6 -2
  102. package/src/images/plan.ts +147 -11
  103. package/src/images/types.ts +13 -4
  104. package/src/images/xai-video-client.ts +72 -10
  105. package/src/lib/gcp-adc.ts +48 -4
  106. package/src/lib/offline-resend.ts +150 -0
  107. package/src/lib/paced-stream.ts +3 -3
  108. package/src/lib/provider-outbound.ts +17 -6
  109. package/src/lib/request-failure-model.ts +2 -0
  110. package/src/lib/response-body-inactivity.ts +23 -1
  111. package/src/lib/upstream-retry.ts +38 -5
  112. package/src/link/explicit-route.ts +4 -4
  113. package/src/link/remote-windows.ts +79 -31
  114. package/src/link/residual-recovery.ts +20 -8
  115. package/src/messaging/budget.ts +23 -5
  116. package/src/messaging/rpc.ts +4 -4
  117. package/src/oauth/antigravity-risk.ts +126 -0
  118. package/src/oauth/generic-account-failover.ts +89 -18
  119. package/src/oauth/generic-session-affinity.ts +10 -3
  120. package/src/oauth/login-cli.ts +35 -1
  121. package/src/oauth/pool-kernel.ts +3 -3
  122. package/src/providers/anthropic-billing-refusal.ts +27 -3
  123. package/src/providers/google-vertex-model-discovery.ts +6 -1
  124. package/src/providers/model-rename-fields.ts +2 -0
  125. package/src/providers/quota/workbuddy.ts +6 -2
  126. package/src/providers/workbuddy-credit-balance.ts +125 -16
  127. package/src/responses/effort-history.ts +732 -0
  128. package/src/routing/history/integrity.ts +41 -4
  129. package/src/server/auth-cors.ts +13 -3
  130. package/src/server/codex-model-list.ts +2 -1
  131. package/src/server/direct-local-http.ts +26 -3
  132. package/src/server/index/link-listener.ts +20 -14
  133. package/src/server/index/serve-options.ts +1 -0
  134. package/src/server/index.ts +3 -2
  135. package/src/server/link-turn.ts +17 -5
  136. package/src/server/management/config-routes.ts +39 -3
  137. package/src/server/management/link-child-preflight.ts +1 -1
  138. package/src/server/management/link-route-edit.ts +20 -1
  139. package/src/server/management/oauth-account-routes.ts +22 -5
  140. package/src/server/management/provider-overwrite-carry.ts +3 -0
  141. package/src/server/management/provider-routes.ts +4 -4
  142. package/src/server/management/static-catalog-probe.ts +33 -0
  143. package/src/server/proxy-liveness.ts +54 -9
  144. package/src/server/relay.ts +6 -1
  145. package/src/server/request-log-conversation.ts +2 -2
  146. package/src/server/request-log.ts +5 -1
  147. package/src/server/reserve-capability-startup.ts +32 -0
  148. package/src/server/responses/adapter-delivery.ts +2 -0
  149. package/src/server/responses/adapter-dispatch.ts +31 -10
  150. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  151. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  152. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  153. package/src/server/responses/core-combo.ts +24 -9
  154. package/src/server/responses/core-errors.ts +9 -6
  155. package/src/server/responses/core-options.ts +8 -0
  156. package/src/server/responses/core.ts +21 -0
  157. package/src/server/responses/estimated-usage.ts +115 -0
  158. package/src/server/responses/jev-model-invoke.ts +7 -2
  159. package/src/server/responses/passthrough-completion.ts +6 -3
  160. package/src/server/responses/passthrough-delivery.ts +47 -8
  161. package/src/server/responses/passthrough-dispatch.ts +3 -0
  162. package/src/server/responses/request-prepare.ts +9 -5
  163. package/src/server/responses/sidecar-execution.ts +5 -0
  164. package/src/service/desktop-supervision.d.mts +2 -0
  165. package/src/service/desktop-supervision.mjs +5 -0
  166. package/src/stall-timeout.ts +11 -0
  167. package/src/types/config.ts +15 -92
  168. package/src/types/provider.ts +13 -0
  169. package/src/types/request.ts +19 -0
  170. package/src/types/routed-catalog-defaults.ts +17 -0
  171. package/src/types/routing-profile.ts +90 -0
  172. package/src/types.ts +1 -0
  173. package/src/update/index.ts +1 -1
  174. package/src/usage/log.ts +14 -4
  175. package/src/usage/telemetry-contract.ts +1 -0
  176. package/src/web-search/passthrough-bridge.ts +7 -0
  177. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  178. package/gui/dist/assets/index-DCdXsMyZ.js +0 -105
  179. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  180. package/gui/dist/classic/assets/index-BqOaGLf5.js +0 -105
  181. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -1651,10 +1651,10 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
1651
1651
  return jsonResponse(await probeJevDecisionProvider(config, name, { signal: req.signal }));
1652
1652
  }
1653
1653
  if (prov.liveModels === false) {
1654
- // A static catalog has no live discovery endpoint to test. This is neither
1655
- // positive connectivity evidence nor an outage, and it must stay before
1656
- // credential resolution/network access for providers such as Antigravity.
1657
- return jsonResponse({ applicable: false, reason: "static_catalog", latencyMs: 0 });
1654
+ // No live discovery endpoint. Only Vertex ADC still has a credential to verify; every other
1655
+ // static catalog must stay before credential resolution/network access (e.g. Antigravity).
1656
+ const { staticCatalogConnectionTest } = await import("./static-catalog-probe");
1657
+ return jsonResponse(await staticCatalogConnectionTest(name, prov, req.signal));
1658
1658
  }
1659
1659
  const { buildModelsRequest, getModelsOAuthAccessSnapshot, resolveModelsAuthToken } = await import("../../oauth");
1660
1660
  const antigravity = effectiveGoogleMode(name, prov) === "cloud-code-assist";
@@ -0,0 +1,33 @@
1
+ import type { OcxProviderConfig } from "../../types";
2
+ import { vertexConfiguredCredentialKind } from "../../lib/gcp-adc";
3
+ import { resolveVertexDiscoveryAuth, selectVertexDiscoveryCredential, vertexDiscoveryDeadline } from "../../providers/google-vertex-model-discovery";
4
+ import { effectiveGoogleMode } from "../../providers/registry";
5
+
6
+ export type StaticCatalogProbeResult =
7
+ | { applicable: false; reason: "static_catalog"; latencyMs: 0 }
8
+ | { ok: boolean; latencyMs: number; message?: string; error?: string };
9
+
10
+ /**
11
+ * Connection test for a provider without live model discovery. There is no models endpoint to
12
+ * call, so most such providers have nothing to test. Vertex on Application Default Credentials
13
+ * (or a `gcp-sa:` marker) still has a credential: minting an access token proves it, needs no
14
+ * model list, and is the same exchange the first real request performs. The probe forces a new
15
+ * exchange: a cached token would keep reporting ok for up to an hour after the credential is revoked.
16
+ */
17
+ export async function staticCatalogConnectionTest(name: string, provider: OcxProviderConfig, signal?: AbortSignal): Promise<StaticCatalogProbeResult> {
18
+ if (effectiveGoogleMode(name, provider) !== "vertex") {
19
+ return { applicable: false, reason: "static_catalog", latencyMs: 0 };
20
+ }
21
+ // A literal key or a keychain:/${ENV} reference is an API key: answer before anything is resolved,
22
+ // so this probe never reads the credential store for a row it cannot test.
23
+ const configured = vertexConfiguredCredentialKind(provider.apiKey);
24
+ if (configured === "api-key" || configured === "reference" || selectVertexDiscoveryCredential(provider).kind === "api-key") {
25
+ return { applicable: false, reason: "static_catalog", latencyMs: 0 };
26
+ }
27
+ const started = Date.now();
28
+ const auth = await resolveVertexDiscoveryAuth(provider, vertexDiscoveryDeadline(signal), { forceExchange: true });
29
+ const latencyMs = Date.now() - started;
30
+ return auth
31
+ ? { ok: true, latencyMs, message: "Google Cloud credentials verified (access token issued). Static model catalog; no live model list." }
32
+ : { ok: false, latencyMs, error: "Google Cloud credentials could not issue an access token. Check `gcloud auth application-default login` or GOOGLE_APPLICATION_CREDENTIALS." };
33
+ }
@@ -17,6 +17,7 @@ import {
17
17
  runtimeOwnerScope, sameRuntimeOwnerScope, verifyPidIdentity, type RuntimeOwnerScope,
18
18
  } from "../config/process-state";
19
19
  import { createServer, isIP } from "node:net";
20
+ import { networkInterfaces } from "node:os";
20
21
  import { loopbackFamilyAvailability } from "../lib/loopback-family";
21
22
  import {
22
23
  LOCAL_ATTESTATION_CHALLENGE_HEADER,
@@ -24,7 +25,7 @@ import {
24
25
  createLocalAttestationChallenge,
25
26
  verifyLocalAttestationProof,
26
27
  } from "../lib/local-management-attestation";
27
- import { directLocalHttpFetch } from "./direct-local-http";
28
+ import { directLocalHttpFetch, isConnectPhaseTimeout } from "./direct-local-http";
28
29
 
29
30
  export interface HealthzIdentity {
30
31
  service?: unknown;
@@ -397,14 +398,36 @@ export async function classifyHealthz(
397
398
  fetchFn: LivenessFetch,
398
399
  timeoutMs: number,
399
400
  ): Promise<EndpointLiveness> {
401
+ return (await classifyHealthzDetailed(url, fetchFn, timeoutMs)).verdict;
402
+ }
403
+
404
+ /** {@link classifyHealthz} plus whether an unknown verdict was a connect that timed out (#8318). */
405
+ async function classifyHealthzDetailed(
406
+ url: string,
407
+ fetchFn: LivenessFetch,
408
+ timeoutMs: number,
409
+ ): Promise<{ verdict: EndpointLiveness; connectTimeout: boolean }> {
410
+ const answer = (verdict: EndpointLiveness, connectTimeout = false) => ({ verdict, connectTimeout });
400
411
  try {
401
412
  const response = await fetchFn(url, { signal: AbortSignal.timeout(timeoutMs) });
402
- if (response.status !== 200) return "unknown";
413
+ if (response.status !== 200) return answer("unknown");
403
414
  const body = (await response.json().catch(() => undefined)) as HealthzIdentity | null | undefined;
404
- if (body === undefined) return "unknown";
405
- return isOpencodexHealthz(body) ? "live" : "dead";
415
+ if (body === undefined) return answer("unknown");
416
+ return answer(isOpencodexHealthz(body) ? "live" : "dead");
406
417
  } catch (error) {
407
- return isConnectionRefused(error) ? "dead" : "unknown";
418
+ return isConnectionRefused(error) ? answer("dead") : answer("unknown", isConnectPhaseTimeout(error));
419
+ }
420
+ }
421
+
422
+ /** Whether `address` (unbracketed) is assigned to one of this machine's network interfaces. */
423
+ export function isLocalInterfaceAddress(address: string): boolean {
424
+ const canonical = (value: string) => isIP(value) === 6 ? new URL(`http://[${value.split("%")[0]}]/`).hostname.slice(1, -1) : value;
425
+ const wanted = canonical(address);
426
+ try {
427
+ return Object.values(networkInterfaces()).some(entries =>
428
+ (entries ?? []).some(entry => canonical(entry.address) === wanted));
429
+ } catch {
430
+ return false;
408
431
  }
409
432
  }
410
433
 
@@ -417,24 +440,46 @@ export async function classifyHealthz(
417
440
  */
418
441
  export async function probeEndpointLiveness(
419
442
  endpoint: { port: number; hostname?: string },
420
- io: Pick<LivenessIo, "fetchFn" | "timeoutMs"> = {},
443
+ io: Pick<LivenessIo, "fetchFn" | "timeoutMs" | "bindProofFn"> & {
444
+ /** Test seam for {@link isLocalInterfaceAddress}. */
445
+ localAddressFn?: (address: string) => boolean;
446
+ } = {},
421
447
  ): Promise<EndpointLiveness> {
422
448
  if (!Number.isFinite(endpoint.port) || endpoint.port <= 0 || endpoint.port > 65535) return "dead";
423
449
  const fetchFn = io.fetchFn ?? directLocalHttpFetch;
424
450
  const timeoutMs = io.timeoutMs ?? 1500;
425
451
  let sawUnknown = false;
426
452
  for (const hostname of loopbackProbeHosts(endpoint.hostname)) {
427
- const result = await classifyHealthz(
453
+ const { verdict, connectTimeout } = await classifyHealthzDetailed(
428
454
  `http://${hostname}:${endpoint.port}/healthz`,
429
455
  fetchFn,
430
456
  timeoutMs,
431
457
  );
432
- if (result === "live") return "live";
433
- if (result === "unknown") sawUnknown = true;
458
+ if (verdict === "live") return "live";
459
+ if (verdict === "unknown" && !(connectTimeout && await provenFreeByBind(hostname, endpoint.port, io))) sawUnknown = true;
434
460
  }
435
461
  return sawUnknown ? "unknown" : "dead";
436
462
  }
437
463
 
464
+ /**
465
+ * #8318: a connect to this machine's own non-loopback address (a Tailscale IP) with nothing
466
+ * listening can time out instead of being refused, which left `ocx resolve` unknown forever. Only
467
+ * a connect-phase timeout on a specific address of a local interface qualifies, and only an
468
+ * exclusive bind that succeeds (and is released at once) proves absence; EADDRINUSE or any other
469
+ * bind error keeps the verdict unknown. Loopback and wildcard binds keep their refusal-only rule,
470
+ * because a wildcard listener can share the port with a specific bind on some platforms.
471
+ */
472
+ async function provenFreeByBind(
473
+ probeHost: string,
474
+ port: number,
475
+ io: { bindProofFn?: LivenessIo["bindProofFn"]; localAddressFn?: (address: string) => boolean },
476
+ ): Promise<boolean> {
477
+ const address = probeHost.replace(/^\[(.*)\]$/, "$1");
478
+ if (isIP(address) === 0 || recoveryLoopbackFamily(address) !== null || isWildcardHostname(address)) return false;
479
+ if (!(io.localAddressFn ?? isLocalInterfaceAddress)(address)) return false;
480
+ return await (io.bindProofFn ?? canBindAddress)(address, port, BIND_PROOF_TIMEOUT_MS);
481
+ }
482
+
438
483
  /** Identity-checked /healthz probe; null when unreachable, non-OK, or not our proxy. */
439
484
  export async function proxyIdentityAt(
440
485
  port: number,
@@ -11,6 +11,7 @@ import {
11
11
  } from "../lib/errors";
12
12
  import { redactSecretString } from "../lib/redact";
13
13
  import { isTranslatorBudgetExceededError } from "../lib/translator-budget";
14
+ import { ExplicitBodyStallError } from "../lib/response-body-inactivity";
14
15
  import { carryPacedStream, pacedQueuingStrategy } from "../lib/paced-stream";
15
16
  import { carryReplayRefusal, isReplayRefusalResponse } from "../lib/upstream-retry";
16
17
  import { isUsageDebugEnabled } from "../usage/debug";
@@ -133,14 +134,18 @@ export function relayWithAbort(
133
134
 
134
135
  export function buildFailedTailPayload(err: unknown, maskCredential?: (text: string) => string): string {
135
136
  const translatorOverflow = isTranslatorBudgetExceededError(err);
137
+ // The operator's explicit stall budget expired: report the stall terminal the adapter paths use.
138
+ // A guard on a default budget (reset selection with the field unset) keeps its earlier reset tail.
139
+ const stalled = err instanceof ExplicitBodyStallError;
136
140
  const raw = translatorOverflow
137
141
  ? "upstream translation buffer exceeded the safe limit"
142
+ : stalled ? err.message
138
143
  : `Upstream stream terminated unexpectedly: ${err instanceof Error ? err.message : String(err)}`;
139
144
  // Exact mask before pattern redaction, which could split a credential and hide it from the mask.
140
145
  const message = redactSecretString(maskCredential?.(raw) ?? raw).slice(0, MAX_TAIL_ERROR_MESSAGE_CHARS);
141
146
  const failure = {
142
147
  type: "upstream_error",
143
- code: translatorOverflow ? "translation_buffer_limit" : "upstream_reset",
148
+ code: translatorOverflow ? "translation_buffer_limit" : stalled ? "upstream_stall_timeout" : "upstream_reset",
144
149
  message,
145
150
  };
146
151
  return JSON.stringify({
@@ -286,8 +286,8 @@ export function conversationIdFromClaudeMetadata(
286
286
  metadata: { user_id?: unknown } | null | undefined,
287
287
  ): string | undefined {
288
288
  if (!metadata || typeof metadata.user_id !== "string") return undefined;
289
- // Too long to persist: skip parsing a blob normalizeLogConversationId rejects anyway.
290
- if (metadata.user_id.trim().length > LOG_CONVERSATION_ID_INPUT_MAX) return undefined;
289
+ // No length guard before stripping tk: an oversized tk still leaves a valid session id,
290
+ // which also gates Claude routing identity (claude-messages.ts claudeNativeSessionId).
291
291
  return normalizeLogConversationId(claudeSessionUserId(metadata.user_id));
292
292
  }
293
293
 
@@ -252,6 +252,10 @@ export interface RequestLogContext extends UpstreamErrorDiagnostics, LinkRequest
252
252
  * responsesUsage in src/bridge.ts), so SSE/JSON re-parsing must not overwrite the raw
253
253
  * provenance — a synthetic cached_tokens:0 is NOT a measured cache read. */
254
254
  usageFromBridge?: boolean;
255
+ /** Set once the client-facing body carries an estimated usage the provider never sent (#7427).
256
+ * The provider's own body was inspected before the estimate was added, so a later parse of
257
+ * the client body must not record the estimate as provider-reported usage. */
258
+ usageEstimatedForClient?: boolean;
255
259
  /** Secret-redacted upstream error reason (e.g. the granular Cursor "rate limit exceeded…"
256
260
  * message) extracted from a `response.failed` SSE payload or non-streaming error body, so the
257
261
  * request log / GUI shows the actual upstream failure rather than only the HTTP-mapped code. */
@@ -1049,7 +1053,7 @@ export function applyResponseLogMetadata(logCtx: RequestLogContext, payload: unk
1049
1053
  logCtx.activeTierMetadata?.observeResponseServiceTier(serviceTier);
1050
1054
  }
1051
1055
  const usage = usageFromResponsesPayload((source as { usage?: unknown }).usage);
1052
- if (usage && !logCtx.usageFromBridge) {
1056
+ if (usage && !logCtx.usageFromBridge && !logCtx.usageEstimatedForClient) {
1053
1057
  if (!recordKeyWireAttemptUsage(logCtx, usage)) {
1054
1058
  logCtx.usage = usage;
1055
1059
  if (logCtx.activeAttempt) logCtx.activeAttempt.usage = usage;
@@ -0,0 +1,32 @@
1
+ import { mutatePersistedConfig } from "../config";
2
+ import { adoptReserveCapabilityMigration, isReserveCapabilityMigrated, migrateReserveCapability } from "../config/reserve-capability";
3
+ import type { OcxConfig } from "../types";
4
+
5
+ /**
6
+ * Persist the one-time Reserve seed at startup (#4961), so a later hand edit of authless cannot move
7
+ * Reserve. The seed is the file's current authless value: the value being migrated.
8
+ *
9
+ * Only the two Reserve fields are adopted, in place: earlier startup migrations may hold in-memory
10
+ * results whose persistence was unavailable, and the loaded object carries identity-keyed state
11
+ * (file-backed provenance) that a copy would lose. On failure nothing is marked, so the legacy
12
+ * reading continues and the next persisted write seeds from the file instead.
13
+ */
14
+ export function migrateStartupReserveCapability(
15
+ config: OcxConfig,
16
+ mutate: typeof mutatePersistedConfig = mutatePersistedConfig,
17
+ ): OcxConfig {
18
+ if (isReserveCapabilityMigrated(config)) return config;
19
+ try {
20
+ const outcome = mutate(fresh => ({ changed: migrateReserveCapability(fresh), value: fresh }));
21
+ if (outcome.status === "unavailable") {
22
+ console.warn(`[reserve-capability-migration] Persistence unavailable (${outcome.reason}); Reserve still follows codexDesktopAuthless until the next config write.`);
23
+ return config;
24
+ }
25
+ adoptReserveCapabilityMigration(config, outcome.value);
26
+ return config;
27
+ } catch {
28
+ // Do not log the exception: filesystem errors may contain private paths.
29
+ console.warn("[reserve-capability-migration] Persistence failed; Reserve still follows codexDesktopAuthless until the next config write.");
30
+ return config;
31
+ }
32
+ }
@@ -30,6 +30,7 @@ import { isNonReplayableResponse } from "../../lib/upstream-retry";
30
30
  import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers";
31
31
  import { currentTurnToolBridgeMaps, guardEmptyToolCatalogEvents, guardEmptyToolCatalogStream } from "../../lib/empty-tool-catalog";
32
32
  import { guardCompactionSummary } from "../../responses/compaction-summary";
33
+ import { settleAnthropicPerMessageEffort } from "../../adapters/anthropic/per-message-effort";
33
34
 
34
35
  /** One responsibility of the Responses request pipeline; state owners are explicit. */
35
36
  export async function deliverAdapterResponse(
@@ -208,6 +209,7 @@ export async function deliverAdapterResponse(
208
209
  // direct client encoder from the fold of the same events.
209
210
  const onCompletedResponse = (response: Record<string, unknown>, providerState?: OcxProviderContinuationState) => {
210
211
  if (!options.abortSignal?.aborted) thinkingSignatureRecovery.rememberSuccess(response);
212
+ settleAnthropicPerMessageEffort(parsed, response, transportState.activeAdapter.name);
211
213
  const served = transportState.sentOAuthSnapshot;
212
214
  if (transportState.activeAdapter.name === "kiro" && response.status === "completed" && served
213
215
  && noteKiroServedSuccess(served.accountId, served.generation)) persistKiroAccountState();
@@ -64,6 +64,7 @@ import {
64
64
  sleepWithAbort,
65
65
  } from "../../lib/upstream-retry";
66
66
  import { describeUpstreamConnectFailure } from "./upstream-error";
67
+ import { createProviderOfflineResendWait } from "../../lib/offline-resend";
67
68
  import type { OpaqueBlobRecoveryGuard } from "./core-opaque-recovery";
68
69
  import type { AttemptRecoveryKind } from "../../usage/log";
69
70
  import type { OAuthAccessSnapshot } from "../../oauth";
@@ -92,6 +93,7 @@ import {
92
93
  quarantineKiroSuspendedAccount,
93
94
  failoverAccountSnapshot,
94
95
  rotateAntigravityAccountOnAuthRefusal,
96
+ rotateAntigravityAccountOnUpstreamFault,
95
97
  } from "../../oauth/generic-account-failover";
96
98
  import {
97
99
  attemptOpaqueBlobRecovery,
@@ -119,10 +121,12 @@ import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers";
119
121
  import { mapCodexAuthContextErrorToResponse } from "./codex-auth-error";
120
122
  import { chargeWorkflowSends } from "../../lib/workflow-budget";
121
123
  import { hasWorkflowSendObserver } from "../../lib/request-execution-budget";
122
- import { isAntigravityValidationRefusal } from "./antigravity-validation-refusal";
124
+ import { isAntigravityAccessDeniedRefusal, isAntigravityValidationRefusal } from "./antigravity-validation-refusal";
123
125
  import { createAntigravityModelDenialRecovery, recoverAntigravityAccount } from "./antigravity-model-denial-recovery";
126
+ import { isAntigravityFaultRotatable } from "./antigravity-fault-rotation";
124
127
  import { adapterSendBudgetRefusal } from "../workflow-refusal";
125
128
  import { AdmissionModelDeniedError, admissionModelDeniedResponse, projectAdmissionModelDeniedLog } from "../admission-model-scope";
129
+ import { rejectAnthropicPerMessageEffort } from "../../adapters/anthropic/per-message-effort";
126
130
  /** One responsibility of the Responses request pipeline; state owners are explicit. */
127
131
  export async function prepareAdapterExchange(
128
132
  requestContext: Pick<ResponsesRequestContext, "options" | "config" | "logCtx" | "req">,
@@ -521,6 +525,7 @@ export async function prepareAdapterExchange(
521
525
  abortSignal: upstream.signal,
522
526
  label: safeHostLabel(builtInitialRequest.url), destination: errorDestinationLabel(builtInitialRequest.url),
523
527
  claimAmbiguousResend: claimPreHeaderResend,
528
+ offlineWait: options.comboAttempt ? undefined : createProviderOfflineResendWait(route.providerName, route.provider, builtInitialRequest.url, config.offlineResendWaitSec),
524
529
  ...(sendBudgetState.workflowRootId || sendBudgetState.adapterSendBudget?.spendEnforced || options.comboDispatchPermit || transientPolicy || resetPolicy || compactPrepaid || options.comboAttempt
525
530
  || billingPoolRequest || autoPauseEnabled
526
531
  ? {
@@ -611,6 +616,9 @@ export async function prepareAdapterExchange(
611
616
  const consoleGoUploadRetryGuard: { attempted: boolean } = { attempted: false };
612
617
  let oauth401ReplayAttempted = transportState.oauth401ReplayAttempted;
613
618
  let antigravityAuthRotationAttempted = false;
619
+ let antigravityFaultRotationAttempted = false;
620
+ const antigravityFaultRotatable = (response: Response) => isAntigravityFaultRotatable(route.providerName, response,
621
+ transportState, antigravityPoolActivated, antigravityFaultRotationAttempted);
614
622
  // Direct requests get one reasoning-effort downgrade. Combo candidates may walk down the
615
623
  // published ladder one refused rung at a time; the request send budget bounds those retries.
616
624
  const reasoningEffortDowngradeGuard: { attempted: boolean } = { attempted: false };
@@ -877,14 +885,14 @@ export async function prepareAdapterExchange(
877
885
  const rotateAntigravityAuth = async (
878
886
  failedResponse: Response,
879
887
  recovery: AttemptRecoveryKind,
880
- modelAccountId?: string,
888
+ // An account id (model-404 recovery already chose it) or a selector; the 403 refusal default.
889
+ pick: string | ((sent: { accountId: string; generation: string }) => string | null) = sent =>
890
+ rotateAntigravityAccountOnAuthRefusal(antigravityPoolActivated, sent.accountId, sent.generation, route.modelId),
881
891
  ): Promise<Response | null> => {
882
892
  const sent = transportState.replayOAuthCredentialSnapshot ?? transportState.sentOAuthSnapshot;
883
893
  if (!antigravityPoolActivated || !sent
884
894
  || transportState.genericFailovers >= transportState.genericFailoverLimit) return null;
885
- const nextId = modelAccountId ?? rotateAntigravityAccountOnAuthRefusal(
886
- antigravityPoolActivated, sent.accountId, sent.generation, route.modelId,
887
- );
895
+ const nextId = typeof pick === "string" ? pick : pick(sent);
888
896
  if (!nextId) return null;
889
897
  const adapterOwnsDispatch = transportState.activeAdapter.fetchResponse !== undefined;
890
898
  return recoverAntigravityAccount({ nextId, failedResponse, adapterOwnsDispatch,
@@ -931,6 +939,7 @@ export async function prepareAdapterExchange(
931
939
 
932
940
  // Preserve the terminal verdict through adapter and combo error formatting.
933
941
  // This also covers a reset reached by a 401/429/413 recovery refetch.
942
+ await rejectAnthropicPerMessageEffort(parsed, upstreamResponse, upstream.signal);
934
943
  if (isNonReplayableResponse(upstreamResponse)) {
935
944
  try {
936
945
  return await sanitizeNonReplayableUpstreamError(upstreamResponse, upstream.signal);
@@ -1076,15 +1085,26 @@ export async function prepareAdapterExchange(
1076
1085
 
1077
1086
  if (route.providerName === "google-antigravity" && upstreamResponse.status === 403
1078
1087
  && transportState.activeAdapter.name === "google"
1079
- && antigravityPoolActivated && !antigravityAuthRotationAttempted
1088
+ && antigravityPoolActivated
1080
1089
  && !isNonReplayableResponse(upstreamResponse)
1081
1090
  && transportState.genericFailovers < transportState.genericFailoverLimit
1082
- && await isAntigravityValidationRefusal(upstreamResponse, options.abortSignal)) {
1091
+ && (!antigravityAuthRotationAttempted && await isAntigravityValidationRefusal(upstreamResponse, options.abortSignal)
1092
+ // A plain access-denied 403 keeps rotating while siblings remain: each refused account is
1093
+ // cooled before the hop, so the ring advances and `genericFailoverLimit` bounds the sends.
1094
+ || await isAntigravityAccessDeniedRefusal(upstreamResponse, options.abortSignal))) {
1083
1095
  antigravityAuthRotationAttempted = true;
1084
1096
  const rotated = await rotateAntigravityAuth(upstreamResponse, "oauth-account-403");
1085
1097
  if (rotated) { upstreamResponse = rotated; continue recovery; }
1086
1098
  }
1087
1099
 
1100
+ // A 502/503/504 that outlived the same-account ladder replays once on a live sibling.
1101
+ if (antigravityFaultRotatable(upstreamResponse)) {
1102
+ antigravityFaultRotationAttempted = true;
1103
+ const rotated = await rotateAntigravityAuth(upstreamResponse, "transient-5xx", sent =>
1104
+ rotateAntigravityAccountOnUpstreamFault(antigravityPoolActivated, sent.accountId, sent.generation, route.modelId));
1105
+ if (rotated) { upstreamResponse = rotated; continue recovery; }
1106
+ }
1107
+
1088
1108
  // Static API-key pools can recover a credential-scoped 401 without abandoning the
1089
1109
  // provider: one revoked or mistyped key says nothing about its siblings. OAuth providers
1090
1110
  // refresh above and never enter here — `hasKeyPoolFailover` rejects oauth/forward modes.
@@ -1629,8 +1649,9 @@ export async function prepareAdapterExchange(
1629
1649
  }
1630
1650
  upstreamResponse = result;
1631
1651
  // The hop's permit is already settled by the dispatch boundary above; continuing
1632
- // only skips the remaining arms, it does not abandon a reservation.
1633
- if (isNonReplayableResponse(upstreamResponse)) continue recovery;
1652
+ // only skips the remaining arms, it does not abandon a reservation. A replacement's
1653
+ // surviving 502/503/504 re-enters recovery so the one-hop fault rotation can run.
1654
+ if (isNonReplayableResponse(upstreamResponse) || antigravityFaultRotatable(upstreamResponse)) continue recovery;
1634
1655
  } catch (err) {
1635
1656
  // A local admission denial is terminal for the whole request: rotating to another
1636
1657
  // account cannot re-scope the key, so the refusal answers in place of the 429.
@@ -1743,7 +1764,7 @@ export async function prepareAdapterExchange(
1743
1764
  transportState.genericFailovers += 1;
1744
1765
  try { void failedResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ }
1745
1766
  upstreamResponse = result;
1746
- if (isNonReplayableResponse(upstreamResponse)) continue recovery;
1767
+ if (isNonReplayableResponse(upstreamResponse) || antigravityFaultRotatable(upstreamResponse)) continue recovery;
1747
1768
  } catch {
1748
1769
  hop.permit?.release();
1749
1770
  break;
@@ -0,0 +1,24 @@
1
+ import { isNonReplayableResponse } from "../../lib/upstream-retry";
2
+
3
+ /**
4
+ * Whether an Antigravity 502/503/504 that outlived the same-account transient ladder may be
5
+ * replayed once on a live sibling. The failing account is cooled briefly (not marked), and the
6
+ * per-request `attempted` flag keeps a pool-wide outage to one extra ladder per request.
7
+ *
8
+ * The recovery loop asks this for the response it is holding and again for the response a 429
9
+ * account hop or a verify-account 403 hop just produced: that hop's replacement can be the 5xx, and
10
+ * without asking here the hop loop would leave recovery with the one-hop fault rotation still unspent.
11
+ */
12
+ export function isAntigravityFaultRotatable(
13
+ providerName: string,
14
+ response: Response,
15
+ state: { activeAdapter: { name: string }; genericFailovers: number; genericFailoverLimit: number },
16
+ poolActivated: boolean,
17
+ faultRotationAttempted: boolean,
18
+ ): boolean {
19
+ return providerName === "google-antigravity" && [502, 503, 504].includes(response.status)
20
+ && state.activeAdapter.name === "google"
21
+ && poolActivated && !faultRotationAttempted
22
+ && !isNonReplayableResponse(response)
23
+ && state.genericFailovers < state.genericFailoverLimit;
24
+ }
@@ -1,23 +1,60 @@
1
- import { ANTIGRAVITY_VALIDATION_REQUIRED_PREFIX, safeAntigravityHttpErrorMessage } from "../../adapters/google-errors";
1
+ import {
2
+ ANTIGRAVITY_ACCESS_DENIED_PREFIX, ANTIGRAVITY_AUTH_FAILED_PREFIX, ANTIGRAVITY_VALIDATION_REQUIRED_PREFIX,
3
+ GOOGLE_PERMISSION_DENIED_SUFFIX, safeAntigravityHttpErrorMessage,
4
+ } from "../../adapters/google-errors";
2
5
  import { readBoundedResponseBody } from "../../lib/bounded-body";
3
- import { hasAntigravityModelNotFoundProvenance } from "../../adapters/antigravity-refusal";
6
+ import { classifyAntigravityRefusal, hasAntigravityModelNotFoundProvenance } from "../../adapters/antigravity-refusal";
4
7
 
5
8
  /** Match only the normalized Antigravity validation-refusal marker. */
6
9
  export function hasAntigravityValidationRefusalMarker(text: string): boolean {
7
10
  return text.startsWith(`${ANTIGRAVITY_VALIDATION_REQUIRED_PREFIX}: `);
8
11
  }
9
12
 
13
+ /**
14
+ * A normalized 403 that Google itself attributed to this account: a structured `PERMISSION_DENIED`
15
+ * envelope, worded either as a plain denial or as invalid/expired credentials. `classifyGoogle` keeps
16
+ * the "(PERMISSION_DENIED)" suffix on both prefixes only when it parsed that enum. Not a validation
17
+ * demand and not a "verify your account" conviction (the dedicated quarantine path owns that one). The
18
+ * caller cools the account and tries a sibling; nothing here marks the account durably.
19
+ *
20
+ * `classifyGoogle` writes the bare "Antigravity access denied" prefix for every 403, including an empty
21
+ * body, a proxy or WAF HTML page, or an envelope without the enum, and the bare "Antigravity
22
+ * authentication failed" prefix for any 403 whose text says "expired" or "unauthenticated". Neither
23
+ * bare prefix says anything about this account, so neither qualifies: accepting one would walk the
24
+ * whole pool and cool every account on a failure that is wrong for all of them.
25
+ *
26
+ * Text that carries the validation marker is never an access denial: that wording belongs to the
27
+ * validation path, and an upstream message imitating it must not earn a different recovery.
28
+ */
29
+ export function hasAntigravityAccessDeniedMarker(text: string): boolean {
30
+ return (text.startsWith(`${ANTIGRAVITY_ACCESS_DENIED_PREFIX}${GOOGLE_PERMISSION_DENIED_SUFFIX}`)
31
+ || text.startsWith(`${ANTIGRAVITY_AUTH_FAILED_PREFIX}${GOOGLE_PERMISSION_DENIED_SUFFIX}`))
32
+ && !text.includes(ANTIGRAVITY_VALIDATION_REQUIRED_PREFIX)
33
+ && classifyAntigravityRefusal(403, text).kind === "other";
34
+ }
35
+
10
36
  /** Inspect only the Google adapter's normalized, already bounded 403 response. */
11
37
  export async function isAntigravityValidationRefusal(response: Response, signal?: AbortSignal): Promise<boolean> {
12
- return inspectValidationRefusal(response, signal, false);
38
+ return inspectValidationRefusal(response, signal, false, hasAntigravityValidationRefusalMarker);
39
+ }
40
+
41
+ /** Normalized 403 whose account is simply refused: cool it and rotate (credential-rejected). */
42
+ export async function isAntigravityAccessDeniedRefusal(response: Response, signal?: AbortSignal): Promise<boolean> {
43
+ return inspectValidationRefusal(response, signal, false, hasAntigravityAccessDeniedMarker);
13
44
  }
14
45
 
15
46
  /** Sidecar dispatch retains the raw Google envelope; normalize only a complete bounded body. */
16
47
  export async function isAntigravityRawValidationRefusal(response: Response, signal?: AbortSignal): Promise<boolean> {
17
- return inspectValidationRefusal(response, signal, true);
48
+ return inspectValidationRefusal(response, signal, true,
49
+ text => hasAntigravityValidationRefusalMarker(text) || hasAntigravityAccessDeniedMarker(text));
18
50
  }
19
51
 
20
- async function inspectValidationRefusal(response: Response, signal: AbortSignal | undefined, raw: boolean): Promise<boolean> {
52
+ async function inspectValidationRefusal(
53
+ response: Response,
54
+ signal: AbortSignal | undefined,
55
+ raw: boolean,
56
+ accepts: (text: string) => boolean,
57
+ ): Promise<boolean> {
21
58
  if (response.status !== 403 || signal?.aborted) return false;
22
59
  try {
23
60
  const body = await readBoundedResponseBody(response.clone(), {
@@ -28,7 +65,7 @@ async function inspectValidationRefusal(response: Response, signal: AbortSignal
28
65
  signal,
29
66
  });
30
67
  return !signal?.aborted && body.displaySafe && !body.truncated && !body.timedOut && !body.oversized
31
- && hasAntigravityValidationRefusalMarker(raw ? safeAntigravityHttpErrorMessage(403, body.text) : body.text);
68
+ && accepts(raw ? safeAntigravityHttpErrorMessage(403, body.text) : body.text);
32
69
  } catch {
33
70
  return false;
34
71
  }