@bitkyc08/opencodex 2.96.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
@@ -7,6 +7,7 @@ import { codexCompatibleUrl } from "../codex/context-compat";
7
7
  import { addFinalRequestLog, markLocalRequestLogRefusal } from "./request-log";
8
8
  import type { WorkflowRefusalLog } from "./workflow-refusal";
9
9
  import { inboundBodyBudget, bindInboundBodyLease, type InboundBodyBudget } from "./inbound-body-budget";
10
+ import { OLLAMA_JSON_BODY_ROUTES } from "./ollama-native-paths";
10
11
 
11
12
  export { configureInboundBodyBudget, MAX_CONCURRENT_INBOUND_BODY_BYTES } from "./inbound-body-budget";
12
13
 
@@ -145,10 +146,12 @@ export async function withRaisedInboundBodyAdmission(
145
146
  configuredLimit: number | undefined,
146
147
  work: () => Promise<Response>,
147
148
  onRefusal: (response: Response) => Response = response => response,
148
- options?: { budget?: InboundBodyBudget; maxWaitMs?: number },
149
+ options?: { budget?: InboundBodyBudget; maxWaitMs?: number; onAdmissionError?: (error: unknown) => Response },
149
150
  ): Promise<Response> {
150
151
  const maxBytes = resolveInboundBodyLimitBytes(configuredLimit);
151
- if (req.method !== "POST" || !CONFIGURABLE_JSON_BODY_ROUTES.has(pathname)
152
+ // Native Ollama generation routes are served only on the authenticated listener, so they sit in
153
+ // their own set: the loopback oracle checks CONFIGURABLE_JSON_BODY_ROUTES against that allowlist.
154
+ if (req.method !== "POST" || !(CONFIGURABLE_JSON_BODY_ROUTES.has(pathname) || OLLAMA_JSON_BODY_ROUTES.has(pathname))
152
155
  || maxBytes <= MAX_DECOMPRESSED_BODY_BYTES || req.signal.aborted) {
153
156
  return work();
154
157
  }
@@ -164,6 +167,7 @@ export async function withRaisedInboundBodyAdmission(
164
167
  lease = await (options?.budget ?? inboundBodyBudget).acquire(maxBytes, req.signal, options?.maxWaitMs);
165
168
  } catch (error) {
166
169
  cancelUnreadBody(req, error);
170
+ if (options?.onAdmissionError) return options.onAdmissionError(error);
167
171
  throw error;
168
172
  }
169
173
  if (!lease) {
@@ -175,6 +179,7 @@ export async function withRaisedInboundBodyAdmission(
175
179
  if (req.signal.aborted) {
176
180
  lease.release();
177
181
  cancelUnreadBody(req, req.signal.reason);
182
+ if (options?.onAdmissionError) return options.onAdmissionError(req.signal.reason);
178
183
  throw req.signal.reason;
179
184
  }
180
185
  const unbind = bindInboundBodyLease(req, lease);
@@ -198,6 +203,8 @@ export function runAdmittedBodyWork(
198
203
  configuredLimit: number | undefined,
199
204
  work: () => Promise<Response>,
200
205
  refusalLog?: WorkflowRefusalLog,
206
+ mapRefusal?: (response: Response) => Response,
207
+ onAdmissionError?: (error: unknown) => Response,
201
208
  ): Promise<Response> {
202
209
  return withRaisedInboundBodyAdmission(req, codexCompatibleUrl(req.url).pathname, configuredLimit, work, refused => {
203
210
  if (refusalLog) {
@@ -208,6 +215,6 @@ export function runAdmittedBodyWork(
208
215
  });
209
216
  refusalLog.onLogged?.();
210
217
  }
211
- return withCors(refused, req, policy);
212
- });
218
+ return withCors(mapRefusal ? mapRefusal(refused) : refused, req, policy);
219
+ }, onAdmissionError ? { onAdmissionError } : undefined);
213
220
  }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Dispatcher arm for the Ollama-compatible inbound API. It runs before the management /api/
3
+ * catch-all and only for the exact native paths; every other /api/ path is untouched. Admission
4
+ * reuses the data-plane gates: generation takes the same key, origin, drain, active-turn,
5
+ * workflow and body admission as /v1/chat/completions, and the read-only routes take the
6
+ * model-discovery admission /v1/models uses. Refusals keep their status and retry advice and are
7
+ * reshaped into the native { "error": string } body.
8
+ */
9
+ import type { Server } from "bun";
10
+ import type { OcxConfig } from "../../types";
11
+ import type { WsData } from "../ws-bridge";
12
+ import { admissionFields, isAllowedRequestOrigin, resolveApiAuth, resolveResponsesApiAuth, withCors, type RequestPolicyView } from "../auth-cors";
13
+ import { withCallerSessionIdentity } from "../caller-session-identity";
14
+ import { captureAdmissionPolicy } from "../capture-admission-policy";
15
+ import { isDraining, type ActiveTurnLease } from "../lifecycle";
16
+ import { handleOllamaGeneration, handleOllamaShow, handleOllamaTags, handleOllamaVersion, ollamaError, toOllamaRefusal } from "../ollama-inbound";
17
+ import { OLLAMA_NATIVE_ROUTES } from "../ollama-native-paths";
18
+ import { nextRequestLogId, type RequestLogContext } from "../request-log";
19
+ import { disableResponsesRequestTimeout } from "../responses";
20
+ import type { AdmittedHttpTurnOptions } from "../admitted-http-turn";
21
+ import type { WorkflowRefusalLog } from "../workflow-refusal";
22
+ import { withRequestLogId } from "./startup-warnings";
23
+
24
+ export interface OllamaRouteDeps {
25
+ config: OcxConfig;
26
+ policy: RequestPolicyView;
27
+ requestServer: Server<WsData>;
28
+ requestMetricsLogContext: Partial<RequestLogContext>;
29
+ drainingResponse: (req: Request, policy: RequestPolicyView) => Response;
30
+ runAdmittedHttpTurn: (
31
+ req: Request,
32
+ policy: RequestPolicyView,
33
+ work: (lease: ActiveTurnLease) => Promise<Response>,
34
+ refusalLog?: WorkflowRefusalLog,
35
+ options?: AdmittedHttpTurnOptions,
36
+ ) => Promise<Response>;
37
+ }
38
+
39
+ /** Returns undefined when the path is not one of the native routes. */
40
+ export async function dispatchOllamaRoute(req: Request, url: URL, deps: OllamaRouteDeps): Promise<Response | undefined> {
41
+ const route = OLLAMA_NATIVE_ROUTES.get(url.pathname);
42
+ if (!route) return undefined;
43
+ const { config, policy } = deps;
44
+ if (req.method !== route.method) {
45
+ const refused = ollamaError(405, `method ${req.method} not allowed`);
46
+ refused.headers.set("Allow", route.method);
47
+ return withCors(refused, req, policy);
48
+ }
49
+ if (route.kind === "version" || route.kind === "tags" || route.kind === "show") {
50
+ // Model discovery never forwards Authorization upstream, so the broader admission set is safe.
51
+ const admission = resolveApiAuth(req, policy);
52
+ if (!admission) return withCors(ollamaError(401, "opencodex API key required"), req, policy);
53
+ if (!isAllowedRequestOrigin(req, policy)) return withCors(ollamaError(403, "cross-origin data-plane request blocked"), req, policy);
54
+ const response = route.kind === "version" ? handleOllamaVersion()
55
+ : route.kind === "tags" ? handleOllamaTags(config, req, admission)
56
+ : await handleOllamaShow(config, req, admission);
57
+ return withCors(response, req, policy);
58
+ }
59
+ const kind = route.kind;
60
+ disableResponsesRequestTimeout(req, deps.requestServer);
61
+ if (isDraining()) return withCors(toOllamaRefusal(deps.drainingResponse(req, policy)), req, policy);
62
+ const admission = resolveResponsesApiAuth(req, policy);
63
+ if (!admission) return withCors(ollamaError(401, "opencodex API key required"), req, policy);
64
+ if (!isAllowedRequestOrigin(req, policy)) return withCors(ollamaError(403, "cross-origin data-plane request blocked"), req, policy);
65
+ const start = Date.now();
66
+ const requestId = nextRequestLogId(start);
67
+ const logCtx: RequestLogContext = {
68
+ model: "unknown",
69
+ provider: "unknown",
70
+ ...deps.requestMetricsLogContext,
71
+ ...admissionFields(admission),
72
+ };
73
+ const sessionReq = withCallerSessionIdentity(req, admission);
74
+ // Expose an id only when the handler or a logged refusal owns the history row.
75
+ let ownsRequestLog = false;
76
+ const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission);
77
+ const response = await deps.runAdmittedHttpTurn(sessionReq, policy, async turnAdmissionLease => {
78
+ ownsRequestLog = true;
79
+ return withCors(
80
+ await handleOllamaGeneration(kind, sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission, advisorAdmissionPolicy }),
81
+ req,
82
+ policy,
83
+ );
84
+ }, { requestId, start, logCtx, onLogged: () => { ownsRequestLog = true; } }, {
85
+ mapRefusal: toOllamaRefusal,
86
+ onAdmissionError: () => ollamaError(499, "request cancelled"),
87
+ });
88
+ return ownsRequestLog ? withRequestLogId(response, requestId) : response;
89
+ }
@@ -203,6 +203,10 @@ import type { OcxConfig } from "../../types";
203
203
  import type { PackageTreeIntegrityGuard } from "../../lib/package-tree-integrity";
