@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.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 (249) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -6,7 +6,37 @@
6
6
  * The submit call uses a 60 s timeout (it only returns an ID); the poll call uses 30 s.
7
7
  * Non-2xx responses throw with the original status code so callers can distinguish
8
8
  * rate-limit / auth failures from transient errors.
9
+ *
10
+ * Both calls go through the provider outbound transport, which resolves the destination host,
11
+ * applies the selected row's `allowPrivateNetwork` to every DNS answer and pins the connection to
12
+ * a validated address, so a hostname that resolves to loopback or private space never receives the
13
+ * bearer key without the opt-in and a later DNS answer cannot redirect it (rebinding).
14
+ * The poll GET carries the same key as the submit POST, so it obeys the same cleartext rules.
9
15
  */
16
+ import type { OcxProviderConfig } from "../types";
17
+ import { getProviderRegistryEntry } from "../providers/registry";
18
+ import {
19
+ providerOutboundGet,
20
+ providerOutboundPost,
21
+ type ProviderOutboundDependencies,
22
+ } from "../lib/provider-outbound";
23
+
24
+ /**
25
+ * Destination and credential of one video provider. `providerName` and the destination fields are
26
+ * the selected row's, read by the outbound policy; the pinned xAI path uses `xai` with no
27
+ * private-network opt-in because its destination is the registry host.
28
+ */
29
+ export interface VideoProviderAuth {
30
+ baseUrl: string;
31
+ token: string;
32
+ providerName: string;
33
+ allowPrivateNetwork?: boolean;
34
+ proxy?: OcxProviderConfig["proxy"];
35
+ noProxy?: OcxProviderConfig["noProxy"];
36
+ }
37
+
38
+ /** Test seam for DNS resolution and the pinned transport; production passes nothing. */
39
+ export type VideoOutboundDependencies = Pick<ProviderOutboundDependencies, "resolveAddresses" | "pinnedGet" | "pinnedPost">;
10
40
 
