@bitkyc08/opencodex 2.99.0 → 2.100.1

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 (276) hide show
  1. package/AGENTS_INSTALL.md +19 -1
  2. package/README.md +37 -33
  3. package/SPONSORS.md +5 -1
  4. package/bin/ocx.mjs +1 -1
  5. package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
  6. package/gui/dist/assets/App-g3Cm2xhZ.js +59 -0
  7. package/gui/dist/assets/Tray-BMDkAiXy.js +1 -0
  8. package/gui/dist/assets/brand-mark-nr3ziR-T.js +1 -0
  9. package/gui/dist/assets/index-Bziu8gTy.css +2 -0
  10. package/gui/dist/assets/index-OYzhQUNP.js +94 -0
  11. package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-DKCVUUTi.js} +1 -1
  12. package/gui/dist/classic/assets/App-CgPBKUP-.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-BedmOsE7.js} +1 -1
  14. package/gui/dist/classic/assets/index-BR-HhNrp.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +1 -0
  16. package/gui/dist/classic/index.html +1 -1
  17. package/gui/dist/index.html +2 -2
  18. package/native/ocx-child/Cargo.lock +215 -0
  19. package/native/ocx-child/Cargo.toml +31 -0
  20. package/native/ocx-child/src/cli.rs +1901 -0
  21. package/native/ocx-child/src/codex_home.rs +429 -0
  22. package/native/ocx-child/src/codex_settings.rs +231 -0
  23. package/native/ocx-child/src/daemon.rs +363 -0
  24. package/native/ocx-child/src/http_wire.rs +619 -0
  25. package/native/ocx-child/src/journal.rs +977 -0
  26. package/native/ocx-child/src/lib.rs +22 -0
  27. package/native/ocx-child/src/main.rs +9 -0
  28. package/native/ocx-child/src/parity.rs +102 -0
  29. package/native/ocx-child/src/platform.rs +1487 -0
  30. package/native/ocx-child/src/relay.rs +1288 -0
  31. package/native/ocx-child/src/relay_auth.rs +166 -0
  32. package/native/ocx-child/src/routes.rs +236 -0
  33. package/native/ocx-child/src/state.rs +190 -0
  34. package/native/ocx-child/src/test_hooks.rs +58 -0
  35. package/native/ocx-child/src/toml_surgeon.rs +1156 -0
  36. package/package.json +8 -2
  37. package/src/adapters/anthropic-image-normalize.ts +1 -1
  38. package/src/adapters/anthropic.ts +28 -2
  39. package/src/adapters/claude-cli/adapter.ts +5 -25
  40. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  41. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  42. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  43. package/src/adapters/client-fingerprint.ts +1 -1
  44. package/src/adapters/coding-agent/protocol.ts +1 -1
  45. package/src/adapters/devin/live-models.ts +3 -0
  46. package/src/adapters/google-http.ts +3 -0
  47. package/src/adapters/google-vertex-key-project.ts +10 -2
  48. package/src/adapters/google.ts +40 -8
  49. package/src/adapters/kiro/usage.ts +3 -13
  50. package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
  51. package/src/adapters/openai-chat-images.ts +100 -0
  52. package/src/adapters/openai-chat.ts +6 -9
  53. package/src/adapters/openai-responses/passthrough.ts +5 -2
  54. package/src/adapters/openai-responses/request-strips.ts +32 -0
  55. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  56. package/src/chat/inbound.ts +1 -1
  57. package/src/claude/auth-detect.ts +26 -8
  58. package/src/claude/inbound-content-options.ts +18 -3
  59. package/src/claude/inbound.ts +5 -2
  60. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  61. package/src/cli/capabilities-agents-routing.ts +2 -2
  62. package/src/cli/capabilities-observe-system.ts +60 -0
  63. package/src/cli/combo-input.ts +6 -0
  64. package/src/cli/combo-result.ts +1 -1
  65. package/src/cli/combo.ts +4 -0
  66. package/src/cli/config-command.ts +16 -2
  67. package/src/cli/connect.ts +12 -10
  68. package/src/cli/dispatch.ts +4 -0
  69. package/src/cli/doctor.ts +11 -0
  70. package/src/cli/help.ts +1 -0
  71. package/src/cli/init.ts +4 -0
  72. package/src/cli/link-enrollment.ts +152 -25
  73. package/src/cli/link-local-control.ts +49 -0
  74. package/src/cli/link.ts +37 -10
  75. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  76. package/src/cli/registry.ts +13 -0
  77. package/src/cli/star-prompt.ts +2 -0
  78. package/src/cli/status.ts +1 -1
  79. package/src/cli/telemetry-profile.ts +206 -0
  80. package/src/cli/telemetry.ts +260 -0
  81. package/src/client/hub-relay.ts +26 -0
  82. package/src/client/machine-api.ts +3 -0
  83. package/src/clients/config-export/t3code.ts +44 -5
  84. package/src/clients/omo-role-models.ts +1 -1
  85. package/src/codex/catalog/bundled.ts +44 -2
  86. package/src/codex/runtime.ts +12 -0
  87. package/src/codex/shim-restore-lock.ts +67 -30
  88. package/src/combos/types.ts +21 -1
  89. package/src/config/atomic-write.ts +24 -1
  90. package/src/config/diagnostics.ts +15 -0
  91. package/src/config/live-reconcile.ts +17 -0
  92. package/src/config/load-degrade.ts +16 -0
  93. package/src/config/provider-validation.ts +29 -0
  94. package/src/config/schema/config-schema.ts +24 -0
  95. package/src/config/schema/leaf-validators.ts +17 -0
  96. package/src/config/telemetry-carry.ts +30 -0
  97. package/src/config.ts +13 -1
  98. package/src/generated/compatibility-version.json +422 -170
  99. package/src/generated/model-metadata.ts +3 -3
  100. package/src/integrations/aside-profiles.ts +7 -1
  101. package/src/integrations/owned-refresh.ts +9 -2
  102. package/src/lab/artifacts/secure-fs.ts +12 -11
  103. package/src/lab/fabric/scratch.ts +11 -9
  104. package/src/lab/public/community.ts +2 -3
  105. package/src/lab/public/file-safety.ts +18 -20
  106. package/src/lab/public/mutation-lock.ts +109 -337
  107. package/src/lab/public/private-file.ts +4 -3
  108. package/src/lib/bun-runtime-preflight.ts +1 -1
  109. package/src/lib/codex-catalog-read-only.ts +122 -0
  110. package/src/lib/config-ownership.ts +56 -18
  111. package/src/lib/errors.ts +11 -0
  112. package/src/lib/gcp-adc.ts +167 -48
  113. package/src/lib/jsonc.ts +4 -2
  114. package/src/lib/local-control-socket.ts +88 -0
  115. package/src/lib/privacy.ts +15 -0
  116. package/src/lib/provider-client-headers.ts +3 -0
  117. package/src/lib/token-estimate.ts +13 -2
  118. package/src/link/child-binary-source.ts +228 -0
  119. package/src/link/ephemeral-child.ts +45 -0
  120. package/src/link/remote-plant.ts +306 -0
  121. package/src/link/remote-windows.ts +59 -5
  122. package/src/link/ssh-argv.ts +71 -8
  123. package/src/link/status-projection.ts +2 -0
  124. package/src/link/store.ts +5 -1
  125. package/src/oauth/anthropic-model-quota.ts +12 -0
  126. package/src/oauth/anthropic-routing.ts +11 -4
  127. package/src/oauth/claude-keychain-read.ts +165 -0
  128. package/src/oauth/kiro-iam-identity-center.ts +4 -1
  129. package/src/oauth/local-token-detect.ts +14 -17
  130. package/src/protocols/envelope.ts +20 -2
  131. package/src/providers/api-key-selection.ts +8 -2
  132. package/src/providers/claude-cli-identity.ts +9 -3
  133. package/src/providers/claude-cli-usage-state.ts +93 -0
  134. package/src/providers/claude-cli-usage.ts +3 -2
  135. package/src/providers/github-copilot-auto.ts +25 -5
  136. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  137. package/src/providers/model-rename-fields.ts +3 -0
  138. package/src/providers/quota/anthropic-family-headers.ts +8 -1
  139. package/src/providers/quota/anthropic-usage-windows.ts +49 -2
  140. package/src/providers/quota/vendor-probes-key.ts +23 -4
  141. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  142. package/src/providers/quota/workbuddy.ts +2 -2
  143. package/src/providers/quota-types.ts +7 -0
  144. package/src/providers/quota.ts +25 -18
  145. package/src/providers/registry/entries-core.ts +7 -4
  146. package/src/providers/registry/entries-extended.ts +42 -8
  147. package/src/providers/registry/model-ids.ts +1 -0
  148. package/src/providers/registry/model-seeds.ts +10 -2
  149. package/src/providers/registry/types.ts +6 -0
  150. package/src/providers/resolved-model-policy.ts +4 -0
  151. package/src/providers/routed-config.ts +30 -3
  152. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  153. package/src/providers/vertex-environment-authority.ts +50 -0
  154. package/src/providers/workbuddy-credit-balance.ts +38 -6
  155. package/src/quota-pool/assemble.ts +14 -6
  156. package/src/responses/retained-compaction.ts +31 -5
  157. package/src/router.ts +1 -0
  158. package/src/server/adapter-resolve.ts +11 -6
  159. package/src/server/audio-dictation.ts +21 -7
  160. package/src/server/auth-cors.ts +19 -0
  161. package/src/server/background-lifecycle.ts +71 -0
  162. package/src/server/chat-completions.ts +2 -0
  163. package/src/server/claude-messages.ts +30 -3
  164. package/src/server/index/live-sideband.ts +15 -1
  165. package/src/server/index/local-control-listener.ts +515 -0
  166. package/src/server/index/optional-listeners.ts +21 -1
  167. package/src/server/index/serve-options.ts +4 -3
  168. package/src/server/index/websocket-handler.ts +2 -0
  169. package/src/server/index.ts +3 -0
  170. package/src/server/management/combo-routes.ts +6 -1
  171. package/src/server/management/context.ts +1 -0
  172. package/src/server/management/link-child-preflight.ts +74 -0
  173. package/src/server/management/link-enrollment.ts +190 -25
  174. package/src/server/management/link-route-state.ts +6 -1
  175. package/src/server/management/link-routes.ts +27 -9
  176. package/src/server/management/model-rows.ts +4 -0
  177. package/src/server/management/oauth-account-routes.ts +9 -4
  178. package/src/server/management/provider-overwrite-carry.ts +9 -2
  179. package/src/server/management/provider-routes.ts +14 -0
  180. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  181. package/src/server/management/route-registry.ts +7 -0
  182. package/src/server/management/session-routes.ts +4 -1
  183. package/src/server/management/telemetry-routes.ts +37 -0
  184. package/src/server/management/usage-aggregate-cache.ts +290 -67
  185. package/src/server/management-api.ts +11 -2
  186. package/src/server/messages-native-preflight.ts +166 -0
  187. package/src/server/messages-native.ts +143 -43
  188. package/src/server/messages-shared.ts +14 -0
  189. package/src/server/proxy-liveness.ts +99 -6
  190. package/src/server/request-log-conversation.ts +18 -2
  191. package/src/server/request-log.ts +7 -2
  192. package/src/server/responses/adapter-continuation.ts +1 -0
  193. package/src/server/responses/adapter-dispatch.ts +11 -28
  194. package/src/server/responses/adapter-failure-message.ts +68 -0
  195. package/src/server/responses/combo-stream-preflight.ts +14 -2
  196. package/src/server/responses/compact.ts +13 -1
  197. package/src/server/responses/core-auth.ts +26 -5
  198. package/src/server/responses/core-codex-account.ts +8 -1
  199. package/src/server/responses/core-combo-failure.ts +6 -1
  200. package/src/server/responses/core-combo-native.ts +150 -37
  201. package/src/server/responses/core-combo.ts +15 -9
  202. package/src/server/responses/core-normalize.ts +1 -0
  203. package/src/server/responses/core-options.ts +7 -1
  204. package/src/server/responses/core-pipeline.ts +21 -1
  205. package/src/server/responses/fetch-helpers.ts +5 -0
  206. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  207. package/src/server/responses/passthrough-delivery.ts +8 -1
  208. package/src/server/responses/passthrough-error.ts +22 -0
  209. package/src/server/responses/request-prepare.ts +7 -1
  210. package/src/server/responses/request-transport.ts +28 -5
  211. package/src/server/responses/run-turn-execution.ts +13 -0
  212. package/src/server/sse-frame-buffer.ts +5 -0
  213. package/src/server/ws-bridge.ts +10 -0
  214. package/src/service/launchd.ts +78 -4
  215. package/src/telemetry/aggregate.ts +348 -0
  216. package/src/telemetry/consent.ts +128 -0
  217. package/src/telemetry/contract.ts +403 -0
  218. package/src/telemetry/disclosure.ts +19 -0
  219. package/src/telemetry/install-id.ts +226 -0
  220. package/src/telemetry/payload.ts +129 -0
  221. package/src/telemetry/profile/client.ts +150 -0
  222. package/src/telemetry/profile/contract.ts +288 -0
  223. package/src/telemetry/profile/disclosure.ts +14 -0
  224. package/src/telemetry/profile/paths.ts +13 -0
  225. package/src/telemetry/profile/routes.ts +99 -0
  226. package/src/telemetry/profile/service.ts +234 -0
  227. package/src/telemetry/profile/state.ts +189 -0
  228. package/src/telemetry/profile/sync.ts +276 -0
  229. package/src/telemetry/routes.ts +183 -0
  230. package/src/telemetry/scheduler.ts +386 -0
  231. package/src/telemetry/sender.ts +97 -0
  232. package/src/telemetry/state.ts +334 -0
  233. package/src/types/combo-jev-effort-mode.ts +11 -0
  234. package/src/types/config.ts +3 -0
  235. package/src/types/provider.ts +11 -1
  236. package/src/types/request.ts +2 -0
  237. package/src/types/telemetry.ts +15 -0
  238. package/src/types/wire.ts +10 -0
  239. package/src/types.ts +5 -0
  240. package/src/update/index.ts +7 -1
  241. package/src/update/minisign.d.mts +17 -0
  242. package/src/update/minisign.mjs +88 -0
  243. package/src/update/signed-supply.d.mts +59 -0
  244. package/src/update/signed-supply.mjs +289 -0
  245. package/src/update/trust-root.json +38 -0
  246. package/src/update/update-bounded-json.d.mts +4 -0
  247. package/src/update/update-bounded-json.mjs +113 -0
  248. package/src/update/update-bytes.d.mts +2 -0
  249. package/src/update/update-bytes.mjs +23 -0
  250. package/src/update/update-candidate-id.d.mts +2 -0
  251. package/src/update/update-candidate-id.mjs +23 -0
  252. package/src/update/update-checkpoint-codec.d.mts +33 -0
  253. package/src/update/update-checkpoint-codec.mjs +217 -0
  254. package/src/update/update-contracts.d.mts +24 -0
  255. package/src/update/update-contracts.mjs +207 -0
  256. package/src/update/update-signature-threshold.d.mts +12 -0
  257. package/src/update/update-signature-threshold.mjs +47 -0
  258. package/src/update/update-signed-version.d.mts +5 -0
  259. package/src/update/update-signed-version.mjs +25 -0
  260. package/src/update/update-trust-anchor.d.mts +2 -0
  261. package/src/update/update-trust-anchor.mjs +2 -0
  262. package/src/usage/cache-diagnostic.ts +195 -50
  263. package/src/usage/expected-prices.ts +20 -2
  264. package/src/usage/filter-index.ts +1469 -0
  265. package/src/usage/ledger-scanner.ts +245 -4
  266. package/src/usage/source-filter.ts +10 -2
  267. package/src/usage/summary.ts +16 -0
  268. package/src/web-search/parse.ts +265 -38
  269. package/gui/dist/assets/App-BepstgEN.js +0 -59
  270. package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
  271. package/gui/dist/assets/brand-mark-wzPe3R-J.js +0 -1
  272. package/gui/dist/assets/index-C-9X2yaI.js +0 -94
  273. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  274. package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
  275. package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
  276. package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