204
204
  import type { ReadinessGate } from "../readiness";
205
205
  import type { WorkflowRefusalLog } from "../workflow-refusal";
206
+ import type { AdmittedHttpTurnOptions } from "../admitted-http-turn";
207
+ import { isOllamaNativePath } from "../ollama-native-paths";
208
+ import { ollamaError } from "../ollama-inbound";
209
+ import { dispatchOllamaRoute } from "./ollama-routes";
206
210
 
207
211
  import { readyProtocolMetadata } from "../../remote/protocol";
208
212
  import { homeInstanceId, stampServedBy } from "../../remote/served-by";
@@ -212,6 +216,7 @@ import { reasoningArchiveErrorResponse } from "../responses/reasoning-archive-er
212
216
  import { withGrokSessionIdentity } from "../../grok/session-identity";
213
217
  import { withCallerSessionIdentity } from "../caller-session-identity";
214
218
  import { agentAssertionUnsupportedResponse, hasAgentAssertionAuthorization } from "../../lib/authorization-scheme";
219
+ import { runTurnStateCallerScope } from "../turn-state-handles";
215
220
 
216
221
  export type ServerIngress = "public" | "unauthenticated-loopback" | "hub-management" | "claude-intercept" | "hub-link";
217
222
 
@@ -256,6 +261,7 @@ export interface ServeOptionsContext {
256
261
  policy: RequestPolicyView,
257
262
  work: (lease: ActiveTurnLease) => Promise<Response>,
258
263
  refusalLog?: WorkflowRefusalLog,
264
+ options?: AdmittedHttpTurnOptions,
259
265
  ) => Promise<Response>;
