@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
@@ -1,9 +1,10 @@
1
1
  import { clientFacingModelLabel } from "../../lib/error-destination";
2
2
  /**
3
- * Native Chat candidates inside the combo loop (PF-07).
3
+ * Native Chat and Messages candidates inside the combo loop.
4
4
  *
5
- * The Chat ingress hands the combo a `ComboProtocolSource` only for a combo route with
6
- * `protocols.rollout.nativeChatCombos` on; without one nothing here runs. For the candidate the
5
+ * Each opted-in ingress hands the combo its `ComboProtocolSource`; without one nothing here
6
+ * runs. Messages supports canonical strict failover children without effort rewriting.
7
+ * For the candidate the
7
8
  * combo is about to dispatch, the concrete route is settled the way the Chat ingress settles a
8
9
  * single route, and the native Chat lane's own eligibility rule decides whether the child goes
9
10
  * native. A native child runs `runNativeChatAttempt` (through the source) on the attempt the combo
@@ -41,7 +42,38 @@ import { resolveOpenCodeGoTransport } from "../../providers/opencode-go-transpor
41
42
  import { getOrAllocateRequestSessionLane } from "../request-log-conversation";
42
43
  import { assertRouteAllowedByScope } from "../admission-model-scope";
43
44
  import { isNativeChatRouteEligible } from "../chat-native-eligibility";
45
+ import { nativeMessagesDeclineReason, type NativeMessagesSelector } from "../messages-native-eligibility";
46
+ import type { NativeMessagesFinishLog } from "../messages-native";
47
+ import { credentialDomainFor } from "../../protocols/opaque-state";
44
48
  import { chatCompletionsErrorResponse } from "../../chat/outbound";
49
+ import { OUTPUT_CONFIG_EFFORTS } from "../../chat/inbound";
50
+ import { anthropicErrorResponse } from "../../claude/outbound";
51
+ import { hasAnthropicOnlyServerTool, hasNativeOnlyTool } from "../../claude/inbound-content-options";
52
+ import { nativeMessagesInlineToolNames } from "../messages-native-tool-guard";
53
+
54
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
55
+ value !== null && typeof value === "object" && !Array.isArray(value);
56
+
57
+ /**
58
+ * An inline definition without a usable name cannot be withdrawn by a tool_reference, so it stays in
59
+ * force; nativeMessagesInlineToolNames tracks only named, callable tools and skips it.
60
+ */
61
+ /** The bridge drops inline removals too, so withdrawing a top-level tool would re-enable it there. */
62
+ function withdrawsTopLevelTool(body: Record<string, unknown>): boolean {
63
+ const declared = new Set(Array.isArray(body.tools)
64
+ ? body.tools.flatMap(tool => isRecord(tool) && typeof tool.name === "string" ? [tool.name] : []) : []);
65
+ return declared.size > 0 && Array.isArray(body.messages) && body.messages.some(message => isRecord(message)
66
+ && message.role === "system" && Array.isArray(message.content) && message.content.some(block => isRecord(block)
67
+ && block.type === "tool_removal" && isRecord(block.tool) && block.tool.type === "tool_reference"
68
+ && typeof block.tool.name === "string" && declared.has(block.tool.name)));
69
+ }
70
+
71
+ function hasUnnamedInlineToolDefinition(body: Record<string, unknown>): boolean {
72
+ return Array.isArray(body.messages) && body.messages.some(message => isRecord(message) && message.role === "system"
73
+ && Array.isArray(message.content) && message.content.some(block => isRecord(block) && block.type === "tool_addition"
74
+ && isRecord(block.tool) && block.tool.type === "tool_definition"
75
+ && !(isRecord(block.tool.definition) && typeof block.tool.definition.name === "string" && block.tool.definition.name.length > 0)));
76
+ }
45
77
  import { isRequestExecutionBudget } from "../../lib/request-execution-budget";
46
78
  import { markResponseNonReplayable } from "../../lib/upstream-retry";
47
79
  import { redactSecretString } from "../../lib/redact";
@@ -58,7 +90,7 @@ type ComboTarget = { provider: string; model: string };
58
90
  /** What the source needs to run one native child on the combo's open attempt. */