@@ -221,15 +221,31 @@ export function fillHermesLogConversationFallback(slot: LogConversationSlot, hea
221
221
  slot.conversationIdIsHermesFallback = true;
222
222
  }
223
223
 
224
+ /**
225
+ * Remote Claude Code adds a per-turn attribution token (`tk`) to its metadata.user_id JSON
226
+ * blob. Drop it, as Claude Code itself does, so every turn of one session keeps one identity.
227
+ * Any other user_id, including one that is nothing but `tk`, is returned unchanged.
228
+ */
229
+ export function claudeSessionUserId(userId: string): string {
230
+ try {
231
+ const parsed: unknown = JSON.parse(userId);
232
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && "tk" in parsed) {
233
+ const { tk: _tk, ...rest } = parsed as Record<string, unknown>;
234
+ if (Object.keys(rest).length > 0) return JSON.stringify(rest);
235
+ }
236
+ } catch { /* not JSON */ }
237
+ return userId;
238
+ }
239
+
224
240
  /**
225
241
  * Claude Code metadata.user_id only — never the system-hash Desktop fallback.
226
- * Hashes the raw user_id once (same opacity goal as inbound prompt_cache_key).
242
+ * Hashes the session's user_id once (same opacity goal as inbound prompt_cache_key).
227
243
  */