11
41
  export interface XaiVideoSubmitRequest {
12
42
  prompt: string;
@@ -30,6 +60,40 @@ const SUBMIT_TIMEOUT_MS = 60_000;
30
60
  const POLL_TIMEOUT_MS = 30_000;
31
61
  const DEFAULT_VIDEO_MODEL = "grok-imagine-video";
32
62
 
63
+ function xaiRegistryBaseUrl(): string {
64
+ return (getProviderRegistryEntry("xai")?.baseUrl ?? "https://api.x.ai/v1").replace(/\/+$/, "");
65
+ }
66
+
67
+ /**
68
+ * Only the registry xAI video endpoints qualify for the outbound fake-IP TUN exception, which
69
+ * keeps the pinned xAI path reachable under Clash/Surge TUN mode as it was with plain fetch.
70
+ */
71
+ function isCanonicalXaiVideoUrl(name: string, url: string): boolean {
72
+ return name === "xai" && url.startsWith(`${xaiRegistryBaseUrl()}/videos/`);
73
+ }
74
+
75
+ function outboundConfig(auth: VideoProviderAuth) {
76
+ return {
77
+ baseUrl: auth.baseUrl,
78
+ ...(auth.allowPrivateNetwork === true ? { allowPrivateNetwork: true } : {}),
79
+ ...(auth.proxy !== undefined ? { proxy: auth.proxy } : {}),
80
+ ...(auth.noProxy !== undefined ? { noProxy: auth.noProxy } : {}),
81
+ };
82
+ }
83
+
84
+ function outboundDependencies(dependencies: VideoOutboundDependencies): ProviderOutboundDependencies {
85
+ return {
86
+ ...dependencies,
87
+ isCanonicalUrl: isCanonicalXaiVideoUrl,
88
+ // A self-hosted http video service is reachable only on localhost or a local address
89
+ // literal, and only when the row itself sets allowPrivateNetwork (see provider-outbound).
90
+ allowLocalCleartextPost: true,
91
+ // The poll GET sends the bearer key too, so it gets exactly the submit POST's cleartext rules:
92
+ // a public answer for an http host, or a proxied http route, is refused before any send.
93
+ cleartextPolicy: "credentialed",
94
+ };
95
+ }
96
+
33
97
  /** Maximum response body size for the submit and poll calls (responses are small JSON). */
34
98
  const MAX_RESPONSE_BYTES = 1024 * 1024; // 1 MiB — these endpoints return small JSON
35
99
 
@@ -64,8 +128,9 @@ async function readBoundedText(resp: Response): Promise<string> {
64
128
  */
65
129
  export async function submitVideoJob(
66
130
  req: XaiVideoSubmitRequest,
67
- auth: { baseUrl: string; token: string },
131
+ auth: VideoProviderAuth,
68
132
  signal?: AbortSignal,
133
+ dependencies: VideoOutboundDependencies = {},
69
134
  ): Promise<XaiVideoSubmitResult> {
70
135
  const body: Record<string, unknown> = {
71
136
  model: req.model ?? DEFAULT_VIDEO_MODEL,
@@ -78,16 +143,14 @@ export async function submitVideoJob(
78
143
  const timeout = AbortSignal.timeout(SUBMIT_TIMEOUT_MS);
79
144
  const linkedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
80
145
 
81
- const resp = await fetch(`${auth.baseUrl}/videos/generations`, {
82
- method: "POST",
83
- redirect: "manual",
146
+ const resp = await providerOutboundPost(auth.providerName, outboundConfig(auth), `${auth.baseUrl}/videos/generations`, {
84
147
  headers: {
85
148
  "Authorization": `Bearer ${auth.token}`,
86
149
  "Content-Type": "application/json",
87
150
  },
88
151
  body: JSON.stringify(body),
89
152
  signal: linkedSignal,
90
- });
153
+ }, outboundDependencies(dependencies));
91
154
 
92
155
  if (!resp.ok) {
93
156
  try { await resp.body?.cancel(); } catch { /* ignore */ }
@@ -111,20 +174,19 @@ export async function submitVideoJob(
111
174
  */
112
175
  export async function pollVideoJob(
113
176
  requestId: string,
114
- auth: { baseUrl: string; token: string },
177
+ auth: VideoProviderAuth,
115
178
  signal?: AbortSignal,
179
+ dependencies: VideoOutboundDependencies = {},
116
180
  ): Promise<XaiVideoPollResult> {
117
181
  const timeout = AbortSignal.timeout(POLL_TIMEOUT_MS);
118
182
  const linkedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
119
183
 
120
- const resp = await fetch(`${auth.baseUrl}/videos/${encodeURIComponent(requestId)}`, {
121
- method: "GET",
122
- redirect: "manual",
184
+ const resp = await providerOutboundGet(auth.providerName, outboundConfig(auth), `${auth.baseUrl}/videos/${encodeURIComponent(requestId)}`, {
123
185
  headers: {
124
186
  "Authorization": `Bearer ${auth.token}`,
125
187
  },
126
188
  signal: linkedSignal,
127
- });
189
+ }, outboundDependencies(dependencies));
128
190
 
129
191
  if (!resp.ok) {
130
192
  try { await resp.body?.cancel(); } catch { /* ignore */ }
@@ -1,5 +1,6 @@
1
1
  import { CYBER_POLICY_FALLBACK_MESSAGE, classifyError } from "./errors";
2
2
  import { classifyUpstreamCondition, upstreamConditionMessage, type UpstreamConditionEvidence } from "./upstream-condition";
3
+ import { isDeveloperRoleRejection } from "./developer-role-rejection";
3
4
 
4
5
  const openaiTypes = ["invalid_request_error", "authentication_error", "permission_error", "not_found_error", "rate_limit_error", "server_error", "upstream_error", "insufficient_quota", "client_cancelled", "cyber_policy", "model_not_allowed_for_key", "api_error", "overloaded_error"] as const;
5
6
  const openaiCodes = [
@@ -42,6 +43,8 @@ export const CLIENT_ERROR_CONTRACTS = {
42
43
  stream_incomplete: "The provider stream ended before the request completed.",
43
44
  } as const;
44
45
  export type ClientErrorContract = keyof typeof CLIENT_ERROR_CONTRACTS;
46
+ /** A provider rejected the `developer` role (#8864); the proxy's own wording, never the provider's. */
47
+ export const DEVELOPER_ROLE_REFUSAL_MESSAGE = "The provider does not accept the developer message role. Send these instructions as a system message, or set foldDeveloperRoleToSystem: true on this provider; retrying this request unchanged will not succeed.";
45
48
  export const UNDECLARED_TOOL_CALL_MESSAGE = "routed provider emitted undeclared client tool; only request-declared tools may be called";
46
49
  /** Only producers of synthetic incomplete events register these process-local origins. */
47
50
  type ProxyIncompleteReason = "adapter_eof" | "upstream_stall_timeout" | "missing_terminal_event";
@@ -138,6 +141,9 @@ export function actionableRefusalMessage(
138
141
  const structured = typeof evidence.code === "string" && evidence.code.length <= 64
139
142
  ? evidence.code.trim().toUpperCase().replaceAll("-", "_") : undefined;
140
143
  if (structured !== undefined && ACTIONABLE_REFUSALS.has(structured)) return ACTIONABLE_REFUSALS.get(structured);
144
+ // A role rejection travels as a plain invalid request, so it is read before the carrier gate.
145
+ if (contract === undefined && (code === null || code === "invalid_request_error")
146
+ && isDeveloperRoleRejection(evidence.status, evidence.message)) return DEVELOPER_ROLE_REFUSAL_MESSAGE;
141
147
  if (code === null || !REFUSAL_CARRIER_CODES.has(code) || typeof evidence.message !== "string") return undefined;
142
148
  const scanned = evidence.message.slice(0, REFUSAL_TOKEN_SCAN);
143
149
  for (const [token, message] of ACTIONABLE_REFUSALS) {
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Whether an upstream 4xx says the provider rejects the `developer` message role (#8864).
3
+ *
4
+ * Read only through fixed lowercase phrases that name the role itself; nothing from the message is
5
+ * returned or stored. Each phrase is a provider's own wording: DashScope compatible-mode (#5664),
6
+ * Moonshot (#7583) and serde-based gateways. Any other 400 stays a plain request rejection.
7
+ */
8
+ const MAX_SCAN = 4096;
9
+ const PHRASES = ["developer is not one of", "role 'developer' is not allowed", "unknown variant `developer`"] as const;
10
+
11
+ export function isDeveloperRoleRejection(status: number | undefined, message: unknown): boolean {
12
+ if (typeof status !== "number" || status < 400 || status >= 500 || typeof message !== "string") return false;
13
+ const scanned = message.slice(0, MAX_SCAN).toLowerCase();
14
+ return PHRASES.some(phrase => scanned.includes(phrase));
15
+ }
@@ -60,6 +60,19 @@ export function gcpCredentialMarkerAccount(value: string | undefined): string |
60
60
  return account;
61
61
  }
62
62
 
63
+ export type VertexConfiguredCredentialKind = "marker" | "ambient" | "reference" | "api-key";
64
+
65
+ /**
66
+ * Classify a Vertex row's configured `apiKey` text without resolving it, so no caller has to read a
67
+ * keychain or the environment just to learn which kind of credential the row names. The management
68
+ * DTO and the static-catalog connection test share this one rule.
69
+ */
70
+ export function vertexConfiguredCredentialKind(key: string | undefined): VertexConfiguredCredentialKind {
71
+ if (key?.startsWith(GCP_CREDENTIAL_MARKER_PREFIX)) return "marker";
72
+ if (!key?.trim() || key === "N/A" || key.startsWith("<")) return "ambient";
73
+ return key.startsWith("keychain:") || /^\$\{?\w+\}?$/.test(key) ? "reference" : "api-key";
74
+ }
75
+
63
76
  /**
64
77
  * Whether a pasted API-key value is in fact a GCP credential JSON. Used by the save path to
65
78
  * divert JSON material out of the literal-key flow before it reaches `config.json`. Deliberately
@@ -125,6 +138,18 @@ const sourceObservations = new Map<string, { source: string; generation: number
125
138
  let sourceEpoch = 0;
126
139
  let lastReconciledGeneration = 0;
127
140
  let liveSources = new Set<string>();
141
+ // Last token exchange that succeeded, per credential scope. Proof the dashboard can show without a
142
+ // network call; it lapses on its own once the source the next resolve would use changes.
143
+ const verifiedSources = new Map<string, { source: string; generation: number }>();
144
+ const adcScope = (markerAccount: string | undefined) => markerAccount ? `marker:${markerAccount}` : "host";
145
+
146
+ /** True when this process minted a token from the credential source the next request would use. */
147
+ export function vertexAdcCredentialVerified(markerAccount?: string): boolean {
148
+ const verified = verifiedSources.get(adcScope(markerAccount));
149
+ if (!verified) return false;
150
+ const current = observeAdcSource(markerAccount);
151
+ return current.source === verified.source && current.generation === verified.generation;
152
+ }
128
153
 
129
154
  export function sweepExpiredGcpAdcTokens(now = Date.now()): number {
130
155
  const skew = getRefreshSkewMs();
@@ -244,7 +269,7 @@ function currentAdcSourceKey(markerAccount: string | undefined): string {
244
269
 
245
270
  /** Every observed source transition gets a fresh incarnation, including A→B→A. */
246
271
  function observeAdcSource(markerAccount: string | undefined): { source: string; generation: number } {
247
- const scope = markerAccount ? `marker:${markerAccount}` : "host";
272
+ const scope = adcScope(markerAccount);
248
273
  const source = currentAdcSourceKey(markerAccount);
249
274
  const previous = sourceObservations.get(scope);
250
275
  if (previous?.source === source) return previous;
@@ -394,8 +419,13 @@ async function resolveAccessTokenUncached(markerAccount: string | undefined, sig
394
419
  );
395
420
  }
396
421
 
397
- /** Returns a Bearer access token for the `Authorization` header on Vertex AI calls (cached + refreshed). */
398
- export async function getVertexAccessTokenWithAuthority(options?: { signal?: AbortSignal; fetch?: FetchImpl; markerAccount?: string; beforeSend?: () => void }): Promise<VertexTokenAuthority> {
422
+ /**
423
+ * Returns a Bearer access token for the `Authorization` header on Vertex AI calls (cached + refreshed).
424
+ * `forceExchange` skips the completed-token cache so the caller observes a real exchange: the
425
+ * connection test uses it, because a cached token outlives a revoked refresh credential. It still
426
+ * joins an exchange already in flight and refreshes the cache on success; other callers keep the cache.
427
+ */
428
+ export async function getVertexAccessTokenWithAuthority(options?: { signal?: AbortSignal; fetch?: FetchImpl; markerAccount?: string; beforeSend?: () => void; forceExchange?: boolean }): Promise<VertexTokenAuthority> {
399
429
  // The marker travels as an argument, never as process-global state: a module-level "active
400
430
  // marker" written by the router would race across concurrent requests for different providers
401
431
  // and could resolve one provider's Vertex call with another provider's service account. The
@@ -418,7 +448,7 @@ export async function getVertexAccessTokenWithAuthority(options?: { signal?: Abo
418
448
  }
419
449
  const writerGeneration = captureConfigGeneration();
420
450
  for (const [source, cached] of tokenCache) {
421
- if (source === expectedSource && cached.generation === expected.generation && cached.expiresAtMs - skew > now) {
451
+ if (!options?.forceExchange && source === expectedSource && cached.generation === expected.generation && cached.expiresAtMs - skew > now) {
422
452
  return { token: cached.token, source, generation: expected.generation, markerAccount };
423
453
  }
424
454
  if (cached.expiresAtMs - skew <= now) tokenCache.delete(source);
@@ -449,12 +479,25 @@ export async function getVertexAccessTokenWithAuthority(options?: { signal?: Abo
449
479
  if (source !== expectedSource || current.source !== source || current.generation !== expected.generation) {
450
480
  throw new Error("Vertex ADC source changed during token exchange");
451
481
  }
482
+ if (typeof token.access_token !== "string" || !token.access_token) {
483
+ throw new Error("Google OAuth token response has no access_token");
484
+ }
452
485
  const expiresAtMs = Date.now() + Math.max(0, token.expires_in * 1000);
453
486
  if (writerGeneration >= lastReconciledGeneration || liveSources.has(source)) {
454
487
  tokenCache.set(source, { token: token.access_token, expiresAtMs, generation: expected.generation });
455
488
  sweepExpiredOnWrite(Date.now());
456
489
  }
490
+ verifiedSources.set(adcScope(markerAccount), { source, generation: expected.generation });
457
491
  return { token: token.access_token, source, generation: expected.generation, markerAccount };
492
+ } catch (error) {
493
+ // Drop only this exchange's own proof: a newer exchange for a changed source may already
494
+ // have recorded its success under the same scope, and that proof still holds.
495
+ const scope = adcScope(markerAccount);
496
+ const verified = verifiedSources.get(scope);
497
+ if (!controller.signal.aborted && verified?.source === expectedSource && verified.generation === expected.generation) {
498
+ verifiedSources.delete(scope);
499
+ }
500
+ throw error;
458
501
  } finally {
459
502
  owned.settled = true;
460
503
  if (inflight.get(cacheKey) === owned) inflight.delete(cacheKey);
@@ -538,6 +581,7 @@ export function vertexRequestAuthorityIsCurrent(request: object, target?: string
538
581
 
539
582
  /** Test seam: restores complete process-local token and reconciliation state. */
540
583
  export function __resetVertexTokenCache(): void {
584
+ verifiedSources.clear();
541
585
  tokenCache.clear();
542
586
  for (const entry of inflight.values()) entry.controller.abort();
543
587
  inflight.clear();
@@ -0,0 +1,150 @@
1
+ import { lookup } from "node:dns/promises";
2
+ import { isIP } from "node:net";
3
+ import type { OcxProviderConfig } from "../types";
4
+ import { isEgressTransparentExecutor, resolveProviderEgress } from "./provider-egress";
5
+ import { effectiveProxyFor, noProxyMatches } from "./proxy-env";
6
+ import { UpstreamRetryEvidenceError } from "./upstream-retry";
7
+
8
+ /** Longest configurable offline wait (#7958): five minutes, the span of a laptop sleep/Wi-Fi hop. */
9
+ export const MAX_OFFLINE_RESEND_WAIT_SEC = 300;
10
+ /** Interval between reachability probes while offline. */
11
+ export const OFFLINE_REACHABILITY_PROBE_INTERVAL_MS = 1_000;
12
+
13
+ /**
14
+ * Only a DNS resolution failure qualifies (#7958): DNS answering again is exactly the evidence that
15
+ * failure lacked. A refused or unreachable connection would resend into the same failure, and with
16
+ * an outbound proxy a direct reachability probe would not test the path the request takes.
17
+ */
18
+ const DNS_FAILURE_CODES = new Set(["ENOTFOUND", "EAI_AGAIN"]);
19
+ const MAX_CAUSE_DEPTH = 3;
20
+
21
+ /** A DNS resolution failure, read from `code` through a bounded cause chain; never from message text. */
22
+ export function isDnsResolutionFailure(error: unknown): boolean {
23
+ let current: unknown = error instanceof UpstreamRetryEvidenceError ? undefined : error;
24
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && current instanceof Error; depth++) {
25
+ const code = (current as { code?: unknown }).code;
26
+ if (typeof code === "string" && DNS_FAILURE_CODES.has(code)) return true;
27
+ current = current.cause;
28
+ }
29
+ return false;
30
+ }
31
+
32
+ /**
33
+ * Decides, at most once per logical request, whether a pre-connect failure may be resent after
34
+ * the destination became reachable again. Returns false for every later call, and never rejects
35
+ * with the abort reason: a cancelled wait answers false so the caller keeps the original failure.
36
+ */
37
+ export type OfflineResendWait = (error: unknown, signal?: AbortSignal) => Promise<boolean>;
38
+
39
+ export interface OfflineResendDependencies {
40
+ /** Resolves when the host resolves; rejects while it does not. */
41
+ resolveHost?: (hostname: string) => Promise<unknown>;
42
+ /** Abortable delay between probes. */
43
+ delay?: (ms: number, signal?: AbortSignal) => Promise<void>;
44
+ /** Abortable timer that ends a probe still pending when the wait runs out. */
45
+ expire?: (ms: number, signal?: AbortSignal) => Promise<void>;
46
+ now?: () => number;
47
+ }
48
+
49
+ let testDependencies: OfflineResendDependencies | undefined;
50
+
51
+ /** Test-only seam for the DNS probe, delay and clock; `undefined` restores the real ones. */
52
+ export function setOfflineResendDependenciesForTests(dependencies: OfflineResendDependencies | undefined): void {
53
+ testDependencies = dependencies;
54
+ }
55
+
56
+ /** The configured wait in milliseconds, or 0 when the opt-in is off or malformed. */
57
+ export function resolveOfflineResendWaitMs(configuredSec: unknown): number {
58
+ if (typeof configuredSec !== "number" || !Number.isFinite(configuredSec) || configuredSec <= 0) return 0;
59
+ return Math.ceil(Math.min(configuredSec, MAX_OFFLINE_RESEND_WAIT_SEC) * 1_000);
60
+ }
61
+
62
+ /**
63
+ * Opt-in offline wait for one request (#7958). After a send fails because the destination's name
64
+ * did not resolve (`isDnsResolutionFailure`), poll its DNS until it resolves or `maxWaitMs` passes,
65
+ * then allow one resend. An IP-literal destination never qualifies: DNS proves nothing about it.
66
+ * Nothing was delivered, so the resend cannot repeat an upstream effect; the caller's send budget
67
+ * still counts it. A rejection that is not pre-connect, a second failure, an exhausted wait or a
68
+ * client abort returns the original failure. A client abort answers false rather than throwing:
69
+ * the abort reason would replace the DNS error, and a Codex pool send would then classify a
70
+ * host-wide `connect_neutral` failure as account-attributed `connect_error`.
71
+ */
72
+ export function createOfflineResendWait(url: string, maxWaitMs: number): OfflineResendWait | undefined {
73
+ if (!(maxWaitMs > 0)) return undefined;
74
+ let hostname: string;
75
+ try { hostname = new URL(url).hostname.replace(/^\[|\]$/g, ""); } catch { return undefined; }
76
+ if (isIP(hostname) !== 0) return undefined;
77
+ let claimed = false;
78
+ return async (error, signal) => {
79
+ if (claimed || !isDnsResolutionFailure(error)) return false;
80
+ claimed = true;
81
+ const deps = testDependencies ?? {};
82
+ const resolveHost = deps.resolveHost ?? ((host: string) => lookup(host));
83
+ const delay = deps.delay ?? abortableDelay;
84
+ const expire = deps.expire ?? abortableDelay;
85
+ const now = deps.now ?? Date.now;
86
+ const deadline = now() + maxWaitMs;
87
+ for (;;) {
88
+ if (signal?.aborted) return false;
89
+ let remaining = deadline - now();
90
+ if (remaining <= 0) return false;
91
+ // A stalled system resolver must not outlive the wait or the client: race each probe against
92
+ // the remaining budget and cancellation, and accept a success only inside the budget. An
93
+ // expiry that rejects (cancellation) ends the wait the same way as one that fires.
94
+ const settle = new AbortController();
95
+ const raceSignal = signal ? AbortSignal.any([signal, settle.signal]) : settle.signal;
96
+ const expiry = new Promise<void>(resolve => resolve(expire(remaining, raceSignal)))
97
+ .then(() => "expired" as const, () => "expired" as const);
98
+ const probe = new Promise(resolve => resolve(resolveHost(hostname))).then(() => true, () => false);
99
+ let outcome: boolean | "expired";
100
+ try { outcome = await Promise.race([probe, expiry]); } finally { settle.abort(); }
101
+ if (outcome === "expired" || signal?.aborted) return false;
102
+ if (outcome) return now() <= deadline;
103
+ remaining = deadline - now();
104
+ if (remaining <= 0) return false;
105
+ try { await delay(Math.min(OFFLINE_REACHABILITY_PROBE_INTERVAL_MS, remaining), signal); } catch { return false; }
106
+ }
107
+ };
108
+ }
109
+
110
+ function abortableDelay(ms: number, signal?: AbortSignal): Promise<void> {
111
+ if (signal?.aborted) return Promise.reject(signal.reason);
112
+ return new Promise<void>((resolve, reject) => {
113
+ const onAbort = () => { clearTimeout(timer); reject(signal?.reason); };
114
+ const timer = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms);
115
+ signal?.addEventListener("abort", onAbort, { once: true });
116
+ });
117
+ }
118
+
119
+ /**
120
+ * The URL whose name the provider's send actually resolves, or `undefined` when that is unknown.
121
+ * A proxied send resolves the proxy's name, and its DNS failure is the proxy's, so the wait probes
122
+ * the proxy; probing the provider instead could resend into a proxy that still fails, or wait out
123
+ * a provider name only the proxy can resolve. The route follows `configuredOutboundFetch`: the
124
+ * provider's own `proxy`/`noProxy` first, then the global proxy unless `NO_PROXY` exempts the URL.
125
+ * A caller-supplied executor picks its own transport, so it gets no probe; OpenCodex's own wrappers
126
+ * (xAI, Mistral Chat) carry the egress-transparent mark because they send through that same route.
127
+ * A malformed route fails the send anyway.
128
+ */
129
+ export function offlineResendProbeUrl(providerName: string, provider: OcxProviderConfig, url: string): string | undefined {
130
+ const executor = (provider as { fetch?: unknown }).fetch;
131
+ if (typeof executor === "function" && !isEgressTransparentExecutor(executor)) return undefined;
132
+ let target: URL;
133
+ try { target = new URL(url); } catch { return undefined; }
134
+ let egress: ReturnType<typeof resolveProviderEgress>;
135
+ try { egress = resolveProviderEgress({ providerName, provider, url: target }); } catch { return undefined; }
136
+ if (egress.kind === "proxy") return egress.proxyUrl;
137
+ if (egress.kind === "direct") return url;
138
+ const globalProxy = effectiveProxyFor(target);
139
+ return globalProxy !== null && !noProxyMatches(target) ? globalProxy : url;
140
+ }
141
+
142
+ /** The request's offline waiter (#7958), probing the name its send resolves; `undefined` when off. */
143
+ export function createProviderOfflineResendWait(
144
+ providerName: string, provider: OcxProviderConfig, url: string, configuredSec: unknown,
145
+ ): OfflineResendWait | undefined {
146
+ const maxWaitMs = resolveOfflineResendWaitMs(configuredSec);
147
+ if (maxWaitMs <= 0) return undefined;
148
+ const probeUrl = offlineResendProbeUrl(providerName, provider, url);
149
+ return probeUrl === undefined ? undefined : createOfflineResendWait(probeUrl, maxWaitMs);
150
+ }
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Pacing that travels with a stream (#8601).
3
3
  *
4
- * A Remote Link turn while the link WebSocket feature is on reads its upstream body only as its client drains. Each
5
- * relay stage between the upstream and the client normally keeps one chunk queued ahead of its reader; a stage whose
6
- * source is paced queues none instead and marks its own output, so the whole chain pulls on demand. Streams that were
4
+ * Every relayed Remote Link turn reads its upstream body only as its client drains, with or without the link WebSocket
5
+ * feature. Each relay stage between the upstream and the client normally keeps one chunk queued ahead of its reader; a
6
+ * stage whose source is paced queues none instead and marks its own output, so the whole chain pulls on demand. Streams that were
7
7
  * never marked keep their default queue: every other request is unchanged.
8
8
  */
9
9
  const paced = new WeakSet<ReadableStream<Uint8Array>>();
@@ -32,7 +32,8 @@ export interface ProviderOutboundDependencies {
32
32
  /** Recheck caller-owned credential authority after DNS and immediately before transport. */
33
33
  beforeSend?: () => boolean;
34
34
  /**
35
- * Caller opt-in for a cleartext `http:` POST to a self-hosted service. Honoured only when the
35
+ * Caller opt-in for a cleartext `http:` POST (or credentialed GET, see `cleartextPolicy`) to a
36
+ * self-hosted service. Honoured only when the
36
37
  * URL host is exactly `localhost` or an address literal in the narrow local allowlist
37
38
  * (`localCleartextAddressAllowed`) AND the provider row itself sets `allowPrivateNetwork: true`
38
39
  * (a registry default does not count). Every resolved answer must stay inside the same
@@ -40,6 +41,13 @@ export interface ProviderOutboundDependencies {
40
41
  * LAN. Every other destination keeps the HTTPS-only POST gate. Defaults to refusing.
41
42
  */
42
43
  allowLocalCleartextPost?: boolean;
44
+ /**
45
+ * Which requests the cleartext rules above bind. A POST always obeys them. `"credentialed"`
46
+ * also holds a GET to them, for a caller whose GET carries the same credential as its POST (the
47
+ * video poll): HTTPS, or the local cleartext opt-in with its allowlisted answers and direct
48
+ * route. Without it a GET keeps the discovery behaviour, which admits `http:`.
49
+ */
50
+ cleartextPolicy?: "credentialed";
43
51
  }
44
52
 
45
53
  function ipv4Octets(address: string): number[] | null {
@@ -234,10 +242,13 @@ async function providerOutboundRequest(
234
242
  const assertSendAllowed = () => {
235
243
  if (dependencies.beforeSend?.() === false) throw new ProviderOutboundSendCancelledError("provider credential changed before send");
236
244
  };
237
- const postUrl = method === "POST" ? new URL(url) : undefined;
245
+ // A POST, and a GET whose caller declared it carries the POST's credential, must not cross the
246
+ // network in cleartext. The messages name a GET explicitly so a refusal says which call failed.
247
+ const label = method === "POST" ? "POST" : "credentialed GET";
248
+ const postUrl = method === "POST" || dependencies.cleartextPolicy === "credentialed" ? new URL(url) : undefined;
238
249
  if (postUrl?.protocol !== undefined && postUrl.protocol !== "https:"
239
250
  && !localCleartextPostAllowed(provider, postUrl, dependencies)) {
240
- throw new ProviderOutboundPolicyError("provider POST URL must use HTTPS");
251
+ throw new ProviderOutboundPolicyError(`provider ${label} URL must use HTTPS`);
241
252
  }
242
253
  // Only reachable after the narrow opt-in above admitted it.
243
254
  const localCleartextPost = postUrl?.protocol === "http:";
@@ -248,7 +259,7 @@ async function providerOutboundRequest(
248
259
  if (typeof provider.fetch === "function") {
249
260
  // An executor resolves names itself, so a cleartext POST through one must name an address.
250
261
  if (localCleartextPost && !isIP(unbracketedHostname(postUrl!))) {
251
- throw new ProviderOutboundPolicyError("a cleartext provider POST through a caller-supplied executor must use an address literal");
262
+ throw new ProviderOutboundPolicyError(`a cleartext provider ${label} through a caller-supplied executor must use an address literal`);
252
263
  }
253
264
  // A caller-owned executor decides its own transport, so a provider egress route cannot be
254
265
  // applied to it. Refusing is the only honest answer: running the executor anyway would send
@@ -310,7 +321,7 @@ async function providerOutboundRequest(
310
321
  // the DNS-failure proxy degradation below, which needs one) would carry it off-host unencrypted.
311
322
  if (localCleartextPost && proxyApplies) {
312
323
  throw new ProviderOutboundPolicyError(
313
- `a cleartext provider POST cannot use an outbound proxy; add ${normalizeProxyHostname(parsed.hostname)} to NO_PROXY`,
324
+ `a cleartext provider ${label} cannot use an outbound proxy; add ${normalizeProxyHostname(parsed.hostname)} to NO_PROXY`,
314
325
  );
315
326
  }
316
327
  const isCanonicalUrl = dependencies.isCanonicalUrl ?? (() => false);
@@ -390,7 +401,7 @@ async function providerOutboundRequest(
390
401
  }
391
402
  if (localCleartextPost
392
403
  && !resolved.addresses.every(answer => localCleartextAddressAllowed(answer.address))) {
393
- throw new ProviderOutboundPolicyError("a cleartext provider POST resolved outside the local address allowlist");
404
+ throw new ProviderOutboundPolicyError(`a cleartext provider ${label} resolved outside the local address allowlist`);
394
405
  }
395
406
  const requestOptions = {
396
407
  headers: init.headers,
@@ -216,6 +216,8 @@ const RECOVERY_KIND_CAUSE = {
216
216
  // turn. One kind cannot say both, so it says the weaker thing.
217
217
  "transient-5xx": "upstream-fault",
218
218
  "connection-reset": "transport-ambiguous",
219
+ // The send it replaced failed DNS resolution, so those bytes provably never left (#7958).
220
+ "offline-resend": "transport-unsent",
219
221
  "oauth-401": "credential-rejected",
220
222
  "oauth-account-403": "credential-rejected",
221
223
  "key-401": "credential-rejected",
@@ -11,6 +11,25 @@ export class ResponseBodyInactivityError extends DOMException {
11
11
  }
12
12
  }
13
13
 
14
+ /**
15
+ * The same expiry from a guard armed by the operator's explicit `stallTimeoutSec` (#8206). Only this
16
+ * one reaches clients as `upstream_stall_timeout`; a guard on a default budget keeps its old terminal.
17
+ */
18
+ export class ExplicitBodyStallError extends ResponseBodyInactivityError {}
19
+
20
+ // Published responses whose upstream reads already run under a positive inactivity guard.
21
+ const guardedResponses = new WeakSet<Response>();
22
+
23
+ /** Record that `response` relays bytes from guarded upstream reads, so no second clock is armed. */
24
+ export function markResponseBodyInactivityGuarded(response: Response): Response {
25
+ guardedResponses.add(response);
26
+ return response;
27
+ }
28
+
29
+ export function isResponseBodyInactivityGuarded(response: Response): boolean {
30
+ return guardedResponses.has(response);
31
+ }
32
+
14
33
  /**
15
34
  * Bound silence only while the consumer is waiting for upstream bytes.
16
35
  *
@@ -23,13 +42,16 @@ export function guardResponseBodyInactivity(
23
42
  response: Response,
24
43
  signal: AbortSignal | undefined,
25
44
  timeoutMs: number,
45
+ options: { explicitBudget?: boolean } = {},
26
46
  ): ResponseBodyInactivityGuard {
27
47
  const source = response.body;
28
48
  if (!source) return { response, dispose: () => {} };
29
49
 
30
50
  const reader = source.getReader();
31
51
  const timeoutEnabled = Number.isFinite(timeoutMs) && timeoutMs > 0;
32
- const timeoutError = new ResponseBodyInactivityError(timeoutMs);
52
+ const timeoutError = options.explicitBudget === true
53
+ ? new ExplicitBodyStallError(timeoutMs)
54
+ : new ResponseBodyInactivityError(timeoutMs);
33
55
  let output!: ReadableStreamDefaultController<Uint8Array>;
34
56
  let settled = false;
35
57
  let timer: ReturnType<typeof setTimeout> | undefined;