260
266
 
261
267
  config: OcxConfig;
@@ -414,6 +420,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
414
420
  url.pathname === "/healthz"
415
421
  || readyzPath !== undefined
416
422
  || url.pathname.startsWith("/v1/")
423
+ || isOllamaNativePath(url.pathname)
417
424
  )) {
418
425
  const message = "OpenCodex package files changed while this proxy was running; it restarts on its own, or run 'ocx restart' ('ocx service restart' for a background service).";
419
426
  const fencedPort = ctx.boundPort ?? requestServer.port ?? listenPort;
@@ -437,7 +444,9 @@ export function createServeOptions(ctx: ServeOptionsContext) {
437
444
  } : {}),
438
445
  error: { code: "package_tree_changed", message },
439
446
  }, 503, req, policy)
440
- : packageTreeChangedResponse(req, policy, message);
447
+ : isOllamaNativePath(url.pathname)
448
+ ? withCors(ollamaError(503, message), req, policy)
449
+ : packageTreeChangedResponse(req, policy, message);
441
450
  const headers = new Headers(response.headers);
442
451
  headers.set("Retry-After", "5");
443
452
  const challenge = fencedHealth ? req.headers.get(LOCAL_ATTESTATION_CHALLENGE_HEADER) : null;
@@ -453,7 +462,8 @@ export function createServeOptions(ctx: ServeOptionsContext) {
453
462
  if (readyzPath !== undefined) {
454
463
  return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, policy);
455
464
  }
456
- const managementPreflight = url.pathname.startsWith("/api/");
465
+ // The exact Ollama-compatible paths are data-plane routes and take data-plane CORS.
466
+ const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname);
457
467
  const allowed = managementPreflight
458
468
  ? isAllowedManagementOrigin(req, config)
459
469
  : isAllowedRequestOrigin(req, policy);
@@ -695,6 +705,12 @@ export function createServeOptions(ctx: ServeOptionsContext) {
695
705
  return new Response(resp.body, { status: 503, headers });
696
706
  }
697
707
 
708
+ // Checked synchronously: an await here would delay every later route's admission capture.
709
+ if (isOllamaNativePath(url.pathname)) {
710
+ const native = await dispatchOllamaRoute(req, url, { config, policy, requestServer, requestMetricsLogContext, drainingResponse, runAdmittedHttpTurn });
711
+ if (native) return native;
712
+ }
713
+
698
714
  if (url.pathname.startsWith("/api/")) {
699
715
  const localManagementAuth = {
700
716
  attestationSecret: localAttestationSecret,
@@ -1971,6 +1987,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1971
1987
  } as const;
1972
1988
  const routeFetch = serveOptions.fetch;
1973
1989
  // x-opencodex-served-by on GET /v1/models, whichever branch answered (src/remote/served-by.ts).
1974
- return { ...serveOptions, fetch: async (req: Request, requestServer: Server<WsData>): Promise<Response> =>
1975
- stampServedBy(req.method, codexCompatibleUrl(req.url).pathname, await routeFetch(req, requestServer)) } as const;
1990
+ // Each request runs with its own caller slot, which admission fills for turn-state handle binding.
1991
+ return { ...serveOptions, fetch: (req: Request, requestServer: Server<WsData>): Promise<Response> => runTurnStateCallerScope(async () =>
1992
+ stampServedBy(req.method, codexCompatibleUrl(req.url).pathname, await routeFetch(req, requestServer))) } as const;
1976
1993
  }
@@ -93,6 +93,7 @@ import type { ServeOptionsContext } from "./serve-options";
93
93
  import type { RequestMetricsRecorder } from "../request-metrics";
94
94
  import { resolveInboundBodyLimitBytes } from "../request-decompress";
95
95
  import { responseToolOwnership } from "../responses/response-tool-ownership";
96
+ import { runTurnStateCallerScope } from "../turn-state-handles";
96
97
 
