@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.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 (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +289 -0
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +115 -3
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,2929 @@
1
+ /**
2
+ * fiche proxy as a single Web-standard fetch handler.
3
+ * Adapted by src/node.ts and src/worker.ts; uses only Request/Response/URL/fetch.
4
+ */
5
+ import { readBrandEnv } from './env.js';
6
+ import { markCacheDead, noteCacheOutcome, responseLeftNoCache } from './session-state.js';
7
+ import { transformRequest } from './transform.js';
8
+ import { isClaudeModel, transformOpenAIChatCompletions, transformOpenAIResponses } from './openai.js';
9
+ import { isAnthropicMessagesPath, isInConfiguredModelBases, isInklingSupportedGptModel, isInklingSupportedModel, } from './applicability.js';
10
+ import { buildBaselineCountTokensBody, buildCacheablePrefixCountTokensBody, isThreadContinuation, } from './measurement.js';
11
+ import { redactSecrets } from './tracker.js';
12
+ import { anthropicMessagesToOpenAIResponses, openAIResponsesToAnthropicResponse, } from './messages-responses-bridge.js';
13
+ import { anthropicMessagesToOpenAIChat, chatCompletionsUrl, openAIChatToAnthropicResponse, } from './messages-chat-bridge.js';
14
+ import { pinCommandResponse, pinCommandResponseOpenAI } from './pin.js';
15
+ import { withClientToolRoundShape } from './client-tool-round.js';
16
+ import { isGoogleInferencePath, parseGoogleModelFromPath, transformGoogleGenerateContent } from './google.js';
17
+ import { isGeminiModel } from './gemini-model-profiles.js';
18
+ import { resolveGptProfile } from './gpt-model-profiles.js';
19
+ import { scrubPromptCacheBreakpoint, supportsExplicitPromptCacheBreakpoint } from './codex-cache.js';
20
+ import { DEFAULT_UPSTREAM_REGISTRY, isFollowRefusal, refuseUnfollowedProviderHost, resolveFollowTarget, } from './upstream-hosts.js';
21
+ import { shouldImageModel } from './reader-tier.js';
22
+ import { resolveTextHygieneMode } from './text-hygiene.js';
23
+ export { parseTrustAdjacentToolRounds, resolveTrustAdjacentToolRoundsEnv, withClientToolRoundShape, } from './client-tool-round.js';
24
+ /** Max chars of 4xx error body captured on ProxyEvent — enough for Anthropic's full error JSON. */
25
+ const ERROR_BODY_MAX = 2048;
26
+ /** Disabled by default (0): upstream and client control request/stream timeouts. */
27
+ const DEFAULT_UPSTREAM_HEADERS_TIMEOUT_MS = 0;
28
+ const DEFAULT_UPSTREAM_IDLE_TIMEOUT_MS = 0;
29
+ /** Past this, an in-flight entry is treated as stale and a retry is let through. */
30
+ const DEFAULT_DUPLICATE_HOLD_MS = 60_000;
31
+ /**
32
+ * Budget for a count-tokens probe. Both probes fail closed (null keeps the original
33
+ * body), so expiring one costs that request's savings, never correctness. The Google
34
+ * pair is awaited before the forward, so this is worst-case added latency; the
35
+ * Anthropic pair only feeds telemetry.
36
+ *
37
+ * Neither provider publishes a latency SLO for count-tokens, and we have no probe
38
+ * timing of our own, so this is not a measured figure. It is bounded by the one number
39
+ * we do have: p99 time-to-headers for a full generation on the same route (30s over
40
+ * 2166 Gemini requests in our telemetry). A probe does strictly less work than
41
+ * first-token generation, so one that misses that mark is wedged rather than slow.
42
+ */
43
+ const COUNT_TOKENS_TIMEOUT_MS = 30_000;
44
+ /** Sweep the in-flight map early once it grows past plausible real concurrency. */
45
+ const INFLIGHT_SWEEP_SIZE = 256;
46
+ /** Floor between size-triggered sweeps so genuine high concurrency stays O(1)/request. */
47
+ const INFLIGHT_SWEEP_MIN_INTERVAL_MS = 1_000;
48
+ function combineAbortSignals(timeoutMs, parent) {
49
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
50
+ if (!parent)
51
+ return timeoutSignal;
52
+ if (typeof AbortSignal.any === 'function') {
53
+ return AbortSignal.any([timeoutSignal, parent]);
54
+ }
55
+ if (parent.aborted)
56
+ return parent;
57
+ const ac = new AbortController();
58
+ const onParent = () => {
59
+ timeoutSignal.removeEventListener('abort', onTimeout);
60
+ ac.abort(parent.reason);
61
+ };
62
+ const onTimeout = () => {
63
+ parent.removeEventListener('abort', onParent);
64
+ ac.abort(timeoutSignal.reason);
65
+ };
66
+ parent.addEventListener('abort', onParent, { once: true });
67
+ timeoutSignal.addEventListener('abort', onTimeout, { once: true });
68
+ return ac.signal;
69
+ }
70
+ /**
71
+ * Abort the response if no chunk arrives for `ms`. Wraps the raw upstream stream so
72
+ * the watchdog sees real network activity rather than post-transform output.
73
+ */
74
+ function withIdleTimeout(res, firstChunkMs, ms, onIdle) {
75
+ if (!res.body || ms <= 0)
76
+ return res;
77
+ let timer;
78
+ const clear = () => {
79
+ if (timer !== undefined) {
80
+ clearTimeout(timer);
81
+ timer = undefined;
82
+ }
83
+ };
84
+ // The watchdog errors its own controller rather than relying on the fetch
85
+ // implementation to tear the body down when the signal aborts.
86
+ let ctl;
87
+ const arm = (budget) => {
88
+ clear();
89
+ timer = setTimeout(() => {
90
+ timer = undefined;
91
+ onIdle();
92
+ try {
93
+ ctl?.error(new Error(`fiche: upstream stalled for ${budget}ms`));
94
+ }
95
+ catch {
96
+ /* already errored or closed */
97
+ }
98
+ }, budget);
99
+ };
100
+ const watched = res.body.pipeThrough(new TransformStream({
101
+ start(controller) {
102
+ ctl = controller;
103
+ // Nothing has streamed yet: the model may still be starting up, which is the
104
+ // same wait the headers budget covers. Real traffic has taken >120s just to
105
+ // return headers (max 146s over 41k requests), so charging the mid-stream idle
106
+ // budget here would abort healthy slow starts.
107
+ arm(firstChunkMs > 0 ? firstChunkMs : ms);
108
+ },
109
+ transform(chunk, controller) {
110
+ // Bytes have flowed: from here a long silence means wedged, not slow.
111
+ arm(ms);
112
+ controller.enqueue(chunk);
113
+ },
114
+ flush() {
115
+ clear();
116
+ },
117
+ }));
118
+ // Wrap readable so consumer cancel() clears any pending idle watchdog immediately.
119
+ const watchedReader = watched.getReader();
120
+ const guardedBody = new ReadableStream({
121
+ async pull(controller) {
122
+ try {
123
+ const { done, value } = await watchedReader.read();
124
+ if (done) {
125
+ clear();
126
+ controller.close();
127
+ return;
128
+ }
129
+ controller.enqueue(value);
130
+ }
131
+ catch (err) {
132
+ clear();
133
+ controller.error(err);
134
+ }
135
+ },
136
+ cancel(reason) {
137
+ clear();
138
+ return watchedReader.cancel(reason).catch(() => undefined);
139
+ },
140
+ });
141
+ return new Response(guardedBody, {
142
+ status: res.status,
143
+ statusText: res.statusText,
144
+ headers: res.headers,
145
+ });
146
+ }
147
+ /**
148
+ * Passthrough that notifies on client disconnect. `cancel` deliberately does not await
149
+ * the inner cancel: with a wedged upstream that call can hang, which would in turn hang
150
+ * the caller's `body.cancel()`.
151
+ */
152
+ function withClientDisconnect(body, onCancel, onDone) {
153
+ const reader = body.getReader();
154
+ let settled = false;
155
+ const finish = () => {
156
+ if (!settled) {
157
+ settled = true;
158
+ onDone?.();
159
+ }
160
+ };
161
+ return new ReadableStream({
162
+ async pull(controller) {
163
+ try {
164
+ const { done, value } = await reader.read();
165
+ if (done) {
166
+ finish();
167
+ controller.close();
168
+ return;
169
+ }
170
+ controller.enqueue(value);
171
+ }
172
+ catch (e) {
173
+ finish();
174
+ controller.error(e);
175
+ }
176
+ },
177
+ cancel(reason) {
178
+ finish();
179
+ onCancel(reason);
180
+ void reader.cancel(reason).catch(() => undefined);
181
+ },
182
+ });
183
+ }
184
+ /** Cap on bodies buffered only to sniff a model name, on paths inkling does not
185
+ * transform. Chat requests naming a model are far below this; uploads that blow
186
+ * past it stream through unbuffered. */
187
+ const MODEL_SNIFF_MAX_BYTES = 1 << 20;
188
+ /** Default ceiling on a buffered inbound body: 16 MiB.
189
+ *
190
+ * Chosen against what the transform actually has to hold, not against what a
191
+ * provider accepts. Real Claude Code requests measured on production traffic sit
192
+ * far below this even with a 400k system slab and a long tool-heavy history, so
193
+ * the limit is not reachable by ordinary use. Hosts that genuinely need more can
194
+ * raise it explicitly; nothing raises it implicitly. */
195
+ export const DEFAULT_MAX_REQUEST_BYTES = 16 << 20;
196
+ /** Validate a host-supplied ceiling. Garbage falls back to the default rather
197
+ * than disabling the check, because "0" or NaN meaning "unlimited" is exactly
198
+ * the failure mode this option exists to remove. */
199
+ function resolveMaxRequestBytes(configured) {
200
+ if (configured === undefined)
201
+ return DEFAULT_MAX_REQUEST_BYTES;
202
+ if (!Number.isSafeInteger(configured) || configured <= 0)
203
+ return DEFAULT_MAX_REQUEST_BYTES;
204
+ return configured;
205
+ }
206
+ function concatChunks(chunks, total) {
207
+ const out = new Uint8Array(total);
208
+ let at = 0;
209
+ for (const chunk of chunks) {
210
+ out.set(chunk, at);
211
+ at += chunk.byteLength;
212
+ }
213
+ return out;
214
+ }
215
+ /**
216
+ * Read a whole request body, stopping once it exceeds `limit`.
217
+ *
218
+ * The declared `content-length` is used only as a shortcut to act without
219
+ * reading a byte. It is never the authority: chunked senders omit it, and a
220
+ * wrong value costs the sender nothing. The streaming loop is what enforces the
221
+ * cap, so a body that lies about its size is bounded by the same number as one
222
+ * that declares nothing.
223
+ *
224
+ * When `restoreOnOverflow` is true, the buffered chunks are replayed lazily ahead
225
+ * of the untouched remainder as a ReadableStream (dropping each chunk reference
226
+ * as handed off upstream), or `req.body` is returned untouched when `content-length`
227
+ * already proved overflow.
228
+ */
229
+ async function readBodyBounded(req, limit, restoreOnOverflow = false) {
230
+ const declaredRaw = req.headers.get('content-length');
231
+ const declared = declaredRaw === null ? NaN : Number(declaredRaw);
232
+ const declaredBytes = Number.isFinite(declared) && declared >= 0 ? declared : undefined;
233
+ if (declaredBytes !== undefined && declaredBytes > limit) {
234
+ return {
235
+ ok: false,
236
+ observedBytes: 0,
237
+ declaredBytes,
238
+ ...(restoreOnOverflow ? { restoredBody: req.body } : {}),
239
+ };
240
+ }
241
+ const body = req.body;
242
+ if (!body)
243
+ return { ok: true, bytes: new Uint8Array(0) };
244
+ const reader = body.getReader();
245
+ const chunks = [];
246
+ let total = 0;
247
+ try {
248
+ for (;;) {
249
+ const { done, value } = await reader.read();
250
+ if (done)
251
+ break;
252
+ if (!value || value.byteLength === 0)
253
+ continue;
254
+ total += value.byteLength;
255
+ if (total > limit) {
256
+ if (!restoreOnOverflow) {
257
+ await reader.cancel().catch(() => { });
258
+ return { ok: false, observedBytes: total, ...(declaredBytes !== undefined ? { declaredBytes } : {}) };
259
+ }
260
+ chunks.push(value);
261
+ let index = 0;
262
+ const restored = new ReadableStream({
263
+ async pull(controller) {
264
+ if (index < chunks.length) {
265
+ const chunk = chunks[index];
266
+ chunks[index] = undefined;
267
+ index++;
268
+ controller.enqueue(chunk);
269
+ return;
270
+ }
271
+ try {
272
+ for (;;) {
273
+ const { done: nextDone, value: nextValue } = await reader.read();
274
+ if (nextDone) {
275
+ controller.close();
276
+ return;
277
+ }
278
+ if (nextValue && nextValue.byteLength > 0) {
279
+ controller.enqueue(nextValue);
280
+ return;
281
+ }
282
+ }
283
+ }
284
+ catch (err) {
285
+ controller.error(err);
286
+ }
287
+ },
288
+ cancel(reason) {
289
+ chunks.length = 0;
290
+ return reader.cancel(reason);
291
+ },
292
+ });
293
+ return {
294
+ ok: false,
295
+ observedBytes: total,
296
+ ...(declaredBytes !== undefined ? { declaredBytes } : {}),
297
+ restoredBody: restored,
298
+ };
299
+ }
300
+ chunks.push(value);
301
+ }
302
+ }
303
+ catch (err) {
304
+ // A client that hangs up mid-body lands here. Release the socket and let the
305
+ // host's error path answer, which is what an unbounded read did too.
306
+ await reader.cancel().catch(() => { });
307
+ throw err;
308
+ }
309
+ return { ok: true, bytes: concatChunks(chunks, total) };
310
+ }
311
+ /**
312
+ * Read at most `maxPrefix` bytes for inspection while keeping the body
313
+ * forwardable byte-for-byte.
314
+ *
315
+ * Used on routes inkling does not transform, where the only thing wanted from the
316
+ * body is the model name for a dashboard label. Rejecting those requests is not
317
+ * an option - the same route carries uploads and audio - so instead of buffering
318
+ * everything, the consumed prefix is replayed ahead of the untouched remainder.
319
+ * Memory stays at one prefix regardless of how large the upload is.
320
+ */
321
+ async function sniffPrefixRestoringBody(req, maxPrefix) {
322
+ const body = req.body;
323
+ if (!body)
324
+ return { prefix: new Uint8Array(0), body: null };
325
+ const reader = body.getReader();
326
+ const prefixChunks = [];
327
+ let total = 0;
328
+ let exhausted = false;
329
+ try {
330
+ while (total < maxPrefix) {
331
+ const { done, value } = await reader.read();
332
+ if (done) {
333
+ exhausted = true;
334
+ break;
335
+ }
336
+ if (!value || value.byteLength === 0)
337
+ continue;
338
+ prefixChunks.push(value);
339
+ total += value.byteLength;
340
+ }
341
+ }
342
+ catch (err) {
343
+ await reader.cancel().catch(() => { });
344
+ throw err;
345
+ }
346
+ const prefix = concatChunks(prefixChunks, total);
347
+ // The whole body fit inside the prefix, so those bytes ARE the body.
348
+ if (exhausted)
349
+ return { prefix, body: prefix };
350
+ const restored = new ReadableStream({
351
+ start(controller) {
352
+ for (const chunk of prefixChunks)
353
+ controller.enqueue(chunk);
354
+ },
355
+ async pull(controller) {
356
+ try {
357
+ const { done, value } = await reader.read();
358
+ if (done) {
359
+ controller.close();
360
+ return;
361
+ }
362
+ if (value && value.byteLength > 0)
363
+ controller.enqueue(value);
364
+ }
365
+ catch (err) {
366
+ controller.error(err);
367
+ }
368
+ },
369
+ cancel(reason) {
370
+ return reader.cancel(reason);
371
+ },
372
+ });
373
+ return { prefix, body: restored };
374
+ }
375
+ /** Read the actual top-level `model` field. The body is already buffered for
376
+ * transformation, so parsing it is both safer and simpler than a prefix regex
377
+ * (which could mistake `metadata.model` for the routing model). */
378
+ function readModelField(body) {
379
+ try {
380
+ const value = JSON.parse(new TextDecoder().decode(body));
381
+ return typeof value.model === 'string' && value.model.length <= 200 ? value.model : null;
382
+ }
383
+ catch {
384
+ return null;
385
+ }
386
+ }
387
+ /** Responses defaults to non-streaming when `stream` is absent. */
388
+ function readStreamField(body) {
389
+ try {
390
+ const parsed = JSON.parse(new TextDecoder().decode(body));
391
+ return parsed.stream === true;
392
+ }
393
+ catch {
394
+ return false;
395
+ }
396
+ }
397
+ /** Read only a bounded clone of a request while leaving its original body
398
+ * untouched for streaming passthrough. */
399
+ async function readBoundedClone(req) {
400
+ const reader = req.clone().body?.getReader();
401
+ if (!reader)
402
+ return new Uint8Array();
403
+ const chunks = [];
404
+ let total = 0;
405
+ try {
406
+ while (total <= MODEL_SNIFF_MAX_BYTES) {
407
+ const { done, value } = await reader.read();
408
+ if (done)
409
+ break;
410
+ total += value.byteLength;
411
+ if (total > MODEL_SNIFF_MAX_BYTES)
412
+ return null;
413
+ chunks.push(value);
414
+ }
415
+ const body = new Uint8Array(total);
416
+ let offset = 0;
417
+ for (const chunk of chunks) {
418
+ body.set(chunk, offset);
419
+ offset += chunk.byteLength;
420
+ }
421
+ return body;
422
+ }
423
+ catch {
424
+ return null;
425
+ }
426
+ finally {
427
+ void reader.cancel().catch(() => undefined);
428
+ }
429
+ }
430
+ /** Read only a bounded clone of a bypassed JSON request. Bypass must keep the
431
+ * original body byte-for-byte, but Responses telemetry still needs to know
432
+ * whether a headerless Codex reply is SSE or JSON. */
433
+ async function readStreamFieldFromClone(req) {
434
+ const body = await readBoundedClone(req);
435
+ return body !== null && readStreamField(body);
436
+ }
437
+ // Claude Code only admits gateway-discovered ids beginning with "claude" or
438
+ // "anthropic". Prefix provider ids for discovery, then remove that compatibility
439
+ // prefix before INKLING_MODELS matching and upstream routing.
440
+ const CLAUDE_GATEWAY_MODEL_PREFIX = 'claude-';
441
+ function claudeGatewayModelId(model) {
442
+ if (model.startsWith('claude-') || model.startsWith('anthropic'))
443
+ return model;
444
+ return CLAUDE_GATEWAY_MODEL_PREFIX + model;
445
+ }
446
+ function resolveClaudeGatewayModelId(model) {
447
+ if (!model?.startsWith(CLAUDE_GATEWAY_MODEL_PREFIX))
448
+ return undefined;
449
+ const providerModel = model.slice(CLAUDE_GATEWAY_MODEL_PREFIX.length);
450
+ return providerModel.includes('/') ? providerModel : undefined;
451
+ }
452
+ function routedModelDisplayName(model, route) {
453
+ if (route === 'cloudflare' && /kimi-k3/i.test(model))
454
+ return 'Kimi K3 (Cloudflare)';
455
+ return `${model} (${route === 'cloudflare' ? 'Cloudflare' : 'OpenAI'})`;
456
+ }
457
+ /** Gzip via CompressionStream — available in Node 18+ and Cloudflare Workers. */
458
+ async function gzipBytes(body) {
459
+ // Cast: TS doesn't model Response(Uint8Array) even though it works in both runtimes.
460
+ const stream = new Response(body).body.pipeThrough(new CompressionStream('gzip'));
461
+ const buf = await new Response(stream).arrayBuffer();
462
+ return new Uint8Array(buf);
463
+ }
464
+ /** SHA-256 hex of a byte buffer. */
465
+ async function sha256Bytes(body) {
466
+ // Cast: Web Crypto accepts Uint8Array at runtime despite the BufferSource type.
467
+ const digest = await crypto.subtle.digest('SHA-256', body);
468
+ const bytes = new Uint8Array(digest);
469
+ let hex = '';
470
+ for (const byte of bytes)
471
+ hex += byte.toString(16).padStart(2, '0');
472
+ return hex;
473
+ }
474
+ async function sha256Text(value) {
475
+ return sha256Bytes(new TextEncoder().encode(value));
476
+ }
477
+ /** Parse one SSE block into the running usage + measurement accumulators. Silent on malformed input. */
478
+ function processSseEvent(block, m, state) {
479
+ // Parse `event:` + `data:` lines; continuation data: lines concatenate per SSE spec.
480
+ let event = '';
481
+ let data = '';
482
+ for (const line of block.split(/\r\n|\r|\n/)) {
483
+ if (line.startsWith('event:'))
484
+ event = line.slice(6).trim();
485
+ else if (line.startsWith('data:'))
486
+ data += line.slice(5).replace(/^\s/, '');
487
+ }
488
+ if (!data)
489
+ return;
490
+ let j;
491
+ try {
492
+ j = JSON.parse(data);
493
+ }
494
+ catch {
495
+ return;
496
+ }
497
+ const obj = j;
498
+ // The Responses wire format identifies events in the JSON `type` field.
499
+ // Some providers also emit an SSE `event:` line, but ChatGPT's
500
+ // /backend-api/codex/responses commonly does not. Prefer the official JSON
501
+ // discriminator when present and use the SSE name as a compatibility fallback.
502
+ const eventType = typeof obj.type === 'string' ? obj.type : event;
503
+ if (eventType !== 'message_delta' && eventType !== 'message_start') {
504
+ // OpenAI chunks have no `event:` line; usage only present when stream_options.include_usage is set.
505
+ const openAIUsage = normalizeUsage(obj.usage);
506
+ if (openAIUsage)
507
+ state.usage = openAIUsage;
508
+ }
509
+ // OpenAI Responses API streams usage nested under `response` on the terminal
510
+ // terminal Responses event — not at the top level.
511
+ if (eventType === 'response.completed'
512
+ || eventType === 'response.incomplete'
513
+ || eventType === 'response.failed') {
514
+ const resp = obj.response;
515
+ const respUsage = normalizeUsage(resp?.usage);
516
+ if (respUsage)
517
+ state.usage = respUsage;
518
+ // Responses API has no stop_reason; normalize terminal status/reason.
519
+ // Preserve a refusal observed in an earlier delta rather than overwriting it.
520
+ const reason = resp?.incomplete_details?.reason;
521
+ const failureCode = resp?.error?.code;
522
+ state.stopReason = typeof reason === 'string' ? reason
523
+ : eventType === 'response.incomplete' ? 'incomplete'
524
+ : eventType === 'response.failed'
525
+ ? (typeof failureCode === 'string' ? failureCode : 'failed')
526
+ : state.stopReason ?? 'stop';
527
+ }
528
+ // Responses streaming deltas are not Chat Completions `choices[]` chunks.
529
+ // Count their visible/reasoning/tool payloads directly from the JSON event.
530
+ if (eventType === 'response.refusal.delta' || eventType === 'response.refusal.done') {
531
+ // `.done` repeats the completed refusal text; only deltas are additive.
532
+ if (eventType === 'response.refusal.delta' && typeof obj.delta === 'string') {
533
+ m.textChars += obj.delta.length;
534
+ }
535
+ state.stopReason = 'refusal';
536
+ }
537
+ else if (eventType === 'response.output_text.delta' && typeof obj.delta === 'string') {
538
+ m.textChars += obj.delta.length;
539
+ }
540
+ else if ((eventType === 'response.reasoning_text.delta'
541
+ || eventType === 'response.reasoning_summary_text.delta')
542
+ && typeof obj.delta === 'string') {
543
+ m.thinkingChars += obj.delta.length;
544
+ }
545
+ else if ((eventType === 'response.function_call_arguments.delta'
546
+ || eventType === 'response.custom_tool_call_input.delta')
547
+ && typeof obj.delta === 'string') {
548
+ m.toolUseChars += obj.delta.length;
549
+ }
550
+ // Google AI Studio / CloudCode streaming chunks: usageMetadata object.
551
+ const usageObj = obj.usageMetadata ?? obj.response?.usageMetadata;
552
+ if (usageObj && typeof usageObj === 'object') {
553
+ const gUsage = normalizeUsage(usageObj);
554
+ if (gUsage)
555
+ state.usage = gUsage;
556
+ }
557
+ measureGoogleCandidates(obj, m, state);
558
+ measureOpenAIChoices(obj, m);
559
+ // OpenAI chat chunks: the final chunk carries choices[].finish_reason (earlier chunks ship null).
560
+ const choices = obj.choices;
561
+ if (Array.isArray(choices)) {
562
+ for (const c of choices) {
563
+ const fr = c?.finish_reason;
564
+ if (typeof fr === 'string')
565
+ state.stopReason = fr;
566
+ }
567
+ }
568
+ if (eventType === 'message_start') {
569
+ const msg = obj.message;
570
+ const usage = normalizeUsage(msg?.usage);
571
+ if (usage)
572
+ state.usage = usage;
573
+ }
574
+ else if (eventType === 'content_block_start') {
575
+ const cb = obj.content_block;
576
+ if (cb?.type === 'redacted_thinking')
577
+ m.redactedBlockCount += 1;
578
+ }
579
+ else if (eventType === 'content_block_delta') {
580
+ const d = obj.delta;
581
+ if (d?.type === 'text_delta' && typeof d.text === 'string') {
582
+ m.textChars += d.text.length;
583
+ }
584
+ else if (d?.type === 'thinking_delta' && typeof d.thinking === 'string') {
585
+ m.thinkingChars += d.thinking.length;
586
+ }
587
+ else if (d?.type === 'input_json_delta' && typeof d.partial_json === 'string') {
588
+ m.toolUseChars += d.partial_json.length;
589
+ }
590
+ }
591
+ else if (eventType === 'message_delta') {
592
+ // Anthropic ships the final stop_reason here ("end_turn", "refusal", …).
593
+ const d = obj.delta;
594
+ if (typeof d?.stop_reason === 'string')
595
+ state.stopReason = d.stop_reason;
596
+ // Authoritative final output_tokens; merge over message_start (which ships output_tokens: 1).
597
+ const u = obj.usage;
598
+ if (u) {
599
+ if (!state.usage)
600
+ state.usage = {};
601
+ const cur = state.usage;
602
+ if (typeof u.output_tokens === 'number')
603
+ cur.output_tokens = u.output_tokens;
604
+ if (typeof u.input_tokens === 'number' &&
605
+ (cur.input_tokens === undefined || cur.input_tokens === 0 || u.input_tokens > 0)) {
606
+ cur.input_tokens = u.input_tokens;
607
+ }
608
+ if (typeof u.cache_creation_input_tokens === 'number') {
609
+ cur.cache_creation_input_tokens = u.cache_creation_input_tokens;
610
+ }
611
+ if (typeof u.cache_read_input_tokens === 'number') {
612
+ cur.cache_read_input_tokens = u.cache_read_input_tokens;
613
+ }
614
+ if (typeof u.cache_creation === 'object' && u.cache_creation !== null) {
615
+ cur.cache_creation = {
616
+ ...cur.cache_creation,
617
+ ...u.cache_creation,
618
+ };
619
+ }
620
+ if (typeof u.server_tool_use === 'object' && u.server_tool_use !== null) {
621
+ cur.server_tool_use = {
622
+ ...cur.server_tool_use,
623
+ ...u.server_tool_use,
624
+ };
625
+ }
626
+ }
627
+ }
628
+ }
629
+ function objectRecord(value) {
630
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
631
+ ? value
632
+ : null;
633
+ }
634
+ function parseJsonObjects(text) {
635
+ const trimmed = text.trim();
636
+ try {
637
+ const parsed = JSON.parse(trimmed);
638
+ if (Array.isArray(parsed)) {
639
+ return parsed.map(objectRecord).filter((item) => item !== null);
640
+ }
641
+ const item = objectRecord(parsed);
642
+ return item ? [item] : null;
643
+ }
644
+ catch {
645
+ const match = /"usageMetadata"\s*:\s*(\{[^}]+\})/.exec(trimmed);
646
+ if (match && match[1]) {
647
+ try {
648
+ const usageMetadata = JSON.parse(match[1]);
649
+ return [{ usageMetadata }];
650
+ }
651
+ catch { }
652
+ }
653
+ }
654
+ return null;
655
+ }
656
+ function normalizeUsage(raw) {
657
+ if (!raw || typeof raw !== 'object')
658
+ return undefined;
659
+ const u = raw;
660
+ const out = {};
661
+ if (typeof u.input_tokens === 'number')
662
+ out.input_tokens = u.input_tokens;
663
+ if (typeof u.output_tokens === 'number')
664
+ out.output_tokens = u.output_tokens;
665
+ if (typeof u.cache_creation_input_tokens === 'number') {
666
+ out.cache_creation_input_tokens = u.cache_creation_input_tokens;
667
+ }
668
+ if (typeof u.cache_read_input_tokens === 'number') {
669
+ out.cache_read_input_tokens = u.cache_read_input_tokens;
670
+ }
671
+ if (typeof u.cache_creation === 'object' && u.cache_creation !== null) {
672
+ out.cache_creation = u.cache_creation;
673
+ }
674
+ if (typeof u.server_tool_use === 'object' && u.server_tool_use !== null) {
675
+ out.server_tool_use = u.server_tool_use;
676
+ }
677
+ // OpenAI field aliases.
678
+ if (typeof u.prompt_tokens === 'number')
679
+ out.input_tokens = u.prompt_tokens;
680
+ if (typeof u.completion_tokens === 'number')
681
+ out.output_tokens = u.completion_tokens;
682
+ // Google AI Studio field aliases.
683
+ if (typeof u.promptTokenCount === 'number')
684
+ out.input_tokens = u.promptTokenCount;
685
+ if (typeof u.candidatesTokenCount === 'number' || typeof u.thoughtsTokenCount === 'number') {
686
+ out.output_tokens =
687
+ (typeof u.candidatesTokenCount === 'number' ? u.candidatesTokenCount : 0) +
688
+ (typeof u.thoughtsTokenCount === 'number' ? u.thoughtsTokenCount : 0);
689
+ }
690
+ if (typeof u.cachedContentTokenCount === 'number')
691
+ out.cached_tokens = u.cachedContentTokenCount;
692
+ // OpenAI prompt-cache hits live in a details sub-object: Responses uses
693
+ // `input_tokens_details.cached_tokens`, Chat uses `prompt_tokens_details`.
694
+ const details = u.input_tokens_details ??
695
+ u.prompt_tokens_details;
696
+ if (details && typeof details.cached_tokens === 'number') {
697
+ out.cached_tokens = details.cached_tokens;
698
+ }
699
+ // Root-level cached_tokens fallback (some OpenAI-compatible gateways).
700
+ if (out.cached_tokens === undefined && typeof u.cached_tokens === 'number') {
701
+ out.cached_tokens = u.cached_tokens;
702
+ }
703
+ // DeepSeek top-level prompt_cache_hit_tokens / prompt_cache_miss_tokens.
704
+ if (typeof u.prompt_cache_hit_tokens === 'number' &&
705
+ (out.cached_tokens === undefined || (out.cached_tokens === 0 && u.prompt_cache_hit_tokens > 0))) {
706
+ out.cached_tokens = u.prompt_cache_hit_tokens;
707
+ }
708
+ if (out.input_tokens === undefined &&
709
+ (typeof u.prompt_cache_hit_tokens === 'number' || typeof u.prompt_cache_miss_tokens === 'number')) {
710
+ out.input_tokens =
711
+ (typeof u.prompt_cache_hit_tokens === 'number' ? u.prompt_cache_hit_tokens : 0) +
712
+ (typeof u.prompt_cache_miss_tokens === 'number' ? u.prompt_cache_miss_tokens : 0);
713
+ }
714
+ // Some OpenAI-compatible providers additionally expose prompt-cache writes.
715
+ // Like cached_tokens, this is a diagnostic subset of input_tokens: consumers
716
+ // must not add it to the input total a second time.
717
+ if (details && typeof details.cache_write_tokens === 'number') {
718
+ out.cache_write_tokens = details.cache_write_tokens;
719
+ }
720
+ const outputDetails = u.output_tokens_details ??
721
+ u.completion_tokens_details;
722
+ if (outputDetails && typeof outputDetails.reasoning_tokens === 'number') {
723
+ out.reasoning_output_tokens = outputDetails.reasoning_tokens;
724
+ }
725
+ return Object.keys(out).length > 0 ? out : undefined;
726
+ }
727
+ /** Event info for a request forwarded untouched because the transform threw. */
728
+ function failOpenInfo(body, message) {
729
+ return {
730
+ compressed: false,
731
+ reason: `transform_error_fail_open: ${message.slice(0, 200)}`,
732
+ origChars: body.byteLength,
733
+ compressedChars: body.byteLength,
734
+ imageCount: 0,
735
+ imageBytes: 0,
736
+ staticChars: 0,
737
+ dynamicChars: 0,
738
+ dynamicBlockCount: 0,
739
+ droppedChars: 0,
740
+ };
741
+ }
742
+ function revertedGoogleInfo(info, reason, baselineProbeStatus) {
743
+ return {
744
+ ...info,
745
+ compressed: false,
746
+ reason,
747
+ compressedChars: 0,
748
+ imageCount: 0,
749
+ imageBytes: 0,
750
+ imagePixels: undefined,
751
+ imageTokens: undefined,
752
+ baselineImagedTokens: undefined,
753
+ nativeInjectedTokens: undefined,
754
+ firstImagePng: undefined,
755
+ firstImageWidth: undefined,
756
+ firstImageHeight: undefined,
757
+ imagePngs: undefined,
758
+ imageDims: undefined,
759
+ imageSourceText: undefined,
760
+ imageSourceTexts: undefined,
761
+ toolResultImgs: undefined,
762
+ collapsedTurns: undefined,
763
+ collapsedChars: undefined,
764
+ collapsedImages: undefined,
765
+ historyTextChars: undefined,
766
+ historyReason: undefined,
767
+ bucketChars: undefined,
768
+ gateEval: undefined,
769
+ textHygieneSavedChars: undefined,
770
+ textHygieneSavedTokens: undefined,
771
+ textHygieneBlocks: undefined,
772
+ textHygieneStages: undefined,
773
+ cliffAvoided: undefined,
774
+ baselineProbeStatus,
775
+ };
776
+ }
777
+ function measureOpenAIChoices(obj, m) {
778
+ const choices = obj.choices;
779
+ if (!Array.isArray(choices))
780
+ return;
781
+ for (const choice of choices) {
782
+ if (!choice || typeof choice !== 'object')
783
+ continue;
784
+ const c = choice;
785
+ const payload = (c.delta ?? c.message);
786
+ if (!payload || typeof payload !== 'object')
787
+ continue;
788
+ if (typeof payload.content === 'string')
789
+ m.textChars += payload.content.length;
790
+ if (typeof payload.reasoning_content === 'string')
791
+ m.thinkingChars += payload.reasoning_content.length;
792
+ const toolCalls = payload.tool_calls;
793
+ if (Array.isArray(toolCalls)) {
794
+ for (const tc of toolCalls) {
795
+ const fn = tc?.function;
796
+ const args = fn?.arguments;
797
+ if (typeof args === 'string')
798
+ m.toolUseChars += args.length;
799
+ }
800
+ }
801
+ }
802
+ }
803
+ function measureGoogleCandidates(obj, m, state) {
804
+ const candidates = Array.isArray(obj.candidates)
805
+ ? obj.candidates
806
+ : (obj.response && typeof obj.response === 'object' && Array.isArray(obj.response.candidates))
807
+ ? obj.response.candidates
808
+ : undefined;
809
+ if (!Array.isArray(candidates))
810
+ return false;
811
+ for (const rawCandidate of candidates) {
812
+ const candidate = objectRecord(rawCandidate);
813
+ if (!candidate)
814
+ continue;
815
+ if (state && typeof candidate.finishReason === 'string')
816
+ state.stopReason = candidate.finishReason;
817
+ const content = objectRecord(candidate.content);
818
+ if (!Array.isArray(content?.parts))
819
+ continue;
820
+ for (const rawPart of content.parts) {
821
+ const part = objectRecord(rawPart);
822
+ if (!part)
823
+ continue;
824
+ if (typeof part.text === 'string') {
825
+ if (part.thought === true)
826
+ m.thinkingChars += part.text.length;
827
+ else
828
+ m.textChars += part.text.length;
829
+ }
830
+ if (part.functionCall !== undefined) {
831
+ try {
832
+ m.toolUseChars += JSON.stringify(part.functionCall).length;
833
+ }
834
+ catch { }
835
+ }
836
+ }
837
+ }
838
+ return true;
839
+ }
840
+ /** Measure non-streaming messages.content[] / choices[] / Responses output[] — same OutputMeasurement shape as the SSE accumulator. */
841
+ function measureFromMessageJson(j) {
842
+ const m = { textChars: 0, thinkingChars: 0, toolUseChars: 0, redactedBlockCount: 0 };
843
+ if (j && typeof j === 'object') {
844
+ const obj = j;
845
+ measureOpenAIChoices(obj, m);
846
+ if (Array.isArray(obj.output)) {
847
+ for (const rawItem of obj.output) {
848
+ if (!rawItem || typeof rawItem !== 'object')
849
+ continue;
850
+ const item = rawItem;
851
+ const itemType = typeof item.type === 'string' ? item.type : '';
852
+ if (itemType === 'message' && Array.isArray(item.content)) {
853
+ for (const p of item.content) {
854
+ if (!p || typeof p !== 'object')
855
+ continue;
856
+ const part = p;
857
+ if ((part.type === 'output_text' || part.type === 'text') && typeof part.text === 'string') {
858
+ m.textChars += part.text.length;
859
+ }
860
+ else if (part.type === 'refusal' && typeof part.refusal === 'string') {
861
+ m.textChars += part.refusal.length;
862
+ }
863
+ }
864
+ }
865
+ else if (itemType === 'reasoning') {
866
+ for (const arr of [item.summary, item.content]) {
867
+ if (!Array.isArray(arr))
868
+ continue;
869
+ for (const p of arr) {
870
+ if (p && typeof p === 'object' && typeof p.text === 'string') {
871
+ m.thinkingChars += (p.text).length;
872
+ }
873
+ }
874
+ }
875
+ }
876
+ else if (itemType === 'function_call' || itemType === 'custom_tool_call') {
877
+ if (typeof item.arguments === 'string')
878
+ m.toolUseChars += item.arguments.length;
879
+ else if (typeof item.input === 'string')
880
+ m.toolUseChars += item.input.length;
881
+ }
882
+ }
883
+ }
884
+ }
885
+ const content = j?.content;
886
+ if (!Array.isArray(content))
887
+ return m;
888
+ for (const block of content) {
889
+ const b = block;
890
+ if (b?.type === 'text' && typeof b.text === 'string') {
891
+ m.textChars += b.text.length;
892
+ }
893
+ else if (b?.type === 'thinking' && typeof b.thinking === 'string') {
894
+ m.thinkingChars += b.thinking.length;
895
+ }
896
+ else if (b?.type === 'redacted_thinking') {
897
+ m.redactedBlockCount += 1;
898
+ }
899
+ else if (b?.type === 'tool_use') {
900
+ try {
901
+ m.toolUseChars += JSON.stringify(b.input ?? {}).length;
902
+ }
903
+ catch {
904
+ /* circular / unserialisable input — leave the counter as-is */
905
+ }
906
+ }
907
+ }
908
+ return m;
909
+ }
910
+ /** Stop reason from a non-streaming response JSON: Anthropic `stop_reason`,
911
+ * OpenAI chat `choices[].finish_reason`, Responses `status` / `incomplete_details.reason`. */
912
+ function readStopReasonFromJson(j) {
913
+ if (!j || typeof j !== 'object')
914
+ return undefined;
915
+ const obj = j;
916
+ if (typeof obj.stop_reason === 'string')
917
+ return obj.stop_reason;
918
+ if (Array.isArray(obj.choices)) {
919
+ for (const c of obj.choices) {
920
+ const fr = c?.finish_reason;
921
+ if (typeof fr === 'string')
922
+ return fr;
923
+ }
924
+ }
925
+ if (obj.status === 'incomplete') {
926
+ const reason = obj.incomplete_details?.reason;
927
+ return typeof reason === 'string' ? reason : 'incomplete';
928
+ }
929
+ if (obj.status === 'failed') {
930
+ const code = obj.error?.code;
931
+ return typeof code === 'string' ? code : 'failed';
932
+ }
933
+ if (typeof obj.status === 'string') {
934
+ return obj.status === 'completed' ? 'stop' : obj.status;
935
+ }
936
+ return undefined;
937
+ }
938
+ const MAX_TEE_BUFFER_BYTES = 256 * 1024;
939
+ function createBoundedScannerStream(source, onChunk, onEof, onAbort) {
940
+ const reader = source.getReader();
941
+ const queued = [];
942
+ let bufferedBytes = 0;
943
+ let done = false;
944
+ let hasError = false;
945
+ let streamErr;
946
+ let canceled = false;
947
+ let settled = false;
948
+ let wakePump;
949
+ let wakePull;
950
+ const finishAbort = () => {
951
+ if (settled)
952
+ return;
953
+ settled = true;
954
+ onAbort();
955
+ };
956
+ const finishEof = () => {
957
+ if (settled)
958
+ return;
959
+ settled = true;
960
+ onEof();
961
+ };
962
+ void (async () => {
963
+ try {
964
+ while (!canceled) {
965
+ if (bufferedBytes >= MAX_TEE_BUFFER_BYTES) {
966
+ await new Promise((r) => {
967
+ wakePump = r;
968
+ });
969
+ continue;
970
+ }
971
+ const { done: isDone, value } = await reader.read();
972
+ if (canceled)
973
+ break;
974
+ if (isDone) {
975
+ done = true;
976
+ finishEof();
977
+ wakePull?.();
978
+ wakePull = undefined;
979
+ break;
980
+ }
981
+ if (value) {
982
+ onChunk(value);
983
+ queued.push(value);
984
+ bufferedBytes += value.byteLength;
985
+ wakePull?.();
986
+ wakePull = undefined;
987
+ }
988
+ }
989
+ }
990
+ catch (err) {
991
+ hasError = true;
992
+ streamErr = err;
993
+ finishAbort();
994
+ wakePull?.();
995
+ wakePull = undefined;
996
+ }
997
+ finally {
998
+ try {
999
+ reader.releaseLock();
1000
+ }
1001
+ catch { /* already released */ }
1002
+ }
1003
+ })();
1004
+ return new ReadableStream({
1005
+ async pull(controller) {
1006
+ while (true) {
1007
+ if (queued.length > 0) {
1008
+ const chunk = queued.shift();
1009
+ bufferedBytes -= chunk.byteLength;
1010
+ if (bufferedBytes < MAX_TEE_BUFFER_BYTES && wakePump) {
1011
+ const wake = wakePump;
1012
+ wakePump = undefined;
1013
+ wake();
1014
+ }
1015
+ controller.enqueue(chunk);
1016
+ return;
1017
+ }
1018
+ if (hasError) {
1019
+ controller.error(streamErr);
1020
+ return;
1021
+ }
1022
+ if (done) {
1023
+ controller.close();
1024
+ return;
1025
+ }
1026
+ await new Promise((r) => {
1027
+ wakePull = r;
1028
+ });
1029
+ }
1030
+ },
1031
+ cancel(reason) {
1032
+ canceled = true;
1033
+ queued.length = 0;
1034
+ bufferedBytes = 0;
1035
+ const pump = wakePump;
1036
+ wakePump = undefined;
1037
+ pump?.();
1038
+ const pull = wakePull;
1039
+ wakePull = undefined;
1040
+ pull?.();
1041
+ finishAbort();
1042
+ return reader.cancel(reason).catch(() => undefined);
1043
+ },
1044
+ });
1045
+ }
1046
+ /**
1047
+ * Pure pull-through scanner for streaming SSE responses: only reads from upstream
1048
+ * when the downstream client pulls, preserving strict 1-chunk backpressure.
1049
+ */
1050
+ function createPullThroughScannerStream(source, onChunk, onEof, onAbort) {
1051
+ const reader = source.getReader();
1052
+ let settled = false;
1053
+ const finishEof = () => {
1054
+ if (settled)
1055
+ return;
1056
+ settled = true;
1057
+ onEof();
1058
+ };
1059
+ const finishAbort = () => {
1060
+ if (settled)
1061
+ return;
1062
+ settled = true;
1063
+ onAbort();
1064
+ };
1065
+ return new ReadableStream({
1066
+ async pull(controller) {
1067
+ try {
1068
+ const { done, value } = await reader.read();
1069
+ if (done) {
1070
+ finishEof();
1071
+ try {
1072
+ reader.releaseLock();
1073
+ }
1074
+ catch { /* already released */ }
1075
+ controller.close();
1076
+ return;
1077
+ }
1078
+ if (value) {
1079
+ onChunk(value);
1080
+ controller.enqueue(value);
1081
+ }
1082
+ }
1083
+ catch (err) {
1084
+ finishAbort();
1085
+ try {
1086
+ reader.releaseLock();
1087
+ }
1088
+ catch { /* already released */ }
1089
+ controller.error(err);
1090
+ }
1091
+ },
1092
+ cancel(reason) {
1093
+ finishAbort();
1094
+ return reader.cancel(reason).catch(() => undefined);
1095
+ },
1096
+ });
1097
+ }
1098
+ /**
1099
+ * Inspect the response body inline with a bounded 256 KiB buffer: small JSON/4xx
1100
+ * responses settle telemetry immediately even if a caller does not consume `res.body`,
1101
+ * while large streams pause upstream once 256 KiB is buffered so slow clients exert
1102
+ * strict backpressure. 5xx, undecoded compressed bodies, and unknown content-types
1103
+ * are returned unwrapped.
1104
+ */
1105
+ function teeForUsage(res, assumeResponsesSse = false, assumeResponsesJson = false, retainStreamReceipt = false, skipBodyScan = false) {
1106
+ const emptyResult = {
1107
+ response: res,
1108
+ usagePromise: Promise.resolve(undefined),
1109
+ errorBodyPromise: Promise.resolve(undefined),
1110
+ measurementPromise: Promise.resolve(undefined),
1111
+ stopReasonPromise: Promise.resolve(undefined),
1112
+ };
1113
+ if (!res.body || skipBodyScan || res.status >= 500) {
1114
+ return emptyResult;
1115
+ }
1116
+ // 4xx: capture up to ERROR_BODY_MAX inline with bounded backpressure.
1117
+ if (res.status >= 400 && res.status < 500) {
1118
+ const decoder = new TextDecoder();
1119
+ let out = '';
1120
+ let resolveErr;
1121
+ const errorBodyPromise = new Promise((r) => {
1122
+ resolveErr = r;
1123
+ });
1124
+ const passThrough = createBoundedScannerStream(res.body, (value) => {
1125
+ if (out.length < ERROR_BODY_MAX) {
1126
+ out += decoder.decode(value, { stream: true });
1127
+ }
1128
+ }, () => {
1129
+ out += decoder.decode();
1130
+ resolveErr(out.length > ERROR_BODY_MAX ? out.slice(0, ERROR_BODY_MAX) : out);
1131
+ }, () => {
1132
+ resolveErr(out.length > 0 ? out.slice(0, ERROR_BODY_MAX) : undefined);
1133
+ });
1134
+ return {
1135
+ response: new Response(passThrough, {
1136
+ status: res.status,
1137
+ statusText: res.statusText,
1138
+ headers: res.headers,
1139
+ }),
1140
+ usagePromise: Promise.resolve(undefined),
1141
+ errorBodyPromise,
1142
+ measurementPromise: Promise.resolve(undefined),
1143
+ stopReasonPromise: Promise.resolve(undefined),
1144
+ };
1145
+ }
1146
+ const ct = (res.headers.get('content-type') ?? '').toLowerCase();
1147
+ const isSse = ct.includes('text/event-stream') || (ct === '' && assumeResponsesSse);
1148
+ const isJson = !isSse && (ct.includes('application/json') || (ct === '' && assumeResponsesJson));
1149
+ // Skip wrapping unknown content-types: zero scanner overhead, zero tee buffering.
1150
+ if (!isSse && !isJson) {
1151
+ return emptyResult;
1152
+ }
1153
+ const decoder = new TextDecoder();
1154
+ let buf = '';
1155
+ let overflow = false;
1156
+ const MAX_SCAN_BYTES = 4 * 1024 * 1024;
1157
+ const sseBoundaryRe = /\r\n\r\n|\n\n|\r\r/g;
1158
+ const state = {
1159
+ usage: undefined,
1160
+ stopReason: undefined,
1161
+ };
1162
+ const streamedMeasurement = isSse
1163
+ ? { textChars: 0, thinkingChars: 0, toolUseChars: 0, redactedBlockCount: 0 }
1164
+ : undefined;
1165
+ let resolveScan;
1166
+ const scanResult = new Promise((r) => {
1167
+ resolveScan = r;
1168
+ });
1169
+ const finalizeOnEof = () => {
1170
+ if (overflow) {
1171
+ return { usage: undefined, measurement: undefined, stopReason: undefined };
1172
+ }
1173
+ buf += decoder.decode();
1174
+ if (isSse && streamedMeasurement) {
1175
+ if (buf.trim().length > 0)
1176
+ processSseEvent(buf, streamedMeasurement, state);
1177
+ return { usage: state.usage, measurement: streamedMeasurement, stopReason: state.stopReason };
1178
+ }
1179
+ try {
1180
+ const objects = parseJsonObjects(buf);
1181
+ if (!objects)
1182
+ return { usage: undefined, measurement: undefined, stopReason: undefined };
1183
+ let usage;
1184
+ let recognizedGoogle = false;
1185
+ const measurement = {
1186
+ textChars: 0, thinkingChars: 0, toolUseChars: 0, redactedBlockCount: 0,
1187
+ };
1188
+ const jsonState = { stopReason: undefined };
1189
+ for (const object of objects) {
1190
+ const nextUsage = normalizeUsage(object.usage
1191
+ ?? object.usageMetadata
1192
+ ?? object.response?.usageMetadata);
1193
+ if (nextUsage)
1194
+ usage = nextUsage;
1195
+ recognizedGoogle = measureGoogleCandidates(object, measurement, jsonState) || recognizedGoogle;
1196
+ }
1197
+ const last = objects[objects.length - 1];
1198
+ return {
1199
+ usage,
1200
+ measurement: recognizedGoogle ? measurement : measureFromMessageJson(last),
1201
+ stopReason: jsonState.stopReason ?? readStopReasonFromJson(last),
1202
+ };
1203
+ }
1204
+ catch {
1205
+ return { usage: undefined, measurement: undefined, stopReason: undefined };
1206
+ }
1207
+ };
1208
+ const scanner = isSse ? createPullThroughScannerStream : createBoundedScannerStream;
1209
+ const passThrough = scanner(res.body, (value) => {
1210
+ if (overflow)
1211
+ return;
1212
+ if (isSse && streamedMeasurement) {
1213
+ const prevLen = buf.length;
1214
+ buf += decoder.decode(value, { stream: true });
1215
+ sseBoundaryRe.lastIndex = Math.max(0, prevLen - 3);
1216
+ let consumedUntil = 0;
1217
+ let boundary;
1218
+ while ((boundary = sseBoundaryRe.exec(buf)) !== null) {
1219
+ const block = buf.slice(consumedUntil, boundary.index);
1220
+ consumedUntil = boundary.index + boundary[0].length;
1221
+ processSseEvent(block, streamedMeasurement, state);
1222
+ }
1223
+ if (consumedUntil > 0)
1224
+ buf = buf.slice(consumedUntil);
1225
+ if (buf.length > MAX_SCAN_BYTES) {
1226
+ overflow = true;
1227
+ buf = '';
1228
+ }
1229
+ }
1230
+ else {
1231
+ buf += decoder.decode(value, { stream: true });
1232
+ if (buf.length > MAX_SCAN_BYTES) {
1233
+ overflow = true;
1234
+ buf = '';
1235
+ }
1236
+ }
1237
+ }, () => {
1238
+ resolveScan(finalizeOnEof());
1239
+ buf = '';
1240
+ }, () => {
1241
+ if (retainStreamReceipt) {
1242
+ resolveScan({
1243
+ usage: state.usage,
1244
+ measurement: streamedMeasurement,
1245
+ stopReason: state.stopReason ?? 'stream_error',
1246
+ });
1247
+ }
1248
+ else {
1249
+ resolveScan({ usage: undefined, measurement: undefined, stopReason: undefined });
1250
+ }
1251
+ buf = '';
1252
+ });
1253
+ return {
1254
+ response: new Response(passThrough, {
1255
+ status: res.status,
1256
+ statusText: res.statusText,
1257
+ headers: res.headers,
1258
+ }),
1259
+ usagePromise: scanResult.then((s) => s.usage),
1260
+ errorBodyPromise: Promise.resolve(undefined),
1261
+ measurementPromise: scanResult.then((s) => s.measurement),
1262
+ stopReasonPromise: scanResult.then((s) => s.stopReason),
1263
+ };
1264
+ }
1265
+ const DEFAULT_UPSTREAM = 'https://api.anthropic.com';
1266
+ const DEFAULT_OPENAI_UPSTREAM = 'https://api.openai.com';
1267
+ const DEFAULT_CHATGPT_UPSTREAM = 'https://chatgpt.com';
1268
+ /** Headers we strip on the way out — they're hop-by-hop or proxy-injected. */
1269
+ const STRIP_REQ_HEADERS = new Set([
1270
+ 'host',
1271
+ 'connection',
1272
+ 'keep-alive',
1273
+ 'proxy-connection',
1274
+ 'transfer-encoding',
1275
+ 'upgrade',
1276
+ 'content-length', // we recompute
1277
+ 'expect',
1278
+ 'accept-encoding', // let upstream choose
1279
+ 'x-fiche-bypass', // fiche-only opt-out signal; never forwarded upstream
1280
+ 'x-inkling-bypass', // legacy opt-out alias; never forwarded upstream
1281
+ 'x-fiche-session-id', // fiche-only swarm/session isolation key; never forwarded upstream
1282
+ 'x-inkling-session-id', // legacy session isolation alias; never forwarded upstream
1283
+ 'x-fiche-warp-auth', // loopback warp->daemon auth token; never forwarded upstream
1284
+ ]);
1285
+ const STRIP_RES_HEADERS = new Set([
1286
+ 'connection',
1287
+ 'keep-alive',
1288
+ 'transfer-encoding',
1289
+ 'content-encoding', // we don't re-encode
1290
+ 'content-length', // body may differ after streaming
1291
+ 'x-fiche-undecoded-encoding', // internal node-fetch signal
1292
+ ]);
1293
+ const STRIP_RES_HEADERS_KEEP_ENCODING = new Set([
1294
+ 'connection',
1295
+ 'keep-alive',
1296
+ 'transfer-encoding',
1297
+ 'x-fiche-undecoded-encoding', // internal node-fetch signal
1298
+ ]);
1299
+ function filterHeaders(src, strip) {
1300
+ const out = new Headers();
1301
+ src.forEach((v, k) => {
1302
+ if (!strip.has(k.toLowerCase()))
1303
+ out.append(k, v);
1304
+ });
1305
+ return out;
1306
+ }
1307
+ const PASSTHROUGH_PREFIXES = [
1308
+ '/anthropic/',
1309
+ '/openai/',
1310
+ '/google-ai-studio/',
1311
+ '/compat/',
1312
+ ];
1313
+ function isProviderPrefixedPath(pathname) {
1314
+ return PASSTHROUGH_PREFIXES.some((prefix) => pathname.startsWith(prefix));
1315
+ }
1316
+ /** Append a provider-prefixed path without doubling the provider segment when
1317
+ * the base already ends with it: base `http://h/anthropic` plus
1318
+ * `/anthropic/v1/messages` is `http://h/anthropic/v1/messages`. */
1319
+ function joinProviderPath(base, path) {
1320
+ const segment = /^\/[^/?]+/.exec(path)?.[0];
1321
+ return segment && base.endsWith(segment) ? base.slice(0, -segment.length) + path : base + path;
1322
+ }
1323
+ /** One optional gateway/provider segment, then an optional `/v1`, before the
1324
+ * wire-shape suffix:
1325
+ *
1326
+ * /v1/chat/completions
1327
+ * /openai/v1/chat/completions
1328
+ * /compat/chat/completions AI Gateway's OpenAI-compatible route
1329
+ * /grok/chat/completions
1330
+ *
1331
+ * Wire shape only: whether the body is OpenAI-shaped enough to parse a model
1332
+ * out of. Routing stays with isProviderPrefixedPath/isCanonicalOpenAIPath
1333
+ * above, so a prefixed path still goes to passthroughUpstream. */
1334
+ const PROVIDER_SEGMENT = String.raw `(?:\/[a-z0-9][a-z0-9._-]*)?(?:\/v1)?`;
1335
+ const OPENAI_CHAT_PATH = new RegExp(`^${PROVIDER_SEGMENT}\\/chat\\/completions$`);
1336
+ const OPENAI_RESPONSES_PATH = new RegExp(`^${PROVIDER_SEGMENT}\\/responses$`);
1337
+ function isOpenAIChatPath(pathname) {
1338
+ return OPENAI_CHAT_PATH.test(pathname)
1339
+ || pathname === '/v1beta/openai/chat/completions'
1340
+ || pathname === '/v1/openai/chat/completions';
1341
+ }
1342
+ function isOpenAIResponsesPath(pathname) {
1343
+ return OPENAI_RESPONSES_PATH.test(pathname)
1344
+ || pathname === '/backend-api/codex/responses';
1345
+ }
1346
+ /** ChatGPT endpoints used by Codex when `requires_openai_auth = true` is set
1347
+ * on a custom provider. Every `/backend-api/` path is ChatGPT's (responses,
1348
+ * responses/compact, models, usage), so all of them go to OPENAI_UPSTREAM and
1349
+ * never to the Anthropic default, which would swap the ChatGPT bearer for an
1350
+ * Anthropic one and hand the conversation to the wrong provider. Only
1351
+ * `codex/responses` is transformed; the rest are forwarded byte-for-byte. */
1352
+ function isChatGPTBackendPath(pathname) {
1353
+ return pathname.startsWith('/backend-api/');
1354
+ }
1355
+ /** Google API shapes that are not inference (countTokens, model listing,
1356
+ * Code Assist control calls, and Gemini OpenAI-compat chat). They go to the
1357
+ * Google upstream. */
1358
+ function isGoogleFamilyPath(pathname) {
1359
+ return /^\/(?:upload\/)?v1(?:beta|alpha)\//.test(pathname)
1360
+ || pathname === '/v1/openai/chat/completions'
1361
+ || pathname.startsWith('/v1internal:')
1362
+ || /^\/v1\/models\/[^/]+:[A-Za-z]+$/.test(pathname);
1363
+ }
1364
+ /** Paths the Anthropic default upstream serves. Anything outside every known
1365
+ * family is refused rather than sent to Anthropic with injected keys. */
1366
+ function isAnthropicFamilyPath(pathname) {
1367
+ return pathname.startsWith('/v1/') || pathname.startsWith('/api/');
1368
+ }
1369
+ function resolveAuthToken(config) {
1370
+ return typeof config.authToken === 'function' ? config.authToken() : config.authToken;
1371
+ }
1372
+ const ANTHROPIC_BEARER_RE = /\bsk-ant-/i;
1373
+ const API_KEY_BEARER_RE = /^Bearer\s+sk-/i;
1374
+ /** Three base64url segments whose first decodes to a JSON header (`eyJ…`). */
1375
+ const JWT_BEARER_RE = /^Bearer\s+eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
1376
+ export function classifyInboundCredential(headers) {
1377
+ const authorization = headers.get('authorization') ?? '';
1378
+ if (ANTHROPIC_BEARER_RE.test(authorization))
1379
+ return 'anthropic-bearer';
1380
+ if (JWT_BEARER_RE.test(authorization))
1381
+ return 'oauth-jwt';
1382
+ if (API_KEY_BEARER_RE.test(authorization))
1383
+ return 'api-key-bearer';
1384
+ if (authorization.trim() !== '')
1385
+ return 'opaque-bearer';
1386
+ if ((headers.get('x-api-key') ?? '').trim() !== '')
1387
+ return 'anthropic-key';
1388
+ return 'none';
1389
+ }
1390
+ /**
1391
+ * Credential policy for a direct OpenAI-family route: `/v1/responses`,
1392
+ * `/v1/chat/completions`, `/v1/models` and the provider-prefixed equivalents,
1393
+ * where the client speaks to the OpenAI upstream itself rather than through a
1394
+ * Messages bridge.
1395
+ *
1396
+ * Three rules, in priority order:
1397
+ *
1398
+ * 1. An Anthropic-shaped credential never reaches an OpenAI upstream. That is a
1399
+ * cross-provider credential disclosure, and a guaranteed 401 on top. The
1400
+ * route classifier already refuses this for the ambiguous `/v1/models` path;
1401
+ * this applies the same rule to every OpenAI route.
1402
+ * 2. Subscription OAuth is preserved even when the host has an API key
1403
+ * configured. A Codex user proxying through inkling means to spend their own
1404
+ * subscription; silently substituting the host key bills the wrong account
1405
+ * and usually fails, and the user has no way to see why.
1406
+ * 3. Otherwise a configured key replaces whatever arrived, and is used as the
1407
+ * fallback when nothing arrived. This is the documented "host supplies the
1408
+ * credential" mode.
1409
+ */
1410
+ export function resolveOpenAIRouteAuth(inbound, hasConfiguredKey) {
1411
+ if (inbound === 'anthropic-bearer' || inbound === 'anthropic-key') {
1412
+ return hasConfiguredKey
1413
+ ? { action: 'replace', reason: 'anthropic-credential-never-crosses-providers' }
1414
+ : { action: 'drop', reason: 'anthropic-credential-never-crosses-providers' };
1415
+ }
1416
+ if (inbound === 'oauth-jwt') {
1417
+ return { action: 'keep-inbound', reason: 'subscription-oauth-belongs-to-the-caller' };
1418
+ }
1419
+ if (hasConfiguredKey) {
1420
+ return { action: 'replace', reason: 'host-configured-key' };
1421
+ }
1422
+ return inbound === 'none'
1423
+ ? { action: 'drop', reason: 'no-credential-available' }
1424
+ : { action: 'keep-inbound', reason: 'caller-credential-forwarded' };
1425
+ }
1426
+ function isNonChatOpenAIPath(pathname) {
1427
+ return pathname === '/v1/embeddings'
1428
+ || pathname.startsWith('/v1/embeddings/')
1429
+ || pathname === '/v1/files'
1430
+ || pathname.startsWith('/v1/files/')
1431
+ || pathname === '/v1/batches'
1432
+ || pathname.startsWith('/v1/batches/')
1433
+ || pathname === '/v1/audio'
1434
+ || pathname.startsWith('/v1/audio/')
1435
+ || pathname === '/v1/images'
1436
+ || pathname.startsWith('/v1/images/');
1437
+ }
1438
+ function isCanonicalOpenAIPath(pathname, headers, hasOpenAIKey) {
1439
+ if (pathname === '/v1/chat/completions'
1440
+ || pathname === '/v1/responses'
1441
+ || pathname.startsWith('/v1/responses/')
1442
+ || isChatGPTBackendPath(pathname)) {
1443
+ return true;
1444
+ }
1445
+ const isModelsPath = pathname === '/v1/models' || pathname.startsWith('/v1/models/');
1446
+ const isOtherOpenAI = isNonChatOpenAIPath(pathname);
1447
+ if (!isModelsPath && !isOtherOpenAI)
1448
+ return false;
1449
+ // Check Host first so explicit first-party Hosts never cross-route.
1450
+ const host = extractHostname(headers.get('host'));
1451
+ if (host === 'api.openai.com' || host === 'chatgpt.com')
1452
+ return true;
1453
+ if (host === 'api.anthropic.com')
1454
+ return false;
1455
+ // Check !isAnthropicAuth BEFORE hasOpenAIKey so setting OPENAI_API_KEY
1456
+ // never hijacks Anthropic /v1/models or /v1/files requests.
1457
+ const inbound = classifyInboundCredential(headers);
1458
+ const isAnthropicAuth = inbound === 'anthropic-key'
1459
+ || inbound === 'anthropic-bearer'
1460
+ || headers.has('x-api-key')
1461
+ || /\bsk-ant-/i.test(headers.get('authorization') ?? '');
1462
+ if (isAnthropicAuth)
1463
+ return false;
1464
+ if (isModelsPath) {
1465
+ return hasOpenAIKey || inbound !== 'none';
1466
+ }
1467
+ // Non-chat OpenAI /v1/* paths (/v1/embeddings, /v1/files, /v1/batches, /v1/audio/*, /v1/images/*)
1468
+ return hasOpenAIKey || inbound === 'oauth-jwt' || inbound === 'api-key-bearer' || inbound === 'opaque-bearer';
1469
+ }
1470
+ /** anthropic-beta values count_tokens has rejected in this process. Clients
1471
+ * (e.g. Claude Code) may send betas that /v1/messages accepts but
1472
+ * /v1/messages/count_tokens does not; we learn them from the 400 and drop them. */
1473
+ const COUNT_TOKENS_REJECTED_BETAS_MAX = 64;
1474
+ const countTokensRejectedBetas = new Set();
1475
+ const REJECTED_BETA_RE = /Unexpected value\(s\) (.+?) for the `anthropic-beta` header/;
1476
+ /** Extract beta names a count_tokens 400 complained about (backtick-quoted). */
1477
+ export function parseRejectedBetas(errorBody) {
1478
+ let msg = errorBody;
1479
+ try {
1480
+ const j = JSON.parse(errorBody);
1481
+ if (typeof j?.error?.message === 'string')
1482
+ msg = j.error.message;
1483
+ }
1484
+ catch { /* not JSON — scan raw text */ }
1485
+ const m = REJECTED_BETA_RE.exec(msg);
1486
+ if (!m)
1487
+ return [];
1488
+ return [...(m[1] ?? '').matchAll(/`([^`]+)`/g)].map((x) => (x[1] ?? '').trim()).filter(Boolean);
1489
+ }
1490
+ function dropRejectedBetas(headers) {
1491
+ const raw = headers.get('anthropic-beta');
1492
+ if (!raw || countTokensRejectedBetas.size === 0)
1493
+ return;
1494
+ const kept = raw.split(',').map((b) => b.trim()).filter((b) => b && !countTokensRejectedBetas.has(b));
1495
+ if (kept.length)
1496
+ headers.set('anthropic-beta', kept.join(','));
1497
+ else
1498
+ headers.delete('anthropic-beta');
1499
+ }
1500
+ /** Test hook. */
1501
+ export function resetCountTokensRejectedBetasForTests() {
1502
+ countTokensRejectedBetas.clear();
1503
+ }
1504
+ /** POST /v1/messages/count_tokens with the given body. Returns the upstream's
1505
+ * `input_tokens` number or null on any failure. count_tokens is documented
1506
+ * as a free endpoint (no input-token billing) — we use it once per request
1507
+ * on the PRE-COMPRESSION body to get the ground-truth baseline. Actual
1508
+ * post-compression tokens already come back free in the /v1/messages usage
1509
+ * block (input_tokens + cache_create + cache_read), so no second probe. */
1510
+ const COUNT_TOKENS_ERROR_MAX_BYTES = 4096;
1511
+ async function readBoundedErrorText(res, maxBytes = COUNT_TOKENS_ERROR_MAX_BYTES) {
1512
+ if (!res.body)
1513
+ return '';
1514
+ const reader = res.body.getReader();
1515
+ const chunks = [];
1516
+ let total = 0;
1517
+ try {
1518
+ while (total < maxBytes) {
1519
+ const { done, value } = await reader.read();
1520
+ if (done)
1521
+ break;
1522
+ if (!value || value.byteLength === 0)
1523
+ continue;
1524
+ const take = Math.min(value.byteLength, maxBytes - total);
1525
+ chunks.push(take === value.byteLength ? value : value.subarray(0, take));
1526
+ total += take;
1527
+ }
1528
+ }
1529
+ catch {
1530
+ // Ignore read errors on error path.
1531
+ }
1532
+ finally {
1533
+ await reader.cancel().catch(() => undefined);
1534
+ try {
1535
+ reader.releaseLock();
1536
+ }
1537
+ catch { /* already released */ }
1538
+ }
1539
+ return new TextDecoder().decode(concatChunks(chunks, total));
1540
+ }
1541
+ async function countTokensUpstream(countTokensUrl, body, headers, onError, retried = false, fetchImpl = globalThis.fetch, parentSignal) {
1542
+ let res;
1543
+ try {
1544
+ if (parentSignal?.aborted)
1545
+ return null;
1546
+ const reqHeaders = new Headers(headers);
1547
+ dropRejectedBetas(reqHeaders);
1548
+ res = await fetchImpl(countTokensUrl, {
1549
+ method: 'POST',
1550
+ headers: reqHeaders,
1551
+ body: body,
1552
+ redirect: 'manual',
1553
+ signal: combineAbortSignals(COUNT_TOKENS_TIMEOUT_MS, parentSignal),
1554
+ });
1555
+ if (res.status === 400 && !retried) {
1556
+ const text = await readBoundedErrorText(res, COUNT_TOKENS_ERROR_MAX_BYTES);
1557
+ const rejected = parseRejectedBetas(text);
1558
+ if (rejected.length > 0 && rejected.some((b) => !countTokensRejectedBetas.has(b))) {
1559
+ for (const b of rejected) {
1560
+ if (countTokensRejectedBetas.size >= COUNT_TOKENS_REJECTED_BETAS_MAX)
1561
+ break;
1562
+ countTokensRejectedBetas.add(b);
1563
+ }
1564
+ return countTokensUpstream(countTokensUrl, body, reqHeaders, onError, true, fetchImpl, parentSignal);
1565
+ }
1566
+ const redacted = redactSecrets(text);
1567
+ onError?.(`http_400${redacted ? ` ${redacted.slice(0, 300)}` : ''}`);
1568
+ return null;
1569
+ }
1570
+ if (!res.ok) {
1571
+ const detail = redactSecrets(await readBoundedErrorText(res, COUNT_TOKENS_ERROR_MAX_BYTES)).slice(0, 300);
1572
+ onError?.(`http_${res.status}${detail ? ` ${detail}` : ''}`);
1573
+ return null;
1574
+ }
1575
+ const json = (await res.json());
1576
+ if (typeof json.input_tokens === 'number')
1577
+ return json.input_tokens;
1578
+ onError?.('no_input_tokens_in_response');
1579
+ return null;
1580
+ }
1581
+ catch (e) {
1582
+ await res?.body?.cancel().catch(() => undefined);
1583
+ const msg = redactSecrets(String(e?.message ?? e)).slice(0, 200);
1584
+ onError?.(`fetch_error ${e?.name ?? ''}: ${msg}`);
1585
+ return null;
1586
+ }
1587
+ }
1588
+ const PREFERRED_GOOGLE_COUNT_SHAPE_MAX = 64;
1589
+ const preferredGoogleCountShapeByHost = new Map();
1590
+ export function resetGoogleCountShapePreferenceForTests() {
1591
+ preferredGoogleCountShapeByHost.clear();
1592
+ }
1593
+ async function countGoogleTokensUpstream(countTokensUrl, body, headers, model, fetchImpl = globalThis.fetch, parentSignal) {
1594
+ try {
1595
+ const rawParsed = JSON.parse(new TextDecoder().decode(body));
1596
+ const request = (rawParsed.request && typeof rawParsed.request === 'object' && !Array.isArray(rawParsed.request))
1597
+ ? rawParsed.request
1598
+ : rawParsed;
1599
+ const shapeBare = JSON.stringify(request);
1600
+ const shapeWrapped = JSON.stringify({ generateContentRequest: { ...request, model: `models/${model}` } });
1601
+ let host = '';
1602
+ try {
1603
+ host = new URL(countTokensUrl).host;
1604
+ }
1605
+ catch { }
1606
+ const cachedShape = host ? preferredGoogleCountShapeByHost.get(host) : undefined;
1607
+ if (host && cachedShape !== undefined) {
1608
+ preferredGoogleCountShapeByHost.delete(host);
1609
+ preferredGoogleCountShapeByHost.set(host, cachedShape);
1610
+ }
1611
+ const preferred = cachedShape ?? 0;
1612
+ const orderedShapes = preferred === 1
1613
+ ? [shapeWrapped, shapeBare]
1614
+ : [shapeBare, shapeWrapped];
1615
+ const deadline = Date.now() + COUNT_TOKENS_TIMEOUT_MS;
1616
+ const perShapeTimeout = Math.floor(COUNT_TOKENS_TIMEOUT_MS / orderedShapes.length);
1617
+ for (const countBody of orderedShapes) {
1618
+ if (parentSignal?.aborted)
1619
+ break;
1620
+ const remainingMs = deadline - Date.now();
1621
+ if (remainingMs <= 0)
1622
+ break;
1623
+ let res;
1624
+ try {
1625
+ res = await fetchImpl(countTokensUrl, {
1626
+ method: 'POST',
1627
+ headers,
1628
+ body: countBody,
1629
+ redirect: 'manual',
1630
+ signal: combineAbortSignals(Math.min(remainingMs, perShapeTimeout), parentSignal),
1631
+ });
1632
+ if (res.ok) {
1633
+ const json = (await res.json());
1634
+ if (typeof json.totalTokens === 'number') {
1635
+ if (host) {
1636
+ preferredGoogleCountShapeByHost.delete(host);
1637
+ preferredGoogleCountShapeByHost.set(host, countBody === shapeWrapped ? 1 : 0);
1638
+ if (preferredGoogleCountShapeByHost.size > PREFERRED_GOOGLE_COUNT_SHAPE_MAX) {
1639
+ const oldest = preferredGoogleCountShapeByHost.keys().next().value;
1640
+ if (oldest !== undefined)
1641
+ preferredGoogleCountShapeByHost.delete(oldest);
1642
+ }
1643
+ }
1644
+ return json.totalTokens;
1645
+ }
1646
+ }
1647
+ else {
1648
+ await res.body?.cancel().catch(() => { });
1649
+ }
1650
+ }
1651
+ catch {
1652
+ await res?.body?.cancel().catch(() => { });
1653
+ // try next payload shape
1654
+ }
1655
+ }
1656
+ return null;
1657
+ }
1658
+ catch {
1659
+ return null;
1660
+ }
1661
+ }
1662
+ /**
1663
+ * Resolve upstream URLs from config. Pure — unit-testable.
1664
+ *
1665
+ * Every env-derived input is trimmed of leading/trailing whitespace before
1666
+ * URL construction, and trailing slashes are stripped so `base + path` joins
1667
+ * cleanly. The trim is defensive: a stray space in OPENAI_UPSTREAM /
1668
+ * ANTHROPIC_UPSTREAM / INKLING_GATEWAY_BASE_URL (commonly introduced by
1669
+ * cmd.exe `set VAR=...`, a copy-paste with a trailing space, or a shell
1670
+ * quoting bug in a launcher script) would otherwise build URLs like
1671
+ * "https://api.openai.com /v1/..." — fetch() then throws
1672
+ * "Failed to parse URL" with no actionable log line, and the operator is
1673
+ * left guessing. Trimming at the URL boundary keeps the failure mode loud
1674
+ * (the proxy still returns a real 401/502 from upstream) instead of silent.
1675
+ */
1676
+ export function resolveUpstreams(config) {
1677
+ if (config.provider === 'cloudflare-ai-gateway') {
1678
+ const base = (config.gatewayBaseUrl ?? '').trim().replace(/\/+$/, '');
1679
+ if (!base) {
1680
+ throw new Error("provider 'cloudflare-ai-gateway' requires gatewayBaseUrl (INKLING_GATEWAY_BASE_URL)");
1681
+ }
1682
+ return { anthropic: `${base}/anthropic`, openai: `${base}/openai`, stripOpenAIV1: true };
1683
+ }
1684
+ return {
1685
+ anthropic: (config.upstream ?? config.sharedUpstream ?? DEFAULT_UPSTREAM).trim().replace(/\/+$/, ''),
1686
+ openai: (config.openAIUpstream ?? config.sharedUpstream ?? DEFAULT_OPENAI_UPSTREAM).trim().replace(/\/+$/, ''),
1687
+ stripOpenAIV1: false,
1688
+ };
1689
+ }
1690
+ /** Parse INKLING_GATEWAY_HEADERS — JSON object or `k=v;k2=v2`. */
1691
+ export function parseGatewayHeaders(spec) {
1692
+ if (!spec)
1693
+ return {};
1694
+ const trimmed = spec.trim();
1695
+ if (trimmed.startsWith('{')) {
1696
+ const obj = JSON.parse(trimmed);
1697
+ const out = {};
1698
+ for (const [k, v] of Object.entries(obj))
1699
+ out[k] = String(v);
1700
+ return out;
1701
+ }
1702
+ const out = {};
1703
+ for (const pair of trimmed.split(';')) {
1704
+ const i = pair.indexOf('=');
1705
+ if (i <= 0)
1706
+ continue;
1707
+ out[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
1708
+ }
1709
+ return out;
1710
+ }
1711
+ function extractHostname(hostHeader) {
1712
+ if (!hostHeader)
1713
+ return '';
1714
+ const trimmed = hostHeader.trim().toLowerCase();
1715
+ if (trimmed.startsWith('[')) {
1716
+ const end = trimmed.indexOf(']');
1717
+ return end !== -1 ? trimmed.slice(1, end) : trimmed;
1718
+ }
1719
+ const colon = trimmed.indexOf(':');
1720
+ return (colon !== -1 ? trimmed.slice(0, colon) : trimmed).replace(/\.$/, '');
1721
+ }
1722
+ function stripTrailingSlashes(str) {
1723
+ let end = str.length;
1724
+ while (end > 0 && str.charCodeAt(end - 1) === 47) {
1725
+ end--;
1726
+ }
1727
+ return str.slice(0, end);
1728
+ }
1729
+ function urlTargetsBase(targetUrl, base) {
1730
+ const trimmed = stripTrailingSlashes(base.trim());
1731
+ if (!trimmed)
1732
+ return false;
1733
+ if (targetUrl === trimmed)
1734
+ return true;
1735
+ return targetUrl.startsWith(`${trimmed}/`) || targetUrl.startsWith(`${trimmed}?`);
1736
+ }
1737
+ function stripAnthropicCredentials(headers) {
1738
+ if (/\bsk-ant-/i.test(headers.get('authorization') ?? ''))
1739
+ headers.delete('authorization');
1740
+ if (/\bsk-ant-/i.test(headers.get('x-api-key') ?? ''))
1741
+ headers.delete('x-api-key');
1742
+ headers.delete('x-anthropic-billing-header');
1743
+ }
1744
+ function resolveGoogleUpstream(req, pathname, passthroughUpstream, config) {
1745
+ if (config.googleUpstream) {
1746
+ return stripTrailingSlashes(config.googleUpstream.trim());
1747
+ }
1748
+ if (config.provider === 'cloudflare-ai-gateway') {
1749
+ return passthroughUpstream;
1750
+ }
1751
+ const host = extractHostname(req.headers.get('host'));
1752
+ if (host === 'daily-cloudcode-pa.googleapis.com' || host === 'cloudcode-pa.googleapis.com' || pathname.startsWith('/v1internal:')) {
1753
+ return host === 'daily-cloudcode-pa.googleapis.com'
1754
+ ? 'https://daily-cloudcode-pa.googleapis.com'
1755
+ : 'https://cloudcode-pa.googleapis.com';
1756
+ }
1757
+ if (host === 'generativelanguage.googleapis.com') {
1758
+ return 'https://generativelanguage.googleapis.com';
1759
+ }
1760
+ if (config.sharedUpstream) {
1761
+ const shared = stripTrailingSlashes(config.sharedUpstream.trim());
1762
+ if (shared && !shared.endsWith('/anthropic')) {
1763
+ return shared;
1764
+ }
1765
+ }
1766
+ if (isProviderPrefixedPath(pathname) && passthroughUpstream !== DEFAULT_UPSTREAM && !passthroughUpstream.endsWith('/anthropic')) {
1767
+ return passthroughUpstream;
1768
+ }
1769
+ return 'https://generativelanguage.googleapis.com';
1770
+ }
1771
+ function resolveOpenAIUpstream(req, pathname, openAIUpstream, config) {
1772
+ if (config.provider === 'cloudflare-ai-gateway') {
1773
+ return openAIUpstream;
1774
+ }
1775
+ if (openAIUpstream === DEFAULT_OPENAI_UPSTREAM &&
1776
+ (isChatGPTBackendPath(pathname) || extractHostname(req.headers.get('host')) === 'chatgpt.com')) {
1777
+ return DEFAULT_CHATGPT_UPSTREAM;
1778
+ }
1779
+ return openAIUpstream;
1780
+ }
1781
+ /** Build the proxy fetch handler. */
1782
+ export function createProxy(config = {}) {
1783
+ const modelRoutes = new Map();
1784
+ const inFlight = new Map();
1785
+ // Entries are released by their holder on every exit path, but the key space is
1786
+ // unbounded (one per distinct body) and the map outlives every request, so a single
1787
+ // missed release would leak for the daemon's lifetime. An entry past the hold window
1788
+ // is already ignored by the duplicate check below, so expiring it costs nothing and
1789
+ // bounds the map by real in-window concurrency instead of by release correctness.
1790
+ let lastSweptAt = 0;
1791
+ const headersTimeoutMs = config.upstreamHeadersTimeoutMs ?? DEFAULT_UPSTREAM_HEADERS_TIMEOUT_MS;
1792
+ const idleTimeoutMs = config.upstreamIdleTimeoutMs ?? DEFAULT_UPSTREAM_IDLE_TIMEOUT_MS;
1793
+ const duplicateHoldMs = config.duplicateHoldMs ?? DEFAULT_DUPLICATE_HOLD_MS;
1794
+ const maxRequestBytes = resolveMaxRequestBytes(config.maxRequestBytes);
1795
+ const oversizedBodyPolicy = config.oversizedBodyPolicy ?? 'reject';
1796
+ // Explicit precedence: Cloudflare > OpenAI > normal family routing.
1797
+ for (const model of config.openAIModels ?? []) {
1798
+ const id = model.trim();
1799
+ if (id)
1800
+ modelRoutes.set(id, 'openai');
1801
+ }
1802
+ for (const model of config.cloudflareModels ?? []) {
1803
+ const id = model.trim();
1804
+ if (id)
1805
+ modelRoutes.set(id, 'cloudflare');
1806
+ }
1807
+ if ((config.cloudflareModels?.length ?? 0) > 0 && config.cloudflareUpstream === undefined) {
1808
+ throw new Error('cloudflareModels requires a Cloudflare chat upstream');
1809
+ }
1810
+ const routes = resolveUpstreams(config);
1811
+ const upstream = routes.anthropic;
1812
+ const openAIUpstream = routes.openai;
1813
+ // Same trim policy as resolveUpstreams: keep provider-prefixed passthroughs
1814
+ // (e.g. /openai/*, /google-ai-studio/*) safe from env whitespace — see the
1815
+ // JSDoc on resolveUpstreams for the full rationale.
1816
+ const gatewayBase = stripTrailingSlashes((config.gatewayBaseUrl ?? '').trim());
1817
+ const passthroughUpstream = config.provider === 'cloudflare-ai-gateway'
1818
+ ? gatewayBase
1819
+ : upstream;
1820
+ const gatewayHeaders = config.gatewayHeaders ?? {};
1821
+ const applyGatewayHeadersIfTargeted = (h, targetUrl) => {
1822
+ if (gatewayBase !== '' && urlTargetsBase(targetUrl, gatewayBase)) {
1823
+ for (const [k, v] of Object.entries(gatewayHeaders))
1824
+ h.set(k, v);
1825
+ }
1826
+ return h;
1827
+ };
1828
+ return async function handle(req) {
1829
+ const t0 = Date.now();
1830
+ const url = new URL(req.url);
1831
+ const path = url.pathname + url.search;
1832
+ // inkling speaks HTTP only. A WebSocket handshake forwarded as a plain GET
1833
+ // comes back 405 from chatgpt.com, and Codex's built-in provider then
1834
+ // retries the socket several times before falling back. 426 is the answer
1835
+ // it takes as "use HTTP" on the first try (measured, codex-cli 0.167.1).
1836
+ if ((req.headers.get('upgrade') ?? '').toLowerCase().includes('websocket')) {
1837
+ return new Response(JSON.stringify({ error: { type: 'websocket_unsupported', message: 'fiche proxies HTTP only; retry over HTTP' } }), {
1838
+ status: 426,
1839
+ headers: { 'content-type': 'application/json', connection: 'close' },
1840
+ });
1841
+ }
1842
+ // Reversibly disguise the configured upstream id for Claude Code's model
1843
+ // picker, matching CLIProxyAPI. The id decodes back to the exact provider
1844
+ // model on /v1/messages, so discovery and routing cannot drift apart.
1845
+ if (req.method === 'GET' && url.pathname === '/v1/models' && modelRoutes.size > 0) {
1846
+ const models = [...modelRoutes].map(([model, route]) => ({
1847
+ id: claudeGatewayModelId(model),
1848
+ type: 'model',
1849
+ display_name: routedModelDisplayName(model, route),
1850
+ created_at: '1970-01-01T00:00:00Z',
1851
+ }));
1852
+ return new Response(JSON.stringify({
1853
+ data: models,
1854
+ has_more: false,
1855
+ first_id: models[0]?.id ?? '',
1856
+ last_id: models.at(-1)?.id ?? '',
1857
+ }), {
1858
+ headers: { 'content-type': 'application/json' },
1859
+ });
1860
+ }
1861
+ // reqBodyBytes: kept for lazy gzip on 4xx. reqBodySha8: computed eagerly for correlation.
1862
+ let reqBodyBytes;
1863
+ let reqBodySha8;
1864
+ let responseContentType;
1865
+ let responseContentEncoding;
1866
+ let reqBodySha256;
1867
+ // Set once the transform returns; read by fire() at event time.
1868
+ let transformMs;
1869
+ // Why the baseline count_tokens probe failed (status + upstream error), if it did.
1870
+ let baselineProbeError;
1871
+ const fetchImpl = config.fetch ?? globalThis.fetch;
1872
+ const upstreamAbort = new AbortController();
1873
+ const clientSignal = req.signal;
1874
+ let clientAbortWired = false;
1875
+ const onClientAbort = () => {
1876
+ if (!upstreamAbort.signal.aborted) {
1877
+ upstreamAbort.abort(clientSignal?.reason ?? new Error('fiche: client disconnected'));
1878
+ }
1879
+ };
1880
+ const ensureClientAbortWired = () => {
1881
+ if (clientAbortWired || !clientSignal)
1882
+ return;
1883
+ clientAbortWired = true;
1884
+ if (clientSignal.aborted)
1885
+ onClientAbort();
1886
+ else
1887
+ clientSignal.addEventListener('abort', onClientAbort, { once: true });
1888
+ };
1889
+ const detachClientAbort = () => {
1890
+ if (!clientAbortWired || !clientSignal)
1891
+ return;
1892
+ clientAbortWired = false;
1893
+ clientSignal.removeEventListener('abort', onClientAbort);
1894
+ };
1895
+ const fire = (status, info, error, firstByteMs, usage, errorBody, measurement, stopReason) => {
1896
+ const is4xx = status >= 400 && status < 500;
1897
+ // Gzip body lazily (only on 4xx).
1898
+ const finalize = async () => {
1899
+ let reqBodyGz;
1900
+ if (config.captureErrorReqBody && is4xx && reqBodyBytes && reqBodyBytes.byteLength > 0) {
1901
+ try {
1902
+ reqBodyGz = await gzipBytes(reqBodyBytes);
1903
+ }
1904
+ catch {
1905
+ // Non-fatal — drop body sample.
1906
+ }
1907
+ }
1908
+ // Await both count_tokens probes so baseline numbers land on the same event row.
1909
+ // Each probe is independent; null leaves the field absent and dashboard math degrades cleanly.
1910
+ if (info && baselineStatusApplies) {
1911
+ // Track both halves so the dashboard can gate on probe completeness (partial vs ok).
1912
+ // A missing cacheable-prefix probe must NOT be treated as cacheable=0 — that fabricates savings.
1913
+ let baselineResolved = null;
1914
+ let cacheableExpected = false;
1915
+ let cacheableResolved = null;
1916
+ if (baselinePromise) {
1917
+ try {
1918
+ baselineResolved = await baselinePromise;
1919
+ if (baselineResolved !== null)
1920
+ info.baselineTokens = baselineResolved;
1921
+ }
1922
+ catch {
1923
+ /* probe threw — drop */
1924
+ }
1925
+ }
1926
+ if (baselineCacheablePromise) {
1927
+ cacheableExpected = true;
1928
+ try {
1929
+ cacheableResolved = await baselineCacheablePromise;
1930
+ if (cacheableResolved !== null)
1931
+ info.baselineCacheableTokens = cacheableResolved;
1932
+ }
1933
+ catch {
1934
+ /* probe threw */
1935
+ }
1936
+ }
1937
+ if (baselineResolved === null) {
1938
+ info.baselineProbeStatus = 'failed';
1939
+ if (baselineProbeError)
1940
+ info.baselineProbeError = baselineProbeError;
1941
+ }
1942
+ else if (cacheableExpected && cacheableResolved === null) {
1943
+ info.baselineProbeStatus = 'partial'; // dashboard excludes row; must not treat as cacheable=0
1944
+ }
1945
+ else if (threadContinue) {
1946
+ // Delta-only baseline vs full-thread usage: rollups must exclude the row.
1947
+ info.baselineProbeStatus = 'partial';
1948
+ }
1949
+ else {
1950
+ info.baselineProbeStatus = 'ok';
1951
+ }
1952
+ if (threadContinue)
1953
+ info.threadContinue = true;
1954
+ }
1955
+ // The Messages compatibility response exposes Anthropic's disjoint
1956
+ // usage buckets to the client. Dashboard accounting still needs the
1957
+ // original Responses/Chat semantics: input includes the cached subset.
1958
+ let eventUsage = usage;
1959
+ if ((bridgedGptMessages || bridgedChatMessages) && usage) {
1960
+ const converted = {
1961
+ ...usage,
1962
+ input_tokens: (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0),
1963
+ cached_tokens: usage.cache_read_input_tokens ?? 0,
1964
+ };
1965
+ if (bridgedChatMessages)
1966
+ delete converted.cache_read_input_tokens;
1967
+ eventUsage = converted;
1968
+ }
1969
+ await config.onRequest?.({
1970
+ method: req.method,
1971
+ path: url.pathname,
1972
+ model: requestModel,
1973
+ // Provider-prefixed OpenCode routes such as `/openai/responses` are
1974
+ // Responses-shaped even though they are not canonical `/v1/*` paths.
1975
+ // Classify by the parsed wire route, otherwise the dashboard ignores
1976
+ // GPT image/baseline telemetry and renders As text / Saved as dashes.
1977
+ accountingProvider: isGoogleRoute
1978
+ ? 'google'
1979
+ : isOpenAIChatWire || isOpenAIResponsesWire || bridgedGptMessages || bridgedChatMessages
1980
+ ? 'openai'
1981
+ : 'anthropic',
1982
+ status,
1983
+ durationMs: Date.now() - t0,
1984
+ firstByteMs,
1985
+ transformMs,
1986
+ info,
1987
+ usage: eventUsage,
1988
+ error,
1989
+ errorBody,
1990
+ reqBodySha8,
1991
+ reqBodyGz,
1992
+ measurement,
1993
+ stopReason,
1994
+ responseContentType,
1995
+ responseContentEncoding,
1996
+ });
1997
+ };
1998
+ return finalize();
1999
+ };
2000
+ const fireWait = (...args) => {
2001
+ const p = fire(...args).catch(() => undefined);
2002
+ config.waitUntil?.(p);
2003
+ };
2004
+ // Transform only known shapes; everything else passes through.
2005
+ // Explicit per-request opt-out (#111): a subprocess that merely inherited
2006
+ // ANTHROPIC_BASE_URL (e.g. a plugin's internal `claude` probe) can send
2007
+ // `x-fiche-bypass: 1` (or legacy `x-inkling-bypass: 1`) via ANTHROPIC_CUSTOM_HEADERS
2008
+ // to have its traffic forwarded byte-for-byte untouched.
2009
+ const bypassHeader = req.headers.get('x-fiche-bypass') ?? req.headers.get('x-inkling-bypass');
2010
+ const bypass = bypassHeader !== null && !/^(?:0|false|off|no)$/i.test(bypassHeader.trim());
2011
+ const ficheSessionRaw = (req.headers.get('x-fiche-session-id') ?? req.headers.get('x-inkling-session-id'))?.trim() ?? null;
2012
+ const ccSessionRaw = req.headers.get('x-claude-code-session-id')?.trim() ?? null;
2013
+ const validatedFicheSessionId = ficheSessionRaw !== null && /^[A-Za-z0-9._:-]{4,128}$/.test(ficheSessionRaw)
2014
+ ? ficheSessionRaw
2015
+ : undefined;
2016
+ const validatedCcSessionId = ccSessionRaw !== null && /^[A-Za-z0-9_-]{8,128}$/.test(ccSessionRaw)
2017
+ ? ccSessionRaw
2018
+ : undefined;
2019
+ const validatedClientSessionId = validatedFicheSessionId ?? validatedCcSessionId;
2020
+ const validatedClientSessionSource = validatedFicheSessionId
2021
+ ? 'fiche-header'
2022
+ : validatedCcSessionId
2023
+ ? 'claude-code-header'
2024
+ : undefined;
2025
+ const registry = config.upstreamRegistry ?? DEFAULT_UPSTREAM_REGISTRY;
2026
+ const rawProviders = typeof config.enabledProviders === 'function'
2027
+ ? config.enabledProviders()
2028
+ : config.enabledProviders;
2029
+ const activeProviderSet = rawProviders ? new Set(rawProviders) : undefined;
2030
+ const followed = config.followHosts
2031
+ ? resolveFollowTarget(url, req.headers.get('host'), registry, activeProviderSet)
2032
+ : refuseUnfollowedProviderHost(req.headers.get('host'), registry);
2033
+ const followRefusal = isFollowRefusal(followed) ? followed : null;
2034
+ /** Set when this request goes to the agent's own third-party host. */
2035
+ const follow = isFollowRefusal(followed) ? null : followed;
2036
+ // Followed hosts mount their API under a prefix (`/anthropic`, `/api`, ...);
2037
+ // classify on the canonical path, forward the original one.
2038
+ const wirePathname = follow ? follow.wirePathname : url.pathname;
2039
+ const providerPrefixed = !follow && isProviderPrefixedPath(url.pathname);
2040
+ // Wire-shape detection stays independent from transform eligibility. A
2041
+ // bypassed Codex request is still an OpenAI Responses request for routing,
2042
+ // accounting, and response scanning; only its body transformation is off.
2043
+ const isMessagesWire = req.method === 'POST'
2044
+ && (isAnthropicMessagesPath(wirePathname) || (Boolean(follow) && wirePathname === '/messages'));
2045
+ const isOpenAIChatWire = req.method === 'POST' && isOpenAIChatPath(wirePathname);
2046
+ const isOpenAIResponsesWire = req.method === 'POST' && isOpenAIResponsesPath(wirePathname);
2047
+ const googleModelFromPath = req.method === 'POST' && !follow
2048
+ ? parseGoogleModelFromPath(url.pathname)
2049
+ : null;
2050
+ const isGoogleInference = req.method === 'POST' && !follow && isGoogleInferencePath(url.pathname);
2051
+ const isGoogleRoute = googleModelFromPath !== null || isGoogleInference;
2052
+ const isGoogleFamily = !follow && (isGoogleRoute || isGoogleFamilyPath(url.pathname));
2053
+ const isOpenAIPath = !follow && isCanonicalOpenAIPath(url.pathname, req.headers, config.openAIApiKey !== undefined);
2054
+ const isAnthropicCredentialRoute = !isGoogleFamily
2055
+ && !isOpenAIChatWire
2056
+ && !isOpenAIResponsesWire
2057
+ && (!providerPrefixed || url.pathname.startsWith('/anthropic/'))
2058
+ && (isAnthropicFamilyPath(url.pathname) || url.pathname.startsWith('/anthropic/') || isMessagesWire);
2059
+ const firstPartyProvider = !follow
2060
+ ? isGoogleFamily
2061
+ ? 'google'
2062
+ : (isOpenAIPath || isOpenAIChatWire || isOpenAIResponsesWire || url.pathname.startsWith('/openai/'))
2063
+ ? 'openai'
2064
+ : (isAnthropicCredentialRoute || isMessagesWire || url.pathname.startsWith('/anthropic/'))
2065
+ ? 'anthropic'
2066
+ : undefined
2067
+ : undefined;
2068
+ const firstPartyDisabled = firstPartyProvider !== undefined && activeProviderSet !== undefined && !activeProviderSet.has(firstPartyProvider);
2069
+ const isMessages = !bypass && !firstPartyDisabled && isMessagesWire;
2070
+ const isOpenAIChat = !bypass && !firstPartyDisabled && isOpenAIChatWire;
2071
+ const isOpenAIResponses = !bypass && !firstPartyDisabled && isOpenAIResponsesWire;
2072
+ const isGoogle = isGoogleRoute && !bypass && !firstPartyDisabled;
2073
+ const googleUpstream = resolveGoogleUpstream(req, url.pathname, passthroughUpstream, config);
2074
+ const resolvedOpenAIUpstream = resolveOpenAIUpstream(req, url.pathname, openAIUpstream, config);
2075
+ const upstreamBase = follow
2076
+ ? follow.origin
2077
+ : isGoogleFamily
2078
+ ? googleUpstream
2079
+ : providerPrefixed
2080
+ ? passthroughUpstream
2081
+ : isOpenAIPath ? resolvedOpenAIUpstream : upstream;
2082
+ let bodyOut = null;
2083
+ /** Set when `decodeRequestBody` undid the request Content-Encoding. */
2084
+ let requestBodyDecoded = false;
2085
+ let info;
2086
+ let requestModel = googleModelFromPath ?? undefined;
2087
+ let bridgedGptMessages = false;
2088
+ let bridgedChatMessages = false;
2089
+ let modelRouteForRequest;
2090
+ // Two count_tokens probes on the pre-compression body (see docs/HISTORY_CACHE_MODEL.md):
2091
+ // baselinePromise → full-body input_tokens
2092
+ // baselineCacheablePromise → input_tokens truncated at last cache_control marker
2093
+ // Dashboard combines them for cache-aware baseline. Both run in parallel with the main forward.
2094
+ let baselinePromise;
2095
+ let baselineCacheablePromise;
2096
+ let baselineStatusApplies = false;
2097
+ // Server-side thread continuation: probe sees only delta while provider bills full thread.
2098
+ let threadContinue = false;
2099
+ let responsesStreaming = false;
2100
+ let isAnthropicMessagesRoute = false;
2101
+ // Refused here, not at resolution: fire() reads the per-request state above.
2102
+ if (followRefusal) {
2103
+ fireWait(followRefusal.status, undefined, followRefusal.message);
2104
+ return new Response(JSON.stringify({ error: followRefusal.reason, message: followRefusal.message }), {
2105
+ status: followRefusal.status,
2106
+ headers: { 'content-type': 'application/json' },
2107
+ });
2108
+ }
2109
+ // Default-deny on the stock Anthropic upstream: a path outside every known
2110
+ // family (an agent we do not recognise, a stray browser fetch) would
2111
+ // otherwise reach api.anthropic.com with the host's keys injected. A
2112
+ // custom gateway upstream keeps forwarding unknown paths, since the
2113
+ // operator chose where they go.
2114
+ if (upstreamBase === DEFAULT_UPSTREAM
2115
+ && !isAnthropicFamilyPath(url.pathname)
2116
+ && !isMessagesWire) {
2117
+ fireWait(404, undefined, `unknown_route: ${url.pathname.slice(0, 200)}`);
2118
+ return new Response(JSON.stringify({
2119
+ error: 'unknown_route',
2120
+ message: `fiche does not forward ${url.pathname}; see docs/SECURITY_MODEL.md`,
2121
+ }), { status: 404, headers: { 'content-type': 'application/json' } });
2122
+ }
2123
+ if ((bypass || firstPartyDisabled) && isOpenAIResponsesWire
2124
+ && (req.headers.get('content-type') ?? '').toLowerCase().includes('json')) {
2125
+ responsesStreaming = await readStreamFieldFromClone(req);
2126
+ }
2127
+ let releaseInFlight = () => { };
2128
+ const acquireInFlightLease = async (bodyBytesForKey) => {
2129
+ if (bodyBytesForKey.byteLength === 0 || duplicateHoldMs <= 0)
2130
+ return null;
2131
+ const rawHash = await sha256Bytes(bodyBytesForKey);
2132
+ const keyHeaders = [];
2133
+ filterHeaders(req.headers, STRIP_REQ_HEADERS).forEach((value, name) => {
2134
+ keyHeaders.push([name, value]);
2135
+ });
2136
+ const hostVal = req.headers.get('host');
2137
+ if (hostVal)
2138
+ keyHeaders.push(['host', hostVal]);
2139
+ keyHeaders.sort(([a, av], [b, bv]) => a.localeCompare(b) || av.localeCompare(bv));
2140
+ const key = await sha256Text(JSON.stringify([
2141
+ req.method,
2142
+ upstreamBase,
2143
+ path,
2144
+ keyHeaders,
2145
+ rawHash,
2146
+ validatedClientSessionId ?? '',
2147
+ ]));
2148
+ const now = Date.now();
2149
+ const sinceSweep = now - lastSweptAt;
2150
+ if (sinceSweep >= duplicateHoldMs
2151
+ || (inFlight.size > INFLIGHT_SWEEP_SIZE && sinceSweep >= INFLIGHT_SWEEP_MIN_INTERVAL_MS)) {
2152
+ for (const [k, v] of inFlight) {
2153
+ if (now - v.startedAt >= duplicateHoldMs)
2154
+ inFlight.delete(k);
2155
+ }
2156
+ lastSweptAt = now;
2157
+ }
2158
+ const existing = inFlight.get(key);
2159
+ if (existing && now - existing.startedAt < duplicateHoldMs) {
2160
+ detachClientAbort();
2161
+ if (!upstreamAbort.signal.aborted) {
2162
+ upstreamAbort.abort(new Error('fiche: duplicate request rejected'));
2163
+ }
2164
+ const message = 'An identical request is already in progress';
2165
+ fireWait(409, undefined, 'duplicate_request_in_flight');
2166
+ const error = isMessages
2167
+ ? { type: 'error', error: { type: 'duplicate_request_in_flight', message } }
2168
+ : { error: { type: 'duplicate_request_in_flight', message } };
2169
+ return new Response(JSON.stringify(error), {
2170
+ status: 409,
2171
+ headers: { 'content-type': 'application/json' },
2172
+ });
2173
+ }
2174
+ const lease = Symbol();
2175
+ inFlight.set(key, { lease, startedAt: now });
2176
+ releaseInFlight = () => {
2177
+ if (inFlight.get(key)?.lease === lease)
2178
+ inFlight.delete(key);
2179
+ };
2180
+ return null;
2181
+ };
2182
+ if (isMessages || isOpenAIChat || isOpenAIResponses || isGoogle) {
2183
+ // Transformable routes have to hold the whole body to rewrite it, so this
2184
+ // is the one place a caller could otherwise choose how much memory fiche
2185
+ // allocates. Bound the read before allocating past `maxRequestBytes`.
2186
+ //
2187
+ // Under `'passthrough'` (loopback Node), a body past the ceiling streams
2188
+ // straight upstream untouched so multimodal payloads are never broken by
2189
+ // a local cap — except when `/v1/messages` model-bridging is configured,
2190
+ // where forwarding unparsed Anthropic JSON could cross provider boundaries.
2191
+ const canStreamOversized = oversizedBodyPolicy === 'passthrough' && !(isMessages && modelRoutes.size > 0);
2192
+ const bounded = await readBodyBounded(req, maxRequestBytes, canStreamOversized);
2193
+ if (!bounded.ok) {
2194
+ if (canStreamOversized) {
2195
+ bodyOut = bounded.restoredBody ?? null;
2196
+ info = {
2197
+ compressed: false,
2198
+ reason: 'body_too_large',
2199
+ origChars: 0,
2200
+ compressedChars: 0,
2201
+ imageCount: 0,
2202
+ imageBytes: 0,
2203
+ staticChars: 0,
2204
+ dynamicChars: 0,
2205
+ dynamicBlockCount: 0,
2206
+ };
2207
+ }
2208
+ else {
2209
+ const message = `request body exceeds the ${maxRequestBytes}-byte fiche limit ` +
2210
+ `(${bounded.declaredBytes !== undefined ? `declared ${bounded.declaredBytes}, ` : ''}` +
2211
+ `read ${bounded.observedBytes})`;
2212
+ const error = isMessages
2213
+ ? { type: 'error', error: { type: 'request_too_large', message } }
2214
+ : { error: { type: 'request_too_large', message } };
2215
+ // Emit like the serialized-size 413 below: a rejected request is still a
2216
+ // dashboard row, otherwise over-limit clients are invisible.
2217
+ fireWait(413, undefined, message);
2218
+ return new Response(JSON.stringify(error), {
2219
+ status: 413,
2220
+ headers: { 'content-type': 'application/json' },
2221
+ });
2222
+ }
2223
+ }
2224
+ else {
2225
+ let bodyIn = bounded.bytes;
2226
+ const contentEncoding = (req.headers.get('content-encoding') ?? '').trim();
2227
+ let decodeTooLarge = false;
2228
+ if (contentEncoding !== '' && contentEncoding.toLowerCase() !== 'identity' && config.decodeRequestBody) {
2229
+ const decoded = config.decodeRequestBody(bodyIn, contentEncoding, maxRequestBytes);
2230
+ if (decoded instanceof Uint8Array) {
2231
+ bodyIn = decoded;
2232
+ requestBodyDecoded = true;
2233
+ }
2234
+ else if (decoded && typeof decoded === 'object') {
2235
+ if (decoded.status === 'ok') {
2236
+ bodyIn = decoded.bytes;
2237
+ requestBodyDecoded = true;
2238
+ }
2239
+ else if (decoded.status === 'too_large') {
2240
+ decodeTooLarge = true;
2241
+ }
2242
+ }
2243
+ }
2244
+ if (decodeTooLarge) {
2245
+ if (!canStreamOversized) {
2246
+ const message = `decoded request body exceeds the ${maxRequestBytes}-byte fiche limit`;
2247
+ const error = isMessages
2248
+ ? { type: 'error', error: { type: 'request_too_large', message } }
2249
+ : { error: { type: 'request_too_large', message } };
2250
+ fireWait(413, undefined, message);
2251
+ return new Response(JSON.stringify(error), {
2252
+ status: 413,
2253
+ headers: { 'content-type': 'application/json' },
2254
+ });
2255
+ }
2256
+ bodyOut = bodyIn;
2257
+ info = {
2258
+ compressed: false,
2259
+ reason: 'body_too_large',
2260
+ origChars: 0,
2261
+ compressedChars: 0,
2262
+ imageCount: 0,
2263
+ imageBytes: 0,
2264
+ staticChars: 0,
2265
+ dynamicChars: 0,
2266
+ dynamicBlockCount: 0,
2267
+ };
2268
+ }
2269
+ else {
2270
+ const dupRes = await acquireInFlightLease(bodyIn);
2271
+ if (dupRes)
2272
+ return dupRes;
2273
+ const encodedUndecoded = contentEncoding !== '' && contentEncoding.toLowerCase() !== 'identity' && !requestBodyDecoded;
2274
+ try {
2275
+ const baseTransformOpts = withClientToolRoundShape(typeof config.transform === 'function' ? config.transform() : config.transform, req.headers);
2276
+ // Bytes still under a coding we did not undo must not be rewritten: the
2277
+ // header would go out unchanged and the upstream would try to decompress
2278
+ // whatever the transform produced. Forward them as they came.
2279
+ const transformOpts = encodedUndecoded
2280
+ ? { ...baseTransformOpts, compress: false }
2281
+ : baseTransformOpts;
2282
+ // Fail-closed: unreadable model → no compression, not a risky guess.
2283
+ const model = googleModelFromPath ?? readModelField(bodyIn);
2284
+ if (isOpenAIResponses)
2285
+ responsesStreaming = readStreamField(bodyIn);
2286
+ requestModel = model ?? undefined;
2287
+ // A turn whose only content is `@inkling pin` / `@inkling unpin` is
2288
+ // configuration, not a question. Answer it here unless compression is
2289
+ // paused/disabled: passthrough mode must forward `@fiche pin` untouched.
2290
+ if (transformOpts?.compress !== false && (isMessages || isOpenAIChat || isOpenAIResponses)) {
2291
+ try {
2292
+ const pinReply = isMessages
2293
+ ? pinCommandResponse(bodyIn)
2294
+ : pinCommandResponseOpenAI(bodyIn, isOpenAIResponses ? 'responses' : 'chat');
2295
+ if (pinReply) {
2296
+ releaseInFlight();
2297
+ return new Response(pinReply.body, {
2298
+ status: 200,
2299
+ headers: {
2300
+ 'content-type': pinReply.contentType,
2301
+ 'cache-control': 'no-cache',
2302
+ },
2303
+ });
2304
+ }
2305
+ }
2306
+ catch {
2307
+ // Fail open: malformed pin parsing must never abort a live agent request.
2308
+ }
2309
+ }
2310
+ // /v1/messages is only a wire schema: Claude Code can target a non-
2311
+ // Anthropic model (for example GPT-5.6 Sol). Do not apply Claude's
2312
+ // renderer or Anthropic count_tokens merely because the route is
2313
+ // Messages-shaped. Enabled GPT models take the standalone
2314
+ // Messages→Responses bridge; unsupported models still fail closed.
2315
+ // Claude Code model aliases decode back to exact Cloudflare model IDs.
2316
+ const decodedByAlias = [...modelRoutes.keys()]
2317
+ .find((candidate) => claudeGatewayModelId(candidate) === model);
2318
+ const decodedChatModel = decodedByAlias ?? resolveClaudeGatewayModelId(model);
2319
+ const routedModel = decodedChatModel ?? model;
2320
+ // A followed host answers for its own models; never bridge them elsewhere.
2321
+ const modelRoute = routedModel && !follow ? modelRoutes.get(routedModel) : undefined;
2322
+ modelRouteForRequest = modelRoute;
2323
+ const forceChat = isMessages && modelRoute === 'cloudflare';
2324
+ const messagesAnthropic = isMessages
2325
+ && modelRoute === undefined && !forceChat && (Boolean(follow) || isClaudeModel(model));
2326
+ isAnthropicMessagesRoute = messagesAnthropic;
2327
+ // Provider routing is explicit. Unlisted Messages models use the
2328
+ // default Anthropic route, regardless of how their id is shaped.
2329
+ bridgedGptMessages =
2330
+ isMessages && !messagesAnthropic && !forceChat
2331
+ && modelRoute === 'openai';
2332
+ // Messages → Chat Completions bridge toward Cloudflare Workers AI.
2333
+ bridgedChatMessages = forceChat;
2334
+ const chatStamp = bridgedChatMessages ? routedModel : undefined;
2335
+ const effectiveModel = (bridgedGptMessages || bridgedChatMessages) ? routedModel : model;
2336
+ // Gemini is in DEFAULT_MODEL_BASES as the family base `gemini`; the same
2337
+ // allowlist gates it so INKLING_MODELS / the chip can opt out.
2338
+ const modelOk = isGoogle
2339
+ ? (isGeminiModel(model) && isInklingSupportedModel(model))
2340
+ : isMessages
2341
+ ? (messagesAnthropic && isInklingSupportedModel(model))
2342
+ || (bridgedGptMessages && isInklingSupportedGptModel(effectiveModel))
2343
+ || (bridgedChatMessages && isInklingSupportedGptModel(effectiveModel))
2344
+ : isInklingSupportedGptModel(model);
2345
+ // Compression eligibility and telemetry follow the model that actually
2346
+ // receives the request, not Claude Code's local gateway alias.
2347
+ if ((bridgedGptMessages || bridgedChatMessages) && effectiveModel) {
2348
+ requestModel = effectiveModel;
2349
+ }
2350
+ const bridgeBody = bridgedGptMessages
2351
+ ? (() => {
2352
+ const bridged = JSON.parse(new TextDecoder().decode(anthropicMessagesToOpenAIResponses(bodyIn)));
2353
+ bridged.model = effectiveModel;
2354
+ return new TextEncoder().encode(JSON.stringify(bridged));
2355
+ })()
2356
+ : bridgedChatMessages
2357
+ ? anthropicMessagesToOpenAIChat(bodyIn, chatStamp ?? undefined)
2358
+ : bodyIn;
2359
+ const routeModel = effectiveModel ?? model ?? undefined;
2360
+ // Third-party hosts never get the OpenAI-only breakpoint field.
2361
+ const allowBreakpoints = !follow && supportsExplicitPromptCacheBreakpoint({
2362
+ pathname: url.pathname,
2363
+ upstream: resolvedOpenAIUpstream,
2364
+ });
2365
+ // Allowlisted models image, except weak or unmeasured readers (Claude
2366
+ // 5.5, Grok, Gemini 4 hydrogen/carbon, DeepSeek, Kimi, GLM, MiniMax),
2367
+ // which stay text unless INKLING_FORCE_IMAGES=1. When compression is not
2368
+ // switched off, weak/text-only/third-party models still receive
2369
+ // prefix-safe deterministic text hygiene (`imageCompress: false`).
2370
+ const imageThisRequest = transformOpts?.stageToggles?.optical !== false &&
2371
+ shouldImageModel(routeModel, modelOk);
2372
+ const hygieneForcedOn = resolveTextHygieneMode(transformOpts?.textHygiene) === 'on';
2373
+ const familyInScope = modelOk || isInConfiguredModelBases(routeModel);
2374
+ const killSwitchOff = transformOpts?.compress === false || (!familyInScope && !hygieneForcedOn);
2375
+ const effectiveOpts = killSwitchOff
2376
+ ? { ...transformOpts, compress: false, explicitPromptCacheBreakpoints: allowBreakpoints }
2377
+ : imageThisRequest
2378
+ ? { ...transformOpts, imageCompress: true, explicitPromptCacheBreakpoints: allowBreakpoints }
2379
+ : { ...transformOpts, imageCompress: false, explicitPromptCacheBreakpoints: allowBreakpoints };
2380
+ // Local render+encode cost only. The Google branch below issues upstream
2381
+ // count_tokens probes, so the timer closes here rather than after them —
2382
+ // otherwise network latency would be charged to our own CPU.
2383
+ const tTransform = Date.now();
2384
+ // Fail open: a renderer or transform bug must never cost the user a
2385
+ // turn. The request goes out as it arrived (after any wire bridge, which
2386
+ // the upstream needs), and the event row records why.
2387
+ const sessionTransformOpts = validatedClientSessionId && validatedClientSessionSource
2388
+ ? {
2389
+ clientSessionId: validatedClientSessionId,
2390
+ clientSessionSource: validatedClientSessionSource,
2391
+ }
2392
+ : undefined;
2393
+ const optsWithSession = sessionTransformOpts
2394
+ ? { ...effectiveOpts, ...sessionTransformOpts }
2395
+ : effectiveOpts;
2396
+ let r;
2397
+ try {
2398
+ r = isGoogle
2399
+ ? await transformGoogleGenerateContent(bridgeBody, model, optsWithSession)
2400
+ : isMessages
2401
+ ? bridgedGptMessages
2402
+ ? await transformOpenAIResponses(bridgeBody, optsWithSession)
2403
+ : bridgedChatMessages
2404
+ ? await transformOpenAIChatCompletions(bridgeBody, optsWithSession)
2405
+ : await transformRequest(bridgeBody, {
2406
+ ...optsWithSession,
2407
+ model: effectiveModel ?? undefined,
2408
+ })
2409
+ : isOpenAIChat
2410
+ ? await transformOpenAIChatCompletions(bridgeBody, optsWithSession)
2411
+ : await transformOpenAIResponses(bridgeBody, optsWithSession);
2412
+ }
2413
+ catch (e) {
2414
+ r = { body: bridgeBody, info: failOpenInfo(bridgeBody, e.message) };
2415
+ }
2416
+ if (!allowBreakpoints && (isOpenAIResponses || isOpenAIChat || bridgedGptMessages || bridgedChatMessages)) {
2417
+ try {
2418
+ r = { ...r, body: scrubPromptCacheBreakpoint(r.body) };
2419
+ }
2420
+ catch {
2421
+ // Fail open if response/body scrubbing encounters an unexpected shape.
2422
+ }
2423
+ }
2424
+ transformMs = Date.now() - tTransform;
2425
+ // CloudCode PA (`/v1internal:*`) has no `:countTokens` endpoint, and
2426
+ // text-hygiene-only turns already have exact local token deltas.
2427
+ if (isGoogle &&
2428
+ r.info.compressed &&
2429
+ (r.info.imageCount ?? 0) > 0 &&
2430
+ !url.pathname.startsWith('/v1internal:')) {
2431
+ try {
2432
+ const countUrl = new URL((isGoogleRoute ? googleUpstream : passthroughUpstream) + url.pathname.replace(/:(?:generateContent|streamGenerateContent)$/, ':countTokens'));
2433
+ for (const [key, value] of url.searchParams)
2434
+ countUrl.searchParams.append(key, value);
2435
+ countUrl.searchParams.delete('alt');
2436
+ const countHeaders = applyGatewayHeadersIfTargeted(filterHeaders(req.headers, STRIP_REQ_HEADERS), countUrl.toString());
2437
+ stripAnthropicCredentials(countHeaders);
2438
+ countHeaders.delete('content-encoding');
2439
+ countHeaders.set('content-type', 'application/json');
2440
+ const syncProbeEnv = readBrandEnv('GOOGLE_SYNC_PROBE') ?? '';
2441
+ const googleSyncProbe = !/^(0|false|no|off)$/i.test(syncProbeEnv.trim());
2442
+ ensureClientAbortWired();
2443
+ if (googleSyncProbe) {
2444
+ const [baseline, transformed] = await Promise.all([
2445
+ countGoogleTokensUpstream(countUrl.toString(), bodyIn, countHeaders, model, fetchImpl, upstreamAbort.signal),
2446
+ countGoogleTokensUpstream(countUrl.toString(), r.body, countHeaders, model, fetchImpl, upstreamAbort.signal),
2447
+ ]);
2448
+ if (baseline !== null && transformed !== null) {
2449
+ if (transformed >= baseline) {
2450
+ r = {
2451
+ body: bodyIn,
2452
+ info: revertedGoogleInfo(r.info, `not_profitable (${transformed} >= ${baseline} tokens)`, 'ok'),
2453
+ };
2454
+ }
2455
+ else {
2456
+ r.info.baselineTokens = baseline;
2457
+ r.info.baselineProbeStatus = 'ok';
2458
+ }
2459
+ }
2460
+ else {
2461
+ // Upstream gateway does not route :countTokens (e.g. Cloudflare AI Gateway).
2462
+ // Retain local profitability decision computed by transformGoogleGenerateContent.
2463
+ r.info.baselineProbeStatus = 'failed';
2464
+ }
2465
+ }
2466
+ else {
2467
+ baselineStatusApplies = true;
2468
+ baselinePromise = countGoogleTokensUpstream(countUrl.toString(), bodyIn, countHeaders, model, fetchImpl, upstreamAbort.signal);
2469
+ }
2470
+ }
2471
+ catch {
2472
+ r.info.baselineProbeStatus = 'failed';
2473
+ }
2474
+ }
2475
+ if (!modelOk && !r.info.compressed && r.info.reason !== 'mmu_hydrate')
2476
+ r.info.reason = 'unsupported_model';
2477
+ bodyOut = r.body; // TS narrows Uint8Array away from BodyInit
2478
+ info = r.info;
2479
+ reqBodyBytes = r.body;
2480
+ r.info.serializedRequestBytes = r.body.byteLength;
2481
+ if (r.body.byteLength > 0) {
2482
+ reqBodySha256 = await sha256Bytes(r.body);
2483
+ reqBodySha8 = reqBodySha256.slice(0, 8);
2484
+ }
2485
+ let requestByteLimit;
2486
+ try {
2487
+ requestByteLimit = requestModel
2488
+ ? resolveGptProfile(requestModel).maxSerializedRequestBytes
2489
+ : undefined;
2490
+ }
2491
+ catch {
2492
+ requestByteLimit = undefined;
2493
+ }
2494
+ if ((r.info.compressed || r.body !== bridgeBody) && requestByteLimit !== undefined) {
2495
+ if (r.body.byteLength > requestByteLimit) {
2496
+ r.info.sizeLimitOutcome = 'rejected';
2497
+ const message = `fiche serialized request exceeds model limit (${r.body.byteLength} > ${requestByteLimit} bytes)`;
2498
+ fireWait(413, r.info, message);
2499
+ const error = isMessages
2500
+ ? { type: 'error', error: { type: 'request_too_large', message } }
2501
+ : { error: { type: 'request_too_large', message } };
2502
+ detachClientAbort();
2503
+ releaseInFlight();
2504
+ return new Response(JSON.stringify(error), {
2505
+ status: 413,
2506
+ headers: { 'content-type': 'application/json' },
2507
+ });
2508
+ }
2509
+ else {
2510
+ r.info.sizeLimitOutcome = 'within_limit';
2511
+ }
2512
+ }
2513
+ // Probes go to the configured Anthropic upstream with the host's keys; a
2514
+ // followed request's prompt must not be copied there.
2515
+ if (isMessages && messagesAnthropic && !follow) {
2516
+ try {
2517
+ baselineStatusApplies = true;
2518
+ threadContinue = isThreadContinuation(bodyIn);
2519
+ // Probes fire on the ORIGINAL body before the main forward so all three overlap.
2520
+ // count_tokens is not billed; ~30-80ms latency is hidden by the main forward.
2521
+ const ctBody = buildBaselineCountTokensBody(bodyIn);
2522
+ if (ctBody) {
2523
+ // Mirror the actual outbound request base+path: count_tokens lives at
2524
+ // `<messages-path>/count_tokens`, so provider-prefixed routes like
2525
+ // `/anthropic/messages` probe `/anthropic/messages/count_tokens`,
2526
+ // joined like the main forward so a `…/anthropic` base isn't doubled.
2527
+ const ctUrl = providerPrefixed
2528
+ ? joinProviderPath(passthroughUpstream, url.pathname + '/count_tokens')
2529
+ : upstream + url.pathname + '/count_tokens';
2530
+ const ctHeaders = applyGatewayHeadersIfTargeted(filterHeaders(req.headers, STRIP_REQ_HEADERS), ctUrl);
2531
+ ctHeaders.delete('content-encoding');
2532
+ ctHeaders.set('content-type', 'application/json');
2533
+ const ctAuth = resolveAuthToken(config);
2534
+ if (config.apiKey)
2535
+ ctHeaders.delete('authorization');
2536
+ if (ctAuth)
2537
+ ctHeaders.delete('x-api-key');
2538
+ if (config.apiKey)
2539
+ ctHeaders.set('x-api-key', config.apiKey);
2540
+ // The probe carries the client's frozen bearer otherwise, so it 401s
2541
+ // exactly when the main forward starts succeeding on the fresh one.
2542
+ if (ctAuth)
2543
+ ctHeaders.set('authorization', `Bearer ${ctAuth}`);
2544
+ ensureClientAbortWired();
2545
+ baselinePromise = countTokensUpstream(ctUrl, ctBody, ctHeaders, (reason) => {
2546
+ if (config.captureErrorReqBody) {
2547
+ baselineProbeError = redactSecrets(reason);
2548
+ }
2549
+ else {
2550
+ const httpMatch = /^(http_\d+)/.exec(reason);
2551
+ baselineProbeError = httpMatch ? httpMatch[1] : reason.split(' ', 1)[0];
2552
+ }
2553
+ }, false, fetchImpl, upstreamAbort.signal);
2554
+ // Null = no markers → cacheable=0 by definition, no probe needed.
2555
+ const ctCacheableBody = buildCacheablePrefixCountTokensBody(bodyIn);
2556
+ if (ctCacheableBody) {
2557
+ baselineCacheablePromise = countTokensUpstream(ctUrl, ctCacheableBody, new Headers(ctHeaders), undefined, false, fetchImpl, upstreamAbort.signal);
2558
+ }
2559
+ }
2560
+ }
2561
+ catch {
2562
+ // Telemetry-only count_tokens probes must never abort the live request.
2563
+ }
2564
+ }
2565
+ }
2566
+ catch (e) {
2567
+ releaseInFlight();
2568
+ if ((bridgedGptMessages || bridgedChatMessages) &&
2569
+ (e.name === 'MessagesBridgeInvalidRequest' || e instanceof SyntaxError)) {
2570
+ detachClientAbort();
2571
+ fireWait(400, undefined, `invalid_request: ${e.message}`);
2572
+ return new Response(JSON.stringify({
2573
+ type: 'error',
2574
+ error: { type: 'invalid_request_error', message: e.message },
2575
+ }), { status: 400, headers: { 'content-type': 'application/json' } });
2576
+ }
2577
+ detachClientAbort();
2578
+ fireWait(502, undefined, `transform_error: ${e.message}`);
2579
+ return new Response(JSON.stringify({ error: 'fiche transform failed' }), {
2580
+ status: 502,
2581
+ headers: { 'content-type': 'application/json' },
2582
+ });
2583
+ }
2584
+ }
2585
+ }
2586
+ }
2587
+ else if (req.method === 'POST') {
2588
+ // The model lives in the body, not the path, so read it here too or the
2589
+ // dashboard row has a blank Model and token columns. Label only: the body
2590
+ // is forwarded byte-for-byte, no transform, no baseline probe, no
2591
+ // accounting change. Never overwrite a model already recovered from the
2592
+ // path — Google routes name it there and carry no body `model`.
2593
+ //
2594
+ // This route also carries uploads and audio, so buffer only what can
2595
+ // plausibly be a JSON request naming a model: declared JSON, declared
2596
+ // length under the cap. Anything else streams and shows a blank Model, as
2597
+ // before. A missing content-length is not evidence of a big body —
2598
+ // chunked clients omit it — so only an explicit over-cap declaration
2599
+ // disqualifies.
2600
+ // A declared length over the sniff cap still disqualifies early, but it is
2601
+ // no longer the only bound: an undeclared or under-declared body used to
2602
+ // reach `arrayBuffer()` and buffer without limit. Now the read itself stops
2603
+ // at the cap and the untouched remainder streams on, so the model label is
2604
+ // best-effort and the memory cost is fixed either way.
2605
+ const declaredType = req.headers.get('content-type') ?? '';
2606
+ const declaredLength = Number(req.headers.get('content-length') ?? NaN);
2607
+ const worthSniffing = declaredType.toLowerCase().includes('json') &&
2608
+ !(Number.isFinite(declaredLength) && declaredLength > MODEL_SNIFF_MAX_BYTES);
2609
+ if (worthSniffing) {
2610
+ const sniffCap = Math.min(MODEL_SNIFF_MAX_BYTES, maxRequestBytes);
2611
+ const { prefix, body: restoredBody } = await sniffPrefixRestoringBody(req, sniffCap);
2612
+ requestModel ??= readModelField(prefix) ?? undefined;
2613
+ bodyOut = restoredBody;
2614
+ }
2615
+ else {
2616
+ bodyOut = req.body; // pass through unchanged, model stays unknown
2617
+ }
2618
+ }
2619
+ else {
2620
+ bodyOut = req.body; // pass through unchanged
2621
+ }
2622
+ // Compute the outbound upstreamUrl BEFORE applying credentials or gateway
2623
+ // headers so every credential/header rule gates on the true destination.
2624
+ // Gateway OpenAI routes drop the `/v1` prefix; provider-prefixed passthrough
2625
+ // routes keep their full path so prefix-routing gateways see `/openai/*`,
2626
+ // `/google-ai-studio/*`, etc. exactly as the client sent them.
2627
+ // The chat bridge forwards to the configured Cloudflare upstream at its
2628
+ // /chat/completions endpoint (chatCompletionsUrl normalizes a bare base,
2629
+ // a /v1 base, or a full …/chat/completions URL). Every other route appends
2630
+ // a path to its resolved base.
2631
+ let upstreamUrl;
2632
+ if (follow) {
2633
+ upstreamUrl = follow.origin + follow.outboundPath;
2634
+ }
2635
+ else if (bridgedChatMessages) {
2636
+ upstreamUrl = chatCompletionsUrl(config.cloudflareUpstream ?? '');
2637
+ }
2638
+ else {
2639
+ const outPath = bridgedGptMessages
2640
+ ? (routes.stripOpenAIV1 ? '/responses' : '/v1/responses')
2641
+ : isOpenAIPath && routes.stripOpenAIV1 ? path.replace(/^\/v1(?=\/)/, '') : path;
2642
+ const requestUpstreamBase = bridgedGptMessages ? openAIUpstream : upstreamBase;
2643
+ upstreamUrl = providerPrefixed && !bridgedGptMessages
2644
+ ? joinProviderPath(requestUpstreamBase, outPath)
2645
+ : requestUpstreamBase + outPath;
2646
+ }
2647
+ const outHeaders = filterHeaders(req.headers, STRIP_REQ_HEADERS);
2648
+ // The body now travels as plain bytes; a stale coding header would make
2649
+ // the upstream try to decompress JSON.
2650
+ if (requestBodyDecoded)
2651
+ outHeaders.delete('content-encoding');
2652
+ if (follow) {
2653
+ // The agent addressed this host with this credential; it is the only one
2654
+ // that may travel. No configured key, no gateway header, and never an
2655
+ // Anthropic-issued credential, which no third party should ever see.
2656
+ stripAnthropicCredentials(outHeaders);
2657
+ }
2658
+ else if (isOpenAIPath || url.pathname.startsWith('/openai/') || bridgedGptMessages || bridgedChatMessages) {
2659
+ // `x-api-key` is Anthropic-only and never belongs on an OpenAI upstream.
2660
+ outHeaders.delete('x-api-key');
2661
+ const anthropicHeaders = [];
2662
+ outHeaders.forEach((_value, name) => {
2663
+ if (name.toLowerCase().startsWith('anthropic-'))
2664
+ anthropicHeaders.push(name);
2665
+ });
2666
+ for (const name of anthropicHeaders)
2667
+ outHeaders.delete(name);
2668
+ // Only inject openAIApiKey when targeting openAIUpstream or gatewayBaseUrl
2669
+ // (never send OPENAI_API_KEY to a custom ANTHROPIC_UPSTREAM on `/openai/*`).
2670
+ const targetsOpenAIOrGateway = urlTargetsBase(upstreamUrl, openAIUpstream)
2671
+ || (gatewayBase !== '' && urlTargetsBase(upstreamUrl, gatewayBase));
2672
+ // The chat bridge uses the Cloudflare token; Responses uses the OpenAI key.
2673
+ const bridgeKey = bridgedChatMessages
2674
+ ? config.cloudflareApiKey
2675
+ : targetsOpenAIOrGateway
2676
+ ? config.openAIApiKey
2677
+ : undefined;
2678
+ if (bridgedGptMessages || bridgedChatMessages) {
2679
+ // A bridged request came in as Anthropic Messages, so whatever credential
2680
+ // it carries is an Anthropic one by construction. Drop it unconditionally
2681
+ // and use only what the host configured for the bridge target.
2682
+ outHeaders.delete('authorization');
2683
+ if (bridgeKey)
2684
+ outHeaders.set('authorization', `Bearer ${bridgeKey}`);
2685
+ }
2686
+ else {
2687
+ // A direct OpenAI-family route. The client's own credential may be the
2688
+ // right one to forward, so decide by shape instead of by whether a host
2689
+ // key happens to be set. See resolveOpenAIRouteAuth for the three rules.
2690
+ const decision = resolveOpenAIRouteAuth(classifyInboundCredential(req.headers), bridgeKey !== undefined && bridgeKey !== '');
2691
+ if (decision.action === 'drop')
2692
+ outHeaders.delete('authorization');
2693
+ else if (decision.action === 'replace')
2694
+ outHeaders.set('authorization', `Bearer ${bridgeKey}`);
2695
+ // 'keep-inbound' leaves the header filterHeaders already copied.
2696
+ }
2697
+ }
2698
+ else if (!isAnthropicCredentialRoute) {
2699
+ // Non-Anthropic provider routes (Google, /compat/, /grok/, /xai/, /deepseek/,
2700
+ // /kimi/, /glm/, etc.) never receive Anthropic credentials.
2701
+ stripAnthropicCredentials(outHeaders);
2702
+ }
2703
+ else {
2704
+ const bearer = resolveAuthToken(config);
2705
+ if (config.apiKey)
2706
+ outHeaders.delete('authorization');
2707
+ if (bearer)
2708
+ outHeaders.delete('x-api-key');
2709
+ if (config.apiKey)
2710
+ outHeaders.set('x-api-key', config.apiKey);
2711
+ if (bearer)
2712
+ outHeaders.set('authorization', `Bearer ${bearer}`);
2713
+ }
2714
+ if (!follow)
2715
+ applyGatewayHeadersIfTargeted(outHeaders, upstreamUrl);
2716
+ // Claude Code smuggles its volatile per-turn billing line inside system
2717
+ // text. transform.ts strips it from the body (no body position is both
2718
+ // cache-safe and invisible — see the billingLine comments there) and hands
2719
+ // it up; it travels upstream as the HTTP header it names.
2720
+ if (info?.billingLine && !follow && isAnthropicMessagesRoute) {
2721
+ const sep = info.billingLine.indexOf(':');
2722
+ if (sep > 0) {
2723
+ try {
2724
+ const headerName = info.billingLine.slice(0, sep).trim().toLowerCase();
2725
+ if (headerName === 'x-anthropic-billing-header') {
2726
+ const headerValue = info.billingLine.slice(sep + 1).replace(/[\r\n]+/g, ' ').trim();
2727
+ outHeaders.set(headerName, headerValue);
2728
+ }
2729
+ }
2730
+ catch {
2731
+ // Malformed header name/value in billingLine must never crash the proxy.
2732
+ }
2733
+ }
2734
+ }
2735
+ // One controller for the whole exchange: headers timeout, stall watchdog and client
2736
+ // disconnect all abort through it, so nothing can hold the socket open indefinitely.
2737
+ ensureClientAbortWired();
2738
+ let timeoutKind;
2739
+ let headersTimer;
2740
+ // Raced explicitly rather than trusting the fetch implementation to reject on
2741
+ // abort — the headers phase must be bounded even if the signal is ignored.
2742
+ const HEADERS_TIMEOUT = Symbol('headers-timeout');
2743
+ const headersDeadline = new Promise((resolve) => {
2744
+ if (headersTimeoutMs <= 0)
2745
+ return;
2746
+ headersTimer = setTimeout(() => {
2747
+ headersTimer = undefined;
2748
+ timeoutKind = 'headers';
2749
+ upstreamAbort.abort(new Error('fiche: upstream headers timeout'));
2750
+ resolve(HEADERS_TIMEOUT);
2751
+ }, headersTimeoutMs);
2752
+ });
2753
+ const clearHeadersTimer = () => {
2754
+ if (headersTimer !== undefined) {
2755
+ clearTimeout(headersTimer);
2756
+ headersTimer = undefined;
2757
+ }
2758
+ };
2759
+ let upstreamRes;
2760
+ try {
2761
+ const upstreamFetch = fetchImpl(upstreamUrl, {
2762
+ method: req.method,
2763
+ headers: outHeaders,
2764
+ // Never auto-follow 3xx redirects upstream: cross-origin redirects could
2765
+ // forward x-api-key, x-goog-api-key, Authorization, or gateway headers.
2766
+ redirect: 'manual',
2767
+ body: bodyOut,
2768
+ signal: upstreamAbort.signal,
2769
+ // duplex is required by spec when sending a stream as body
2770
+ ...(bodyOut instanceof ReadableStream ? { duplex: 'half' } : {}),
2771
+ });
2772
+ const raced = headersTimeoutMs > 0 ? await Promise.race([upstreamFetch, headersDeadline]) : await upstreamFetch;
2773
+ clearHeadersTimer();
2774
+ if (raced === HEADERS_TIMEOUT) {
2775
+ // Abandoned: cancel any late response body so streams never linger unconsumed.
2776
+ void upstreamFetch.then((lateRes) => lateRes.body?.cancel().catch(() => undefined), () => undefined);
2777
+ throw new Error('fiche: upstream headers timeout');
2778
+ }
2779
+ upstreamRes = raced;
2780
+ // Watch the raw upstream stream, before any bridge re-encodes it.
2781
+ upstreamRes = withIdleTimeout(upstreamRes, headersTimeoutMs, idleTimeoutMs, () => {
2782
+ timeoutKind = 'idle';
2783
+ upstreamAbort.abort(new Error('fiche: upstream stalled'));
2784
+ });
2785
+ if (bridgedGptMessages) {
2786
+ upstreamRes = await openAIResponsesToAnthropicResponse(upstreamRes, requestModel ?? '');
2787
+ }
2788
+ else if (bridgedChatMessages) {
2789
+ upstreamRes = await openAIChatToAnthropicResponse(upstreamRes, requestModel ?? '');
2790
+ }
2791
+ }
2792
+ catch (e) {
2793
+ clearHeadersTimer();
2794
+ if (upstreamRes?.body && !upstreamRes.body.locked) {
2795
+ void upstreamRes.body.cancel().catch(() => undefined);
2796
+ }
2797
+ if (!upstreamAbort.signal.aborted) {
2798
+ upstreamAbort.abort(e instanceof Error ? e : new Error(String(e)));
2799
+ }
2800
+ detachClientAbort();
2801
+ releaseInFlight();
2802
+ if (timeoutKind) {
2803
+ const detail = timeoutKind === 'headers'
2804
+ ? `no response headers within ${headersTimeoutMs}ms`
2805
+ : `no upstream bytes for ${idleTimeoutMs}ms`;
2806
+ fireWait(504, info, `upstream_timeout: ${detail}`);
2807
+ return new Response(JSON.stringify({ error: `fiche upstream timeout (${detail})` }), {
2808
+ status: 504,
2809
+ headers: { 'content-type': 'application/json' },
2810
+ });
2811
+ }
2812
+ fireWait(502, info, `upstream_error: ${e.message}`);
2813
+ return new Response(JSON.stringify({ error: 'fiche upstream unreachable' }), {
2814
+ status: 502,
2815
+ headers: { 'content-type': 'application/json' },
2816
+ });
2817
+ }
2818
+ const finalUpstreamRes = upstreamRes;
2819
+ const firstByteMs = Date.now() - t0;
2820
+ const keepUndecodedEncoding = finalUpstreamRes.headers.has('x-fiche-undecoded-encoding');
2821
+ responseContentType = finalUpstreamRes.headers.get('content-type') ?? undefined;
2822
+ responseContentEncoding = finalUpstreamRes.headers.get('content-encoding') ?? undefined;
2823
+ // Inline pull-through scanner: client gets backpressure directly; 5xx/unknown/undecoded skip wrapping.
2824
+ let teed;
2825
+ let usagePromise;
2826
+ let errorBodyPromise;
2827
+ let measurementPromise;
2828
+ let stopReasonPromise;
2829
+ try {
2830
+ ({ response: teed, usagePromise, errorBodyPromise, measurementPromise, stopReasonPromise } =
2831
+ teeForUsage(finalUpstreamRes, isOpenAIResponsesWire && responsesStreaming, isOpenAIResponsesWire && !responsesStreaming, isMessages || isGoogle || isOpenAIChatWire || isOpenAIResponsesWire || bridgedGptMessages || bridgedChatMessages, keepUndecodedEncoding));
2832
+ }
2833
+ catch (e) {
2834
+ if (finalUpstreamRes.body && !finalUpstreamRes.body.locked) {
2835
+ void finalUpstreamRes.body.cancel().catch(() => undefined);
2836
+ }
2837
+ if (!upstreamAbort.signal.aborted) {
2838
+ upstreamAbort.abort(e instanceof Error ? e : new Error(String(e)));
2839
+ }
2840
+ detachClientAbort();
2841
+ releaseInFlight();
2842
+ throw e;
2843
+ }
2844
+ // Client disconnect: drop the lease immediately and abort upstream, rather than
2845
+ // waiting on scanner promises that a wedged connection would never settle.
2846
+ let settleStreamDone = () => { };
2847
+ const streamDonePromise = finalUpstreamRes.status >= 500 && Boolean(teed.body)
2848
+ ? new Promise((resolve) => {
2849
+ let done = false;
2850
+ settleStreamDone = () => {
2851
+ if (!done) {
2852
+ done = true;
2853
+ resolve();
2854
+ }
2855
+ };
2856
+ })
2857
+ : Promise.resolve();
2858
+ const clientBody = teed.body
2859
+ ? withClientDisconnect(teed.body, () => {
2860
+ settleStreamDone();
2861
+ clearHeadersTimer();
2862
+ detachClientAbort();
2863
+ releaseInFlight();
2864
+ if (!upstreamAbort.signal.aborted) {
2865
+ upstreamAbort.abort(new Error('fiche: client disconnected'));
2866
+ }
2867
+ }, () => {
2868
+ settleStreamDone();
2869
+ })
2870
+ : null;
2871
+ // Fire event in background once all scanner promises (and any 5xx body stream) resolve.
2872
+ const bgTask = Promise.all([
2873
+ usagePromise.catch(() => undefined),
2874
+ errorBodyPromise.catch(() => undefined),
2875
+ measurementPromise.catch(() => undefined),
2876
+ stopReasonPromise.catch(() => undefined),
2877
+ streamDonePromise,
2878
+ ]).then(([usage, errorBody, measurement, stopReason]) => {
2879
+ // A rejected request never populated a prefix cache, so the append-only
2880
+ // freeze this session was protecting protects nothing: let the next turn
2881
+ // re-cut the grid for density instead of preserving dead bytes.
2882
+ const sessionKey = info?.sessionKey ?? info?.firstUserSha8;
2883
+ if (responseLeftNoCache(finalUpstreamRes.status, errorBody)) {
2884
+ markCacheDead(sessionKey, requestModel ? { model: requestModel } : undefined);
2885
+ }
2886
+ // Feed the provider's own cache accounting back into the session store. A
2887
+ // read proves the prefix was live; a create proves one was just written.
2888
+ // Either way the next turn must not re-cut the grid or assume cold cache.
2889
+ if (finalUpstreamRes.ok && usage !== undefined && (isAnthropicMessagesRoute || isGoogle || isOpenAIChatWire || isOpenAIResponsesWire || bridgedGptMessages || bridgedChatMessages)) {
2890
+ noteCacheOutcome(sessionKey, usage.cache_read_input_tokens ?? usage.cached_tokens, bridgedGptMessages || bridgedChatMessages
2891
+ ? undefined
2892
+ : (usage.cache_creation_input_tokens ?? usage.cache_write_tokens), requestModel ? { model: requestModel } : undefined);
2893
+ }
2894
+ return fire(finalUpstreamRes.status, info, timeoutKind === 'idle' ? `upstream_timeout: no upstream bytes for ${idleTimeoutMs}ms` : undefined, firstByteMs, usage, config.captureErrorReqBody && errorBody ? redactSecrets(errorBody) : undefined, measurement, stopReason);
2895
+ }).finally(() => {
2896
+ clearHeadersTimer();
2897
+ detachClientAbort();
2898
+ releaseInFlight();
2899
+ }).catch(() => undefined);
2900
+ config.waitUntil?.(bgTask);
2901
+ const resHeaders = filterHeaders(finalUpstreamRes.headers, keepUndecodedEncoding ? STRIP_RES_HEADERS_KEEP_ENCODING : STRIP_RES_HEADERS);
2902
+ if (info && (info.compressed || (info.textHygieneSavedTokens ?? 0) > 0 || (info.textHygieneStages?.length ?? 0) > 0)) {
2903
+ const imagedSaved = info.compressed
2904
+ ? Math.max(0, (info.baselineImagedTokens ?? Math.round((info.compressedChars ?? 0) / 4)) -
2905
+ (info.imageTokens ?? 0))
2906
+ : 0;
2907
+ const savedTokens = (info.textHygieneSavedTokens ?? 0) + imagedSaved;
2908
+ const stages = [
2909
+ ...(info.compressed && (info.imageCount ?? 0) > 0 ? ['image'] : []),
2910
+ ...(info.textHygieneStages ?? []),
2911
+ ];
2912
+ if (savedTokens > 0)
2913
+ resHeaders.set('x-fiche-saved-tokens', String(savedTokens));
2914
+ if (stages.length > 0)
2915
+ resHeaders.set('x-fiche-stages', [...new Set(stages)].join(','));
2916
+ if (info.cliffAvoided && info.cliffAvoided.savedUsd > 0) {
2917
+ resHeaders.set('x-fiche-cliff-saved-usd', info.cliffAvoided.savedUsd.toFixed(4));
2918
+ }
2919
+ }
2920
+ if (!clientBody)
2921
+ detachClientAbort();
2922
+ return new Response(clientBody, {
2923
+ status: finalUpstreamRes.status,
2924
+ statusText: finalUpstreamRes.statusText,
2925
+ headers: resHeaders,
2926
+ });
2927
+ };
2928
+ }
2929
+ //# sourceMappingURL=proxy.js.map