@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
@@ -19,9 +19,10 @@ import type {
19
19
  import { isAllowedToolChoice, namespacedToolName, resolveToolChoiceWireName, toolChoiceToolPredicate } from "../types";
20
20
  import type { OcxTool } from "../types";
21
21
  import { contentPartsToText, parseDataUrl } from "./image";
22
- import { GCP_CREDENTIAL_MARKER_PREFIX, gcpCredentialMarkerAccount, getVertexAccessToken } from "../lib/gcp-adc";
22
+ import { bindVertexRequestAuthority, GCP_CREDENTIAL_MARKER_PREFIX, gcpCredentialMarkerAccount, getVertexAccessTokenWithAuthority } from "../lib/gcp-adc";
23
23
  import { fetchAntigravityWithRetry, fetchVertexWithRetry } from "./google-http";
24
24
  import { safeAntigravityHttpErrorMessage, safeVertexHttpErrorMessage } from "./google-errors";
25
+ import { readDisplaySafeErrorPayloadText } from "./upstream-http-error";
25
26
  import { isVertexTruncatedTurn, vertexTruncationErrorEvent } from "./google-truncation";
26
27
  import { antigravitySessionAnchor, antigravityUserAgentForWireModel, antigravitySessionId, isLikelyRealThoughtSignature, sanitizeAntigravityClaudeSignatures } from "./google-antigravity-wire";
27
28
  import { summarizeGoogleWireShape } from "./google-wire-shape";
@@ -37,6 +38,7 @@ import {
37
38
  } from "./google-antigravity-replay";
38
39
  import { canonicalAntigravityUsageModel, resolveAntigravityEffortWireModel } from "../providers/antigravity-models";
39
40
  import { selectVertexEndpoint, vertexInferenceUrl, vertexReplayModelKey } from "./google-vertex-endpoint";
41
+ import { captureVertexAmbientKey, vertexAmbientKeyIsCurrent } from "../providers/vertex-environment-authority";
40
42
  import { resolveVertexApiKeyProject, VERTEX_PROJECT_AUTO } from "./google-vertex-key-project";
41
43
  import { forgetThoughtSignatureForReplay, lookupReplayThoughtSignature } from "../responses/thought-signature-replay";
42
44
  import {
@@ -945,11 +947,15 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
945
947
  // session replay cache), but durable-store eviction is intentionally narrower: it only runs
946
948
  // when the error text explicitly mentions a signature, so a generic tool-schema
947
949
  // INVALID_ARGUMENT does not destroy valid durable signatures.
948
- function handleSignatureRejection(errorMessage?: string) {
950
+ //
951
+ // `httpStatus` is the real upstream status when the rejection arrived as an HTTP error. The
952
+ // normalized Vertex/Antigravity error text keeps only Google's message, not its status enum,
953
+ // so a 400 such as "bad model" would otherwise leave the poisoned session entry in place (#8054).
954
+ function handleSignatureRejection(errorMessage?: string, httpStatus?: number) {
949
955
  const replayModel = provider.googleMode === "cloud-code-assist" ? antigravityModel : vertexReplayModel;
950
956
  const replaySession = provider.googleMode === "cloud-code-assist" ? antigravitySession : vertexReplaySession;
951
957
  const text = errorMessage ?? "";
952
- const isInvalidArgument = /invalid_argument|invalid argument/i.test(text);
958
+ const isInvalidArgument = httpStatus === 400 || /invalid_argument|invalid argument/i.test(text);
953
959
  const isSignatureError = /signature|thought_signature|thoughtSignature/i.test(text);
954
960
  // The in-memory Antigravity replay cache only exists for CCA/Vertex, so clearing it stays
955
961
  // scoped to those modes (replayModel/replaySession are undefined elsewhere anyway).
@@ -981,12 +987,23 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
981
987
  // 429 rotation and raw error formatting.
982
988
  ...(provider.googleMode === "vertex" || provider.googleMode === "cloud-code-assist"
983
989
  ? {
984
- fetchResponse: (request: AdapterRequest, ctx?: AdapterFetchContext): Promise<Response> =>
985
- (provider.googleMode === "cloud-code-assist" ? fetchAntigravityWithRetry : fetchVertexWithRetry)(
990
+ fetchResponse: async (request: AdapterRequest, ctx?: AdapterFetchContext): Promise<Response> => {
991
+ const res = await (provider.googleMode === "cloud-code-assist" ? fetchAntigravityWithRetry : fetchVertexWithRetry)(
986
992
  request,
987
993
  ctx,
988
994
  { toolSchemaProfile, toolSchemaPolicy },
989
- ),
995
+ );
996
+ // A rejected replay usually arrives as a real HTTP 400, and the dispatcher reports a
997
+ // non-ok response without ever calling parseStream/parseResponse — the only other
998
+ // callers of clear-on-invalid. Without this, the bad signature stays cached and is
999
+ // replayed on every turn until the TTL expires (#8054). Read a clone so the body the
1000
+ // dispatcher formats is untouched, and await it so the next turn cannot race ahead of
1001
+ // the eviction. No resend here: payload rejection stays resend-is-futile.
1002
+ if (res.status === 400) {
1003
+ handleSignatureRejection(await readDisplaySafeErrorPayloadText(res.clone(), ctx?.abortSignal), res.status);
1004
+ }
1005
+ return res;
1006
+ },
990
1007
  formatErrorBody: (status: number, _headers: Headers, payloadText: string): string =>
991
1008
  (provider.googleMode === "cloud-code-assist" ? safeAntigravityHttpErrorMessage : safeVertexHttpErrorMessage)(status, payloadText),
992
1009
  }
@@ -1222,10 +1239,17 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
1222
1239
  }
1223
1240
 
1224
1241
  if (provider.googleMode === "vertex") {
1242
+ if (provider.authMode === "forward") throw new Error("Vertex does not support forward authentication");
1225
1243
  const compiled = compileGoogleWireBody(body, toolSchemaProfile, toolSchemaPolicy);
1226
1244
  reportToolSchemaLoss(compiled.toolSchemaLossReport);
1227
1245
  restoreGoogleToolName = compiled.restoreToolName;
1228
1246
  const apiKey = resolveVertexApiKey(provider.apiKey);
1247
+ const ambientAuthority = apiKey && (!provider.apiKey || provider.apiKey.startsWith("<") || provider.apiKey === "N/A")
1248
+ ? captureVertexAmbientKey(apiKey) : undefined;
1249
+ const beforeCredentialSend = () => {
1250
+ incoming?.beforePhysicalSend?.();
1251
+ if (ambientAuthority && !vertexAmbientKeyIsCurrent(ambientAuthority)) throw new Error("Vertex credential authority changed before auxiliary send");
1252
+ };
1229
1253
  let vertexEndpoint = selectVertexEndpoint(provider, Boolean(apiKey));
1230
1254
  if (apiKey && vertexEndpoint.kind === "project" && vertexEndpoint.project === VERTEX_PROJECT_AUTO) {
1231
1255
  // Unresolved keys use express for this request so Google's status drives key failover.
@@ -1233,6 +1257,7 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
1233
1257
  signal: incoming?.abortSignal,
1234
1258
  provider,
1235
1259
  providerName: incoming?.providerName,
1260
+ beforeSend: beforeCredentialSend,
1236
1261
  });
1237
1262
  vertexEndpoint = project ? { ...vertexEndpoint, project } : { kind: "express" };
1238
1263
  }
@@ -1254,13 +1279,20 @@ export function createGoogleAdapter(provider: OcxProviderConfig): ProviderAdapte
1254
1279
  );
1255
1280
  }
1256
1281
  // Endpoint, location and model path were validated above, before any credential is attached.
1282
+ let adcAuthority: Awaited<ReturnType<typeof getVertexAccessTokenWithAuthority>> | undefined;
1257
1283
  if (apiKey) headers["x-goog-api-key"] = apiKey;
1258
1284
  else {
1259
1285
  // Resolve each marker per request; never share a process-global active account.
1260
1286
  const markerAccount = gcpCredentialMarkerAccount(provider.apiKey);
1261
- headers["Authorization"] = `Bearer ${await getVertexAccessToken({ markerAccount })}`;
1287
+ adcAuthority = await getVertexAccessTokenWithAuthority({ markerAccount, signal: incoming?.abortSignal, beforeSend: beforeCredentialSend });
1288
+ headers["Authorization"] = `Bearer ${adcAuthority.token}`;
1289
+ }
1290
+ const request = { url, method: "POST", headers, body: JSON.stringify(compiled.body) };
1291
+ if (adcAuthority) bindVertexRequestAuthority(request, url, headers["Authorization"]!, { source: adcAuthority.source, generation: adcAuthority.generation, markerAccount: adcAuthority.markerAccount });
1292
+ else if (apiKey && ambientAuthority) {
1293
+ bindVertexRequestAuthority(request, url, apiKey, { ambientKey: ambientAuthority });
1262
1294
  }
1263
- return { url, method: "POST", headers, body: JSON.stringify(compiled.body) };
1295
+ return request;
1264
1296
  }
