@bitkyc08/opencodex 2.99.0-preview.20261108 → 2.100.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 (258) 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-CitvEefy.js +59 -0
  7. package/gui/dist/assets/Tray-CeKVWQyB.js +1 -0
  8. package/gui/dist/assets/{brand-mark-DpiBmFGI.js → brand-mark-M92UnxX2.js} +1 -1
  9. package/gui/dist/assets/index-BP47do6-.js +94 -0
  10. package/gui/dist/assets/index-DmDooSAG.css +2 -0
  11. package/gui/dist/assets/{segment-thumb-features-JcszQ18T.js → segment-thumb-features-CcxZBnxv.js} +1 -1
  12. package/gui/dist/classic/assets/App-aYgIQMxI.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-5v86r9Az.js → Tray-D8jfUXpQ.js} +1 -1
  14. package/gui/dist/classic/assets/index-CfGqHooN.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.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.ts +28 -2
  38. package/src/adapters/claude-cli/adapter.ts +5 -25
  39. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  40. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  41. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  42. package/src/adapters/coding-agent/protocol.ts +1 -1
  43. package/src/adapters/devin/live-models.ts +3 -0
  44. package/src/adapters/google-http.ts +3 -0
  45. package/src/adapters/google-vertex-key-project.ts +10 -2
  46. package/src/adapters/google.ts +40 -8
  47. package/src/adapters/kiro/usage.ts +3 -13
  48. package/src/adapters/openai-responses/passthrough.ts +5 -2
  49. package/src/adapters/openai-responses/request-strips.ts +32 -0
  50. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  51. package/src/chat/inbound.ts +1 -1
  52. package/src/claude/auth-detect.ts +26 -8
  53. package/src/claude/inbound-content-options.ts +18 -3
  54. package/src/claude/inbound.ts +5 -2
  55. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  56. package/src/cli/capabilities-agents-routing.ts +2 -2
  57. package/src/cli/capabilities-observe-system.ts +60 -0
  58. package/src/cli/combo-input.ts +6 -0
  59. package/src/cli/combo-result.ts +1 -1
  60. package/src/cli/combo.ts +4 -0
  61. package/src/cli/config-command.ts +16 -2
  62. package/src/cli/connect.ts +12 -10
  63. package/src/cli/dispatch.ts +4 -0
  64. package/src/cli/doctor.ts +11 -0
  65. package/src/cli/help.ts +1 -0
  66. package/src/cli/init.ts +4 -0
  67. package/src/cli/link-enrollment.ts +152 -25
  68. package/src/cli/link-local-control.ts +49 -0
  69. package/src/cli/link.ts +37 -10
  70. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  71. package/src/cli/registry.ts +13 -0
  72. package/src/cli/star-prompt.ts +2 -0
  73. package/src/cli/status.ts +1 -1
  74. package/src/cli/telemetry-profile.ts +206 -0
  75. package/src/cli/telemetry.ts +260 -0
  76. package/src/client/hub-relay.ts +26 -0
  77. package/src/client/machine-api.ts +3 -0
  78. package/src/clients/config-export/t3code.ts +44 -5
  79. package/src/clients/omo-role-models.ts +1 -1
  80. package/src/codex/catalog/bundled.ts +44 -2
  81. package/src/codex/runtime.ts +12 -0
  82. package/src/codex/shim-restore-lock.ts +67 -30
  83. package/src/combos/types.ts +21 -1
  84. package/src/config/atomic-write.ts +24 -1
  85. package/src/config/diagnostics.ts +15 -0
  86. package/src/config/live-reconcile.ts +17 -0
  87. package/src/config/load-degrade.ts +16 -0
  88. package/src/config/provider-validation.ts +29 -0
  89. package/src/config/schema/config-schema.ts +24 -0
  90. package/src/config/schema/leaf-validators.ts +17 -0
  91. package/src/config/telemetry-carry.ts +30 -0
  92. package/src/config.ts +13 -1
  93. package/src/generated/compatibility-version.json +405 -153
  94. package/src/generated/model-metadata.ts +3 -3
  95. package/src/integrations/aside-profiles.ts +7 -1
  96. package/src/integrations/owned-refresh.ts +9 -2
  97. package/src/lab/artifacts/secure-fs.ts +12 -11
  98. package/src/lab/fabric/scratch.ts +11 -9
  99. package/src/lab/public/community.ts +2 -3
  100. package/src/lab/public/file-safety.ts +18 -20
  101. package/src/lab/public/mutation-lock.ts +109 -337
  102. package/src/lab/public/private-file.ts +4 -3
  103. package/src/lib/bun-runtime-preflight.ts +1 -1
  104. package/src/lib/codex-catalog-read-only.ts +122 -0
  105. package/src/lib/config-ownership.ts +49 -18
  106. package/src/lib/errors.ts +11 -0
  107. package/src/lib/gcp-adc.ts +167 -48
  108. package/src/lib/jsonc.ts +4 -2
  109. package/src/lib/local-control-socket.ts +88 -0
  110. package/src/lib/privacy.ts +15 -0
  111. package/src/lib/provider-client-headers.ts +3 -0
  112. package/src/lib/token-estimate.ts +13 -2
  113. package/src/link/child-binary-source.ts +228 -0
  114. package/src/link/ephemeral-child.ts +45 -0
  115. package/src/link/remote-plant.ts +306 -0
  116. package/src/link/remote-windows.ts +59 -5
  117. package/src/link/ssh-argv.ts +71 -8
  118. package/src/link/status-projection.ts +2 -0
  119. package/src/link/store.ts +5 -1
  120. package/src/oauth/claude-keychain-read.ts +165 -0
  121. package/src/oauth/local-token-detect.ts +14 -17
  122. package/src/protocols/envelope.ts +20 -2
  123. package/src/providers/api-key-selection.ts +8 -2
  124. package/src/providers/claude-cli-usage-state.ts +93 -0
  125. package/src/providers/github-copilot-auto.ts +25 -5
  126. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  127. package/src/providers/model-rename-fields.ts +3 -0
  128. package/src/providers/quota/vendor-probes-key.ts +23 -4
  129. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  130. package/src/providers/quota/workbuddy.ts +2 -2
  131. package/src/providers/quota.ts +25 -18
  132. package/src/providers/registry/entries-core.ts +7 -4
  133. package/src/providers/registry/entries-extended.ts +39 -7
  134. package/src/providers/registry/model-seeds.ts +10 -2
  135. package/src/providers/resolved-model-policy.ts +4 -0
  136. package/src/providers/routed-config.ts +30 -3
  137. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  138. package/src/providers/vertex-environment-authority.ts +50 -0
  139. package/src/providers/workbuddy-credit-balance.ts +38 -6
  140. package/src/quota-pool/assemble.ts +14 -6
  141. package/src/router.ts +1 -0
  142. package/src/server/adapter-resolve.ts +11 -6
  143. package/src/server/audio-dictation.ts +21 -7
  144. package/src/server/auth-cors.ts +19 -0
  145. package/src/server/background-lifecycle.ts +71 -0
  146. package/src/server/chat-completions.ts +2 -0
  147. package/src/server/claude-messages.ts +30 -3
  148. package/src/server/index/live-sideband.ts +15 -1
  149. package/src/server/index/local-control-listener.ts +515 -0
  150. package/src/server/index/optional-listeners.ts +21 -1
  151. package/src/server/index/serve-options.ts +4 -3
  152. package/src/server/index/websocket-handler.ts +2 -0
  153. package/src/server/index.ts +3 -0
  154. package/src/server/management/combo-routes.ts +6 -1
  155. package/src/server/management/context.ts +1 -0
  156. package/src/server/management/link-child-preflight.ts +74 -0
  157. package/src/server/management/link-enrollment.ts +190 -25
  158. package/src/server/management/link-route-state.ts +6 -1
  159. package/src/server/management/link-routes.ts +27 -9
  160. package/src/server/management/model-rows.ts +4 -0
  161. package/src/server/management/oauth-account-routes.ts +9 -4
  162. package/src/server/management/provider-overwrite-carry.ts +9 -2
  163. package/src/server/management/provider-routes.ts +14 -0
  164. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  165. package/src/server/management/route-registry.ts +7 -0
  166. package/src/server/management/session-routes.ts +4 -1
  167. package/src/server/management/telemetry-routes.ts +37 -0
  168. package/src/server/management/usage-aggregate-cache.ts +290 -67
  169. package/src/server/management-api.ts +11 -2
  170. package/src/server/messages-native-preflight.ts +166 -0
  171. package/src/server/messages-native.ts +143 -43
  172. package/src/server/messages-shared.ts +14 -0
  173. package/src/server/proxy-liveness.ts +99 -6
  174. package/src/server/request-log-conversation.ts +18 -2
  175. package/src/server/request-log.ts +7 -2
  176. package/src/server/responses/adapter-continuation.ts +1 -0
  177. package/src/server/responses/adapter-dispatch.ts +11 -28
  178. package/src/server/responses/adapter-failure-message.ts +68 -0
  179. package/src/server/responses/combo-stream-preflight.ts +14 -2
  180. package/src/server/responses/core-auth.ts +26 -5
  181. package/src/server/responses/core-codex-account.ts +8 -1
  182. package/src/server/responses/core-combo-failure.ts +6 -1
  183. package/src/server/responses/core-combo-native.ts +150 -37
  184. package/src/server/responses/core-combo.ts +15 -9
  185. package/src/server/responses/core-normalize.ts +1 -0
  186. package/src/server/responses/core-options.ts +7 -1
  187. package/src/server/responses/core-pipeline.ts +21 -1
  188. package/src/server/responses/fetch-helpers.ts +5 -0
  189. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  190. package/src/server/responses/passthrough-delivery.ts +8 -1
  191. package/src/server/responses/passthrough-error.ts +22 -0
  192. package/src/server/responses/request-prepare.ts +7 -1
  193. package/src/server/responses/request-transport.ts +28 -5
  194. package/src/server/responses/run-turn-execution.ts +13 -0
  195. package/src/server/sse-frame-buffer.ts +5 -0
  196. package/src/server/ws-bridge.ts +10 -0
  197. package/src/service/launchd.ts +78 -4
  198. package/src/telemetry/aggregate.ts +348 -0
  199. package/src/telemetry/consent.ts +128 -0
  200. package/src/telemetry/contract.ts +403 -0
  201. package/src/telemetry/disclosure.ts +19 -0
  202. package/src/telemetry/install-id.ts +226 -0
  203. package/src/telemetry/payload.ts +129 -0
  204. package/src/telemetry/profile/client.ts +150 -0
  205. package/src/telemetry/profile/contract.ts +288 -0
  206. package/src/telemetry/profile/disclosure.ts +14 -0
  207. package/src/telemetry/profile/paths.ts +13 -0
  208. package/src/telemetry/profile/routes.ts +99 -0
  209. package/src/telemetry/profile/service.ts +234 -0
  210. package/src/telemetry/profile/state.ts +189 -0
  211. package/src/telemetry/profile/sync.ts +276 -0
  212. package/src/telemetry/routes.ts +183 -0
  213. package/src/telemetry/scheduler.ts +386 -0
  214. package/src/telemetry/sender.ts +97 -0
  215. package/src/telemetry/state.ts +334 -0
  216. package/src/types/combo-jev-effort-mode.ts +11 -0
  217. package/src/types/config.ts +3 -0
  218. package/src/types/provider.ts +11 -1
  219. package/src/types/request.ts +2 -0
  220. package/src/types/telemetry.ts +15 -0
  221. package/src/types/wire.ts +10 -0
  222. package/src/types.ts +5 -0
  223. package/src/update/index.ts +7 -1
  224. package/src/update/minisign.d.mts +17 -0
  225. package/src/update/minisign.mjs +88 -0
  226. package/src/update/signed-supply.d.mts +59 -0
  227. package/src/update/signed-supply.mjs +289 -0
  228. package/src/update/trust-root.json +38 -0
  229. package/src/update/update-bounded-json.d.mts +4 -0
  230. package/src/update/update-bounded-json.mjs +113 -0
  231. package/src/update/update-bytes.d.mts +2 -0
  232. package/src/update/update-bytes.mjs +23 -0
  233. package/src/update/update-candidate-id.d.mts +2 -0
  234. package/src/update/update-candidate-id.mjs +23 -0
  235. package/src/update/update-checkpoint-codec.d.mts +33 -0
  236. package/src/update/update-checkpoint-codec.mjs +217 -0
  237. package/src/update/update-contracts.d.mts +24 -0
  238. package/src/update/update-contracts.mjs +207 -0
  239. package/src/update/update-signature-threshold.d.mts +12 -0
  240. package/src/update/update-signature-threshold.mjs +47 -0
  241. package/src/update/update-signed-version.d.mts +5 -0
  242. package/src/update/update-signed-version.mjs +25 -0
  243. package/src/update/update-trust-anchor.d.mts +2 -0
  244. package/src/update/update-trust-anchor.mjs +2 -0
  245. package/src/usage/cache-diagnostic.ts +195 -50
  246. package/src/usage/expected-prices.ts +20 -2
  247. package/src/usage/filter-index.ts +1469 -0
  248. package/src/usage/ledger-scanner.ts +245 -4
  249. package/src/usage/source-filter.ts +10 -2
  250. package/src/usage/summary.ts +16 -0
  251. package/src/web-search/parse.ts +244 -38
  252. package/gui/dist/assets/App-CWz0areF.js +0 -59
  253. package/gui/dist/assets/Tray-BosDoskm.js +0 -1
  254. package/gui/dist/assets/index-CAxjGWkm.js +0 -94
  255. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  256. package/gui/dist/classic/assets/App-BOEsFmiN.js +0 -58
  257. package/gui/dist/classic/assets/index-ClZ_zZ77.js +0 -94
  258. package/gui/dist/classic/assets/quota-summary-xwvDtvu7.js +0 -1