97
98
  /**
98
99
  * The WebSocket half of the Bun.serve options, split out of serve-options.ts to keep that file
@@ -310,7 +311,8 @@ export function createWebsocketHandler(
310
311
  const payload: Record<string, unknown> = { ...frame };
311
312
  delete payload.type;
312
313
  turnAdmissionLease.bindAbortController(turnAbort);
313
- void (async () => {
314
+ // The frame runs with its own caller slot, which admission fills for turn-state handle binding.
315
+ void runTurnStateCallerScope(async () => {
314
316
  const start = Date.now();
315
317
  const requestId = nextRequestLogId(start);
316
318
  // Resolved once at the handshake — a frame has no request headers left
@@ -431,7 +433,7 @@ export function createWebsocketHandler(
431
433
  if (!logged && turnAbort.signal.aborted) finalizeLog(499);
432
434
  if (ws.data.cancel === cancelTurn) ws.data.cancel = undefined;
433
435
  }
434
- })();
436
+ });
435
437
  },
436
438
  close(ws: ServerWebSocket<WsData>, code: number, reason: string) {
437
439
  if (ws.data.kind === "remote-workspace-agent") {
@@ -2,7 +2,9 @@ import { remoteWorkspaceEnabled } from "../remote-control/workspace-activation";
2
2
  import { scheduleDesktopCompatibilityStartup } from "./index/desktop-compatibility-startup";
3
3
  import { AuxiliaryListenerBindError } from "./ports";
4
4
  import { normalizeBindHostname } from "./bind-host";
5
- import { configureInboundBodyBudget, runAdmittedBodyWork } from "./inbound-body-admission";
5
+ import { configureInboundBodyBudget } from "./inbound-body-admission";
6
+ import { createAdmittedHttpTurn } from "./admitted-http-turn";
7
+ import { isOllamaNativePath } from "./ollama-native-paths";
6
8
  import {
7
9
  buildWarmupCompletionFrames,
8
10
  buildWsErrorFrame,
@@ -93,9 +95,7 @@ import {
93
95
  runListenerShutdown,
94
96
  setServerRef,
95
97
  trackStreamLifetime,
96
- tryAdmitTurn,
97
98
  unregisterTurn,
98
- type ActiveTurnLease,
99
99
  } from "./lifecycle";
100
100
  export {
101
101
  drainAndShutdown,
@@ -116,9 +116,7 @@ import {
116
116
  type RequestLogContext,
117
117
  type RequestLogEntry,
118
118
  } from "./request-log";
119
- import { sessionLaneIdFromRequest } from "./request-log-conversation";
120
119
  import { setUsageLedgerRetention } from "./usage-ledger-retention";
121
- import { admitHttpWorkflowTurn, workflowDecisionRefusalResponse, type WorkflowRefusalLog } from "./workflow-refusal";
122
120
  export {
123
121
  addFinalRequestLog,
124
122
  filterRequestLogs, queryRequestLogs,
@@ -450,6 +448,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe
450
448
  }
451
449
  if (rawPath === "/remote-workspace/pair") return remoteWorkspaceEnabled(config) && req.method === "POST";
452
450
  if (rawPath === "/opencodex-session") return req.method === "GET" || req.method === "POST";
451
+ // Ollama-compatible inference paths are data plane, not management: never via Tailscale Serve.
452
+ if (isOllamaNativePath(rawPath)) return false;
453
453
  if (rawPath.startsWith("/api/")) return true;
454
454
  if (req.method !== "GET" && req.method !== "HEAD") return false;
455
455
  let decodedPath: string;
@@ -500,37 +500,7 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe
500
500
  }), req, policy);
501
501
  }
502
502
 
503
- async function runAdmittedHttpTurn(
504
- req: Request,
505
- policy: RequestPolicyView,
506
- work: (lease: ActiveTurnLease) => Promise<Response>,
507
- refusalLog?: WorkflowRefusalLog,
508
- ): Promise<Response> {
509
- const lease = tryAdmitTurn(sessionLaneIdFromRequest(req.headers), req.signal);
510
- if (!lease) return serverBusyResponse(req, "active turns", policy);
511
- // Root, lane, and the refusal that follows from them, all live in ./workflow-refusal.
512
- let workflow: ReturnType<typeof admitHttpWorkflowTurn>;
513
- try { workflow = admitHttpWorkflowTurn(req.headers); }
514
- catch (error) { lease.release(); throw error; }
515
- if (workflow && !workflow.admitted) {
516
- lease.release();
517
- // withCors, because without Access-Control-Allow-Origin the exposed refusal header is
518
- // still unreadable to a browser dashboard -- which made exposing it pointless.
519
- return withCors(workflowDecisionRefusalResponse(workflow, undefined, refusalLog), req, policy);
520
- }
521
- if (workflow?.admitted) lease.attach(workflow.lease);
522
- let response: Response;
523
- try {
524
- response = await runAdmittedBodyWork(req, policy, config.maxInboundBodyBytes, () => work(lease), refusalLog);
525
- } catch (error) {
526
- lease.release();
527
- throw error;
528
- }
529
- if (!lease.isTransferred()) {
530
- lease.release();
531
- }
532
- return response;
533
- }
503
+ const runAdmittedHttpTurn = createAdmittedHttpTurn(() => config.maxInboundBodyBytes, serverBusyResponse);
534
504
 
535
505
  // Readiness gate: one PRIVATE controller per startServer invocation, captured
536
506
  // by this listener's closure. Starting/failing a second server in the same
@@ -1,3 +1,4 @@
1
+ import type { FailureVerdictSink } from "../../chat/failure-verdict";
1
2
  /**
2
3
  * Adapter delivery straight into a Chat or Messages client's wire (PF-09).
3
4
  *
@@ -215,6 +216,7 @@ export async function deliverClientEncodedResponse(input: ClientEncodedDelivery)
215
216
  recorder?.noteRelayedEvent(observation);
216
217
  },
217
218
  };
219
+ const failureVerdictSink: FailureVerdictSink = {};
218
220
  const encodeOptions = {
219
221
  model: encoder.model,
220
222
  translatorBudget,
@@ -224,7 +226,7 @@ export async function deliverClientEncodedResponse(input: ClientEncodedDelivery)
224
226
  hooks,
225
227
  };
226
228
  const encoded = encoder.protocol === "chat"
227
- ? encodeChatCompletionSse(events, encodeOptions)
229
+ ? encodeChatCompletionSse(events, { ...encodeOptions, failureVerdictSink, proxyErrorContext: logCtx, get localUpstream() { return input.localUpstream; } })
228
230
  : encodeAnthropicMessageSse(events, {
229
231
  ...encodeOptions,
230
232
  get localUpstream() { return input.localUpstream; },
@@ -238,7 +240,7 @@ export async function deliverClientEncodedResponse(input: ClientEncodedDelivery)
238
240
  } else {
239
241
  // The routed turn always streams internally; a non-streaming client gets the fold.
240
242
  response = encoder.protocol === "chat"
241
- ? await collectChatCompletionResponse(tracked, encoder.model, translatorBudget)
243
+ ? await collectChatCompletionResponse(tracked, encoder.model, translatorBudget, failureVerdictSink)
242
244
  : await collectAnthropicMessageResponse(tracked, encoder.model, translatorBudget);
243
245
  }
244
246
  return attachClientWireLog(markClientWire(response, encoder.protocol), log);
@@ -0,0 +1,44 @@
1
+ import { Buffer } from "node:buffer";
2
+
3
+ type Frame =
4
+ | { items: readonly unknown[]; index: number }
5
+ | { record: Record<string, unknown>; keys: readonly string[]; index: number };
6
+
7
+ /**
8
+ * UTF-8 byte length of JSON.stringify(value) for a JSON.parse result, computed without
9
+ * recursion: a valid body nested deeper than the call stack must be measured, not crash.
10
+ * Each open container keeps one cursor frame, so arrays add no per-element queue; an object
11
+ * frame retains its key list, which stays bounded by the input size.
12
+ */
13
+ export function serializedJsonByteLength(value: unknown): number {
14
+ let bytes = 0;
15
+ const stack: Frame[] = [];
16
+ const visit = (item: unknown): void => {
17
+ if (item === null || typeof item !== "object") {
18
+ bytes += Buffer.byteLength(JSON.stringify(item) ?? "null", "utf8");
19
+ } else if (Array.isArray(item)) {
20
+ bytes += 2 + Math.max(0, item.length - 1);
21
+ stack.push({ items: item, index: 0 });
22
+ } else {
23
+ const record = item as Record<string, unknown>;
24
+ const keys = Object.keys(record);
25
+ bytes += 2 + Math.max(0, keys.length - 1);
26
+ stack.push({ record, keys, index: 0 });
27
+ }
28
+ };
29
+ visit(value);
30
+ while (stack.length > 0) {
31
+ const frame = stack[stack.length - 1]!;
32
+ if ("items" in frame) {
33
+ if (frame.index < frame.items.length) visit(frame.items[frame.index++]);
34
+ else stack.pop();
35
+ } else if (frame.index < frame.keys.length) {
36
+ const key = frame.keys[frame.index++]!;
37
+ bytes += Buffer.byteLength(JSON.stringify(key), "utf8") + 1;
38
+ visit(frame.record[key]);
39
+ } else {
40
+ stack.pop();
41
+ }
42
+ }
43
+ return bytes;
44
+ }
@@ -562,26 +562,28 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
562
562
  const body = parsedBody as { enabled?: unknown };