1265
1297
 
1266
1298
  // Go and Zen use separate guarded Gemini endpoints; AI Studio retains /v1beta.
@@ -1,4 +1,4 @@
1
- import { estimateTokens, estimateTokensFromCharacterCounts } from "../../lib/token-estimate";
1
+ import { countCjk, estimateTokens, estimateTokensFromCharacterCounts } from "../../lib/token-estimate";
2
2
  import { KIRO_MODEL_CONTEXT_WINDOWS, normalizeKiroModelId } from "../../providers/kiro-models";
3
3
  import { kiroObservedContextWindow } from "../../providers/kiro-model-catalog";
4
4
  import { modelRecordValue } from "../../reasoning-effort";
@@ -77,18 +77,8 @@ export function estimateKiroTokens(text: string, modelId?: string): number {
77
77
  return estimateTokens(text, modelId ? `kiro/${modelId}` : "kiro");
78
78
  }
79
79
 
80
- /** Hangul/Han/kana ranges, matching the shared estimator's own CJK classification. */
81
- export function kiroCjkCount(text: string): number {
82
- let cjk = 0;
83
- for (let i = 0; i < text.length; i++) {
84
- const c = text.charCodeAt(i);
85
- if (
86
- (c >= 0xac00 && c <= 0xd7a3) || (c >= 0x1100 && c <= 0x11ff) || (c >= 0x3130 && c <= 0x318f)
87
- || (c >= 0x4e00 && c <= 0x9fff) || (c >= 0x3400 && c <= 0x4dbf) || (c >= 0x3040 && c <= 0x30ff)
88
- ) cjk++;
89
- }
90
- return cjk;
91
- }
80
+ /** The wire and shared estimates use the same UTF-16 CJK buckets. */
81
+ export const kiroCjkCount = countCjk;
92
82
 
