-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathbase.ts
More file actions
1750 lines (1630 loc) · 77.1 KB
/
Copy pathbase.ts
File metadata and controls
1750 lines (1630 loc) · 77.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { HTTP_STATUS, FETCH_TIMEOUT_MS } from "../config/constants.ts";
import { getRegistryEntry } from "../config/providerRegistry.ts";
import { resolveFetchStartTimeout } from "../utils/fetchStartTimeoutPolicy.ts";
import {
resolveAlternateFormat,
type AlternateFormat,
} from "../config/providers/alternateFormats.ts";
import {
CLAUDE_CLI_STAINLESS_RUNTIME_VERSION,
getClaudeCliBillingVersion,
mergeClientAnthropicBeta,
normalizeAnthropicHeaderVariants,
} from "../config/anthropicHeaders.ts";
import { applyContextEditingToBody } from "../config/contextEditing.ts";
import {
findOffendingField,
detectUnsupportedParam,
stripGroqUnsupportedFields,
} from "../config/providerFieldStrips.ts";
import {
recordLearnedThinkingCap,
parseThinkingBudgetMax,
} from "../services/learnedThinkingCaps.ts";
import {
recordLearnedReasoningEffort,
parseReasoningEffortEnum,
} from "../services/learnedReasoningEffortCaps.ts";
import {
getParamFilterConfig,
addParamToBlocklist,
isAutoLearnGloballyEnabled,
} from "@/lib/db/paramFilters";
import { applyFingerprint, isCliCompatEnabled, stripInternalBodyFields } from "../config/cliFingerprints.ts";
import { supportsClaudeMaxEffort, supportsXHighEffort } from "../config/providerModels.ts";
import { getThinkingBudgetConfig, ThinkingMode } from "../services/thinkingBudget.ts";
import {
recordFreeWindowAttempt,
correctFromRateLimitHeaders,
resolveAccountKey,
isFreeVariantModel,
} from "../services/openrouterFreeWindow.ts";
import { gateOutboundRequest } from "../services/wafRateLimit.ts";
import type { PoolConfig } from "../services/sessionPool/types.ts";
import type { Session } from "../services/sessionPool/session.ts";
import { SessionPool } from "../services/sessionPool/sessionPool.ts";
import { PoolRegistry } from "../services/sessionPool/poolRegistry.ts";
import {
getRotatingApiKey,
getValidApiKey,
resolveKeyForRequest,
} from "../services/apiKeyRotator.ts";
import type { KeyHealth } from "../services/apiKeyRotator.ts";
import { getOpenAICompatibleType, isClaudeCodeCompatible } from "../services/provider.ts";
import { usesCcWireImage } from "../services/ccWireImageBuiltins.ts";
import {
runWithOnPersist,
getRefreshLeadMs,
isUnrecoverableRefreshError,
} from "../services/tokenRefresh.ts";
import type { ProviderRequestDefaults } from "../services/providerRequestDefaults.ts";
import { signRequestBody } from "../services/claudeCodeCCH.ts";
import { normalizeCacheControlTtl } from "../services/claudeCodeConstraints.ts";
import {
appendAnthropicBetaHeader,
CLAUDE_CODE_COMPATIBLE_REDACT_THINKING_BETA,
CONTEXT_1M_BETA_HEADER,
enforceThinkingTemperature,
modelHasNativeContext1m,
modelSupportsContext1mBeta,
} from "../services/claudeCodeCompatible.ts";
import { getClaudeCodeCompatibleRequestDefaults } from "@/lib/providers/requestDefaults";
import {
cloakThirdPartyToolNames,
remapToolNamesInRequest,
} from "../services/claudeCodeToolRemapper.ts";
import { obfuscateInBody } from "../services/claudeCodeObfuscation.ts";
import { sanitizeClaudeToolSchemas } from "../translator/helpers/schemaCoercion.ts";
import { sanitizeResponsesInputItems } from "../services/responsesInputSanitizer.ts";
import { applySystemTransformPipeline, PROVIDER_CLAUDE } from "../services/systemTransforms.ts";
import * as prl from "../utils/providerRequestLogging.ts";
import {
fixToolPairs,
fixToolAdjacency,
stripTrailingAssistantOrphanToolUse,
stripTrailingAssistantForProvider,
} from "../services/contextManager.ts";
import { randomUUID } from "node:crypto";
import {
getClaudeCodeVersion,
CLAUDE_CODE_STAINLESS_VERSION,
buildUserIdJson,
getSessionId,
parseUpstreamMetadataUserId,
passthroughUpstreamSessionId,
resolveAccountUUID,
resolveCliUserID,
selectBetaFlags,
stainlessArch,
stainlessOS,
stripProxyToolPrefix,
} from "./claudeIdentity.ts";
import { withForcedResponsesUpstream } from "./forceResponsesUpstream.ts";
import {
mergeUpstreamExtraHeaders,
setUserAgentHeader,
applyConfiguredUserAgent,
stripStainlessHeadersForOpenAICompat,
} from "./base/headers.ts";
import { applyPeerTraceHeader } from "@/shared/resilience/peerRouting";
import { applyClineProtocolHeaders } from "@/shared/utils/clineAuth";
import { isProbeContext } from "@/shared/utils/probeOrigin";
import {
parseAndValidatePublicUrl,
parseAndValidateNonMetadataUrl,
} from "@/shared/network/outboundUrlGuard";
import { getProviderValidationGuard } from "@/shared/network/outboundUrlGuardPolicy";
import { isLocalProvider, isSelfHostedChatProvider } from "@/shared/constants/providers";
// Header helpers extracted to a pure leaf; re-exported for external importers
// (executors + tests) that import them from "./base.ts".
export {
mergeUpstreamExtraHeaders,
getCustomUserAgent,
setUserAgentHeader,
applyConfiguredUserAgent,
isOpenAICompatibleEndpoint,
stripStainlessHeadersForOpenAICompat,
} from "./base/headers.ts";
import { sanitizeReasoningEffortForProvider } from "./base/reasoningEffort.ts";
// Reasoning-effort sanitation extracted to a pure leaf; re-exported for external
// importers (mimoThinking service + tests) that import it from "./base.ts".
export { sanitizeReasoningEffortForProvider } from "./base/reasoningEffort.ts";
/**
* Sanitizes a custom API path to prevent path traversal attacks.
* Valid paths must start with '/', contain no '..' segments,
* no null bytes, and be reasonable in length.
*/
function sanitizePath(path: string): boolean {
if (typeof path !== "string") return false;
if (!path.startsWith("/")) return false;
if (path.includes("\0")) return false; // null byte
if (path.includes("..")) return false; // path traversal
if (path.length > 512) return false; // sanity limit
return true;
}
type JsonRecord = Record<string, unknown>;
export type ProviderConfig = {
id?: string;
baseUrl?: string;
baseUrls?: string[];
responsesBaseUrl?: string;
messagesUrl?: string;
chatPath?: string;
clientVersion?: string;
clientId?: string;
clientSecret?: string;
tokenUrl?: string;
refreshUrl?: string;
authUrl?: string;
headers?: Record<string, string>;
requestDefaults?: ProviderRequestDefaults;
timeoutMs?: number;
format?: string;
};
export type ProviderCredentials = {
accessToken?: string;
refreshToken?: string;
apiKey?: string;
email?: string | null;
projectId?: string | null;
expiresAt?: string;
connectionId?: string; // T07: used for API key rotation index
maxConcurrent?: number | null;
providerSpecificData?: JsonRecord;
requestEndpointPath?: string;
};
export type ExecutorLog = {
debug?: (tag: string, message: string) => void;
info?: (tag: string, message: string) => void;
warn?: (tag: string, message: string) => void;
error?: (tag: string, message: string) => void;
};
export type ExecuteInput = {
model: string;
body: unknown;
stream: boolean;
credentials: ProviderCredentials;
signal?: AbortSignal | null;
log?: ExecutorLog | null;
extendedContext?: boolean;
/** Merged after auth + CLI fingerprint headers (values override same-named defaults). */
upstreamExtraHeaders?: Record<string, string> | null;
/** Original client request headers (read-only). Executors may forward select headers upstream. */
clientHeaders?: Record<string, string> | null;
/** Response format the end client expects (e.g. "openai-responses"). Executors
* that do their own Claude→OpenAI stream translation (GLM, zed-hosted) use
* this to apply client-format-aware policies such as `</think>` close-marker
* suppression. */
clientResponseFormat?: string | null;
/** Callback to persist tokens that are proactively refreshed during execution.
* Accepts a partial credentials patch (e.g. `{ accessToken, refreshToken }` or
* `{ testStatus: "expired", isActive: false }`); the caller merges into the
* stored connection row. */
onCredentialsRefreshed?: (
newCredentials: Partial<ProviderCredentials> & Record<string, unknown>
) => Promise<void> | void;
/** When true, skip the intra-URL 429 retry in execute() so the caller handles fallback. */
skipUpstreamRetry?: boolean;
/** Delegated Context Editing (Claude only): when enabled, attach the
* `context_management.clear_tool_uses` strategy so the provider clears stale
* tool-use blocks server-side. Honored only on the genuine `claude` path. */
contextEditing?: { enabled: boolean } | null;
};
export type CountTokensInput = {
body: Record<string, unknown>;
credentials: ProviderCredentials;
log?: ExecutorLog | null;
model: string;
signal?: AbortSignal | null;
};
export function mergeAbortSignals(primary: AbortSignal, secondary: AbortSignal): AbortSignal {
const controller = new AbortController();
const abortFrom = (source: AbortSignal) => {
if (!controller.signal.aborted) {
controller.abort(source.reason);
}
};
if (primary.aborted) {
abortFrom(primary);
return controller.signal;
}
if (secondary.aborted) {
abortFrom(secondary);
return controller.signal;
}
primary.addEventListener("abort", () => abortFrom(primary), { once: true });
secondary.addEventListener("abort", () => abortFrom(secondary), { once: true });
return controller.signal;
}
import {
hasActiveClaudeThinking,
readNestedThinkingBudget,
clampNestedThinkingBudget,
} from "../utils/thinkingBudget.ts";
/**
* Strip the OmniRoute provider prefix from tool model fields (e.g.
* `cc/claude-opus-4-8` → `claude-opus-4-8`). Versioned built-in tool types carry
* an 8-digit date suffix (`advisor_20260301`, `bash_20250124`); non-versioned
* server tools (Task/subagent, web_search) carry the same prefixed model. The
* real Claude CLI sends a bare model id there, never a prefixed one, so a leaked
* OmniRoute prefix makes Anthropic reject the request.
*
* Two mechanisms, applied to any tool with a string `model`:
* 1. Versioned built-in types (`type` matches `_\d{8}$`): strip the last path
* segment (`model.split("/").pop()`), matching legacy behavior for kiro/ etc.
* 2. Any tool whose model starts with a 9router Claude provider prefix
* (`cc/`, `claude/`): strip exactly that prefix (`slice`), preserving foreign
* providers such as `openrouter/anthropic/...` — mirrors upstream
* normalizeClaudeServerToolModels (9router#2649).
* Mutates in place.
*/
const CLAUDE_TOOL_MODEL_PREFIXES = ["cc/", "claude/"] as const;
export function stripVersionedToolModelPrefix(tools: unknown): void {
if (!Array.isArray(tools)) return;
for (const t of tools as Array<Record<string, unknown>>) {
if (typeof t.model !== "string") continue;
const model = t.model;
if (
typeof t.type === "string" &&
/^[a-z][a-z0-9_]*_\d{8}$/.test(t.type) &&
model.includes("/")
) {
t.model = model.split("/").pop();
} else {
const prefix = CLAUDE_TOOL_MODEL_PREFIXES.find((candidate) => model.startsWith(candidate));
if (prefix) t.model = model.slice(prefix.length);
}
}
}
/**
* BaseExecutor - Base class for provider executors.
* Implements the Strategy pattern: subclasses override specific methods
* (buildUrl, buildHeaders, transformRequest, etc.) for each provider.
*/
/**
* What an executor's `execute()` may resolve to.
*
* Both arms are real: the web/scraping executors return a bare `Response` from their
* error and passthrough paths, while the HTTP executors return the richer capture
* object used for upstream request logging. `normalizeExecutorResult()` accepts
* exactly this union and wraps the bare form, so the contract is the union — not the
* object shape that `BaseExecutor.execute` happens to infer from its single return.
*/
export type ExecutorExecuteResult =
| Response
| {
response: Response;
url?: string;
headers?: Record<string, string>;
transformedBody?: unknown;
transport?: string;
};
export class BaseExecutor {
provider: string;
config: ProviderConfig;
// Session pool support — subclasses can set poolConfig to opt in
protected poolConfig?: PoolConfig;
private _pool: import("../services/sessionPool/sessionPool.ts").SessionPool | null = null;
constructor(provider: string, config: ProviderConfig) {
this.provider = provider;
this.config = config;
}
getProvider() {
return this.provider;
}
protected getPool(): SessionPool | null {
if (!this.poolConfig) return null;
if (!this._pool) {
const pool = new SessionPool(this.provider, this.poolConfig);
pool.warmUp(this.poolConfig.minSessions).catch(() => {});
PoolRegistry.register(this.provider, pool);
this._pool = pool;
}
return this._pool;
}
protected buildPoolHeaders(session: Session | null): Record<string, string> {
if (!session) return {};
return session.buildHeaders();
}
getBaseUrls() {
return this.config.baseUrls || (this.config.baseUrl ? [this.config.baseUrl] : []);
}
getFallbackCount() {
return this.getBaseUrls().length || 1;
}
getTimeoutMs() {
const configured = this.config?.timeoutMs;
if (typeof configured !== "number" || !Number.isFinite(configured)) {
return FETCH_TIMEOUT_MS;
}
return Math.max(1, Math.floor(configured));
}
getCountTokensTimeoutMs() {
return this.getTimeoutMs();
}
buildUrl(
model: string,
stream: boolean,
urlIndex = 0,
credentials: ProviderCredentials | null = null
) {
void model;
void stream;
if (this.provider?.startsWith?.("openai-compatible-")) {
const psd = credentials?.providerSpecificData;
const baseUrl = typeof psd?.baseUrl === "string" ? psd.baseUrl : "https://api.openai.com/v1";
const normalized = baseUrl.replace(/\/$/, "");
// Sanitize custom path: must start with '/', no path traversal, no null bytes
const rawPath = typeof psd?.chatPath === "string" && psd.chatPath ? psd.chatPath : null;
const customPath = rawPath && sanitizePath(rawPath) ? rawPath : null;
if (customPath) return `${normalized}${customPath}`;
const path =
getOpenAICompatibleType(this.provider, psd) === "responses"
? "/responses"
: "/chat/completions";
return `${normalized}${path}`;
}
const baseUrls = this.getBaseUrls();
return baseUrls[urlIndex] || baseUrls[0] || this.config.baseUrl || "";
}
/**
* Resolve the effective base URL for a request, preferring per-connection
* providerSpecificData.baseUrl over the static provider config baseUrl.
*/
protected resolveBaseUrl(credentials: ProviderCredentials | null, fallback?: string): string {
const psdBaseUrl = credentials?.providerSpecificData?.baseUrl;
// Operator's manual override always wins (#6147).
if (typeof psdBaseUrl === "string" && psdBaseUrl) return psdBaseUrl;
// An alternate protocol selected on the connection carries its own URL.
const alternate = this.resolveAlternate(credentials);
if (alternate?.baseUrl) return alternate.baseUrl;
return fallback || this.config.baseUrl || "";
}
/**
* SSRF guard for the runtime dispatch path (GHSA-4f49-hj64-448x). A persisted,
* caller-supplied `providerSpecificData.baseUrl` reaches the fetch() calls
* below, so a `manage`-scope actor (or, on a keyless install, an anonymous
* one) could point a provider at loopback / internal / cloud-metadata hosts
* and exfiltrate the stored upstream key. Mirror the provider VALIDATION
* guard so runtime dispatch makes the same decision the validation layer
* already makes: local / self-hosted providers are exempt (they legitimately
* use private URLs, and the OMNIROUTE_ALLOW_PRIVATE_PROVIDER_URLS opt-in still
* applies through the guard), and for everything else `public-only` mode
* blocks private + metadata while the default `block-metadata` mode blocks the
* cloud-metadata IMDS pivot. Throws on a blocked URL.
*/
protected assertOutboundUrlAllowed(url: string): void {
if (!url) return;
if (isLocalProvider(this.provider) || isSelfHostedChatProvider(this.provider)) return;
if (getProviderValidationGuard() === "public-only") {
parseAndValidatePublicUrl(url);
return;
}
parseAndValidateNonMetadataUrl(url);
}
/**
* Alternate protocol selected on this connection, if the provider declares one
* that matches. Centralizes the registry lookup so every call-site resolves the
* same way.
*/
protected resolveAlternate(credentials: ProviderCredentials | null): AlternateFormat | null {
return resolveAlternateFormat(
getRegistryEntry(this.provider),
credentials?.providerSpecificData
);
}
protected usesClaudeCodeProtocol(credentials: ProviderCredentials | null): boolean {
if (!isClaudeCodeCompatible(this.provider)) return false;
const format = this.resolveAlternate(credentials)?.format;
return format !== "openai" && format !== "openai-responses";
}
/**
* Resolve the effective API key via extra-keys round-robin rotation.
* Mutates `credentials.providerSpecificData.selectedKeyId` on rotation.
*/
protected resolveEffectiveKey(credentials: ProviderCredentials): string | undefined {
const extraKeys =
(credentials.providerSpecificData?.extraApiKeys as string[] | undefined) ?? [];
const selectedKeyId = (credentials.providerSpecificData as Record<string, unknown> | undefined)
?.selectedKeyId as string | undefined;
const validExtras = extraKeys.filter((k) => typeof k === "string" && k.trim().length > 0);
let effectiveKey = credentials.apiKey;
// Rotate whenever extras exist — including empty primary + populated extras (#8467).
// getValidApiKey already skips a blank primary and round-robins the extras alone.
if (validExtras.length > 0 && credentials.connectionId) {
const resolved = resolveKeyForRequest(
credentials.connectionId,
credentials.apiKey || "",
validExtras,
selectedKeyId ?? null
);
effectiveKey = resolved?.key ?? credentials.apiKey;
if (resolved && credentials.providerSpecificData) {
(credentials.providerSpecificData as Record<string, unknown>).selectedKeyId =
resolved.keyId;
}
}
return effectiveKey;
}
/**
* Build the common header preamble shared by BaseExecutor and DefaultExecutor:
* Content-Type, config.headers, per-provider User-Agent env override, and
* resolved effective key (via extra-keys round-robin).
*/
protected buildHeadersPreamble(
credentials: ProviderCredentials,
stream: boolean
): { headers: Record<string, string>; effectiveKey: string | undefined } {
const alternate = this.resolveAlternate(credentials);
const headers: Record<string, string> = {
"Content-Type": "application/json",
...this.config.headers,
...(alternate?.headers || {}),
};
// Allow per-provider User-Agent override via environment variable.
// Example: CLAUDE_USER_AGENT="my-agent/2.0" overrides the default for the Claude provider.
const providerId = this.config?.id || this.provider;
if (providerId) {
const envKey = `${providerId.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_USER_AGENT`;
const envUA = process.env[envKey]?.trim();
if (envUA) {
setUserAgentHeader(headers, envUA);
}
}
const effectiveKey = this.resolveEffectiveKey(credentials);
void stream;
return { headers, effectiveKey };
}
buildHeaders(
credentials: ProviderCredentials,
stream = true,
clientHeaders?: Record<string, string> | null,
model?: string,
health?: Record<string, KeyHealth>,
body?: unknown
): Record<string, string> {
void clientHeaders;
void model;
const { headers, effectiveKey } = this.buildHeadersPreamble(credentials, stream);
if (credentials.accessToken) {
headers["Authorization"] = `Bearer ${credentials.accessToken}`;
} else if (effectiveKey) {
headers["Authorization"] = `Bearer ${effectiveKey}`;
}
headers["Accept"] = stream ? "text/event-stream" : "application/json";
normalizeAnthropicHeaderVariants(headers);
return headers;
}
// Override in subclass for provider-specific transformations
transformRequest(
model: string,
body: unknown,
stream: boolean,
credentials: ProviderCredentials
): unknown {
void model;
void stream;
void credentials;
// Fix #1674: Remove empty string values from optional parameters
// like tool descriptions to avoid upstream validation failures.
if (body && typeof body === "object" && !Array.isArray(body)) {
const cloned = { ...body } as Record<string, unknown>;
if (Array.isArray(cloned.input)) {
cloned.input = sanitizeResponsesInputItems(cloned.input, false);
}
if (Array.isArray(cloned.tools)) {
cloned.tools = cloned.tools.map((tool: unknown) => {
if (tool && typeof tool === "object" && !Array.isArray(tool)) {
const toolRecord = tool as JsonRecord;
const toolFunction = toolRecord.function;
if (toolFunction && typeof toolFunction === "object" && !Array.isArray(toolFunction)) {
const func = { ...(toolFunction as JsonRecord) };
if (func.description === "") delete func.description;
if (typeof func.name !== "string" || func.name.trim() === "") {
func.name = "unnamed_tool";
}
return { ...toolRecord, function: func };
}
}
return tool;
});
}
// Fix #1884: Cursor sends prompt_cache_retention which breaks strict upstream endpoints
delete cloned.prompt_cache_retention;
// Also clean up top level optional fields that commonly cause issues when empty
const optionalKeys = ["user", "stop", "seed", "response_format"];
for (const key of optionalKeys) {
if (cloned[key] === "") delete cloned[key];
}
stripInternalBodyFields(cloned);
return cloned;
}
return body;
}
shouldRetry(status: number, urlIndex: number) {
return status === HTTP_STATUS.RATE_LIMITED && urlIndex + 1 < this.getFallbackCount();
}
// Intra-URL retry config: retry same URL before falling back to next node
static readonly RETRY_CONFIG = { maxAttempts: 2, delayMs: 2000 };
// WAF (400 content-blocked) retry config: agentrouter.org's WAF is burst-sensitive
// and recovers after a short cooldown. Use exponential backoff with a higher
// starting delay than the generic 429 retry (which is 2s) because the WAF
// needs more time to clear its per-IP suspicion bucket.
static readonly WAF_RETRY_CONFIG = {
maxAttempts: 2,
delayMs: 1500,
backoffMultiplier: 2,
};
// Timeout for receiving the initial upstream response headers. Once the response
// starts streaming, STREAM_IDLE_TIMEOUT_MS / Undici bodyTimeout handle stalls.
static FETCH_START_TIMEOUT_MS = FETCH_TIMEOUT_MS;
// Override in subclass for provider-specific refresh
async refreshCredentials(
credentials: ProviderCredentials,
log: ExecutorLog | null
): Promise<Partial<ProviderCredentials> | null> {
void credentials;
void log;
return null;
}
needsRefresh(credentials?: ProviderCredentials | null) {
if (!credentials?.expiresAt) return false;
const expiresAtMs = new Date(credentials.expiresAt).getTime();
// Use the provider-specific lead time (REFRESH_LEAD_MS) so rotating-token
// providers like Codex refresh proactively far ahead of expiry. Keeping the
// refresh_token "warm" prevents Auth0 from marking it as stale and revoking
// the token family on first use after long idle.
const lead = getRefreshLeadMs(this.provider);
return expiresAtMs - Date.now() < lead;
}
parseError(response: Response, bodyText: string) {
return { status: response.status, message: bodyText || `HTTP ${response.status}` };
}
buildCountTokensUrl(model: string, credentials: ProviderCredentials | null = null) {
void model;
void credentials;
const baseUrl = this.buildUrl(model, false, 0, credentials);
if (typeof baseUrl !== "string" || baseUrl.length === 0) return null;
if (this.config?.format !== "claude" || !baseUrl.includes("/messages")) return null;
const [path, query = ""] = baseUrl.split("?");
const normalizedPath = path.endsWith("/messages")
? `${path}/count_tokens`
: `${path}/count_tokens`;
return query ? `${normalizedPath}?${query}` : normalizedPath;
}
async countTokens({ model, body, credentials, signal, log }: CountTokensInput) {
const url = this.buildCountTokensUrl(model, credentials);
if (!url) return null;
this.assertOutboundUrlAllowed(url); // GHSA-4f49
const headers = this.buildHeaders(credentials, false);
const requestBody =
body && typeof body === "object"
? {
...body,
model,
}
: { model };
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let activeSignal = signal || null;
let controller: AbortController | null = null;
const timeoutMs = this.getCountTokensTimeoutMs();
if (timeoutMs > 0) {
controller = new AbortController();
timeoutId = setTimeout(() => controller?.abort(), timeoutMs);
activeSignal = signal ? mergeAbortSignals(signal, controller.signal) : controller.signal;
}
try {
const response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(requestBody),
signal: activeSignal || undefined,
});
const text = await response.text();
if (!response.ok) {
const parsedError = this.parseError(response, text);
throw new Error(parsedError.message);
}
const parsed = text ? JSON.parse(text) : {};
const inputTokens = Number(parsed?.input_tokens);
if (!Number.isFinite(inputTokens)) {
throw new Error("Provider count_tokens response missing input_tokens");
}
return { input_tokens: inputTokens, provider: this.provider, source: "provider" };
} catch (error) {
log?.debug?.(
"COUNT_TOKENS",
`${this.provider}/${model} real count unavailable: ${error instanceof Error ? error.message : String(error)}`
);
return null;
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
}
async execute(input: ExecuteInput): Promise<ExecutorExecuteResult> {
const {
model,
body,
stream,
credentials,
signal,
log,
extendedContext,
upstreamExtraHeaders,
clientHeaders,
skipUpstreamRetry = false,
onCredentialsRefreshed,
contextEditing,
} = input;
const fallbackCount = this.getFallbackCount();
let lastError: unknown = null;
let lastStatus = 0;
let activeCredentials = credentials;
// Track per-URL intra-retry attempts to avoid infinite loops
const retryAttemptsByUrl: Record<number, number> = {};
// Probe-origin dispatches must not consume a refresh-token rotation —
// routing state untouched; the reactive 401/403 path is probe-guarded
// in chatCore (#9817).
if (!isProbeContext() && this.needsRefresh(credentials)) {
try {
// Fix A: wire onCredentialsRefreshed through runWithOnPersist so it runs
// INSIDE the per-connection mutex inside getAccessToken. Not every
// executor routes through getAccessToken (e.g. github.ts), so use a flag
// to detect whether the persist callback actually fired and fall back to
// post-refresh mutation when it didn't.
let proactivePersistRan = false;
const proactiveOnPersist = onCredentialsRefreshed
? async (refreshResult: Record<string, unknown>) => {
proactivePersistRan = true;
activeCredentials = {
...credentials,
...(refreshResult as Partial<ProviderCredentials>),
};
await onCredentialsRefreshed(refreshResult as Partial<ProviderCredentials>);
}
: null;
const refreshed = await runWithOnPersist(proactiveOnPersist, () =>
this.refreshCredentials(credentials, log || null)
);
if (refreshed && !proactivePersistRan) {
// ─────────────────────────────────────────────────────────────────────
// ⚠️ SOURCE OF TRUTH — do not flip the proactive path back to
// "persist expired+inactive". Ask the operator first.
//
// History (do not repeat past regressions):
// - ad3d4b696 (#2718, 2026-05-25): per-connection mutex + onPersist
// wiring so multi-account Codex (rotating refresh tokens) stops
// hitting refresh_token_reused under concurrent load.
// - 0c94c397d (#2743, 2026-05-26): a multi-agent review added a
// `await onCredentialsRefreshed({ testStatus: "expired",
// isActive: false })` here. That BROKE multi-account Codex —
// transient sentinels (refresh_token_reused recoverable via
// rotation map; generic invalid_request blips) were treated as
// terminal, so the proactive path sequentially disabled
// working accounts in the DB before any upstream call confirmed
// the failure. Reverted intentionally.
//
// Contract for the PROACTIVE refresh path:
// - Classify the sentinel ONLY to avoid spreading it into
// activeCredentials (which would send a non-token upstream).
// - DO NOT persist `{ testStatus: "expired", isActive: false }`
// from here. That decision belongs to the REACTIVE path in
// open-sse/handlers/chatCore.ts:~3912, which runs AFTER the
// upstream confirmed the auth failure. By then the rotation
// map (tokenRefresh.ts:~1541) and the DB-staleness check have
// already had their chance to recover the request.
//
// If a future review/agent thinks the expired-flip is "missing"
// here, STOP — flipping it here re-introduces the multi-account
// Codex regression. Discuss with the operator before touching.
// ─────────────────────────────────────────────────────────────────────
if (isUnrecoverableRefreshError(refreshed)) {
const refreshCode = (refreshed as Record<string, unknown>).code;
log?.warn?.(
"TOKEN",
`${this.provider.toUpperCase()} | proactive refresh returned unrecoverable sentinel (code=${String(refreshCode ?? "unknown")}); keeping stale credentials, deferring to reactive path.`
);
// Intentionally NOT spreading the sentinel and NOT persisting
// expired status. The next upstream call either succeeds (rotation
// map / DB-staleness saved us) or fails — chatCore.ts then marks
// the account expired with confidence.
} else {
activeCredentials = {
...credentials,
...refreshed,
};
if (onCredentialsRefreshed) {
await onCredentialsRefreshed(refreshed);
}
}
}
} catch (error) {
// tokenRefresh.ts:1352 documents that onPersist throws are re-thrown so
// the caller is aware of the persistence failure. Honor that contract:
// log at error level (not warn), with sanitized message — and let the
// request continue with stale credentials so the user-visible error
// surfaces upstream rather than being silently absorbed here.
log?.error?.(
"TOKEN",
`Credential refresh failed for ${this.provider}: ${error instanceof Error ? error.message : String(error)}`
);
}
}
// Set by the Context Editing 400-fallback below: once an upstream rejects the
// `context_management` param, suppress its re-injection on every later
// retry/fallback URL (each iteration rebuilds a fresh `transformedBody`).
let contextEditingDisabled = false;
// Tracks which request fields have already been stripped via the generic 400
// field-downgrade below, so each known field is stripped at most once across
// all fallback URLs (bounded retry loop).
const strippedFields = new Set<string>();
// Set by the thinking_budget 400 clamp-and-retry below: the upstream's
// advertised max (parsed from the error) is applied to every later
// retry/fallback URL so they don't re-hit the same 400. The clamp itself
// fires at most once per URL (guarded inline) so a persistent 400 cannot
// loop. The learned cap is also recorded process-wide via
// recordLearnedThinkingCap so future requests skip the 400 entirely.
let thinkingBudgetClampedMax: number | null = null;
// Set by the reasoning_effort 4xx clamp-and-retry below — guards the same
// "fires at most once per URL" invariant as thinkingBudgetClampedMax above.
let reasoningEffortClamped = false;
for (let urlIndex = 0; urlIndex < fallbackCount; urlIndex++) {
const requestCredentials = withForcedResponsesUpstream(
this.provider,
body,
activeCredentials
);
const url = this.buildUrl(model, stream, urlIndex, requestCredentials);
const headers = this.buildHeaders(
requestCredentials,
stream,
clientHeaders,
model,
undefined,
body
);
applyConfiguredUserAgent(headers, requestCredentials?.providerSpecificData);
// Strip OpenAI SDK (X-Stainless-*) metadata + normalize SDK-derived User-Agent
// on OpenAI-compatible passthrough requests — some upstream gateways 403 on them.
const strippedStainless = stripStainlessHeadersForOpenAICompat(headers, this.provider, url);
if (strippedStainless.length > 0) {
log?.debug?.(
"HEADERS",
`Stripped X-Stainless-* from OpenAI-compatible request: ${strippedStainless.join(", ")}`
);
}
const usesClaudeCodeProtocol = this.usesClaudeCodeProtocol(requestCredentials);
const fingerprintProvider =
usesCcWireImage(this.provider) && !usesClaudeCodeProtocol ? "codex" : this.provider;
const ccRequestDefaults = usesClaudeCodeProtocol
? getClaudeCodeCompatibleRequestDefaults(requestCredentials?.providerSpecificData)
: {};
const shouldForwardExtendedContext =
extendedContext && modelSupportsContext1mBeta(model) && !usesClaudeCodeProtocol;
const shouldForwardCcCompatibleContext1m =
usesClaudeCodeProtocol &&
ccRequestDefaults.context1m === true &&
!modelHasNativeContext1m(model);
if (shouldForwardExtendedContext || shouldForwardCcCompatibleContext1m) {
appendAnthropicBetaHeader(headers, CONTEXT_1M_BETA_HEADER);
}
const rawTransformedBody = await this.transformRequest(
model,
body,
stream,
requestCredentials
);
let transformedBody = sanitizeReasoningEffortForProvider(
rawTransformedBody,
this.provider,
model,
log
);
if (this.provider === "groq") {
transformedBody = stripGroqUnsupportedFields(
transformedBody as Record<string, unknown>
) as typeof transformedBody;
}
// A previous URL in this execute() already hit a thinking_budget 400 and
// recorded the upstream's max. Pre-clamp this URL's fresh transformedBody
// so it doesn't re-hit the same 400 (avoids one wasted round-trip per
// fallback URL). No-op when nothing has been learned this execute().
if (thinkingBudgetClampedMax !== null) {
clampNestedThinkingBudget(transformedBody, thinkingBudgetClampedMax);
}
// Timeout only covers response start; stream stalls are handled downstream.
// #11526: streaming requests cap the headers-wait phase to a client-realistic
// ceiling (see fetchStartTimeoutPolicy.ts) — non-streaming keeps the flat default.
// Declared outside the try/catch below so the catch's TIMEOUT log (on the
// error path) reports the same effective value the fetch actually used.
const fetchStartTimeoutPolicy = resolveFetchStartTimeout({
baseTimeoutMs: this.getTimeoutMs(),
stream,
});
const fetchStartTimeoutMs = fetchStartTimeoutPolicy.timeoutMs;
if (fetchStartTimeoutPolicy.capped) {
log?.debug?.(
"TIMEOUT",
`fetch-start timeout capped ${fetchStartTimeoutPolicy.baseTimeoutMs}ms -> ${fetchStartTimeoutMs}ms (streaming)`
);
}
try {
const fetchWithStartTimeout = async (requestUrl: string, requestOptions: RequestInit) => {
// GHSA-4f49: guard here (not only next to the first buildUrl) so retries
// and fallback URLs are validated too, before any bytes leave the host.
this.assertOutboundUrlAllowed(requestUrl);
const timeoutController = fetchStartTimeoutMs > 0 ? new AbortController() : null;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
if (timeoutController) {
timeoutId = setTimeout(() => {
const timeoutError = new Error(
`Fetch timeout after ${fetchStartTimeoutMs}ms on ${requestUrl}`
);
timeoutError.name = "TimeoutError";
timeoutController.abort(timeoutError);
}, fetchStartTimeoutMs);
}
const timeoutSignal = timeoutController?.signal ?? null;
const combinedSignal =
signal && timeoutSignal
? mergeAbortSignals(signal, timeoutSignal)
: signal || timeoutSignal;
const optionsWithSignal = combinedSignal
? { ...requestOptions, signal: combinedSignal }
: requestOptions;
try {
return await fetch(requestUrl, optionsWithSignal);
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
};
const isClaudeCodeClient =
clientHeaders?.["x-app"] === "cli" ||
(clientHeaders?.["user-agent"] &&
clientHeaders["user-agent"].toLowerCase().includes("claude-code")) ||
(clientHeaders?.["user-agent"] &&
clientHeaders["user-agent"].toLowerCase().includes("claude-cli"));
// Anthropic's user:sessions:claude_code OAuth scope expects CLI-shaped
// traffic. Apply the cloak whenever we have an OAuth token, regardless
// of upstream client.
const hasClaudeOAuthToken =
typeof activeCredentials?.accessToken === "string" &&
activeCredentials.accessToken.startsWith("sk-ant-oat") &&
!activeCredentials?.apiKey;
if (
((this.provider === "claude" && (isClaudeCodeClient || hasClaudeOAuthToken)) ||
usesClaudeCodeProtocol) &&
typeof transformedBody === "object" &&
transformedBody !== null
) {
const tb = transformedBody as Record<string, unknown>;
stripProxyToolPrefix(tb);
remapToolNamesInRequest(tb);
// Cloak third-party tool names + sanitize invalid tool schemas so
// Anthropic does not refuse native Claude OAuth traffic with a
// misleading "out of extra usage" placeholder. See Spec E.
cloakThirdPartyToolNames(tb);
if (Array.isArray(tb.tools)) {
tb.tools = sanitizeClaudeToolSchemas(tb.tools);
}
obfuscateInBody(tb);
// NOTE (issue #2260): This is the native `claude` provider OAuth path.
// It is intentionally NOT routed through applyCcBridgeTransformPipeline.
// The native OAuth path already prepends its own billing line + sentinel
// (see lines ~744-773 below, dayStamp-based, cc_entrypoint=cli, cch=00000
// placeholder, signed at body level). The CC bridge transforms DSL is
// wired into buildAndSignClaudeCodeRequest (claudeCodeCompatible.ts step 5b)
// which is the anthropic-compatible-cc-* relay path — a different,
// separately classified surface. Do not double-prepend here.