563
563
  if (typeof body.enabled !== "boolean") return jsonResponse({ error: "body.enabled must be a boolean" }, 400);
564
564
  const { isDefaultModeRequestUserInputEnabled, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, activeCodexConfigPath } = await import("../../codex/features");
565
- const before = isDefaultModeRequestUserInputEnabled();
566
- let toggle = deps.toggleDefaultModeRequestUserInput;
567
- if (!toggle) {
568
- try {
569
- const { codexFeaturesInvocationAsync, runCodexFeaturesCommand } = await import("../../cli/v2");
570
- const action = body.enabled ? "enable" : "disable";
571
- const invocation = await codexFeaturesInvocationAsync(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, process.platform, { requireAvailable: true });
572
- toggle = (_enabled, env, validate) => runCodexFeaturesCommand(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, env, validate, invocation);
573
- } catch (error) {
574
- return jsonResponse({ error: `default_mode_request_user_input toggle failed: ${error instanceof Error ? error.message : String(error)}` }, 502);
565
+ const selectionWrite = await beginCodexCliSelectionParentWriteAsync({ signal: req.signal });
566
+ if (!selectionWrite.entered) return jsonResponse({ error: "codex_cli_selection_busy", retryable: true }, 503);
567
+ try {
568
+ const before = isDefaultModeRequestUserInputEnabled();
569
+ let toggle = deps.toggleDefaultModeRequestUserInput;
570
+ if (!toggle) {
571
+ try {
572
+ const { codexFeaturesInvocation, runCodexFeaturesCommand } = await import("../../cli/v2");
573
+ const action = body.enabled ? "enable" : "disable";
574
+ const invocation = selectionWrite.commit(() => codexFeaturesInvocation(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, process.platform, { requireAvailable: true }));
575
+ toggle = (_enabled, env, validate) => runCodexFeaturesCommand(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, env, validate, invocation);
576
+ } catch (error) {
577
+ if (error instanceof CodexCliSelectionMutationBusyError) throw error;
578
+ return jsonResponse({ error: `default_mode_request_user_input toggle failed: ${error instanceof Error ? error.message : String(error)}` }, 502);
579
+ }
575
580
  }
576
- }
577
- // The `codex features` subprocess rewrites config.toml itself — run it
578
- // under the shared write lock so it cannot interleave with an opencodex
579
- // scalar edit or injection mid-write on either side.
580
- const { acquireConfigWriteLock, releaseConfigWriteLock, configWriteLockFailureMessage, runConfigWriteChild, ConfigWriteDestinationChanged } = await import("../../codex/config-write-lock");
581
- const configPath = activeCodexConfigPath();
582
- // Preserve native home creation only after executable resolution succeeds.
583
- prepareCodexHome(dirname(configPath));
584
- {
581
+ // Keep selection ownership across the config-lock await and the whole
582
+ // synchronous child execution: an updater must not replace this command.
583
+ const { acquireConfigWriteLock, releaseConfigWriteLock, configWriteLockFailureMessage, runConfigWriteChild, ConfigWriteDestinationChanged } = await import("../../codex/config-write-lock");
584
+ const configPath = activeCodexConfigPath();
585
+ // Preserve native home creation only after executable resolution succeeds.
586
+ selectionWrite.commit(() => prepareCodexHome(dirname(configPath)));
585
587
  const configLock = await acquireConfigWriteLock(configPath);
586
588
  if (!configLock.ok) {
587
589
  return jsonResponse({ error: configWriteLockFailureMessage(configLock), retryable: configLock.error === "locked" }, 502);
@@ -589,8 +591,9 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
589
591
  let toggleError: string | null = null;
590
592
  let destinationChanged = false;
591
593
  try {
592
- runConfigWriteChild(configPath, configLock.handle, (env, validate) => toggle!(body.enabled as boolean, env, validate));
594
+ selectionWrite.commit(() => runConfigWriteChild(configPath, configLock.handle, (env, validate) => toggle!(body.enabled as boolean, env, validate)));
593
595
  } catch (error) {
596
+ if (error instanceof CodexCliSelectionMutationBusyError) throw error;
594
597
  destinationChanged = error instanceof ConfigWriteDestinationChanged;
595
598
  const err = error as { stderr?: unknown; message?: string };
596
599
  const raw = err.stderr;
@@ -613,7 +616,7 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
613
616
  warnings.push("Applies to new sessions; restart the Codex app or wait out its picker cache to see the change.");
614
617
  }
615
618
  return jsonResponse({ ok: true, enabled, changed: enabled !== before, warnings });
616
- }
619
+ } finally { selectionWrite.exit(); }
617
620
  }
618
621
 
619
622
  // Subagent prompt injection model: single native or routed model whose info is
@@ -25,7 +25,8 @@ export async function handleCodexCliUpdateRoutes(ctx: ManagementContext): Promis
25
25
  }