93
83
  /**
94
84
  * Token estimate for walked payload text, with the wire expansion applied to the Latin portion
@@ -22,6 +22,14 @@ function isRecord(value: unknown): value is Record<string, unknown> {
22
22
  return value !== null && typeof value === "object" && !Array.isArray(value);
23
23
  }
24
24
 
25
+ /** Checks for a nonempty image URL string in either supported shape, not URL syntax or reachability. */
26
+ function hasUsableImageUrl(part: Record<string, unknown>): boolean {
27
+ if (part.type !== "image_url") return false;
28
+ const imageUrl = part.image_url;
29
+ return (typeof imageUrl === "string" && imageUrl.length > 0)
30
+ || (isRecord(imageUrl) && typeof imageUrl.url === "string" && imageUrl.url.length > 0);
31
+ }
32
+
25
33
  /**
26
34
  * Keep the newest images a first-party Mistral request may carry and replace older ones with a
27
35
  * text note, across every message (promoted tool-result images included). Normalizes the outbound
@@ -30,21 +38,26 @@ function isRecord(value: unknown): value is Record<string, unknown> {
30
38
  export function limitMistralChatImages(messages: unknown, provider: OcxProviderConfig, modelId: string): unknown {
31
39
  if (!isMistralChatTarget(provider) || !Array.isArray(messages)) return messages;
32
40
  const maxImages = mistralMaxImages(provider, modelId);
33
- const images: Array<{ message: number; part: number }> = [];
34
- messages.forEach((message, index) => {
35
- if (!isRecord(message) || !Array.isArray(message.content)) return;
36
- message.content.forEach((part, partIndex) => {
37
- if (isRecord(part) && part.type === "image_url") images.push({ message: index, part: partIndex });
38
- });
39
- });
40
- const excess = images.length - maxImages;
41
- if (excess <= 0) return messages;
42
41
  const note = { type: "text", text: `[image omitted: Mistral accepts at most ${maxImages} images per request for this model; older images were dropped]` };
43
- const out = [...messages];
44
- for (const { message, part } of images.slice(0, excess)) {
45
- const original = messages[message] as Record<string, unknown>;
46
- if (out[message] === original) out[message] = { ...original, content: [...(original.content as unknown[])] };
47
- ((out[message] as Record<string, unknown>).content as unknown[])[part] = note;
42
+ const missingNote = { type: "text", text: "[image omitted: missing or malformed image URL]" };
43
+ let imagesKept = 0;
44
+ let out: unknown[] | undefined;
45
+ for (let index = messages.length - 1; index >= 0; index--) {
46
+ const message = messages[index];
47
+ if (!isRecord(message) || !Array.isArray(message.content)) continue;
48
+ const content = message.content;
49
+ let nextContent: unknown[] | undefined;
50
+ for (let partIndex = content.length - 1; partIndex >= 0; partIndex--) {
51
+ const part = content[partIndex];
52
+ if (!isRecord(part) || part.type !== "image_url") continue;
53
+ const usable = hasUsableImageUrl(part);
54
+ if (usable && imagesKept++ < maxImages) continue;
55
+ nextContent ??= content.slice();
56
+ nextContent[partIndex] = usable ? note : missingNote;
57
+ }
58
+ if (!nextContent) continue;
59
+ out ??= messages.slice();
60
+ out[index] = { ...message, content: nextContent };
48
61
  }
49
- return out;
62
+ return out ?? messages;
50
63
  }
@@ -1,4 +1,7 @@
1
1
  import { parseDataUrl } from "./image";
2
+ import { sniffImageDimensions } from "./anthropic-image-guard";
3
+ import { MAX_INPUT_PIXELS } from "./anthropic-image-codec";
4
+ import { enterImageDecode } from "./anthropic-image-normalize";
2
5
  import {
3
6
  normalizeImageTargets,
4
7
  type NormalizeOptions,
@@ -12,6 +15,18 @@ import {
12
15
  */
13
16
  export const OPENAI_CHAT_IMAGE_BASE64_BUDGET = 3_670_016; // 3.5MiB
14
17
 