228
244
  export function conversationIdFromClaudeMetadata(
229
245
  metadata: { user_id?: unknown } | null | undefined,
230
246
  ): string | undefined {
231
247
  if (!metadata || typeof metadata.user_id !== "string") return undefined;
232
- return normalizeLogConversationId(metadata.user_id);
248
+ return normalizeLogConversationId(claudeSessionUserId(metadata.user_id));
233
249
  }
234
250
 
235
251
  /** @deprecated Prefer conversationIdFromClaudeMetadata; kept for call-site clarity. */
@@ -104,7 +104,7 @@ const CACHE_DIAGNOSTIC_HOOK = Symbol.for("opencodex.cache-diagnostic.v1");
104
104
  interface CacheDiagnosticHooks {
105
105
  /** Whether inbound bodies are actually recorded; the hook is registered at import either way. */
106
106
  enabled(): boolean;
107
- observeInbound(body: unknown, headers: Headers, source: PromptCacheKeySource): CacheDiagnosticDraft;
107
+ observeInbound(body: unknown, headers: Headers, source: PromptCacheKeySource, admissionPrincipal?: string): CacheDiagnosticDraft;
108
108
  rebind(body: unknown, draft: CacheDiagnosticDraft | undefined): void;
109
109
  finalize(facts: CacheDiagnosticFinalFacts): void;
110
110
  }