26
26
  if (ctx.url.pathname !== "/api/codex/cli-update/apply") return null;
27
27
  if (ctx.req.method !== "POST") return jsonResponse({ error: "method_not_allowed" }, 405, ctx.req, ctx.config);
28
- if (!hasHumanDashboardSession(ctx) || !ctx.trustedLoopbackIngress) {
28
+ if (!hasHumanDashboardSession(ctx) || !ctx.trustedLoopbackIngress
29
+ || ctx.sessionControl?.isPaired(ctx.req, ctx.config) !== true) {
29
30
  return jsonResponse({ error: "local_dashboard_confirmation_required" }, 403, ctx.req, ctx.config);
30
31
  }
31
32
  let body: unknown;
@@ -180,7 +180,7 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [
180
180
  { method: "POST", path: "/api/codex/desktop-compatibility/settings", module: "server/management/desktop-compatibility-settings-routes", mutates: true, mechanism: "path-constant", exempt: { reason: "session-only", why: "Saved native observation intent requires an operator-paired local GUI action and fresh field revision." } },
181
181
  // server/management/codex-cli-update-routes
182
182
  { method: "GET", path: "/api/codex/cli-update/plan", module: "server/management/codex-cli-update-routes", mutates: false, exempt: { reason: "local-transport", why: "The CLI runs the same proof-bound plan builder locally; the authenticated route also supplies the dashboard plan." } },
183
- { method: "POST", path: "/api/codex/cli-update/apply", module: "server/management/codex-cli-update-routes", mutates: true, exempt: { reason: "session-only", why: "HTTP apply requires a confirmed trusted loopback GUI session; the CLI invokes the same durable job owner locally." } },
183
+ { method: "POST", path: "/api/codex/cli-update/apply", module: "server/management/codex-cli-update-routes", mutates: true, exempt: { reason: "session-only", why: "HTTP apply requires a current paired dashboard session on trusted loopback ingress, matching origin, CSRF and confirmed: true; the local CLI uses --yes independently." } },
184
184
  { method: "GET", path: "/api/codex/cli-update/jobs/{jobId}", module: "server/management/codex-cli-update-routes", mutates: false, mechanism: "regex", exempt: { reason: "local-transport", why: "The CLI status command reads the same protected job record directly and does not use job IDs as authorization." } },
185
185
  { method: "PUT", path: "/api/codex-auth/features/default-mode-request-user-input", module: "server/management/agent-settings-routes", mutates: true },
186
186
  { method: "PUT", path: "/api/effort-caps", module: "server/management/agent-settings-routes", mutates: true },
@@ -1,3 +1,4 @@
1
+ import { clientFacingModelLabel } from "../lib/error-destination";
1
2
  import {
2
3
  AdmissionModelDeniedError, routeAllowedByScope, UNNAMED_DESTINATION_MODEL, type AdmissionModelScope,
3
4
  } from "./admission-model-scope";
@@ -58,7 +59,7 @@ export function nativeMessagesToolScopeDenial(
58
59
  if (!isAdvisor(tool)) continue;
59
60
  const modelId = typeof tool.model === "string" && tool.model.trim() ? tool.model : undefined;
60
61
  if (modelId === undefined || !routeAllowedByScope(scope, { providerName, modelId })) {
61
- return new AdmissionModelDeniedError(requestedModel, { providerName, modelId: modelId ?? UNNAMED_DESTINATION_MODEL });
62
+ return new AdmissionModelDeniedError(clientFacingModelLabel(requestedModel), { providerName, modelId: modelId ?? UNNAMED_DESTINATION_MODEL });
62
63
  }
63
64
  }
64
65
  return undefined;
@@ -110,7 +110,7 @@ export function guardNativeMessagesEmptyToolCatalog(
110
110
  && (index === undefined || !permittedInputBlocks.has(index))) name ??= "<unnamed>";
111
111
  if (name !== undefined) {
112
112
  clear();
113
- const message = redactSecretString(undeclaredToolCallMessage(name));
113
+ const message = redactSecretString(undeclaredToolCallMessage());
114
114
  onRefusal(message);
115
115
  enqueue(controller, `event: error\ndata: ${JSON.stringify(anthropicErrorBody(502, message, "api_error", UNDECLARED_TOOL_CALL_ERROR_CODE))}\n\n`);
116
116
  settled = true;
@@ -44,7 +44,7 @@ import { readBoundedResponseBody } from "../lib/bounded-body";
44
44
  import { classifyError } from "../lib/errors";
45
45
  import { relaySseWithPayloadRewrite } from "./sse-payload-rewrite";
46
46
  import { redactSecretString } from "../lib/redact";
47
- import { resolveClientRetryAfter } from "../lib/retry-after";
47
+ import { formatClientRetryAfter, resolveClientRetryAfter } from "../lib/retry-after";
48
48
  import { enrichOpenCodeZenUpstreamMessage } from "../providers/opencode-zen-rate-limit";
49
49
  import { isTranslatorBudgetExceededError, type TranslatorBudget } from "../lib/translator-budget";
50
50
  import {
@@ -130,7 +130,7 @@ import { linkAbortSignal } from "./responses/core-lifetime";
130
130
  import { attachRequestSpendTracker } from "./responses/request-spend";
131
131
  import { workflowRefusalResponse } from "./workflow-refusal";
132
132
  import { sseFieldValue } from "../lib/sse-decoder";
133
- import { admissionModelDeniedResponse, type AdmissionModelScope } from "./admission-model-scope";
133
+ import { admissionModelDeniedResponse, projectAdmissionModelDeniedLog, type AdmissionModelScope } from "./admission-model-scope";
134
134
  import { nativeMessagesToolScopeDenial } from "./messages-native-scope";
135
135
  import { retainUpstreamMessagesRequestId } from "./messages-response-headers";
136
136
 
@@ -380,7 +380,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
380
380
  const localOAuthFailure = (error: unknown): Response | null => {
381
381
  if (error instanceof AnthropicAccountCooldownError) {
382
382
  const response = fail(429, error.message, "rate_limit_error");
383
- if (error.retryAfterSeconds !== null) response.headers.set("retry-after", String(error.retryAfterSeconds));
383
+ const advice = error.retryAfterSeconds !== null ? formatClientRetryAfter(error.retryAfterSeconds) : undefined;
384
+ if (advice !== undefined) response.headers.set("retry-after", advice);
384
385
  return response;
385
386
  }
386
387
  if (error instanceof OAuthAccountPausedError) return fail(403, publicOAuthAuthenticationErrorMessage(error), "permission_error");
@@ -394,6 +395,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
394
395
 
395
396
  const toolScopeDenial = nativeMessagesToolScopeDenial(options.modelScope, route.providerName, requestedModel, body);
396
397
  if (toolScopeDenial) {
398
+ projectAdmissionModelDeniedLog(toolScopeDenial, logCtx);
397
399
  finishLog(403, toolScopeDenial.message);
398
400
  return admissionModelDeniedResponse(toolScopeDenial);
399
401
  }
@@ -454,7 +456,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
454
456
  cleanupAbort(); upstream.abort();
455
457
  if (!(error instanceof RequestPacingQueueOverloadError)) throw error;
456
458
  const refusal = fail(429, error.message, "rate_limit_error");
457
- refusal.headers.set("Retry-After", String(error.retryAfterSeconds));
459
+ const advice = formatClientRetryAfter(error.retryAfterSeconds);
460
+ if (advice !== undefined) refusal.headers.set("Retry-After", advice);
458
461
  return refusal;
459
462
  }
460
463
  }
@@ -835,7 +838,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
835
838
  const sendError = error instanceof UpstreamRetryEvidenceError ? error.cause : error;
836
839
  if (sendError instanceof RequestPacingQueueOverloadError) {
837
840
  const refusal = fail(429, sendError.message, "rate_limit_error");
838
- refusal.headers.set("Retry-After", String(sendError.retryAfterSeconds));
841
+ const advice = formatClientRetryAfter(sendError.retryAfterSeconds);
842
+ if (advice !== undefined) refusal.headers.set("Retry-After", advice);
839
843
  return refusal;
840
844
  }
841
845
  if (sendError instanceof SendBudgetExhaustedError) return fail(429, sendError.message, "send_budget_exhausted", "send_budget_exhausted");
@@ -1002,7 +1006,7 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions)
1002
1006
  const undeclaredTool = clientDeclaredEmptyToolCatalog ? nativeMessagesClientToolName(message, declaredInlineTools) : undefined;
1003
1007
  if (undeclaredTool !== undefined) {
1004
1008
  logCtx.errorCode = UNDECLARED_TOOL_CALL_ERROR_CODE;
1005
- return fail(502, undeclaredToolCallMessage(undeclaredTool), "api_error", UNDECLARED_TOOL_CALL_ERROR_CODE);
1009
+ return fail(502, undeclaredToolCallMessage(), "api_error", UNDECLARED_TOOL_CALL_ERROR_CODE);
1006
1010
  }
1007
1011
  bindUsage(anthropicUsageToOcx(isRec(message.usage) ? message.usage : undefined));
1008
1012
  if (logIds) recordFirstOutput(logCtx, logIds.start);
@@ -1085,7 +1089,8 @@ function nativeMessagesErrorResponse(response: Response, bodyText: string, finis
1085
1089
  ?? (upstreamRetryAfter?.trim() === "0" ? "0" : undefined);
1086
1090
  finishLog(response.status, safeMessage);
1087
1091
  const headers = new Headers({ "Content-Type": "application/json" });
1088
- if (retryAfter) headers.set("Retry-After", retryAfter);
1092
+ const clientRetryAfter = formatClientRetryAfter(retryAfter);
1093
+ if (clientRetryAfter) headers.set("Retry-After", clientRetryAfter);
1089
1094
  else if (transient) headers.set("Retry-After", "2");
1090
1095
  if (replayRefusal) applyReplayRefusalClientHeaders(headers);
1091
1096
  // The native envelope keeps its shape (no added code); only an overflow's wording changes, so
@@ -28,6 +28,7 @@ import { isTranslatorBudgetExceededError } from "../lib/translator-budget";
28
28
  import { AnthropicRequestError, isRec, type Rec } from "../claude/inbound-records";
29
29
  import type { RequestLogContext } from "./request-log";
30
30
  import { recordGenerationEvent } from "./request-log-generation-window";
31
+ import { recordLocalFailureDetail } from "./request-log-failure-detail";
31
32
  import type { OcxConfig } from "../types";
32
33
 
33
34
  export function anthropicUsageToOcx(usage: Rec | undefined): { inputTokens: number; outputTokens: number; cachedInputTokens?: number; cacheReadInputTokens?: number; cacheCreationInputTokens?: number; cacheCreation1hInputTokens?: number } | undefined {
@@ -267,7 +268,8 @@ export function tapAnthropicSseForLog(
267
268
  // A cut-short turn, logged as the Responses relay logs a stall-timeout incomplete
268
269
  // (httpStatusForRequestLogTerminal: only a max_output_tokens incomplete is a 200). A 200
269
270
  // row with no terminalStatus also lost its failure diagnostics in usage.jsonl.
270
- logCtx.upstreamError = message.slice(0, 500);
271
+ recordLocalFailureDetail(logCtx, message, closeReason === "body_stall"
272
+ ? { code: "body_stall", value: guard?.stallMs ?? 0 } : { code: "body_overflow", value: guard?.maxBytes ?? 0 });
271
273
  finalize(502, { terminalStatus: "incomplete", closeReason });
272
274
  closeWithErrorFrame(errType, message);
273
275
  }
@@ -350,7 +352,7 @@ export function tapAnthropicSseForLog(
350
352
  // reset (below), so the client never reads a partial answer as a finished message.
351
353
  logCtx.transportPhase = "mid_stream";
352
354
  logCtx.terminalSource = "synthetic";
353
- logCtx.upstreamError = failure;
355
+ recordLocalFailureDetail(logCtx, failure, { code: lastDeliveredStop === "error" ? "stream_error_stop" : "stream_ended_early" });
354
356
  if (logCtx.activeAttempt) logCtx.activeAttempt.streamAborted = true;
355
357
  finalize(502, { terminalStatus: "failed", closeReason: "terminal" });
356
358
  closeWithErrorFrame("api_error", failure);
@@ -411,6 +413,8 @@ export function tapAnthropicSseForLog(
411
413
  const message = redactSecretString(`anthropic passthrough upstream stream failed: ${err instanceof Error ? err.message : String(err)}`);
412
414
  logCtx.transportPhase = "mid_stream";
413
415
  logCtx.terminalSource = "synthetic";
416
+ // The runtime error text stays internal; the row keeps the fixed sentence only.
417
+ recordLocalFailureDetail(logCtx, "anthropic passthrough upstream stream failed", { code: "stream_failed" });
414
418
  logCtx.upstreamError = message.slice(0, 500);
415
419
  if (logCtx.activeAttempt) logCtx.activeAttempt.streamAborted = true;
416
420
  finalize(502, { terminalStatus: "failed", closeReason: "terminal" });