-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathproviderModelFactory.ts
More file actions
1949 lines (1716 loc) · 75.3 KB
/
providerModelFactory.ts
File metadata and controls
1949 lines (1716 loc) · 75.3 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 assert from "node:assert";
import type { XaiProviderOptions } from "@ai-sdk/xai";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import { wrapLanguageModel, type LanguageModel } from "ai";
import type { ThinkingLevel } from "@/common/types/thinking";
import { Ok, Err } from "@/common/types/result";
import type { Result } from "@/common/types/result";
import type { SendMessageError } from "@/common/types/errors";
import {
PROVIDER_REGISTRY,
PROVIDER_DEFINITIONS,
type ProviderName,
} from "@/common/constants/providers";
import {
CODEX_ENDPOINT,
isCodexOauthAllowedModelId,
isCodexOauthRequiredModelId,
} from "@/common/constants/codexOAuth";
import { parseCodexOauthAuth } from "@/node/utils/codexOauthAuth";
import type { Config, ProviderConfig, ProvidersConfig } from "@/node/config";
import type { MuxProviderOptions } from "@/common/types/providerOptions";
import type { ExternalSecretResolver } from "@/common/types/secrets";
import { isOpReference } from "@/common/utils/opRef";
import { isProviderDisabledInConfig } from "@/common/utils/providers/isProviderDisabled";
import { isGatewayModelAccessibleFromAuthoritativeCatalog } from "@/common/utils/providers/gatewayModelCatalog";
import { maybeGetProviderModelEntryId } from "@/common/utils/providers/modelEntries";
import {
isCopilotModelAccessible,
selectCopilotApiMode,
toCopilotModelId,
} from "@/common/utils/copilot/modelRouting";
import { CopilotResponsesLanguageModel } from "@/node/services/copilot/copilotResponsesLanguageModel";
import type { PolicyService } from "@/node/services/policyService";
import type { ProviderService } from "@/node/services/providerService";
import type { CodexOauthService } from "@/node/services/codexOauthService";
import type { DevToolsService } from "@/node/services/devToolsService";
import { captureAndStripDevToolsHeader } from "@/node/services/devToolsHeaderCapture";
import { createDevToolsMiddleware } from "@/node/services/devToolsMiddleware";
import { log } from "@/node/services/log";
import { resolveProviderOptionsNamespaceKey } from "@/common/utils/ai/providerOptions";
import { resolveRoute, type RouteContext } from "@/common/routing";
import {
getExplicitGatewayPrefix as getExplicitGatewayProvider,
normalizeToCanonical,
} from "@/common/utils/ai/models";
import type { AnthropicCacheTtl } from "@/common/utils/ai/cacheStrategy";
import { MUX_APP_ATTRIBUTION_TITLE, MUX_APP_ATTRIBUTION_URL } from "@/constants/appAttribution";
import { resolveProviderCredentials } from "@/node/utils/providerRequirements";
import {
normalizeGatewayStreamUsage,
normalizeGatewayGenerateResult,
} from "@/node/utils/gatewayStreamNormalization";
import { EnvHttpProxyAgent, type Dispatcher } from "undici";
import packageJson from "../../../package.json";
// ---------------------------------------------------------------------------
// Undici agent with unlimited timeouts for AI streaming requests.
// Safe because users control cancellation via AbortSignal from the UI.
// Uses EnvHttpProxyAgent to automatically respect HTTP_PROXY, HTTPS_PROXY,
// and NO_PROXY environment variables for debugging/corporate network support.
// ---------------------------------------------------------------------------
const unlimitedTimeoutAgent = new EnvHttpProxyAgent({
bodyTimeout: 0, // No timeout - prevents BodyTimeoutError on long reasoning pauses
headersTimeout: 0, // No timeout for headers
});
// Extend RequestInit with undici-specific dispatcher property (Node.js only)
type RequestInitWithDispatcher = RequestInit & { dispatcher?: Dispatcher };
const muxVersionFromEnv = (() => {
const value = process.env.MUX_VERSION?.trim();
return value && value.length > 0 ? value : undefined;
})();
const muxVersionFromPackageJson = (() => {
if (typeof packageJson.version !== "string") {
return undefined;
}
const value = packageJson.version.trim();
return value.length > 0 ? value : undefined;
})();
// Stable default User-Agent for AI provider requests.
// Prefer MUX_VERSION when provided by the runtime; otherwise fall back to package.json.
// This keeps attribution consistent across all provider SDKs that use fetch.
export const MUX_AI_PROVIDER_USER_AGENT = `mux/${
muxVersionFromEnv ?? muxVersionFromPackageJson ?? "dev"
}`;
assert(
MUX_AI_PROVIDER_USER_AGENT.length > "mux/".length,
"MUX_AI_PROVIDER_USER_AGENT must include a non-empty version"
);
/**
* Resolve the header source for provider fetch calls.
*
* When fetch is called with a Request object, that Request may already carry
* auth/content headers. Preserve those unless init.headers is explicitly provided,
* matching fetch override semantics.
*/
export function resolveAIProviderHeaderSource(
input: RequestInfo | URL,
init?: RequestInit
): HeadersInit | undefined {
if (init?.headers != null) {
return init.headers;
}
return input instanceof Request ? input.headers : undefined;
}
/**
* Build request headers for provider fetch calls.
*
* Always includes Mux attribution in User-Agent while preserving provider SDK info
* for downstream diagnostics and compatibility.
* Exported for testing.
*/
export function buildAIProviderRequestHeaders(existingHeaders: HeadersInit | undefined): Headers {
const headers = new Headers(existingHeaders);
const existingUserAgent = headers.get("user-agent")?.trim();
if (!existingUserAgent) {
headers.set("User-Agent", MUX_AI_PROVIDER_USER_AGENT);
return headers;
}
assert(existingUserAgent.length > 0, "existingUserAgent should be non-empty after trim");
// Avoid duplicating prefix when callers already include Mux attribution.
if (
existingUserAgent !== MUX_AI_PROVIDER_USER_AGENT &&
!existingUserAgent.startsWith(`${MUX_AI_PROVIDER_USER_AGENT} `)
) {
headers.set("User-Agent", `${MUX_AI_PROVIDER_USER_AGENT} ${existingUserAgent}`);
}
return headers;
}
/**
* Default fetch function with unlimited timeouts for AI streaming.
* Uses undici Agent to remove artificial timeout limits while still
* respecting user cancellation via AbortSignal.
*
* Note: If users provide custom fetch in providers.jsonc, they are
* responsible for configuring timeouts appropriately. Custom fetch
* implementations using undici should set bodyTimeout: 0 and
* headersTimeout: 0 to prevent BodyTimeoutError on long-running
* reasoning models.
*/
const defaultFetchWithUnlimitedTimeout = (async (
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> => {
const headerSource = resolveAIProviderHeaderSource(input, init);
const headers = buildAIProviderRequestHeaders(headerSource);
// Capture final request headers for DevTools if a synthetic step ID is present.
// This runs after buildAIProviderRequestHeaders so the Mux user-agent is included.
// The synthetic header is stripped before the request is sent.
captureAndStripDevToolsHeader(headers);
// dispatcher is a Node.js undici-specific property for custom HTTP agents
const requestInit: RequestInitWithDispatcher = {
...(init ?? {}),
headers,
dispatcher: unlimitedTimeoutAgent,
};
return fetch(input, requestInit);
}) as typeof fetch;
type FetchWithBunExtensions = typeof fetch & {
preconnect?: typeof fetch extends { preconnect: infer P } ? P : unknown;
certificate?: typeof fetch extends { certificate: infer C } ? C : unknown;
};
const globalFetchWithExtras = fetch as FetchWithBunExtensions;
const defaultFetchWithExtras = defaultFetchWithUnlimitedTimeout as FetchWithBunExtensions;
if (typeof globalFetchWithExtras.preconnect === "function") {
defaultFetchWithExtras.preconnect = globalFetchWithExtras.preconnect.bind(globalFetchWithExtras);
}
if (typeof globalFetchWithExtras.certificate === "function") {
defaultFetchWithExtras.certificate =
globalFetchWithExtras.certificate.bind(globalFetchWithExtras);
}
// ---------------------------------------------------------------------------
// Fetch wrappers
// ---------------------------------------------------------------------------
function mergeAnthropicCacheControl(
existing: unknown,
cacheTtl?: AnthropicCacheTtl | null
): Record<string, string> {
const merged: Record<string, string> = { type: "ephemeral" };
if (typeof existing === "object" && existing !== null) {
const existingRecord = existing as Record<string, unknown>;
if (typeof existingRecord.type === "string") {
merged.type = existingRecord.type;
}
if (typeof existingRecord.ttl === "string") {
merged.ttl = existingRecord.ttl;
}
}
if (cacheTtl) {
merged.ttl = cacheTtl;
}
return merged;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function hasAnthropicProviderCacheControl(value: unknown): boolean {
if (!isRecord(value)) {
return false;
}
const anthropicOptions = value.anthropic;
return isRecord(anthropicOptions) && isRecord(anthropicOptions.cacheControl);
}
/**
* Count Anthropic prompt-cache breakpoints in a shaped request payload.
*
* This intentionally counts both raw `cache_control` blocks and untransformed
* `providerOptions.anthropic.cacheControl` markers so tests can guard the
* budget across direct and gateway request-shaping paths.
*/
export function countAnthropicCacheBreakpoints(requestBody: unknown): number {
const pending: unknown[] = [requestBody];
let count = 0;
while (pending.length > 0) {
const current = pending.pop();
if (current == null) {
continue;
}
if (Array.isArray(current)) {
for (const value of current) {
pending.push(value);
}
continue;
}
if (!isRecord(current)) {
continue;
}
if (isRecord(current.cache_control)) {
count += 1;
}
if (hasAnthropicProviderCacheControl(current.providerOptions)) {
count += 1;
}
for (const value of Object.values(current)) {
pending.push(value);
}
}
return count;
}
/**
* Wrap fetch to normalize Anthropic cache_control directly on the final request body.
*
* This keeps routed Anthropic payloads aligned with Mux's manual cache markers
* and lets a higher-level cacheTtl override win at the last wire-shaping step.
*
* Injects cache_control on:
* 1. Last tool (caches all tool definitions)
* 2. Last message's last content part (caches entire conversation)
*/
function wrapFetchWithAnthropicCacheControl(
baseFetch: typeof fetch,
cacheTtl?: AnthropicCacheTtl | null
): typeof fetch {
const cachingFetch = async (
input: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1]
): Promise<Response> => {
// Only modify POST requests with JSON body
if (init?.method?.toUpperCase() !== "POST" || typeof init?.body !== "string") {
return baseFetch(input, init);
}
try {
const json = JSON.parse(init.body) as Record<string, unknown>;
// Inject cache_control on the last tool if tools array exists.
// If the SDK already populated cache_control, preserve it but override ttl
// when a higher-level cacheTtl is configured.
if (Array.isArray(json.tools) && json.tools.length > 0) {
const lastTool = json.tools[json.tools.length - 1] as Record<string, unknown>;
lastTool.cache_control = mergeAnthropicCacheControl(lastTool.cache_control, cacheTtl);
}
// Inject cache_control on last message's last content part
// This caches the entire conversation
// Handle both formats:
// - Direct Anthropic provider: json.messages (Anthropic API format)
// - Gateway provider: json.prompt (AI SDK internal format)
const messages = Array.isArray(json.messages)
? json.messages
: Array.isArray(json.prompt)
? json.prompt
: null;
if (messages && messages.length >= 1) {
const lastMsg = messages[messages.length - 1] as Record<string, unknown>;
// For gateway: add providerOptions.anthropic.cacheControl at message level
// (gateway validates schema strictly, doesn't allow raw cache_control on messages)
if (Array.isArray(json.prompt)) {
const providerOpts = (lastMsg.providerOptions ?? {}) as Record<string, unknown>;
const anthropicOpts = (providerOpts.anthropic ?? {}) as Record<string, unknown>;
anthropicOpts.cacheControl = mergeAnthropicCacheControl(
anthropicOpts.cacheControl,
cacheTtl
);
providerOpts.anthropic = anthropicOpts;
lastMsg.providerOptions = providerOpts;
}
// For direct Anthropic: add cache_control to last content part
const content = lastMsg.content;
if (Array.isArray(content) && content.length > 0) {
const lastPart = content[content.length - 1] as Record<string, unknown>;
lastPart.cache_control = mergeAnthropicCacheControl(lastPart.cache_control, cacheTtl);
}
}
// Update body with modified JSON
const newBody = JSON.stringify(json);
const headers = new Headers(init?.headers);
headers.delete("content-length"); // Body size changed
return baseFetch(input, { ...init, headers, body: newBody });
} catch {
// If parsing fails, pass through unchanged
return baseFetch(input, init);
}
};
return Object.assign(cachingFetch, baseFetch) as typeof fetch;
}
/**
* Wrap fetch so any mux-gateway 401 response clears local credentials (best-effort).
*
* This ensures the UI immediately reflects that the user has been logged out
* when the gateway session expires.
*/
function wrapFetchWithMuxGatewayAutoLogout(
baseFetch: typeof fetch,
providerService: ProviderService
): typeof fetch {
const wrappedFetch = async (
input: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1]
): Promise<Response> => {
const response = await baseFetch(input, init);
if (response.status === 401) {
try {
await providerService.setConfig("mux-gateway", ["couponCode"], "");
await providerService.setConfig("mux-gateway", ["voucher"], "");
} catch {
// Ignore failures clearing local credentials
}
}
return response;
};
return Object.assign(wrappedFetch, baseFetch) as typeof fetch;
}
/**
* Get fetch function for provider - use custom if provided, otherwise unlimited timeout default
*/
function getProviderFetch(providerConfig: ProviderConfig): typeof fetch {
if (typeof providerConfig.fetch !== "function") {
return defaultFetchWithUnlimitedTimeout;
}
const customFetch = providerConfig.fetch as typeof fetch;
// Wrap custom fetch to strip the synthetic DevTools correlation header.
// Without this, x-mux-devtools-step-id can leak to upstream APIs because
// only defaultFetchWithUnlimitedTimeout strips it natively.
const wrappedFetch = async (
input: Parameters<typeof fetch>[0],
init?: Parameters<typeof fetch>[1]
): Promise<Response> => {
// Build merged headers: start from the Request (if any), then overlay init.headers.
const merged = new Headers(input instanceof Request ? input.headers : undefined);
if (init?.headers) {
for (const [key, value] of new Headers(init.headers).entries()) {
merged.set(key, value);
}
}
captureAndStripDevToolsHeader(merged);
return customFetch(input, { ...init, headers: merged });
};
return Object.assign(wrappedFetch, customFetch) as typeof fetch;
}
// ---------------------------------------------------------------------------
// Exported helpers (re-exported from aiService.ts for backward compatibility)
// ---------------------------------------------------------------------------
/**
* Normalize Anthropic base URL to ensure it ends with /v1 suffix.
*
* The Anthropic SDK expects baseURL to include /v1 (default: https://api.anthropic.com/v1).
* Many users configure base URLs without the /v1 suffix, which causes API calls to fail.
* This function automatically appends /v1 if missing.
*
* @param baseURL - The base URL to normalize (may or may not have /v1)
* @returns The base URL with /v1 suffix
*/
export function normalizeAnthropicBaseURL(baseURL: string): string {
const trimmed = baseURL.replace(/\/+$/, ""); // Remove trailing slashes
if (trimmed.endsWith("/v1")) {
return trimmed;
}
return `${trimmed}/v1`;
}
import { getErrorMessage } from "@/common/utils/errors";
/**
* Build app attribution headers used by OpenRouter (and other compatible platforms).
*
* Attribution docs:
* - OpenRouter: https://openrouter.ai/docs/app-attribution
* - Vercel AI Gateway: https://vercel.com/docs/ai-gateway/app-attribution
*
* Exported for testing.
*/
export function buildAppAttributionHeaders(
existingHeaders: Record<string, string> | undefined
): Record<string, string> {
// Clone to avoid mutating caller-provided objects.
const headers: Record<string, string> = existingHeaders ? { ...existingHeaders } : {};
// Header names are case-insensitive. Preserve user-provided values by never overwriting.
const existingLowercaseKeys = new Set(Object.keys(headers).map((key) => key.toLowerCase()));
if (!existingLowercaseKeys.has("http-referer")) {
headers["HTTP-Referer"] = MUX_APP_ATTRIBUTION_URL;
}
if (!existingLowercaseKeys.has("x-title")) {
headers["X-Title"] = MUX_APP_ATTRIBUTION_TITLE;
}
return headers;
}
/**
* Preload AI SDK provider modules to avoid race conditions in concurrent test environments.
* This function loads @ai-sdk/anthropic, @ai-sdk/openai, and ollama-ai-provider-v2 eagerly
* so that subsequent dynamic imports in createModel() hit the module cache instead of racing.
*
* In production, providers are lazy-loaded on first use to optimize startup time.
* In tests, we preload them once during setup to ensure reliable concurrent execution.
*/
export async function preloadAISDKProviders(): Promise<void> {
// Preload providers to ensure they're in the module cache before concurrent tests run
await Promise.all(Object.values(PROVIDER_REGISTRY).map((importFn) => importFn()));
}
/**
* Parse provider and model ID from model string.
* Handles model IDs with colons (e.g., "ollama:gpt-oss:20b").
* Only splits on the first colon to support Ollama model naming convention.
*
* @param modelString - Model string in format "provider:model-id"
* @returns Tuple of [providerName, modelId]
* @example
* parseModelString("anthropic:claude-opus-4") // ["anthropic", "claude-opus-4"]
* parseModelString("ollama:gpt-oss:20b") // ["ollama", "gpt-oss:20b"]
*/
export function parseModelString(modelString: string): [string, string] {
const colonIndex = modelString.indexOf(":");
const providerName = colonIndex !== -1 ? modelString.slice(0, colonIndex) : modelString;
const modelId = colonIndex !== -1 ? modelString.slice(colonIndex + 1) : "";
return [providerName, modelId];
}
/**
* Classify a Copilot API request as "user" or "agent" initiated by inspecting
* the last conversational item in the request body. GitHub Copilot bills premium
* requests only for "user"-initiated calls.
*
* Heuristic: if the last chat-completions message or Responses input item is a
* user turn, treat the request as user-initiated. Assistant continuations, tool
* calls, tool outputs, and stored item references are agent-initiated.
*/
export function classifyCopilotInitiator(body: string | null | undefined): "user" | "agent" {
try {
if (typeof body !== "string") return "user"; // can't parse -> safe default
const parsed = JSON.parse(body) as { messages?: unknown[]; input?: unknown };
const messages = parsed.messages;
if (Array.isArray(messages) && messages.length > 0) {
const last = messages[messages.length - 1] as { role?: string } | undefined;
return last?.role === "user" ? "user" : "agent";
}
const input = parsed.input;
if (Array.isArray(input)) {
for (let index = input.length - 1; index >= 0; index -= 1) {
const item: unknown = input[index];
if (typeof item !== "object" || item === null) {
continue;
}
const role = (item as { role?: unknown }).role;
if (typeof role === "string") {
if (role === "user") {
return "user";
}
if (role === "assistant") {
return "agent";
}
continue;
}
// AI SDK Responses conversion only emits non-role items for assistant or
// tool-driven state, such as function calls, tool outputs, reasoning, and
// item references. Treat those as agent-initiated to preserve Copilot billing.
const type = (item as { type?: unknown }).type;
if (typeof type === "string") {
return "agent";
}
}
}
return "user";
} catch {
return "user"; // parse failure -> safe fallback (don't hide usage)
}
}
function parseAnthropicCacheTtl(value: unknown): AnthropicCacheTtl | undefined {
if (value === "5m" || value === "1h") {
return value;
}
return undefined;
}
// ---------------------------------------------------------------------------
// Model cost tracking
// ---------------------------------------------------------------------------
const MUX_MODEL_COSTS_INCLUDED = Symbol("mux:modelCostsIncluded");
type LanguageModelWithMuxCostsIncluded = LanguageModel & {
[MUX_MODEL_COSTS_INCLUDED]?: true;
};
function markModelCostsIncluded(model: LanguageModel): void {
(model as LanguageModelWithMuxCostsIncluded)[MUX_MODEL_COSTS_INCLUDED] = true;
}
export function modelCostsIncluded(model: LanguageModel): boolean {
return (model as LanguageModelWithMuxCostsIncluded)[MUX_MODEL_COSTS_INCLUDED] === true;
}
const CODEX_ALLOWED_PARAMS = new Set([
"model",
"input",
"instructions",
"tools",
"tool_choice",
"parallel_tool_calls",
"stream",
"store",
"prompt_cache_key",
"reasoning",
"temperature",
"top_p",
"include",
"text", // structured output via Output.object -> text.format
]);
// ---------------------------------------------------------------------------
// Content extraction
// ---------------------------------------------------------------------------
/**
* Extract text from AI SDK message content.
* Content may be a plain string or a structured array like [{type:"text", text:"..."}].
*/
function extractTextContent(content: unknown): string {
if (typeof content === "string") return content.trim();
if (Array.isArray(content)) {
return (content as unknown[])
.filter(
(part): part is { type: string; text: string } =>
typeof part === "object" &&
part !== null &&
(part as { type?: unknown }).type === "text" &&
typeof (part as { text?: unknown }).text === "string"
)
.map((part) => part.text)
.join("")
.trim();
}
return "";
}
export function normalizeCodexResponsesBody(body: string): string {
const json = JSON.parse(body) as Record<string, unknown>;
// ChatGPT's Codex endpoint is stricter than the public OpenAI Responses API
// and currently rejects the `truncation` field entirely.
delete json.truncation;
// Codex-compatible Responses requests must disable storage and strip unsupported params.
json.store = false;
for (const key of Object.keys(json)) {
if (!CODEX_ALLOWED_PARAMS.has(key)) {
delete json[key];
}
}
// item_reference entries depend on stored state lookups, which fail with store=false.
if (Array.isArray(json.input)) {
json.input = (json.input as Array<Record<string, unknown>>).filter(
(item) => !(item && typeof item === "object" && item.type === "item_reference")
);
}
const existingInstructions =
typeof json.instructions === "string" ? json.instructions.trim() : "";
if (existingInstructions.length === 0) {
const derivedParts: string[] = [];
const keptInput: unknown[] = [];
const responseInput = json.input;
if (Array.isArray(responseInput)) {
for (const item of responseInput as unknown[]) {
if (!item || typeof item !== "object") {
keptInput.push(item);
continue;
}
const role = (item as { role?: unknown }).role;
if (role !== "system" && role !== "developer") {
keptInput.push(item);
continue;
}
const content = (item as { content?: unknown }).content;
const text = extractTextContent(content);
if (text.length > 0) {
derivedParts.push(text);
}
}
json.input = keptInput;
}
const joined = derivedParts.join("\n\n").trim();
json.instructions = joined.length > 0 ? joined : "You are a helpful assistant.";
}
return JSON.stringify(json);
}
function getConfiguredProviderModelIds(providerConfig: ProviderConfig | undefined): string[] {
const models = providerConfig?.models;
if (!Array.isArray(models)) {
return [];
}
return models.flatMap((entry) => {
const modelId = maybeGetProviderModelEntryId(entry);
return modelId == null ? [] : [modelId];
});
}
function createGatewayModelAccessibilityChecker(providersConfig: ProvidersConfig) {
return (gateway: string, gatewayModelId: string): boolean =>
isGatewayModelAccessibleFromAuthoritativeCatalog(
gateway,
gatewayModelId,
providersConfig[gateway]?.models
);
}
// ---------------------------------------------------------------------------
// ProviderModelFactory
// ---------------------------------------------------------------------------
/**
* Factory responsible for creating AI SDK LanguageModel instances from model strings.
*
* Extracted from AIService to isolate provider/model construction logic from the
* streaming and orchestration concerns that AIService owns.
*/
export class ProviderModelFactory {
private readonly config: Config;
private readonly providerService: ProviderService;
private readonly policyService?: PolicyService;
private readonly devToolsService?: DevToolsService;
codexOauthService?: CodexOauthService;
constructor(
config: Config,
providerService: ProviderService,
policyService?: PolicyService,
codexOauthService?: CodexOauthService,
devToolsService?: DevToolsService,
private readonly opResolver?: ExternalSecretResolver
) {
this.config = config;
this.providerService = providerService;
this.policyService = policyService;
this.codexOauthService = codexOauthService;
this.devToolsService = devToolsService;
}
/**
* Resolve an API key that may be a 1Password op:// reference.
* Returns the original key for non-op:// values, or the resolved secret for op:// refs.
* Returns undefined if the reference cannot be resolved.
*/
private async resolveApiKey(apiKey: string | undefined): Promise<string | undefined> {
if (!apiKey || !isOpReference(apiKey)) return apiKey;
if (!this.opResolver) return undefined;
return this.opResolver(apiKey);
}
private isProviderAvailableForRouting(
provider: ProviderName,
providersConfig: ProvidersConfig,
config: ReturnType<Config["loadConfigOrDefault"]>
): boolean {
const providerConfig = providersConfig[provider] ?? {};
const credentials = resolveProviderCredentials(provider, providerConfig);
// OpenAI Codex OAuth is a valid credential path even without an API key;
// routing should treat it as available so direct OpenAI routes are honored.
const hasCodexOauth =
provider === "openai" &&
parseCodexOauthAuth((providerConfig as { codexOauth?: unknown }).codexOauth) !== null;
if (!credentials.isConfigured && !hasCodexOauth) {
return false;
}
// Route resolution must honor the shared provider-level enabled=false switch
// before considering legacy gateway-specific config gates.
if (isProviderDisabledInConfig(providerConfig as { enabled?: unknown })) {
return false;
}
if (provider === "mux-gateway") {
return config.muxGatewayEnabled !== false;
}
return true;
}
/**
* Create an AI SDK model from a model string (e.g., "anthropic:claude-opus-4-1")
*
* IMPORTANT: We ONLY use providers.jsonc as the single source of truth for provider configuration.
* We DO NOT use environment variables or default constructors that might read them.
* This ensures consistent, predictable configuration management.
*
* Provider configuration from providers.jsonc is passed verbatim to the provider
* constructor, ensuring automatic parity with Vercel AI SDK - any configuration options
* supported by the provider will work without modification.
*/
async createModel(
modelString: string,
muxProviderOptions?: MuxProviderOptions,
opts?: {
agentInitiated?: boolean;
workspaceId?: string;
routeContext?: RouteContext;
}
): Promise<Result<LanguageModel, SendMessageError>> {
const result = await this._createModelCore(modelString, muxProviderOptions, opts);
if (!result.success) {
return result;
}
// DevTools middleware wrappers currently support LanguageModelV3 instances only.
if (typeof result.data === "string" || result.data.specificationVersion !== "v3") {
return result;
}
let model: LanguageModel = result.data;
const workspaceId = opts?.workspaceId;
const devToolsService = this.devToolsService;
if (workspaceId != null && devToolsService?.enabled) {
model = wrapLanguageModel({
model,
middleware: createDevToolsMiddleware(workspaceId, devToolsService),
});
}
return Ok(model);
}
private async _createModelCore(
modelString: string,
muxProviderOptions?: MuxProviderOptions,
opts?: { agentInitiated?: boolean; routeContext?: RouteContext }
): Promise<Result<LanguageModel, SendMessageError>> {
try {
// Route resolution is centralized here so every caller gets identical,
// provider-agnostic dispatch behavior. resolveGatewayModelString is idempotent,
// so already-routed strings pass through unchanged.
const explicitGateway = getExplicitGatewayProvider(modelString);
modelString = this.resolveGatewayModelString(
modelString,
opts?.routeContext,
explicitGateway
);
// Parse model string (format: "provider:model-id")
const [providerName, modelId] = parseModelString(modelString);
if (!providerName || !modelId) {
return Err({
type: "invalid_model_string",
message: `Invalid model string format: "${modelString}". Expected "provider:model-id"`,
});
}
// Check if provider is supported (prevents silent failures when adding to PROVIDER_REGISTRY
// but forgetting to implement handler below)
if (!(providerName in PROVIDER_REGISTRY)) {
return Err({
type: "provider_not_supported",
provider: providerName,
});
}
if (this.policyService?.isEnforced()) {
const provider = providerName as ProviderName;
if (!this.policyService.isProviderAllowed(provider)) {
return Err({
type: "policy_denied",
message: `Provider ${providerName} is not allowed by policy`,
});
}
if (!this.policyService.isModelAllowed(provider, modelId)) {
return Err({
type: "policy_denied",
message: `Model ${providerName}:${modelId} is not allowed by policy`,
});
}
}
// Load providers configuration - the ONLY source of truth
const providersConfig = this.config.loadProvidersConfig() ?? {};
// Backend config is authoritative for Anthropic prompt cache TTL on any
// Anthropic-routed model (direct Anthropic, mux-gateway:anthropic/*,
// openrouter:anthropic/*). We still allow request-level values when config
// is unset for backward compatibility with older clients.
const configAnthropicCacheTtl = parseAnthropicCacheTtl(providersConfig.anthropic?.cacheTtl);
const isAnthropicRoutedModel =
providerName === "anthropic" || modelId.startsWith("anthropic/");
// Anthropic-specific: merge global disableBetaFeatures into muxProviderOptions.
const configDisableBeta = providersConfig.anthropic?.disableBetaFeatures;
if (isAnthropicRoutedModel && configDisableBeta === true) {
muxProviderOptions ??= {};
muxProviderOptions.anthropic = {
...(muxProviderOptions.anthropic ?? {}),
disableBetaFeatures: muxProviderOptions.anthropic?.disableBetaFeatures ?? true,
};
}
if (isAnthropicRoutedModel && configAnthropicCacheTtl && muxProviderOptions) {
muxProviderOptions.anthropic = {
...(muxProviderOptions.anthropic ?? {}),
cacheTtl: configAnthropicCacheTtl,
};
}
const effectiveAnthropicCacheTtl =
muxProviderOptions?.anthropic?.cacheTtl ?? configAnthropicCacheTtl;
// OpenAI-specific: merge global store setting into muxProviderOptions.
const isOpenAIRoutedModel = providerName === "openai" || modelId.startsWith("openai/");
const configOpenAIStore = providersConfig.openai?.store;
if (isOpenAIRoutedModel && typeof configOpenAIStore === "boolean") {
muxProviderOptions ??= {};
muxProviderOptions.openai = {
...(muxProviderOptions.openai ?? {}),
store: muxProviderOptions.openai?.store ?? configOpenAIStore,
};
}
let providerConfig = providersConfig[providerName] ?? {};
// Providers can be disabled in providers.jsonc without deleting credentials.
if (
providerName !== "mux-gateway" &&
isProviderDisabledInConfig(providerConfig as { enabled?: unknown })
) {
return Err({ type: "provider_disabled", provider: providerName });
}
// Map baseUrl to baseURL if present (SDK expects baseURL)
const { baseUrl, ...configWithoutBaseUrl } = providerConfig;
providerConfig = baseUrl
? { ...configWithoutBaseUrl, baseURL: baseUrl }
: configWithoutBaseUrl;
// Policy: force provider base URL (if configured).
const forcedBaseUrl = this.policyService?.isEnforced()
? this.policyService.getForcedBaseUrl(providerName as ProviderName)
: undefined;
if (forcedBaseUrl) {
providerConfig = { ...providerConfig, baseURL: forcedBaseUrl };
}
// Inject app attribution headers (used by OpenRouter and other compatible platforms).
// We never overwrite user-provided values (case-insensitive header matching).
providerConfig = {
...providerConfig,
headers: buildAppAttributionHeaders(providerConfig.headers),
};
// Handle Anthropic provider
if (providerName === "anthropic") {
// Resolve credentials from config + env (single source of truth)
const creds = resolveProviderCredentials("anthropic", providerConfig);
if (!creds.isConfigured) {
return Err({ type: "api_key_not_found", provider: providerName });
}
// Resolve op:// reference if API key is a 1Password reference
const resolvedApiKey = await this.resolveApiKey(creds.apiKey);
if (creds.apiKey && isOpReference(creds.apiKey) && !resolvedApiKey) {
return Err({ type: "api_key_not_found", provider: providerName });
}
// Build config with resolved credentials
const configWithApiKey = resolvedApiKey
? { ...providerConfig, apiKey: resolvedApiKey }
: providerConfig;
// Normalize base URL to ensure /v1 suffix (SDK expects it)
const effectiveBaseURL = configWithApiKey.baseURL ?? creds.baseUrl?.trim();
const normalizedConfig = effectiveBaseURL
? { ...configWithApiKey, baseURL: normalizeAnthropicBaseURL(effectiveBaseURL) }
: configWithApiKey;
// 1M context beta header is injected per-request via buildRequestHeaders() →
// streamText({ headers }), not at provider creation time. This avoids duplicating
// header logic across direct and gateway handlers.
// Lazy-load Anthropic provider to reduce startup time
const { createAnthropic } = await PROVIDER_REGISTRY.anthropic();
// Wrap fetch to normalize cache_control on the final Anthropic payload.
// Use getProviderFetch to preserve any user-configured custom fetch (e.g., proxies)
const baseFetch = getProviderFetch(providerConfig);
const disableBeta = muxProviderOptions?.anthropic?.disableBetaFeatures === true;
const fetchWithCacheControl = disableBeta
? baseFetch
: wrapFetchWithAnthropicCacheControl(baseFetch, effectiveAnthropicCacheTtl);
const providerFetch = fetchWithCacheControl;
const provider = createAnthropic({
...normalizedConfig,
fetch: providerFetch,
});
return Ok(provider(modelId));
}
// Handle OpenAI provider (using Responses API)
if (providerName === "openai") {
const fullModelId = `${providerName}:${modelId}`;