@@ -13,6 +13,7 @@ import { loadConfig } from "../config";
13
13
  import { isLoopbackHostname, isWildcardHostname } from "../codex/loopback-target";
14
14
  import { normalizeBindHostname } from "./bind-host";
15
15
  import { isOcxCommandLine, readAlivePid, readProcessCommandLine, readRuntimePort, verifyPidIdentity } from "../config/process-state";
16
+ import { createServer, isIP } from "node:net";
16
17
  import { loopbackFamilyAvailability } from "../lib/loopback-family";
17
18
  import {
18
19
  LOCAL_ATTESTATION_CHALLENGE_HEADER,
@@ -46,6 +47,35 @@ export interface HealthzIdentity {
46
47
 
47
48
  export type EndpointLiveness = "live" | "dead" | "unknown";
48
49
 
50
+ /**
51
+ * Whether this process can bind `hostname:port` right now. A successful bind proves no process
52
+ * owns that address, which no probe of it can: connecting to this machine's own non-loopback
53
+ * address (a Tailscale IP, a LAN IP) with nothing listening TIMES OUT on some hosts instead of
54
+ * being refused, and a timeout is indistinguishable from a slow owner. The listener is closed
55
+ * immediately. Any bind error (EADDRINUSE, EADDRNOTAVAIL, EACCES) answers false, so an address
56
+ * we cannot bind stays "unknown" and startup keeps refusing.
57
+ */
58
+ const BIND_PROOF_TIMEOUT_MS = 1_500;
59
+
60
+ export function canBindAddress(hostname: string, port: number, timeoutMs = BIND_PROOF_TIMEOUT_MS): Promise<boolean> {
61
+ if (!Number.isInteger(port) || port <= 0 || port > 65_535) return Promise.resolve(false);
62
+ return new Promise<boolean>(resolve => {
63
+ const server = createServer();
64
+ let settled = false;
65
+ const finish = (bound: boolean): void => {
66
+ if (settled) return;
67
+ settled = true;
68
+ clearTimeout(timer);
69
+ try { server.close(); } catch { /* never bound */ }
70
+ resolve(bound);
71
+ };
72
+ const timer = setTimeout(() => finish(false), timeoutMs);
73
+ server.once("error", () => finish(false));
74
+ server.once("listening", () => finish(true));
75
+ try { server.listen({ host: hostname, port, exclusive: true }); } catch { finish(false); }
76
+ });
77
+ }
78
+
49
79
  export interface LivenessIo {
50
80
  fetchFn?: typeof fetch;
51
81
  readPidFn?: () => number | null;
@@ -57,6 +87,12 @@ export interface LivenessIo {
57
87
  /** Fresh command-line evidence: undefined/empty is unreadable, never confirmed foreign. */
58
88
  readCommandLineFn?: typeof readProcessCommandLine;
59
89
  loopbackAvailabilityFn?: typeof loopbackFamilyAvailability;
90
+ /**
91
+ * Test seam for the bind proof (see `canBindAddress`): whether `hostname:port` can be bound by
92
+ * this process right now, which proves no process owns that address. `hostname` is the raw
93
+ * socket address (IPv6 unbracketed) and `timeoutMs` the remaining discovery budget.
94
+ */
95
+ bindProofFn?: (hostname: string, port: number, timeoutMs: number) => Promise<boolean>;
60
96
  readRuntimeFn?: (pid?: number) => { pid?: number; port: number; hostname?: string } | null;
61
97
  configFn?: () => { port?: number; hostname?: string };
62
98
  timeoutMs?: number;
@@ -479,19 +515,34 @@ export type ProxyLivenessObservation =
479
515
 
480
516
  /** Recovery additionally covers both available loopback families and fresh PID identity. */
481
517
  export async function observeProxyLiveness(io: LivenessIo = {}): Promise<ProxyLivenessObservation> {
482
- let alivePid: number | null = null, unknown = false;
518
+ let alivePid: number | null = null, runtimePid: number | undefined, unknown = false;
483
519
  const live = await discoverLiveProxy(io, {
484
520
  pid: pid => { alivePid = pid; },
521
+ runtimePid: pid => { runtimePid = pid; },
485
522
  endpoint: result => { if (result === "unknown") unknown = true; },
486
523
  });
487
524
  if (live) return { kind: "live", live };
488
- if (alivePid !== null && !unknown) {
525
+ const candidates = new Set<number>();
526
+ if (alivePid !== null) candidates.add(alivePid);
527
+ if (runtimePid !== undefined && Number.isSafeInteger(runtimePid) && runtimePid > 0) candidates.add(runtimePid);
528
+ for (const pid of candidates) {
529
+ if (unknown) break;
530
+ if (io.deadlineAt !== undefined && (io.nowFn ?? Date.now)() >= io.deadlineAt) { unknown = true; break; }
531
+ if (pid !== alivePid) {
532
+ try { process.kill(pid, 0); } catch (error) {
533
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") continue;
534
+ // Permission or an indeterminate probe is not proof that the process is dead.
535
+ unknown = true;
536
+ break;
537
+ }
538
+ }
489
539
  // A failed verifier alone conflates foreign with unreadable. Only fresh positive
490
540
  // evidence of a foreign command line releases a reused PID; never signal it.
491
- const commandLine = (io.readCommandLineFn ?? readProcessCommandLine)(alivePid);
541
+ const commandLine = (io.readCommandLineFn ?? readProcessCommandLine)(pid);
492
542
  unknown = !commandLine?.trim() || isOcxCommandLine(commandLine);
493
543
  if (io.deadlineAt !== undefined && (io.nowFn ?? Date.now)() >= io.deadlineAt) unknown = true;
494
544
  }
545
+ if (io.deadlineAt !== undefined && (io.nowFn ?? Date.now)() >= io.deadlineAt) unknown = true;
495
546
  return { kind: unknown ? "unknown" : "absent", live: null };
496
547
  }
497
548
 
@@ -506,6 +557,7 @@ export async function findLiveProxy(io: LivenessIo = {}): Promise<LiveProxy | nu
506
557
 
507
558
  async function discoverLiveProxy(io: LivenessIo, observer?: {
508
559
  pid: (pid: number | null) => void;
560
+ runtimePid: (pid: number | undefined) => void;
509
561
  endpoint: (result: EndpointLiveness) => void;
510
562
  }): Promise<LiveProxy | null> {
511
563
  // Prefer the cheap alive-pid check: the Windows cmdline probe (WMIC/PowerShell) is too
@@ -520,18 +572,38 @@ async function discoverLiveProxy(io: LivenessIo, observer?: {
520
572
  const budgetExhausted = (): boolean =>
521
573
  deadlineAt !== undefined && nowFn() >= deadlineAt;
522
574
  const expired = (): null => { observer?.endpoint("unknown"); return null; };
575
+ // The proof stays inside the discovery deadline: it is skipped once the budget is spent, its
576
+ // own timeout is capped by what remains, and a proof that finishes past the deadline is
577
+ // discarded, so an exhausted discovery still answers "unknown". A socket takes the raw
578
+ // address, never the bracketed URL spelling `probeHostname` composes for IPv6.
579
+ const bindProof = async (hostname: string, port: number): Promise<boolean> => {
580
+ const remainingMs = deadlineAt === undefined ? BIND_PROOF_TIMEOUT_MS : Math.min(BIND_PROOF_TIMEOUT_MS, deadlineAt - nowFn());
581
+ if (remainingMs <= 0) return false;
582
+ const socketHost = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
583
+ // A hostname can resolve to different addresses for the probe and the bind.
584
+ if (isIP(socketHost) === 0) return false;
585
+ const bound = await (io.bindProofFn ?? canBindAddress)(socketHost, port, remainingMs);
586
+ return bound && !budgetExhausted();
587
+ };
523
588
  const probe = async (port: number, opts: { hostname?: string; expectedPid?: number }) => {
524
589
  // Missing/blank means an actual loopback bind, not a later config's bind scope.
525
590
  const bindHostname = opts.hostname?.trim() || "127.0.0.1";
526
591
  const hostname = normalizeBindHostname(opts.hostname);
527
- if (!observer || (!isLoopbackHostname(hostname) && !isWildcardHostname(hostname))) {
528
- const identity = await proxyIdentityAtObserved(port, opts, probeIo, observer?.endpoint);
592
+ if (!observer || (!recoveryLoopbackFamily(hostname) && !isWildcardHostname(hostname))) {
593
+ // Recovery only (an observer is present): a transport miss on a specific non-loopback bind
594
+ // address is "unknown", and a bind proof is the one thing that turns it into "dead".
595
+ let verdict: EndpointLiveness | undefined;
596
+ const identity = await proxyIdentityAtObserved(port, opts, probeIo, observer ? (r => { verdict = r; }) : undefined);
597
+ if (observer && !identity && verdict !== undefined) {
598
+ if (verdict === "unknown" && await bindProof(hostname, port)) verdict = "dead";
599
+ observer.endpoint(verdict);
600
+ }
529
601
  return identity ? { ...identity, hostname: bindHostname,
530
602
  ...(observer ? { probeHostname: probeHostname(opts.hostname) } : {}) } : null;
531
603
  }
532
604
  // Parallel families share the existing per-probe attempts/timeout and absolute
533
605
  // deadline. A slow family cannot multiply the serial discovery budget.
534
- const hosts = loopbackProbeHosts(hostname).filter(host =>
606
+ const hosts = recoveryProbeHosts(hostname).filter(host =>
535
607
  (io.loopbackAvailabilityFn ?? loopbackFamilyAvailability)(host) !== "unavailable");
536
608
  const identities = await Promise.all(hosts.map(async hostname => {
537
609
  const identity = await proxyIdentityAtObserved(port, { ...opts, hostname }, probeIo, observer.endpoint);
@@ -587,6 +659,7 @@ async function discoverLiveProxy(io: LivenessIo, observer?: {
587
659
  // sibling command, manual deletion). The runtime record still says where it listens —
588
660
  // identity-probe it so ensure/update/stop see the live proxy instead of shadowing it.
589
661
  const record = readRuntimeFn();
662
+ observer?.runtimePid(record?.pid);
590
663
  if (record?.port && record.port !== probedPort) {
591
664
  if (budgetExhausted()) return expired();
592
665
  const expectedPid = typeof record.pid === "number" ? record.pid : undefined;
@@ -629,6 +702,26 @@ async function discoverLiveProxy(io: LivenessIo, observer?: {
629
702
  return null;
630
703
  }
631
704
 
705
+ // Recovery classification is intentionally local: it must not broaden admission or bind policy.
706
+ function recoveryLoopbackFamily(hostname: string): 4 | 6 | null {
707
+ if (isLoopbackHostname(hostname)) return hostname.includes(":") ? 6 : 4;
708
+ const address = hostname.replace(/^\[(.*)\]$/, "$1");
709
+ const family = isIP(address);
710
+ if (family === 4) return address.startsWith("127.") ? 4 : null;
711
+ if (family !== 6) return null;
712
+ // URL serializes validated IPv6 literals canonically, including dotted IPv4-mapped forms.
713
+ const canonical = new URL(`http://[${address.split("%")[0]}]/`).hostname.slice(1, -1);
714
+ if (canonical === "::1") return 6;
715
+ return /^::ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(canonical) ? 4 : null;
716
+ }
717
+
718
+ function recoveryProbeHosts(hostname: string): string[] {
719
+ if (isWildcardHostname(hostname)) return ["127.0.0.1", "[::1]"];
720
+ const family = recoveryLoopbackFamily(hostname);
721
+ if (family) return [probeHostname(hostname), family === 6 ? "127.0.0.1" : "[::1]"];
722
+ return [probeHostname(hostname)];
723
+ }
724
+
632
725
  /**
633
726
  * Loopback addresses to ask about a port whose holder must be identified before a
634
727
  * decision that is destructive when it answers "nobody".
@@ -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
  /**
@@ -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)) {