18
+ /** Longest edge an undersized image may be stretched to while reaching the minimum edge. */
19
+ export const OPENAI_CHAT_UPSCALE_MAX_EDGE = 4096;
20
+
21
+ /** Resizes decoded image bytes to exactly `width` x `height` and returns base64 plus media type. */
22
+ export type UpscaleFn = (input: Buffer, width: number, height: number) => Promise<{ data: string; mediaType: string }>;
23
+
24
+ /** Default upscaler: Bun.Image resize, re-encoded as PNG so small text strips stay sharp. */
25
+ export const bunImageUpscale: UpscaleFn = async (input, width, height) => {
26
+ const out = await new Bun.Image(input).resize(width, height).png().toBuffer();
27
+ return { data: Buffer.from(out).toString("base64"), mediaType: "image/png" };
28
+ };
29
+
15
30
  export interface NormalizeOpenAIChatImagesOptions
16
31
  extends Pick<NormalizeOptions, "encode" | "tierBias" | "validate"> {
17
32
  abortSignal?: AbortSignal;
@@ -61,6 +76,91 @@ export function hasShrinkableOpenAIChatImages(messages: unknown): boolean {
61
76
  return found;
62
77
  }
63
78
 
79
+ /**
80
+ * Target size for an image whose short edge is below `minEdge`, or null when it already
81
+ * fits or cannot be handled safely. Aspect ratio is kept; the long edge is clamped to
82
+ * OPENAI_CHAT_UPSCALE_MAX_EDGE, which only distorts extreme strips.
83
+ */
84
+ export function upscaledImageSize(width: number, height: number, minEdge: number): { width: number; height: number } | null {
85
+ if (!(width > 0 && height > 0) || Math.min(width, height) >= minEdge) return null;
86
+ if (width * height > MAX_INPUT_PIXELS) return null;
87
+ const scale = minEdge / Math.min(width, height);
88
+ const clamp = (edge: number): number => Math.min(OPENAI_CHAT_UPSCALE_MAX_EDGE, Math.max(minEdge, Math.ceil(edge * scale)));
89
+ return { width: clamp(width), height: clamp(height) };
90
+ }
91
+
92
+ /** Whether any inline image has a sniffable short edge below `minEdge`. */
93
+ export function hasUndersizedOpenAIChatImages(messages: unknown, minEdge: number): boolean {
94
+ let found = false;
95
+ forEachImagePart(messages, (_imageUrl, url) => {
96
+ const source = parseDataUrl(url);
97
+ const dims = source ? sniffImageDimensions(source.base64) : null;
98
+ if (dims && upscaledImageSize(dims.width, dims.height, minEdge)) {
99
+ found = true;
100
+ return false;
101
+ }
102
+ });
103
+ return found;
104
+ }
105
+
106
+ /**
107
+ * Upscale inline images below `minEdge` in already-built Chat Completions messages, in place.
108
+ * Runs after budget normalization, because that step can itself floor a wide screenshot
109
+ * under the minimum. An image that cannot be decoded keeps its original URL.
110
+ */
111
+ export async function upscaleUndersizedOpenAIChatImages(
112
+ messages: unknown,
113
+ minEdge: number,
114
+ options: { upscale?: UpscaleFn; abortSignal?: AbortSignal } = {},
115
+ ): Promise<void> {
116
+ const upscale = options.upscale ?? bunImageUpscale;
117
+ const jobs: Array<{ imageUrl: Record<string, unknown>; base64: string; width: number; height: number }> = [];
118
+ forEachImagePart(messages, (imageUrl, url) => {
119
+ const source = parseDataUrl(url);
120
+ const dims = source ? sniffImageDimensions(source.base64) : null;
121
+ const target = dims ? upscaledImageSize(dims.width, dims.height, minEdge) : null;
122
+ if (source && target) jobs.push({ imageUrl, base64: source.base64, ...target });
123
+ });
124
+ const throwIfAborted = (): void => {
125
+ if (options.abortSignal?.aborted) throw options.abortSignal.reason ?? new DOMException("Aborted", "AbortError");
126
+ };
127
+ for (const job of jobs) {
128
+ throwIfAborted();
129
+ // Decoded bitmaps share the process-wide decode bound with the other image normalizers.
130
+ const release = await enterImageDecode(options.abortSignal);
131
+ try {
132
+ const out = await upscale(Buffer.from(job.base64, "base64"), job.width, job.height);
133
+ job.imageUrl.url = `data:${out.mediaType};base64,${out.data}`;
134
+ } catch {
135
+ // Keep the original image; the upstream reports its own validation error.
136
+ } finally {
137
+ release();
138
+ }
139
+ }
140
+ // A cancellation during the last resize must not let a request for a cancelled turn through.
141
+ throwIfAborted();
142
+ }
143
+
144
+ /**
145
+ * Image work the openai-chat adapter must finish before it builds the request, or null when
146
+ * there is none. Budget normalization runs first because it can floor a wide screenshot below
147
+ * the upstream minimum. A failure keeps the original images unless the request was cancelled.
148
+ */
149
+ export function prepareOpenAIChatImages(
150
+ messages: unknown,
151
+ minImageEdge: number | undefined,
152
+ options: NormalizeOpenAIChatImagesOptions = {},
153
+ ): Promise<void> | null {
154
+ const shrink = hasShrinkableOpenAIChatImages(messages);
155
+ if (!shrink && (minImageEdge === undefined || !hasUndersizedOpenAIChatImages(messages, minImageEdge))) return null;
156
+ return (async () => {
157
+ if (shrink) await normalizeOpenAIChatImages(messages, options);
158
+ if (minImageEdge !== undefined) await upscaleUndersizedOpenAIChatImages(messages, minImageEdge, { abortSignal: options.abortSignal });
159
+ })().catch(error => {
160
+ if (options.abortSignal?.aborted) throw error;
161
+ });
162
+ }
163
+
64
164
  /**
65
165
  * Normalize image_url parts in already-built Chat Completions messages, in place.
66
166
  *
@@ -1,6 +1,7 @@
1
1
  import { applyChatDestinationPolicy } from "./openai-chat/destination-policy";
2
2
  import { withRequiredChatToolResult } from "./openai-chat/required-tool-result";
3
- import { hasShrinkableOpenAIChatImages, normalizeOpenAIChatImages } from "./openai-chat-images";
3
+ import { prepareOpenAIChatImages } from "./openai-chat-images";
4
+ import { registryEntryForProviderDestination } from "../providers/registry";
4
5
  import { protectGlmSummaryBudget, resolveMaxTokens } from "./openai-chat/summary-budget";
5
6
  import { chatParallelToolCallsWireValue } from "./openai-chat/parallel-tool-calls";
6
7
  import { applyExplicitChatReasoningWirePolicy, declaresIndependentChatReasoningEffort } from "./openai-chat/reasoning-wire";
@@ -93,6 +94,7 @@ function canSerializeOpenAIChatServiceTier(
93
94
  export function createOpenAIChatAdapter(provider: OcxProviderConfig): ProviderAdapter {
94
95
  let lastRequestedModelId: string | undefined;
95
96
  let freeformTools = new Map<string, FreeformToolIdentity>();
97
+ const minImageEdge = registryEntryForProviderDestination(provider)?.minImageEdge;
96
98
  return withRequiredChatToolResult(withOpenAIChatToolNames(toolNames => ({
97
99
  name: "openai-chat",
98
100
 
@@ -266,14 +268,9 @@ export function createOpenAIChatAdapter(provider: OcxProviderConfig): ProviderAd
266
268
  ...(tierLog ? { tierLog } : {}),
267
269
  };
268
270
  };
269
- if (hasShrinkableOpenAIChatImages(messages)) {
270
- const imageOptions = { tierBias: incoming?.imageTierBias, abortSignal: incoming?.abortSignal };
271
- return normalizeOpenAIChatImages(messages, imageOptions).then(finish, error => {
272
- if (incoming?.abortSignal?.aborted) throw error;
273
- return finish();
274
- });
275
- }
276
- return finish();
271
+ const imageOptions = { tierBias: incoming?.imageTierBias, abortSignal: incoming?.abortSignal };
272
+ const prepared = prepareOpenAIChatImages(messages, minImageEdge, imageOptions);
273
+ return prepared ? prepared.then(finish) : finish();
277
274
  },
278
275
 
279
276
  async *parseStream(
@@ -40,7 +40,7 @@ import {
40
40
  emittedFastWire,
41
41
  } from "../../providers/fastwire";
42
42
  import { dropResponsesReasoningInputItems, mapRoutedResponsesReasoningEffort, normalizeConfiguredReasoningSummaryDelivery, sanitizeReasoningInputContent, stripDisabledReasoningSummaries, stripDisabledVerbosity, stripInternalReasoningEnabled, stripNoneReasoningSummary, stripUnsupportedReasoningSummaryDelivery } from "./reasoning";
43
- import { repairUrlCitationAnnotations, scrubOcxCompactionItems, stripUnsupportedOutputInclude, stripCanonicalOnlyInputItems, stripCanonicalOnlyToolFields, stripCanonicalOnlyTopLevelFields, stripInternalChatMessageMetadataPassthrough, stripInvalidItemIds, stripItemIdsWhenUnstored, stripProviderInputItemMetadata, stripRejectedSamplingParams } from "./request-strips";
43
+ import { repairUrlCitationAnnotations, scrubOcxCompactionItems, stripUnsupportedOutputInclude, stripArkKimiOrphanCipher, stripCanonicalOnlyInputItems, stripCanonicalOnlyToolFields, stripCanonicalOnlyTopLevelFields, stripInternalChatMessageMetadataPassthrough, stripInvalidItemIds, stripItemIdsWhenUnstored, stripProviderInputItemMetadata, stripRejectedSamplingParams } from "./request-strips";
44
44
  import { notePlaintextReasoningDropped } from "./plaintext-reasoning-notice";
45
45
  import { stripCanonicalForwardPromptCacheOptions, stripDeprecatedPromptCacheRetention } from "./prompt-cache";
46
46
  import { isPlainObject } from "./internal";
@@ -363,8 +363,10 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
363
363
  // Azure also rejects this exact include entry, including on plain Responses routes.
364
364
  const isAzureResponses = provider.adapter === "azure" || provider.adapter === "azure-openai"
365
365
  || new URL(url).hostname.toLowerCase().endsWith(".openai.azure.com");
366
+ const arkKimi = !forward && provider.arkKimiResponsesModels?.includes(parsed.modelId);
367
+ if (arkKimi) outBody = stripArkKimiOrphanCipher(outBody);
366
368
  if (isXaiResponsesDestination(provider) || isMetaAiResponsesDestination(url) || isAzureResponses
367
- || isKimiCodingResponsesHttpsUrl(url)) {
369
+ || isKimiCodingResponsesHttpsUrl(url) || arkKimi) {
368
370
  outBody = stripUnsupportedOutputInclude(outBody);
369
371
  }
370
372
  // xAI and explicitly classified compatible gateways reject these OpenAI web_search
@@ -449,6 +451,7 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig):
449
451
  provider.preserveResponsesInputItemIds === true,
450
452
  ),
451
453
  isXaiSchemaTarget(provider),
454
+ parsed._chatCompletionsInput === true && isOpenAiOperatedResponsesDestination(provider),
452
455
  );
453
456
  const unnormalizedBody = stripDisabledVerbosity(
454
457
  stripDisabledReasoningSummaries(
@@ -23,6 +23,38 @@ export function stripUnsupportedOutputInclude(body: unknown): unknown {
23
23
  return { ...body, include };
24
24
  }
25
25
 
26
+ /** 仅移除已验证孤立边界中无摘要、未被引用的推理项密文,保留整条历史项。 */
27
+ export function stripArkKimiOrphanCipher(body: unknown): unknown {
28
+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;
29
+ const input = body.input;
30
+ const isUser = (item: unknown) => isPlainObject(item) && item.role === "user"
31
+ && (item.type === undefined || item.type === "message");
32
+ const referenced = new Set(input.filter(item => isPlainObject(item) && item.type === "item_reference").map(item => item.id));
33
+ let changed = false;
34
+ const next = input.map((item, i) => {
35
+ // A matching call/result pair is the other confirmed boundary before an orphan.
36
+ const call = input[i - 2], result = input[i - 1];
37
+ const afterTool = isPlainObject(call) && call.type === "function_call"
38
+ && isPlainObject(result) && result.type === "function_call_output"
39
+ && typeof call.call_id === "string" && call.call_id.length > 0 && result.call_id === call.call_id;
40
+ // 仅放宽已配对工具结果之后的 developer 边界,其他角色仍保留密文。
41
+ const following = input[i + 1];
42
+ const developerAfterTool = afterTool && isPlainObject(following) && following.role === "developer"
43
+ && (following.type === undefined || following.type === "message");
44
+ if ((!isUser(result) && !afterTool) || (!isUser(following) && !developerAfterTool) || !isPlainObject(item)
45
+ || item.type !== "reasoning" || !Array.isArray(item.summary) || item.summary.length
46
+ || typeof item.encrypted_content !== "string" || !item.encrypted_content
47
+ || (item.id !== undefined && referenced.has(item.id))
48
+ // Codex can explicitly serialize the absent content channel as null.
49
+ || !Object.keys(item).every(key => ["type", "id", "status", "summary", "encrypted_content"].includes(key)
50
+ || (key === "content" && item.content === null))) return item;
51
+ const { encrypted_content: _cipher, ...rest } = item;
52
+ changed = true;
53
+ return rest;
54
+ });
55
+ return changed ? { ...body, input: next } : body;
56
+ }
57
+
26
58
  /**
27
59
  * Provider-opaque replay metadata is client history, not an OpenAI input-item field (#7111).
28
60
  * The caller gates this on OpenAI-operated destinations; arbitrary gateways may accept it.
@@ -10,12 +10,17 @@ import {
10
10
  import { isPlainObject } from "./internal";
11
11
  import { hasItemProvenance, isHistoricalItem } from "../../responses/item-provenance";
12
12
 
13
- function normalizeFunctionToolSchema(tool: unknown, xaiTarget: boolean): unknown | undefined {
13
+ function normalizeFunctionToolSchema(tool: unknown, xaiTarget: boolean, chatDefaults: boolean): unknown | undefined {
14
14
  if (!isPlainObject(tool) || tool.type !== "function") return tool;
15
15
  // Runs for every Responses destination, forward auth included: the ChatGPT backend is where
16
16
  // the `\p{…}` rejection was observed, and it reaches this function through the same seam.
17
17
  const compatible = stripUnicodePropertyPatterns(tool);
18
- const source = isPlainObject(compatible) ? compatible : tool;
18
+ const compatibleTool = isPlainObject(compatible) ? compatible : tool;
19
+ // Chat defaults to non-strict; OpenAI Responses otherwise normalizes an omitted flag to
20
+ // strict, making optional alternatives (such as pointer index vs coordinates) required.
21
+ const source = chatDefaults && compatibleTool.strict === undefined
22
+ ? { ...compatibleTool, strict: false }
23
+ : compatibleTool;
19
24
  if (xaiTarget) {
20
25
  const parameters = normalizeXaiToolParameters(isPlainObject(source.parameters) ? source.parameters : {});
21
26
  return parameters === undefined ? undefined : { ...source, parameters };
@@ -73,7 +78,7 @@ function reconcileToolChoiceForOmittedTools(
73
78
  return body;
74
79
  }
75
80
 
76
- export function normalizeToolSchemas(body: unknown, xaiTarget: boolean): unknown {
81
+ export function normalizeToolSchemas(body: unknown, xaiTarget: boolean, chatDefaults = false): unknown {
77
82
  if (!isPlainObject(body)) return body;
78
83
 
79
84
  const omittedFunctionNames = new Set<string>();
@@ -81,7 +86,7 @@ export function normalizeToolSchemas(body: unknown, xaiTarget: boolean): unknown
81
86
  let changed = false;
82
87
  const normalized: unknown[] = [];
83
88
  for (const tool of tools) {
84
- const fixed = normalizeFunctionToolSchema(tool, xaiTarget);
89
+ const fixed = normalizeFunctionToolSchema(tool, xaiTarget, chatDefaults);
85
90
  if (fixed === undefined) {
86
91
  changed = true;
87
92
  if (isPlainObject(tool) && typeof tool.name === "string") omittedFunctionNames.add(tool.name);
@@ -34,7 +34,7 @@ export function assertChatCompletionsRoutingBody(raw: unknown): asserts raw is C
34
34
  // Pi's "off" thinking level onto it (src/clients/config-export.ts). Dropping it here let a
35
35
  // provider default re-enable thinking the caller had explicitly turned off — and for the
36
36
  // Anthropic families that think by default, omission is not the same as disabled.
37
- const OUTPUT_CONFIG_EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);
37
+ export const OUTPUT_CONFIG_EFFORTS: ReadonlySet<string> = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);
38
38
  const OUTPUT_CONFIG_SUMMARIES = new Set(["auto", "concise", "detailed", "none"]);
39
39
 
40
40
  export function contentToText(content: unknown): string {
@@ -14,6 +14,7 @@ import { existsSync, readFileSync } from "node:fs";
14
14
  import { homedir } from "node:os";
15
15
  import { join } from "node:path";
16
16
  import { spawnSync } from "node:child_process";
17
+ import { CLAUDE_KEYCHAIN_SERVICE, claudeKeychainReader, isSyncTimeout, type ClaudeKeychainReader } from "../oauth/claude-keychain-read";
17
18
 
18
19
  export type AuthPresence = "present" | "absent" | "unknown";
19
20
 
@@ -34,11 +35,33 @@ export type AuthSourceId =
34
35
  */
35
36
  export const PROXY_MARKER = "opencodex-proxy";
36
37
 
37
- const KEYCHAIN_SERVICE = "Claude Code-credentials";
38
+ const KEYCHAIN_SERVICE = CLAUDE_KEYCHAIN_SERVICE;
38
39
  /** `security` exit code for "the item does not exist" — a real absent, not a failure. */
39
40
  const KEYCHAIN_ITEM_NOT_FOUND = 44;
40
41
  const KEYCHAIN_TIMEOUT_MS = 1_500;
41
42
 
43
+ /**
44
+ * The metadata probe under the Keychain reader's admission (#8161). Its synchronous timeout still
45
+ * signals the child, so it does not spawn while a read is blocked or the backoff is active, and its
46
+ * own timeout starts that backoff: a locked keychain sees at most one such kill per window.
47
+ */
48
+ export function probeClaudeKeychain(
49
+ platform: string,
50
+ reader: Pick<ClaudeKeychainReader, "syncReadBlocked" | "noteSyncTimeout">,
51
+ run: () => { status: number | null; signal: string | null; error?: Error },
52
+ ): AuthPresence {
53
+ if (platform !== "darwin") return "absent";
54
+ if (reader.syncReadBlocked()) return "unknown";
55
+ const result = run();
56
+ if (result.error || result.signal !== null) {
57
+ if (isSyncTimeout(result.error ?? { signal: result.signal })) reader.noteSyncTimeout();
58
+ return "unknown";
59
+ }
60
+ if (result.status === 0) return "present";
61
+ if (result.status === KEYCHAIN_ITEM_NOT_FOUND) return "absent";
62
+ return "unknown";
63
+ }
64
+
42
65
  export interface AuthSourceResult {
43
66
  source: AuthSourceId;
44
67
  presence: AuthPresence;
@@ -204,15 +227,10 @@ export function defaultAuthDetectDeps(
204
227
  return existsSync(join(configDir, ".credentials.json"));
205
228
  },
206
229
  keychainProbe() {
207
- if (process.platform !== "darwin") return "absent";
208
- const result = spawnSync("security", ["find-generic-password", "-s", KEYCHAIN_SERVICE], {
230
+ return probeClaudeKeychain(process.platform, claudeKeychainReader, () => spawnSync("security", ["find-generic-password", "-s", KEYCHAIN_SERVICE], {
209
231
  timeout: KEYCHAIN_TIMEOUT_MS,
210
232
  stdio: ["ignore", "ignore", "ignore"],
211
- });
212
- if (result.error || result.signal !== null) return "unknown";
213
- if (result.status === 0) return "present";
214
- if (result.status === KEYCHAIN_ITEM_NOT_FOUND) return "absent";
215
- return "unknown";
233
+ }));
216
234
  },
217
235
  env: () => env,
218
236
  ownTokens,
@@ -53,14 +53,17 @@ export function systemCachePrefix(system: unknown): string | undefined {
53
53
  return last >= 0 && last < system.length - 1 ? systemToInstructions(system.slice(0, last + 1)) : undefined;
54
54
  }
55
55
 
56
+ function isRestrictedSearch(raw: unknown): boolean {
57
+ return isRec(raw) && typeof raw.type === "string" && raw.type.startsWith("web_search")
58
+ && ["allowed_domains", "blocked_domains", "user_location"].some(key => Object.hasOwn(raw, key));
59
+ }
60
+
56
61
  export function toolsToResponses(tools: unknown): Rec[] | undefined {
57
62
  if (!Array.isArray(tools) || tools.length === 0) return undefined;
58
63
  // The shared hosted-search lane cannot enforce these constraints on every destination or
59
64
  // sidecar backend. Omit search rather than broaden it; a duplicate declaration cannot opt out.
60
65
  // Typed originals still travel separately to an Anthropic destination.
61
- const restrictedSearch = tools.some(raw => isRec(raw) && typeof raw.type === "string"
62
- && raw.type.startsWith("web_search")
63
- && ["allowed_domains", "blocked_domains", "user_location"].some(key => Object.hasOwn(raw, key)));
66
+ const restrictedSearch = tools.some(isRestrictedSearch);
64
67
  const out: Rec[] = [];
65
68
  for (const raw of tools) {
66
69
  if (!isRec(raw)) continue;
@@ -106,6 +109,18 @@ export function declaredAnthropicServerTools(raw: unknown): Rec[] | undefined {
106
109
  return tools.length > 0 ? tools : undefined;
107
110
  }
108
111
 
112
+ /** A declared tool the translated body drops and no out-of-body lane carries (bash_*, text_editor_*, ...). */
113
+ export function hasNativeOnlyTool(raw: Rec): boolean {
114
+ return Array.isArray(raw.tools)
115
+ && raw.tools.some(tool => !toolsToResponses([tool]) && !declaredAnthropicServerTools({ tools: [tool] }));
116
+ }
117
+
118
+ /** A declared web_fetch or restricted web_search: only the out-of-body lane to first-party Anthropic carries it. */
119
+ export function hasAnthropicOnlyServerTool(raw: Rec): boolean {
120
+ return Array.isArray(raw.tools) && raw.tools.some(tool => isRestrictedSearch(tool)
121
+ || (isRec(tool) && typeof tool.type === "string" && tool.type.startsWith("web_fetch_")));
122
+ }
123
+
109
124
  /** Validate original call/result order without inventing inputs or pairing a later call backwards. */
110
125
  function replayableServerRun(run: readonly Rec[]): boolean {
111
126
  const pending = new Map<string, Rec>();
@@ -13,6 +13,7 @@ import { CLAUDE_CONTEXT_OVERFLOW_MESSAGE, markProxyError } from "../lib/client-e
13
13
  */
14
14
  import type { OcxClaudeCodeConfig } from "../types";
15
15
  import { createHash } from "node:crypto";
16
+ import { claudeSessionUserId } from "../server/request-log-conversation";
16
17
 
17
18
  export { AnthropicRequestError, DesktopModelMappingUnavailableError } from "./inbound-records";
18
19
  export { resolveInboundModel, effortForThinkingBudget, effortFromOutputConfig, extractOcxRouteDirective, extractOcxEffortDirective } from "./inbound-model-options";
@@ -598,8 +599,10 @@ function applyAnthropicSettings(
598
599
  // their session id; without it consecutive /v1/messages turns reported
599
600
  // cached_tokens: 0 on the ChatGPT backend — devlog 090). Claude Code's
600
601
  // metadata.user_id embeds the session uuid, so hashing it yields a stable
601
- // per-session key with a bounded length/charset.
602
- body.prompt_cache_key = userIdHash.slice(0, 32);
602
+ // per-session key with a bounded length/charset. Remote Claude Code adds a per-turn
603
+ // attribution token (`tk`) to that blob; it is dropped, as Claude Code itself drops it,
604
+ // so every turn of one session keeps one key.
605
+ body.prompt_cache_key = createHash("sha256").update(claudeSessionUserId(raw.metadata.user_id)).digest("hex").slice(0, 32);
603
606
  cacheKeySource = "metadata";
604
607
  } else if (typeof cacheSystem === "string" || cacheSystem.length > 0) {
605
608
  // Claude Desktop sends no metadata.user_id (H1, devlog 130): without any key the