59
91
  export interface NativeComboChildRun {
60
92
  route: RouteResult;
61
- /** A fresh copy of the source Chat body, never another candidate's rewritten one. */
93
+ /** A fresh copy of the source body, never another candidate's rewritten one. */
62
94
  body: Rec;
63
95
  childLog: RequestLogContext;
64
96
  attemptHandle: InferenceAttempt;
@@ -71,13 +103,22 @@ export interface NativeComboChildRun {
71
103
  }
72
104
 
73
105
  /** Supplied by the Chat ingress for a combo route when `nativeChatCombos` is on. */
74
- export interface ComboProtocolSource {
106
+ interface NativeChatComboSource {
75
107
  readonly inbound: "chat";
76
108
  readonly envelope: ProtocolEnvelope;
77
109
  /** Runs `runNativeChatAttempt`; the response it returns is in the Chat wire. */
78
110
  dispatchNativeChild(input: NativeComboChildRun): Promise<Response>;
79
111
  }
80
112
 
113
+ interface NativeMessagesComboSource {
114
+ readonly inbound: "messages";
115
+ readonly envelope: ProtocolEnvelope;
116
+ readonly selector?: NativeMessagesSelector;
117
+ dispatchNativeChild(input: Omit<NativeComboChildRun, "finishLog"> & { finishLog: NativeMessagesFinishLog }): Promise<Response>;
118
+ }
119
+
120
+ export type ComboProtocolSource = NativeChatComboSource | NativeMessagesComboSource;
121
+
81
122
  /** The native plan for one dispatch: the settled route and its own fresh body. */
82
123
  export interface NativeComboChildPlan {
83
124
  route: RouteResult;
@@ -86,21 +127,28 @@ export interface NativeComboChildPlan {
86
127
  }
87
128
 
88
129
  export interface ComboProtocolLanes {
89
- /** Pick predicate. False only for a candidate the `reject` policy skips. */
130
+ /** Pick predicate. False for a candidate the `reject` policy skips or a translated child of a native-only tool. */
90
131
  pickable(target: ComboTarget): boolean;
91
132
  /** The ingress refusal when every enabled candidate was skipped; otherwise undefined. */
92
133
  refusal(): Response | undefined;
93
- /** The native plan for the candidate about to dispatch, or undefined to keep the bridge. */
134
+ /**
135
+ * The native plan for the candidate about to dispatch, or undefined to keep the bridge.
136
+ * `decisionOwnsEffort` is the caller's pre-decision reading of `jevEffortMode`: re-reading a
137
+ * combo the management API can replace mid-decision would split this lane from its log label.
138
+ */
94
139
  nativeChild(
95
140
  target: ComboTarget,
96
141
  targetRoute: RouteResult,
97
142
  targetSendBudget: TransientSendBudget | undefined,
98
- initialDecision?: Pick<JevDecision, "effort">,
143
+ initialDecision: Pick<JevDecision, "effort"> | undefined,
144
+ decisionOwnsEffort: boolean,
99
145
  ): NativeComboChildPlan | undefined;
100
146
  }
101
147
 
102
148
  interface CandidateVerdict {
103
149
  skip?: ProtocolFeature[];
150
+ /** A translated child would silently drop the request's native-only tool. */
151
+ nativeOnly?: true;
104
152
  }
105
153
 
106
154
  /** Build opt-in native eligibility and child plans; only the initial plan applies a JEV choice. */
@@ -118,6 +166,8 @@ export function createComboProtocolLanes(input: {
118
166
  const { source, req, config, logCtx, admissionScope, droidDefaultEffort, comboId, targets } = input;
119
167
  if (!source) return undefined;
120
168
  const envelope = source.envelope;
169
+ const inbound = source.inbound;
170
+ const inboundWire = inbound === "messages" ? "anthropic" : "chat";
121
171
  const reject = resolveProtocolSettings(config).unrepresentable === "reject";
122
172
  const selector = (target: ComboTarget): string => `${target.provider}/${target.model}`;
123
173
 
@@ -130,9 +180,9 @@ export function createComboProtocolLanes(input: {
130
180
  assertRouteAllowedByScope(admissionScope, clientFacingModelLabel(undefined), route);
131
181
  const routedProvider = route.provider;
132
182
  route.staticPolicy = captureRouteStaticPolicy(
133
- route.providerName, route.modelId, routedProvider, route.staticPolicy.effectiveAlias, "chat",
183
+ route.providerName, route.modelId, routedProvider, route.staticPolicy.effectiveAlias, inboundWire,
134
184
  );
135
- const wireProvider = resolveWireProtocolOverride(route.providerName, route.modelId, routedProvider, "chat", route.staticPolicy);
185
+ const wireProvider = resolveWireProtocolOverride(route.providerName, route.modelId, routedProvider, inboundWire, route.staticPolicy);
136
186
  route.provider = resolveOpenCodeGoTransport(wireProvider, getOrAllocateRequestSessionLane(req), routedProvider);
137
187
  return route;
138
188
  } catch {
@@ -140,19 +190,34 @@ export function createComboProtocolLanes(input: {
140
190
  }
141
191
  };
142
192
 
143
- // Eligibility reads a body, and a body is a charged copy, so the adapter is checked first:
144
- // a candidate that can never go native costs no copy at all.
145
- const nativeBody = (target: ComboTarget, route: RouteResult | undefined): Rec | undefined => {
146
- if (!route || route.provider.adapter !== "openai-chat") return undefined;
147
- const body = envelope.freshBody();
193
+ // Eligibility only reads the body, so it reads the source in place: judging a candidate charges
194
+ // no copy and can never refuse the turn on the translator budget. Only a dispatch takes a copy.
195
+ const nativeEligible = (target: ComboTarget, route: RouteResult | undefined): route is RouteResult => {
196
+ if (!route || route.provider.adapter !== (inbound === "messages" ? "anthropic" : "openai-chat")) return false;
197
+ if (inbound === "messages") {
198
+ const combo = getCombo(config, comboId);
199
+ // ponytail: exact replay supports no combo effort rewrite; the existing bridge owns those policies.
200
+ if (!combo || combo.strategy !== "failover" || comboDefaultEffort(config, comboId)
201
+ || combo.reasoningEffortMode !== "strict" || !credentialDomainFor(route.provider)?.firstPartyAnthropic
202
+ || supportedLadderFor({ provider: route.provider, modelId: route.modelId })?.length === 0) return false;
203
+ }
148
204
  // The concrete selector, as the bridge child's body carries it; the wire model comes from
149
205
  // the route either way, and the pinned-effort lookup reads this.
150
- body.model = selector(target);
151
- return isNativeChatRouteEligible(route, body, config) ? body : undefined;
206
+ const body = { ...envelope.readBody(), model: selector(target) };
207
+ return inbound === "messages"
208
+ ? nativeMessagesDeclineReason(route, body, config, { ...(source.inbound === "messages" ? source.selector : undefined), routeSelector: selector(target) }) === undefined
209
+ : isNativeChatRouteEligible(route, body, config);
152
210
  };
153
211
 
154
212
  const verdicts = new Map<string, CandidateVerdict>();
155
213
  let skipRecorded = false;
214
+ let nativeOnlyTool: boolean | undefined;
215
+ let anthropicOnlyTool: boolean | undefined;
216
+ // The bridge keeps only text from system messages, so an active inline tool_addition definition
217
+ // has no translated equivalent either; fail closed like a top-level native-only tool.
218
+ const declaresNativeOnlyTool = (body: Record<string, unknown>) =>
219
+ hasNativeOnlyTool(body) || nativeMessagesInlineToolNames(body).size > 0 || hasUnnamedInlineToolDefinition(body)
220
+ || withdrawsTopLevelTool(body);
156
221
  const judge = (target: ComboTarget): CandidateVerdict => {
157
222
  const key = selector(target);
158
223
  const cached = verdicts.get(key);
@@ -167,11 +232,11 @@ export function createComboProtocolLanes(input: {
167
232
  }
168
233
  if (targetRoute) {
169
234
  const settled = settle(target, targetRoute);
170
- const native = nativeBody(target, settled) !== undefined;
171
- const upstream = native ? "chat" : upstreamWireForAdapter((settled ?? targetRoute).provider.adapter);
235
+ const native = nativeEligible(target, settled);
236
+ const upstream = native ? inbound : upstreamWireForAdapter((settled ?? targetRoute).provider.adapter);
172
237
  const checked = checkRepresentable({
173
- inbound: "chat",
174
- requestPath: requestPathForLane("chat", native ? "native" : "bridge", upstream),
238
+ inbound,
239
+ requestPath: requestPathForLane(inbound, native ? "native" : "bridge", upstream),
175
240
  features: envelope.features(),
176
241
  policy: "reject",
177
242
  });
@@ -182,13 +247,26 @@ export function createComboProtocolLanes(input: {
182
247
  addProtocolEntryReason(logCtx, "feature-unrepresentable");
183
248
  }
184
249
  }
250
+ // Under any policy: the source chose a native-only tool, so a translated child never runs it.
251
+ // web_fetch and a restricted web_search only travel out of body, to a first-party Anthropic child.
252
+ if (!native && inbound === "messages") {
253
+ const provider = (settled ?? targetRoute).provider;
254
+ if ((nativeOnlyTool ??= declaresNativeOnlyTool(envelope.readBody()))
255
+ || ((anthropicOnlyTool ??= hasAnthropicOnlyServerTool(envelope.readBody()))
256
+ && !(provider.adapter === "anthropic" && credentialDomainFor(provider)?.firstPartyAnthropic))) {
257
+ verdict.nativeOnly = true;
258
+ }
259
+ }
185
260
  }
186
261
  verdicts.set(key, verdict);
187
262
  return verdict;
188
263
  };
189
264
 
190
265
  return {
191
- pickable: target => !reject || judge(target).skip === undefined,
266
+ pickable: target => {
267
+ const verdict = judge(target);
268
+ return verdict.nativeOnly !== true && (!reject || verdict.skip === undefined);
269
+ },
192
270
  refusal: () => {
193
271
  if (!reject) return undefined;
194
272
  const enabled = targets.filter(target => {
@@ -201,24 +279,28 @@ export function createComboProtocolLanes(input: {
201
279
  const features = [...new Set(skipped.flatMap(verdict => verdict.skip ?? []))];
202
280
  // The same refusal the ingress gives a single route: 400 in the Chat shape, feature keys
203
281
  // only, a blocked trace, and no upstream send.
204
- markProtocolBlocked(logCtx, { inbound: "chat", reasonCodes: ["feature-unrepresentable"], features });
282
+ markProtocolBlocked(logCtx, { inbound, reasonCodes: ["feature-unrepresentable"], features });
205
283
  logCtx.errorCode = "unsupported_feature";
206
- return markClientWire(chatCompletionsErrorResponse(
284
+ return markClientWire((inbound === "messages" ? anthropicErrorResponse : chatCompletionsErrorResponse)(
207
285
  400, unrepresentableMessage(features), "invalid_request_error", "unsupported_feature",
208
- ), "chat");
286
+ ), inbound);
209
287
  },
210
- nativeChild: (target, targetRoute, targetSendBudget, initialDecision) => {
288
+ nativeChild: (target, targetRoute, targetSendBudget, initialDecision, decisionOwnsEffort) => {
211
289
  // Without the request's execution budget a native child could not share its sends, so it
212
290
  // keeps the bridge rather than opening a tracker of its own.
213
291
  if (!isRequestExecutionBudget(targetSendBudget)) return undefined;
214
292
  const route = settle(target, targetRoute);
215
- const body = nativeBody(target, route);
216
- if (!route || !body) return undefined;
293
+ if (!nativeEligible(target, route)) return undefined;
294
+ const body = envelope.freshBody();
295
+ body.model = selector(target);
296
+ if (inbound === "messages") return initialDecision ? undefined : { route, body, sendBudget: targetSendBudget };
217
297
  applyDroidReasoningDefault(body, droidDefaultEffort, {
218
298
  provider: targetRoute.provider,
219
299
  modelId: targetRoute.modelId,
220
300
  });
221
- if (initialDecision) {
301
+ // `client` keeps the decision's target but not its tier, so the ordinary combo effort
302
+ // policy applies instead of the decision's effort.
303
+ if (initialDecision && decisionOwnsEffort) {
222
304
  // A validated JEV choice owns only this first dispatch, including explicit no-effort.
223
305
  // Do not run ordinary force defaults for null: they require a non-null default.
224
306
  delete body.service_tier;
@@ -255,9 +337,20 @@ function applyComboEffort(
255
337
  ): void {
256
338
  const combo = getCombo(config, comboId);
257
339
  if (!combo) return;
340
+ // Same precedence as the Chat inbound parser (`resolveReasoningEffort`): a string
341
+ // `reasoning_effort` first, a string nested `reasoning.effort` second. A non-string top-level
342
+ // value (an explicit null) is no caller effort, so the nested one still decides.
343
+ const nested = body.reasoning && typeof body.reasoning === "object" && !Array.isArray(body.reasoning)
344
+ ? (body.reasoning as Rec).effort
345
+ : undefined;
258
346
  const hadEffort = Object.hasOwn(body, "reasoning_effort");
347
+ // With no string anywhere, a present top-level value (an explicit null) is passed on as before.
348
+ const callerEffort = typeof body.reasoning_effort === "string" ? body.reasoning_effort
349
+ // The parser reads a nested effort only when it is a level it knows; anything else is no effort.
350
+ : typeof nested === "string" && OUTPUT_CONFIG_EFFORTS.has(nested) ? nested
351
+ : hadEffort ? body.reasoning_effort : undefined;
259
352
  const shaped = concreteComboRequestBody(
260
- hadEffort ? { reasoning: { effort: body.reasoning_effort } } : {},
353
+ callerEffort !== undefined || hadEffort ? { reasoning: { effort: callerEffort } } : {},
261
354
  target,
262
355
  comboDefaultEffort(config, comboId),
263
356
  supportedLadderFor({ provider: targetRoute.provider, modelId: targetRoute.modelId }),
@@ -281,7 +374,7 @@ export interface ComboChildCallbacks {
281
374
  }
282
375
 
283
376
  /**
284
- * Run one native child on the attempt the combo opened, and mark its answer as Chat wire.
377
+ * Run one native child on the attempt the combo opened, and mark its client wire.
285
378
  *
286
379
  * The child's outcomes map onto the combo's existing child callbacks: a terminal or cancellation
287
380
  * after the response was handed over publishes through the gate (and so reaches the parent's
@@ -302,10 +395,11 @@ export async function dispatchNativeComboChild(input: {
302
395
  callbacks: ComboChildCallbacks;
303
396
  }): Promise<Response> {
304
397
  const { plan, logCtx, childLog, attempt, startedAt, callbacks } = input;
398
+ const inbound = input.source.inbound;
305
399
  childLog.providerAdapter = plan.route.provider.adapter;
306
400
  markAttemptProtocolPath(attempt, {
307
- mode: deliveryModeForLane("chat", "native", "chat"),
308
- requestPath: requestPathForLane("chat", "native", "chat"),
401
+ mode: deliveryModeForLane(inbound, "native", inbound),
402
+ requestPath: requestPathForLane(inbound, "native", inbound),
309
403
  });
310
404
  let outputSeen = false;
311
405
  const finishLog: NativeChatFinishLog = (status, message, closeReason = "non_stream") => {
@@ -332,7 +426,7 @@ export async function dispatchNativeComboChild(input: {
332
426
  seal: label => sealRequestAttemptIdentity(attempt, childLog.provider, childLog.providerAdapter ?? attempt.adapter, label),
333
427
  finish: (status, usage) => finishRequestAttempt(attempt, status, Date.now() - startedAt, usage),
334
428
  };
335
- const response = await input.source.dispatchNativeChild({
429
+ const child = {
336
430
  route: plan.route,
337
431
  body: plan.body,
338
432
  childLog,
@@ -344,8 +438,27 @@ export async function dispatchNativeComboChild(input: {
344
438
  outputSeen = true;
345
439
  input.onFirstOutput();
346
440
  },
347
- finishLog,
348
- });
441
+ };
442
+ let response: Response | undefined;
443
+ try {
444
+ response = await (input.source.inbound === "messages"
445
+ ? input.source.dispatchNativeChild({ ...child, finishLog: (status, message, meta) => {
446
+ if (meta?.terminalStatus === "incomplete") {
447
+ childLog.terminalHttpStatus = status;
448
+ if (childLog.usage !== undefined) logCtx.usage = childLog.usage;
449
+ callbacks.onTerminal("incomplete");
450
+ return;
451
+ }
452
+ // A 200 stream whose terminal was an upstream error event did not complete.
453
+ if (childLog.streamErrorStatus !== undefined && status < 400) return finishLog(childLog.streamErrorStatus, message, "terminal");
454
+ finishLog(status, message, meta?.closeReason === "client_cancel" ? "client_cancel"
455
+ : meta?.closeReason && meta.closeReason !== "non_stream" ? "terminal" : "non_stream");
456
+ } })
457
+ : input.source.dispatchNativeChild({ ...child, finishLog }));
458
+ } finally {
459
+ // A failed child's copy is spent; the next target takes its own, so this charge must not outlive it.
460
+ if (!response?.ok) input.source.envelope.releaseBody(plan.body);
461
+ }
349
462
  if (!response.ok && outputSeen) markResponseNonReplayable(response);
350
- return markClientWire(response, "chat");
463
+ return markClientWire(response, inbound);
351
464
  }
@@ -413,7 +413,7 @@ export async function executeComboResponses(
413
413
  // internal request carries the caller's captured scope on options.admissionScope even though
414
414
  // its own admission is the host's broad key; recomputing from options.admission would lose it.
415
415
  const admissionScope = options.admissionScope ?? resolveAdmissionModelScope(config, options.admission);
416
- // PF-07: present only for a Chat combo with `nativeChatCombos` on; otherwise every child
416
+ // Present only when an opted-in ingress supplied a native source; otherwise every child
417
417
  // takes the bridge below exactly as before.
418
418
  const protocolLanes = createComboProtocolLanes({
419
419
  source: options.protocolSource,
@@ -1058,6 +1058,10 @@ export async function executeComboResponses(
1058
1058
  modelId: targetRoute.modelId,
1059
1059
  });
1060
1060
  const initialJevDecision = firstComboTarget ? jevDecision : undefined;
1061
+ // `client` keeps the decision's target but not its tier: the caller and the target ladder
1062
+ // own the wire effort, so a provider whose effort swaps the upstream model id is never
1063
+ // re-tiered mid-session and its prompt cache survives the turn.
1064
+ const jevEffortApplies = initialJevDecision !== undefined && combo.jevEffortMode !== "client";
1061
1065
  const childInput = options.droidDefaultEffort && isPlainObject(body) ? { ...body } : body;
1062
1066
  applyDroidResponsesReasoningDefault(childInput, options.droidDefaultEffort, {
1063
1067
  provider: targetRoute.provider,
@@ -1066,14 +1070,16 @@ export async function executeComboResponses(
1066
1070
  const childBody = concreteComboRequestBody(
1067
1071
  childInput,
1068
1072
  pick.target,
1069
- initialJevDecision ? initialJevDecision.effort : comboDefaultEffort(config, comboId),
1070
- initialJevDecision?.effort === null ? [] : targetReasoningEfforts,
1073
+ jevEffortApplies ? initialJevDecision.effort : comboDefaultEffort(config, comboId),
1074
+ jevEffortApplies && initialJevDecision.effort === null ? [] : targetReasoningEfforts,
1071
1075
  combo.reasoningEffortMode,
1072
- initialJevDecision ? (initialJevDecision.effort === null ? "fallback" : "force") : combo.defaultEffortMode,
1076
+ jevEffortApplies
1077
+ ? (initialJevDecision.effort === null ? "fallback" : "force")
1078
+ : combo.defaultEffortMode,
1073
1079
  );
1074
1080
  if (initialJevDecision) {
1075
- delete childBody.service_tier;
1076
- if (initialJevDecision.effort !== null) {
1081
+ if (jevEffortApplies) delete childBody.service_tier;
1082
+ if (jevEffortApplies && initialJevDecision.effort !== null) {
1077
1083
  const childReasoning = childBody.reasoning;
1078
1084
  const preservedReasoning = childReasoning && typeof childReasoning === "object" && !Array.isArray(childReasoning)
1079
1085
  ? childReasoning as Record<string, unknown>
@@ -1182,7 +1188,7 @@ export async function executeComboResponses(
1182
1188
  && targetEligible(target)
1183
1189
  && !isComboTargetInCooldown(comboId, target),
1184
1190
  );
1185
- const nativeChild = protocolLanes?.nativeChild(pick.target, targetRoute, targetSendBudget, initialJevDecision);
1191
+ const nativeChild = protocolLanes?.nativeChild(pick.target, targetRoute, targetSendBudget, initialJevDecision, jevEffortApplies);
1186
1192
  response = nativeChild ? await dispatchNativeComboChild({
1187
1193
  source: options.protocolSource!,
1188
1194
  plan: nativeChild,
@@ -1238,7 +1244,7 @@ export async function executeComboResponses(
1238
1244
  onResponseComplete: callbackGate.onResponseComplete,
1239
1245
  });
1240
1246
  // Both lanes applied the initial choice before provider pins/caps; retain those transitions.
1241
- restoreOriginalRequestedEffort(childLog, initialJevDecision?.effort);
1247
+ restoreOriginalRequestedEffort(childLog, jevEffortApplies ? initialJevDecision?.effort : undefined);
1242
1248
  } catch (error) {
1243
1249
  callbackGate.discard();
1244
1250
  if (options.abortSignal?.aborted) {
@@ -1258,7 +1264,7 @@ export async function executeComboResponses(
1258
1264
 
1259
1265
  // A native Chat child reports a pre-stream failure by status before any byte, so its body
1260
1266
  // is never peeked; a non-OK one takes the ordinary failure path below.
1261
- if (response.ok && !runTurnAdapterSseResponses.has(response) && clientWireOf(response) !== "chat") {
1267
+ if (response.ok && !runTurnAdapterSseResponses.has(response) && clientWireOf(response) === undefined) {
1262
1268
  const nativePassthrough = isNativePassthroughSseResponse(response);
1263
1269
  const eagerRelay = isEagerRelaySseResponse(response);
1264
1270
  let preflight;
@@ -147,6 +147,7 @@ export async function applyFinalRouteRequestNormalization(args: {
147
147
  droidDefaultEffort?: HandleResponsesOptions["droidDefaultEffort"];
148
148
  }): Promise<void> {
149
149
  const { parsed, route, config, req, logCtx, inboundWire, inboundTransport } = args;
150
+ parsed._chatCompletionsInput = inboundWire === "chat";
150
151
  const effortSelector = prepareEffortNormalization(parsed, route);
151
152
  if (applyDroidResponsesReasoningDefault(
152
153
  parsed._rawBody,
@@ -204,7 +204,7 @@ export interface HandleResponsesOptions {
204
204
  anthropicToolLoadingSource?: Readonly<Record<string, unknown>>;
205
205
  /** Droid's per-request effort default; each concrete combo or policy target applies it only if its ladder allows it. */
206
206
  droidDefaultEffort?: string;
207
- /** PF-07: the Chat source a combo child may send natively; set only by the Chat ingress. */
207
+ /** The Chat or Messages source a combo child may send natively; set only by that ingress. */
208
208
  protocolSource?: import("./core-combo-native").ComboProtocolSource;
209
209
  /** Internal transport identity for route-scoped upstream compatibility policy. */
210
210
  inboundTransport?: "websocket";
@@ -293,6 +293,12 @@ export interface HandleResponsesOptions {
293
293
  clientEncoder?: ClientEncoderOption;
294
294
  /** Chat ingress raw-channel delivery preference; never an upstream generation option. */
295
295
  chatRawReasoningVisible?: boolean;
296
+ /** Value-free fact retained before Chat instruction content is projected to text. */
297
+ chatInstructionImage?: boolean;
298
+ /** Original Responses instruction image, retained across preprocessing and combo replay. */
299
+ responsesInstructionImage?: boolean;
300
+ /** File-backed Responses image retained before parsing and replay. */
301
+ responsesFileImage?: boolean;
296
302
  /** Set only by the Chat or Messages ingress on an eligible Antigravity route; see {@link DirectRequestOption}. */
297
303
  directRequest?: DirectRequestOption;
298
304
  }
@@ -1,4 +1,4 @@
1
- import { markProxyError } from "../../lib/client-error-body";
1
+ import { markProxyError, rememberProxyErrorMessage } from "../../lib/client-error-body";
2
2
  import { supportsNativeResponsesCompactionTrigger } from "../../providers/openai-tiers";
3
3
  import type { OcxConfig } from "../../types";
4
4
  import type { RequestLogContext } from "../request-log";
@@ -25,6 +25,8 @@ import { releaseUpstreamHostAdmission } from "../../codex/upstream-host-health";
25
25
  import { releaseCodexAuthContextProbeLease } from "../../codex/auth-context";
26
26
  import { formatErrorResponse } from "../../bridge";
27
27
  import { InvalidRetainedCompactionSummary, prepareCompactionRetention } from "./compaction-retention";
28
+ import { responsesHasInstructionImage } from "../../adapters/claude-cli/instruction-images";
29
+ import { markResponseNonReplayable } from "../../lib/upstream-retry";
28
30
 
29
31
  /** Compose request phases while retaining the original admission-finally ownership. */
30
32
  export async function handleResponsesInner(
@@ -46,6 +48,24 @@ export async function handleResponsesInner(
46
48
  if (requestState instanceof Response) return requestState;
47
49
  const transportState = await prepareResponsesTransport(requestContext, admissionState, requestState);
48
50
  if (transportState instanceof Response) return markProxyError(transportState);
51
+ if (transportState.runTurnAdapter.name === "claude-cli") {
52
+ const instructionImage = options.chatInstructionImage || options.responsesInstructionImage
53
+ || responsesHasInstructionImage(requestState.parsed._rawBody)
54
+ || requestState.parsed.context.messages.some(message => message.role === "developer"
55
+ && Array.isArray(message.content) && message.content.some(part => part.type === "image"));
56
+ if (instructionImage || options.responsesFileImage) {
57
+ const message = instructionImage ? "Claude Code CLI does not support images in developer instructions."
58
+ : "Claude Code CLI does not support file-backed image references.";
59
+ const response = new Response(JSON.stringify({ error: {
60
+ type: "invalid_request_error", code: "unsupported_input_modality", param: null,
61
+ message,
62
+ } }), { status: 400, headers: { "Content-Type": "application/json" } });
63
+ rememberProxyErrorMessage(logCtx, message, { status: 400, type: "invalid_request_error", code: "unsupported_input_modality" });
64
+ markProxyError(response);
65
+ markResponseNonReplayable(response);
66
+ return response;
67
+ }
68
+ }
49
69
  options.onCompactionRecoveryRoute?.(requestState.route);
50
70
  if (requestState.parsed._compactionRequest && options.compactionRecoveryKind !== "compaction-v1"
51
71
  && (requestState.parsed._portableCompaction || !supportsNativeResponsesCompactionTrigger(requestState.route.provider))) {
@@ -54,6 +54,7 @@ const PHYSICAL_DISPATCH = Symbol.for("opencodex.physical-dispatch");
54
54
  // Final destination and headers after plugin rewrites and queued rebuilds, for observers that
55
55
  // must attribute a response to the credential that actually reached the wire.
56
56
  const PHYSICAL_SEND_OBSERVER = Symbol.for("opencodex.physical-send-observer");
57
+ const PHYSICAL_SEND_GUARD = Symbol.for("opencodex.physical-send-guard");
57
58
  export type AccountAutoPauseObserver = ((response: Response) => Promise<Response>) & {
58
59
  physical?: (sameDestination: boolean, headers: Headers) => void;
59
60
  };
@@ -66,6 +67,9 @@ export function physicalSendObserverInit(observer: AccountAutoPauseObserver | un
66
67
  physical?.(destination === target, headers);
67
68
  } } : {};
68
69
  }
70
+ export function physicalSendGuardInit(guard: (destination: string, headers: Headers) => void): Record<symbol, unknown> {
71
+ return { [PHYSICAL_SEND_GUARD]: guard };
72
+ }
69
73
  // One WS attempt and its HTTP fallback are one logical physical-send receipt.
70
74
  const WS_FALLBACK_RECEIPT = Symbol.for("opencodex.ws-fallback-receipt");
71
75
 
@@ -234,6 +238,7 @@ export function sendWithConnectionPolicy(
234
238
  const largeCodexBody = !compressed && typeof body === "string"
235
239
  && isCanonicalCodexResponsesUrl(target)
236
240
  && Buffer.byteLength(body, "utf8") >= 1024 * 1024;
241
+ (init as Record<symbol, ((destination: string, headers: Headers) => void) | undefined> | undefined)?.[PHYSICAL_SEND_GUARD]?.(target, headers);
237
242
  (init as Record<symbol, (() => void) | undefined> | undefined)?.[PHYSICAL_DISPATCH]?.();
238
243
  (init as Record<symbol, ((destination: string, headers: Headers) => void) | undefined> | undefined)?.[PHYSICAL_SEND_OBSERVER]?.(target, headers);
239
244
  // Final headers, after plugin rewrites: an upstream can only echo what it received here, so the
@@ -27,6 +27,10 @@ function outputCommits(output: unknown): boolean {
27
27
  return !Array.isArray(output) || output.some(item => !isPlainObject(item)
28
28
  || (item.type !== "reasoning" && (item.type !== "message" || !Array.isArray(item.content) || item.content.some(partCommits))));
29
29
  }
30
+ /** A snapshot's aggregate output_text is output too; anything but absent, null or "" is evidence (#8333). */
31
+ function snapshotTextCommits(snapshot: RecordValue): boolean {
32
+ return snapshot.output_text != null && snapshot.output_text !== "";
33
+ }
30
34
  function wellFormedEmpty(snapshot: unknown): snapshot is RecordValue {
31
35
  return isPlainObject(snapshot) && typeof snapshot.id === "string" && snapshot.id.trim().length > 0
32
36
  && snapshot.object === "response" && snapshot.status === "completed" && Array.isArray(snapshot.output)
@@ -39,7 +43,7 @@ function eventCommits(event: RecordValue): boolean {
39
43
  if (event.replayUnsafe === true) return true;
40
44
  switch (event.type) {
41
45
  case "response.created": case "response.in_progress": case "response.queued": case "response.heartbeat":
42
- return isPlainObject(event.response) && outputCommits(event.response.output);
46
+ return isPlainObject(event.response) && (outputCommits(event.response.output) || snapshotTextCommits(event.response));
43
47
  case "response.output_item.added": case "response.output_item.done": return outputCommits([event.item]);
44
48
  case "response.content_part.added": case "response.content_part.done": return partCommits(event.part);
45
49
  case "response.output_text.delta": return event.delta !== "";
@@ -150,7 +154,7 @@ async function inspect(response: Response, options: OpenGatewayCompletionGuardOp
150
154
  let snapshot: unknown;
151
155
  try { snapshot = JSON.parse(decoder.decode(joinSseFrameBytes(held.flatMap(chunk => chunk ? [chunk] : [])))); }
152
156
  catch { return terminal(undefined); }
153
- if (isPlainObject(snapshot) && (outputCommits(snapshot.output)
157
+ if (isPlainObject(snapshot) && (outputCommits(snapshot.output) || snapshotTextCommits(snapshot)
154
158
  || snapshot.error != null || ["failed", "incomplete", "queued", "in_progress"].includes(String(snapshot.status)))) return pass();
155
159
  return terminal(snapshot);
156
160
  }
@@ -167,7 +171,7 @@ async function inspect(response: Response, options: OpenGatewayCompletionGuardOp
167
171
  if (!isPlainObject(event)) return pass();
168
172
  if (event.replayUnsafe === true) return pass();
169
173
  if (event.type === "response.completed") {
170
- if (isPlainObject(event.response) && outputCommits(event.response.output)) return pass();
174
+ if (isPlainObject(event.response) && (outputCommits(event.response.output) || snapshotTextCommits(event.response))) return pass();
171
175
  return terminal(event.response);
172
176
  }
173
177
  if (eventCommits(event)) return pass();
@@ -57,6 +57,7 @@ import { clientCancelledResponse, readDisplaySafeErrorText } from "./core-errors
57
57
  import { streamingContextOverflowResponse, jsonContextOverflowResponse } from "./context-overflow";
58
58
  import { formatPassthroughUpstreamError } from "./passthrough-error";
59
59
  import { rewriteUpstreamPolicyRefusal } from "./policy-refusal";
60
+ import { stampMetaMusePlanRefusal } from "../../providers/meta-muse-plan-refusal";
60
61
  import {
61
62
  resolvePassthroughWebSearchBridgeAuth,
62
63
  planPassthroughWebSearchBridge,
@@ -642,7 +643,11 @@ export async function deliverPassthroughResponse(
642
643
  // "captures passthrough failed usage from its original bounded body exactly once").
643
644
  // Attaching a guard would be a second `.body` access and break that contract for no
644
645
  // gain, since the bounded reader owns settlement on this path.
645
- const failure = await consumeComboFailure(upstreamResponse, options.abortSignal);
646
+ // Only the plan-refusal cause is carried to this leg's row (#8352); a throwaway holder
647
+ // keeps the other diagnostics this path has never recorded off it.
648
+ const comboCause: Pick<typeof logCtx, "causeHint"> = {};
649
+ const failure = await consumeComboFailure(upstreamResponse, options.abortSignal, undefined, comboCause);
650
+ if (comboCause.causeHint) logCtx.causeHint = comboCause.causeHint;
646
651
  options.onConsumedComboFailure?.(failure);
647
652
  return failure.response;
648
653
  }
@@ -665,6 +670,8 @@ export async function deliverPassthroughResponse(
665
670
  turnAdmissionLease: options.turnAdmissionLease,
666
671
  });
667
672
  if (policyRefusal) return policyRefusal;
673
+ // Meta's Muse Code refusal is a plan restriction, not a rejected credential (#8352).
674
+ stampMetaMusePlanRefusal(logCtx, upstreamResponse.status, errorText);
668
675
  return carryPolicyCandidateRefusal(upstreamResponse, carryProxyError(upstreamResponse, formatPassthroughUpstreamError(upstreamResponse.status, errorText, {
669
676
  statusText: upstreamResponse.statusText,
670
677
  headers,
@@ -10,6 +10,7 @@ import {
10
10
  formatClientRetryAfter,
11
11
  resolveClientRetryAfter,
12
12
  } from "../../lib/retry-after";
13
+ import { isMetaMusePlanFailure, META_MUSE_PLAN_REFUSAL_MESSAGE } from "../../providers/meta-muse-plan-refusal";
13
14
 
14
15
  function isCyberPolicyBody(body: string): boolean {
15
16
  if (isCyberPolicyMessage(body)) return true;
@@ -92,6 +93,27 @@ export function formatPassthroughUpstreamError(
92
93
  ): Response {
93
94
  const trimmed = bodyText.trim();
94
95
  const now = options?.now ?? Date.now();
96
+ // Meta's Muse Code subscription refusal is relayed as this proxy's own explanation (#8352):
97
+ // the upstream body names the restriction but not the supported path, and a verbatim relay
98
+ // reads as a rejected credential. The shared classifier keeps the subscription class.
99
+ if (isMetaMusePlanFailure(status, trimmed)) {
100
+ const refusal = formatErrorResponse(status, "permission_error", META_MUSE_PLAN_REFUSAL_MESSAGE);
101
+ if (!options?.headers) {
102
+ return options?.statusText
103
+ ? new Response(refusal.body, { status: refusal.status, statusText: options.statusText, headers: refusal.headers })
104
+ : refusal;
105
+ }
106
+ // The body is this proxy's own, but the relayed headers the caller already sanitized (the
107
+ // upstream request id among them) stay; a plan restriction names no wait.
108
+ const headers = new Headers(options.headers);
109
+ for (const name of ["content-length", "content-encoding", "retry-after"]) headers.delete(name);
110
+ refusal.headers.forEach((value, name) => headers.set(name, value));
111
+ return new Response(refusal.body, {
112
+ status: refusal.status,
113
+ ...(options.statusText ? { statusText: options.statusText } : {}),
114
+ headers,
115
+ });
116
+ }
95
117
  const upstreamRetryAfter = options?.headers?.get("retry-after")?.trim() || undefined;
96
118
  const cyberPolicyFailure = isCyberPolicyBody(trimmed);
97
119
  const replayRefusal = options?.replayRefusal === true || isReplayRefusalBody(trimmed);