@@ -252,6 +252,10 @@ export interface RequestLogContext extends UpstreamErrorDiagnostics {
252
252
  upstreamCondition?: UpstreamCondition; // classified at capture where the evidence is not kept on the context
253
253
  /** HTTP status derived from a terminal `response.failed` SSE payload (429/401/503/etc.). */
254
254
  terminalHttpStatus?: number;
255
+ /** Status of an upstream `error` event that ended a 200 Messages stream; the row stays 200, a combo child reads it. */
256
+ streamErrorStatus?: number;
257
+ /** Bytes other than a ping followed that upstream `error` event, so a retry would repeat output. */
258
+ streamErrorFollowed?: true;
255
259
  /** Recognized structured terminal code whose exact identity must survive status mapping. */
256
260
  terminalErrorCode?: typeof CYBER_POLICY_ERROR_CODE;
257
261
  /**
@@ -289,8 +293,9 @@ export function observeCacheDiagnosticInbound(
289
293
  body: unknown,
290
294
  headers: Headers,
291
295
  source: PromptCacheKeySource,
296
+ admissionPrincipal?: string,
292
297
  ): void {
293
- const draft = cacheDiagnosticHooks()?.observeInbound(body, headers, source);
298
+ const draft = cacheDiagnosticHooks()?.observeInbound(body, headers, source, admissionPrincipal);
294
299
  if (draft) logCtx.cacheDiagnosticDraft = draft;
295
300
  }
296
301
 
@@ -222,6 +222,7 @@ export function createAdapterContinuations(
222
222
  headers: requestState.selectedForwardHeaders,
223
223
  providerName: route.providerName,
224
224
  translatorBudget,
225
+ abortSignal: upstream.signal,
225
226
  ...(transportState.imageTierBias > 0 ? { imageTierBias: transportState.imageTierBias } : {}),
226
227
  });
227
228
  recordAdapterReasoning(logCtx, continuationRequest);
@@ -35,7 +35,7 @@ import {
35
35
  sealRequestAttemptIdentity,
36
36
  recordAttemptCredentialSource,
37
37
  } from "../request-log";
38
- import { anthropicPoolCooldownResponse, clientCancelledResponse, readDisplaySafeErrorText, normalizeUpstreamErrorText } from "./core-errors";
38
+ import { anthropicPoolCooldownResponse, clientCancelledResponse, readDisplaySafeErrorText } from "./core-errors";
39
39
  import { isTranslatorBudgetExceededError } from "../../lib/translator-budget";
40
40
  import { redactSecretString } from "../../lib/redact";
41
41
  import { rewriteUpstreamPolicyRefusal } from "./policy-refusal";
@@ -101,19 +101,15 @@ import {
101
101
  } from "./core-opaque-recovery";
102
102
  import { createAnthropicThinkingRecovery } from "./anthropic-thinking-recovery";
103
103
  import { shouldAttemptImageTierRetry } from "../image-retry";
104
- import {
105
- isTransientConsoleGoUploadRejection,
106
- enrichOpenCodeZenUpstreamMessage,
107
- } from "../../providers/opencode-zen-rate-limit";
104
+ import { isTransientConsoleGoUploadRejection } from "../../providers/opencode-zen-rate-limit";
108
105
  import { planReasoningEffortDowngrade } from "../../providers/reasoning-metadata";
106
+ import { formatAdapterUpstreamFailure } from "./adapter-failure-message";
109
107
  import { consumeComboFailure } from "./core-combo-failure";
110
108
  import { streamingContextOverflowResponse, jsonContextOverflowResponse, lateAttributionLimitResponse } from "./context-overflow";
111
109
  import { OllamaLateAttributionBudgetError } from "../../adapters/ollama-native";
112
110
  import { isFixedCodexAccount } from "./core-codex-account";
113
111
  import { recordSubagentQuotaFailureForThreadSpawn } from "../../codex/subagent-model-fallback";
114
112
  import {
115
- isCyberPolicyCode,
116
- CYBER_POLICY_FALLBACK_MESSAGE,
117
113
  CYBER_POLICY_ERROR_CODE,
118
114
  SEND_BUDGET_EXHAUSTED_CODE,
119
115
  } from "../../lib/errors";
@@ -1927,32 +1923,19 @@ export async function prepareAdapterExchange(
1927
1923
  // Upstreams occasionally echo request details in error bodies — scrub token-shaped
1928
1924
  // material before it reaches the client-facing error surface.
1929
1925
  const upstreamRetryAfter = upstreamResponse.headers.get("retry-after");
1930
- const normalized = normalizeUpstreamErrorText(errorText, "unknown error");
1926
+ const { normalized, message } = formatAdapterUpstreamFailure({
1927
+ status: upstreamResponse.status,
1928
+ errorText,
1929
+ route,
1930
+ upstreamRetryAfter,
1931
+ denialMessage: fallback => antigravityDenial.message(route.modelId, fallback),
1932
+ logCtx,
1933
+ });
1931
1934
  options.onCompactionRecoveryAdapterEvent?.({
1932
1935
  type: "error", status: upstreamResponse.status,
1933
1936
  errorType: normalized.type, code: normalized.code,
1934
1937
  message: "Structured upstream failure observed before client formatting",
1935
1938
  });
1936
- const message = antigravityDenial.message(route.modelId, normalized.cyberPolicy
1937
- ? normalized.message
1938
- ?? (isCyberPolicyCode(normalized.code) ? CYBER_POLICY_FALLBACK_MESSAGE : normalized.safeText)
1939
- : enrichOpenCodeZenUpstreamMessage(
1940
- `Provider error ${upstreamResponse.status}: ${normalized.safeText}`,
1941
- {
1942
- status: upstreamResponse.status,
1943
- providerName: route.providerName,
1944
- baseUrl: route.provider.baseUrl,
1945
- adapter: route.provider.adapter,
1946
- authMode: route.provider.authMode,
1947
- hasApiKey: Boolean(route.provider.apiKey?.trim()),
1948
- upstreamRetryAfter,
1949
- upstreamErrorType: normalized.type,
1950
- upstreamErrorCode: normalized.code,
1951
- // This recovery path is the HTTP Responses wire; custom runTurn transports
1952
- // never reach enrichOpenCodeZenUpstreamMessage here.
1953
- supportsHttpSameKeyRetry: true,
1954
- },
1955
- ));
1956
1939
  const retryAfter = normalized.cyberPolicy
1957
1940
  ? undefined
1958
1941
  : resolveClientRetryAfter({
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Client-facing message for an adapter's non-2xx upstream response.
3
+ *
4
+ * This is the HTTP Responses recovery path's own composition: scrub the body once, let a plan
5
+ * refusal this proxy proved outrank the upstream wording, then let Antigravity's model-denial
6
+ * sentence and the OpenCode Zen rate-limit enrichment adjust what remains. The caller needs the
7
+ * normalized envelope as well — it decides the cyber-policy status and type in the response —
8
+ * so both are returned from the single read rather than normalizing twice.
9
+ */
10
+ import { normalizeUpstreamErrorText, type NormalizedUpstreamErrorText } from "./core-errors";
11
+ import { enrichOpenCodeZenUpstreamMessage } from "../../providers/opencode-zen-rate-limit";
12
+ import { stampMetaMusePlanRefusal } from "../../providers/meta-muse-plan-refusal";
13
+ import { isCyberPolicyCode, CYBER_POLICY_FALLBACK_MESSAGE } from "../../lib/errors";
14
+ import type { RequestFailureCause } from "../../usage/telemetry-contract";
15
+
16
+ /** The provider facts the Zen enrichment reads; a name or endpoint alone is not enough. */
17
+ export interface AdapterFailureProviderFacts {
18
+ providerName: string;
19
+ provider: {
20
+ baseUrl: string;
21
+ adapter: string;
22
+ authMode?: string | undefined;
23
+ apiKey?: string | null;
24
+ };
25
+ }
26
+
27
+ export interface AdapterFailureMessageInput {
28
+ status: number;
29
+ errorText: string;
30
+ route: AdapterFailureProviderFacts;
31
+ upstreamRetryAfter: string | null;
32
+ /** The Antigravity request-local denial sentence, already bound to its recovery state. */
33
+ denialMessage: (fallback: string) => string;
34
+ logCtx: { causeHint?: RequestFailureCause };
35
+ }
36
+
37
+ export interface AdapterFailureMessage {
38
+ normalized: NormalizedUpstreamErrorText;
39
+ message: string;
40
+ }
41
+
42
+ export function formatAdapterUpstreamFailure(input: AdapterFailureMessageInput): AdapterFailureMessage {
43
+ const normalized = normalizeUpstreamErrorText(input.errorText, "unknown error");
44
+ // Meta's Muse Code refusal is a plan restriction, not a rejected credential (#8352). The body
45
+ // proved it here, so stamp the cause and answer with this proxy's own sentence.
46
+ const musePlanRefusal = stampMetaMusePlanRefusal(input.logCtx, input.status, input.errorText);
47
+ const message = musePlanRefusal ?? input.denialMessage(normalized.cyberPolicy
48
+ ? normalized.message
49
+ ?? (isCyberPolicyCode(normalized.code) ? CYBER_POLICY_FALLBACK_MESSAGE : normalized.safeText)
50
+ : enrichOpenCodeZenUpstreamMessage(
51
+ `Provider error ${input.status}: ${normalized.safeText}`,
52
+ {
53
+ status: input.status,
54
+ providerName: input.route.providerName,
55
+ baseUrl: input.route.provider.baseUrl,
56
+ adapter: input.route.provider.adapter,
57
+ authMode: input.route.provider.authMode,
58
+ hasApiKey: Boolean(input.route.provider.apiKey?.trim()),
59
+ upstreamRetryAfter: input.upstreamRetryAfter,
60
+ upstreamErrorType: normalized.type,
61
+ upstreamErrorCode: normalized.code,
62
+ // This recovery path is the HTTP Responses wire; custom runTurn transports never reach
63
+ // enrichOpenCodeZenUpstreamMessage here.
64
+ supportsHttpSameKeyRetry: true,
65
+ },
66
+ ));
67
+ return { normalized, message };
68
+ }
@@ -28,6 +28,16 @@ const PRE_OUTPUT_CONTROL_EVENTS = new Set([
28
28
  "response.heartbeat",
29
29
  ]);
30
30
 
31
+ // The Codex WebSocket metadata channel (`codex-ws-metadata.ts`) writes these into the same SSE
32
+ // body, typically ahead of `response.created`. They are rebuilt field by field from quota and
33
+ // header metadata, so they are neither output nor a terminal. Committing on them made a native
34
+ // target that declined before any output (#8107) final for the whole combo. Every other unknown
35
+ // type still commits.
36
+ const CODEX_METADATA_CONTROL_EVENTS = new Set([
37
+ "codex.rate_limits",
38
+ "codex.response.metadata",
39
+ ]);
40
+
31
41
  const TERMINAL_EVENTS = new Set([
32
42
  "response.completed",
33
43
  "response.failed",
@@ -143,7 +153,8 @@ function retryableZeroOutputTerminal(payload: unknown): boolean {
143
153
  /**
144
154
  * Decide when replaying the request on another combo target would risk duplicating
145
155
  * client-visible output or a tool-side effect. Unknown event types commit the child
146
- * conservatively; only the small Responses lifecycle preamble remains replayable.
156
+ * conservatively; only the small Responses lifecycle preamble and Codex metadata control frames
157
+ * remain replayable.
147
158
  */
148
159
  export function comboStreamPayloadCommitsOutput(payload: unknown): boolean {
149
160
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) return true;
@@ -159,7 +170,8 @@ export function comboStreamPayloadCommitsOutput(payload: unknown): boolean {
159
170
  if (Array.isArray(output) && output.length > 0) return true;
160
171
  }
161
172
  }
162
- return !PRE_OUTPUT_CONTROL_EVENTS.has(type) && !TERMINAL_EVENTS.has(type);
173
+ return !PRE_OUTPUT_CONTROL_EVENTS.has(type) && !CODEX_METADATA_CONTROL_EVENTS.has(type)
174
+ && !TERMINAL_EVENTS.has(type);
163
175
  }
164
176
 
165
177
  /**
@@ -152,6 +152,7 @@ import { requiresPlaintextReasoningReplay } from "../../adapters/openai-response
152
152
  import { destinationDecodesNativeCompactionBlob, isOpenAiOperatedResponsesDestination } from "../../providers/openai-tiers-destination";
153
153
  import { bindRouteReasoningReplayScope } from "./core-replay";
154
154
  import { commitReasoningReplayServingIdentity } from "../../responses/reasoning-replay-cache";
155
+ import { findInvalidRetainedCompactionEnvelope, InvalidRetainedCompactionEnvelopeError } from "../../responses/retained-compaction";
155
156
  import { nativeCompactResponseSchema } from "../../responses/schema";
156
157
  import { NATIVE_RESERVE_MODEL } from "../../codex/catalog/native-models";
157
158
  import {
@@ -670,6 +671,11 @@ export async function bufferCompactResponse(
670
671
 
671
672
 
672
673
 
674
+ /**
675
+ * Route one `/v1/responses/compact` request: validate the body (rejecting malformed
676
+ * proxy-owned retained envelopes before routing or credential resolution), select the
677
+ * compact target, and dispatch through the adapter pipeline.
678
+ */
673
679
  export async function handleResponsesCompact(
674
680
  req: Request,
675
681
  config: OcxConfig,
@@ -699,6 +705,10 @@ export async function handleResponsesCompact(
699
705
  if (typeof raw.model !== "string" || raw.model.length === 0) {
700
706
  return formatErrorResponse(400, "invalid_request_error", "compaction request requires a model");
701
707
  }
708
+ // A malformed proxy-owned envelope is a caller error, so reject it before routing or
709
+ // credential resolution can spend a token refresh on a request that cannot succeed.
710
+ const invalidEnvelope = findInvalidRetainedCompactionEnvelope(raw.input);
711
+ if (invalidEnvelope) return formatErrorResponse(400, "invalid_request_error", invalidEnvelope.message);
702
712
  options.onRequestBodyRead?.();
703
713
  // Correct the IDENTITY before routing, or the synthetic id does not route at all. Held in
704
714
  // a local rather than written back to `raw.model`: assigning to the property widens it out
@@ -1305,7 +1315,9 @@ export async function handleResponsesCompact(
1305
1315
  let outcomeCtx = authCtx;
1306
1316
  const localDispatchRefusal = (error: unknown): Response | undefined => {
1307
1317
  const cause = unwrapUpstreamRetryEvidenceError(error);
1308
- const response = requestPacingOverloadResponse(cause) ?? spendLedgerStorageErrorResponse(error, logCtx) ?? (cause instanceof SendBudgetExhaustedError
1318
+ const response = cause instanceof InvalidRetainedCompactionEnvelopeError
1319
+ ? formatErrorResponse(400, "invalid_request_error", cause.message)
1320
+ : requestPacingOverloadResponse(cause) ?? spendLedgerStorageErrorResponse(error, logCtx) ?? (cause instanceof SendBudgetExhaustedError
1309
1321
  ? unboundPoolSpendRefusalResponse(logCtx) ?? formatErrorResponse(429, "request_send_budget_exhausted", cause.message)
1310
1322
  : mapCodexAuthContextErrorToResponse(cause, {
1311
1323
  now: Date.now(), accountSelector: route.codexAccountNamespace,
@@ -73,6 +73,24 @@ export type ResponsesAuthResolution =
73
73
  export type CodexCredentialOwnershipOptions = Pick<HandleResponsesOptions,
74
74
  "admission" | "callerDirectAuth" | "stripClaudeMainAuthForNoncanonicalForward" | "trustedClaudeMainAuth">;
75
75
 
76
+ /**
77
+ * Restore the provider's permitted caller metadata onto a header set rebuilt from a credential
78
+ * allowlist. Every physical send of one Responses turn goes through this rule: the first send,
79
+ * the 401 refresh replay and the alternate-account retry. The copier fills only names the target
80
+ * does not already carry, so a selected Pool installation identity and configured provider
81
+ * headers keep precedence over the caller's values.
82
+ */
83
+ export function restoreResponsesClientMetadata(
84
+ headers: Headers,
85
+ incoming: Headers,
86
+ provider: OcxProviderConfig,
87
+ compactionRecoveryKind?: HandleResponsesOptions["compactionRecoveryKind"],
88
+ ): void {
89
+ if (provider.adapter === "openai-responses" || compactionRecoveryKind === "compaction-v1") {
90
+ copyResponsesClientMetadata(headers, incoming, provider);
91
+ }
92
+ }
93
+
76
94
  /**
77
95
  * The caller credential the final Codex auth resolution will be given, as far as the ROUTE
78
96
  * decides it: a route change that may cross a credential domain drops the raw caller credential,
@@ -360,11 +378,9 @@ export async function resolveResponsesCodexAuth(
360
378
  headers.delete("chatgpt-account-id");
361
379
  }
362
380
  }
363
- // Codex auth materialization keeps only its credential allowlist. A compact-v1 handoff
364
- // must also retain the permitted client fingerprint for its routed summarizer send.
365
- if (options.compactionRecoveryKind === "compaction-v1") {
366
- copyResponsesClientMetadata(headers, authInputHeaders, route.provider);
367
- }
381
+ // Auth materialization keeps only its credential allowlist. Responses turns and compact
382
+ // handoffs also need the provider's permitted metadata, without replacing selected identity.
383
+ restoreResponsesClientMetadata(headers, authInputHeaders, route.provider, options.compactionRecoveryKind);
368
384
  // dual_header: the assertion is first-party only and travels only beside the caller's own
369
385
  // unchanged Bearer, compared with the ORIGINAL request (injected credentials do not count).
370
386
  if (isCanonicalOpenAiForwardProvider(route.provider) && authCtx?.kind === "main" && !substituteMainCredential) {
@@ -534,6 +550,9 @@ export async function refreshPoolForwardAuth(args: {
534
550
  signal: options.abortSignal,
535
551
  nativeMainRefreshDependencies: options.nativeMainRefreshDependencies,
536
552
  });
553
+ // The replay is a second physical send of the same turn: it keeps the caller metadata the
554
+ // first send carried instead of reverting to the credential-only allowlist.
555
+ restoreResponsesClientMetadata(headers, req.headers, provider, options.compactionRecoveryKind);
537
556
  return { ok: true, authCtx: refreshedAuthCtx, provider, headers };
538
557
  } catch (error) {
539
558
  if (isTerminalPoolRefreshFailure(error)) {
@@ -611,6 +630,8 @@ export async function refreshNativeMainForwardAuth(args: {
611
630
  signal: options.abortSignal,
612
631
  nativeMainRefreshDependencies: options.nativeMainRefreshDependencies,
613
632
  });
633
+ // Same rule as the stored Pool refresh: the replay keeps permitted caller metadata.
634
+ restoreResponsesClientMetadata(headers, req.headers, provider, options.compactionRecoveryKind);
614
635
  return { ok: true, authCtx: refreshedAuthCtx, provider, headers };
615
636
  } catch (error) {
616
637
  if (options.abortSignal?.aborted || req.signal.aborted) {
@@ -75,7 +75,7 @@ import {
75
75
  import { ACCOUNT_GATED_NATIVE_OPENAI_MODELS } from "../../codex/catalog/native-models";
76
76
  import { createBoundedSameTargetRecovery, hasWorkflowSendObserver, isRequestExecutionBudget } from "../../lib/request-execution-budget";
77
77
  import type { SingleUseDispatchPermit } from "../../lib/request-execution-budget";
78
- import { codexRouteCredentialOwnership, type CodexCredentialOwnershipOptions } from "./core-auth";
78
+ import { codexRouteCredentialOwnership, restoreResponsesClientMetadata, type CodexCredentialOwnershipOptions } from "./core-auth";
79
79
  import { bindRouteReasoningReplayScope } from "./core-replay";
80
80
  import {
81
81
  conversationStateBindingFromAuth,
@@ -506,6 +506,8 @@ export interface CodexPoolAccountRetryArgs {
506
506
  sendBudget?: TransientSendBudget;
507
507
  /** Root workflow this turn belongs to, so the move is charged there as well. */
508
508
  workflowRootId?: string;
509
+ /** Compact recovery keeps client metadata even on adapters that do not forward by default. */
510
+ compactionRecoveryKind?: "compaction-v1" | "compaction-v2";
509
511
  };
510
512
  firstAuthCtx: Extract<CodexAuthContext, { kind: "pool" | "main-pool" }>;
511
513
  firstResponse: Response;
@@ -893,6 +895,11 @@ export async function retryCodexPoolOnAlternateAccount(
893
895
  try {
894
896
  retryHeaders = headersForCodexAuthContext(callerAuthHeaders, retryAuthCtx, options.codexAuthPolicy ?? config, route.modelId, options.admission);
895
897
  retryProvider = applyCodexAuthContextToProvider(stripCodexRuntimeProviderFields(route.provider), retryAuthCtx, "pool");
898
+ // The alternate send is a second physical send of the same turn. Its credential-listed
899
+ // headers were rebuilt from the caller's sanitized set, so restore the provider's permitted
900
+ // client metadata the same way the first send did; the copier never overwrites a header the
901
+ // rebuild or the provider already selected.
902
+ restoreResponsesClientMetadata(retryHeaders, callerAuthHeaders, retryProvider, options.compactionRecoveryKind);
896
903
  } catch (error) {
897
904
  if (!(error instanceof CodexPoolAccountCreditsOffError) && !(error instanceof CodexInstallationIdUnavailableError)) throw error;
898
905
  // Body/entitlement reads above can outlive credit consent. No alternate will send:
@@ -30,6 +30,8 @@ import { carryReplayRefusal, isNonReplayableResponse, isReplayRefusalResponse, m
30
30
  import { MODEL_NOT_ALLOWED_FOR_KEY } from "../admission-model-scope";
31
31
  import { usageFromResponsesPayload } from "../request-log";
32
32
  import type { ResponsesTerminalStatus } from "../../bridge";
33
+ import { stampMetaMusePlanRefusal } from "../../providers/meta-muse-plan-refusal";
34
+ import type { RequestFailureCause } from "../../usage/telemetry-contract";
33
35
 
34
36
  export function sanitizedRetryAfter(value: string | null, now: number): string | undefined {
35
37
  const trimmed = value?.trim();
@@ -44,7 +46,7 @@ export async function consumeComboFailure(
44
46
  response: Response,
45
47
  signal?: AbortSignal,
46
48
  now = Date.now(),
47
- logCtx?: { failureDetail?: FailureDetail },
49
+ logCtx?: { failureDetail?: FailureDetail; causeHint?: RequestFailureCause },
48
50
  ): Promise<ConsumedComboFailure> {
49
51
  // Read before the body: the marker lives on this Response object, and the failure below is
50
52
  // rebuilt as a new one that would otherwise lose it.
@@ -84,6 +86,9 @@ export async function consumeComboFailure(
84
86
  }
85
87
  if (body.displaySafe && !body.truncated) {
86
88
  if (logCtx) recordUpstreamValidationDetail(logCtx, response.status, body.text);
89
+ // A combo child's row is attributed from the same evidence the parent uses: Meta's Muse
90
+ // Code refusal is a plan restriction, not a rejected credential (#8352).
91
+ if (logCtx) stampMetaMusePlanRefusal(logCtx, response.status, body.text);
87
92
  if (response.status === 400) codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
88
93
  const normalized = normalizeUpstreamErrorText(body.text, fallback);
89
94
  if (utf8Trusted || isCyberPolicyCode(normalized.code) || isCyberPolicyMessage(normalized.safeText)) {