model-registry.test.ts 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  1. import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { AnthropicMessagesCompat, Api, Context, Model, OpenAICompletionsCompat } from "@earendil-works/pi-ai";
  5. import { getApiProvider } from "@earendil-works/pi-ai";
  6. import { getOAuthProvider } from "@earendil-works/pi-ai/oauth";
  7. import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
  8. import { AuthStorage } from "../src/core/auth-storage.ts";
  9. import { clearApiKeyCache, ModelRegistry, type ProviderConfigInput } from "../src/core/model-registry.ts";
  10. import { clearDeprecationWarningsForTests } from "../src/utils/deprecation.ts";
  11. describe("ModelRegistry", () => {
  12. let tempDir: string;
  13. let modelsJsonPath: string;
  14. let authStorage: AuthStorage;
  15. beforeEach(() => {
  16. tempDir = join(tmpdir(), `pi-test-model-registry-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  17. mkdirSync(tempDir, { recursive: true });
  18. modelsJsonPath = join(tempDir, "models.json");
  19. authStorage = AuthStorage.create(join(tempDir, "auth.json"));
  20. clearDeprecationWarningsForTests();
  21. });
  22. afterEach(() => {
  23. if (tempDir && existsSync(tempDir)) {
  24. rmSync(tempDir, { recursive: true });
  25. }
  26. clearApiKeyCache();
  27. clearDeprecationWarningsForTests();
  28. vi.restoreAllMocks();
  29. });
  30. /** Create minimal provider config */
  31. function providerConfig(
  32. baseUrl: string,
  33. models: Array<{ id: string; name?: string }>,
  34. api: string = "anthropic-messages",
  35. ): ProviderConfigInput {
  36. return {
  37. baseUrl,
  38. apiKey: "test-key",
  39. api: api as Api,
  40. models: models.map((m) => ({
  41. id: m.id,
  42. name: m.name ?? m.id,
  43. reasoning: false,
  44. input: ["text"],
  45. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  46. contextWindow: 100000,
  47. maxTokens: 8000,
  48. })),
  49. };
  50. }
  51. function writeModelsJson(providers: Record<string, ReturnType<typeof providerConfig>>) {
  52. writeFileSync(modelsJsonPath, JSON.stringify({ providers }));
  53. }
  54. function getModelsForProvider(registry: ModelRegistry, provider: string) {
  55. return registry.getAll().filter((m) => m.provider === provider);
  56. }
  57. function toShPath(value: string): string {
  58. return value.replace(/\\/g, "/").replace(/"/g, '\\"');
  59. }
  60. /** Create a baseUrl-only override (no custom models) */
  61. function overrideConfig(baseUrl: string, headers?: Record<string, string>) {
  62. return { baseUrl, ...(headers && { headers }) };
  63. }
  64. /** Write raw providers config (for mixed override/replacement scenarios) */
  65. function writeRawModelsJson(providers: Record<string, unknown>) {
  66. writeFileSync(modelsJsonPath, JSON.stringify({ providers }));
  67. }
  68. const openAiModel: Model<Api> = {
  69. id: "test-openai-model",
  70. name: "Test OpenAI Model",
  71. api: "openai-completions",
  72. provider: "openai",
  73. baseUrl: "https://api.openai.com/v1",
  74. reasoning: false,
  75. input: ["text"],
  76. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  77. contextWindow: 128000,
  78. maxTokens: 4096,
  79. };
  80. const emptyContext: Context = {
  81. messages: [],
  82. };
  83. describe("baseUrl override (no custom models)", () => {
  84. test("overriding baseUrl keeps all built-in models", () => {
  85. writeRawModelsJson({
  86. anthropic: overrideConfig("https://my-proxy.example.com/v1"),
  87. });
  88. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  89. const anthropicModels = getModelsForProvider(registry, "anthropic");
  90. // Should have multiple built-in models, not just one
  91. expect(anthropicModels.length).toBeGreaterThan(1);
  92. expect(anthropicModels.some((m) => m.id.includes("claude"))).toBe(true);
  93. });
  94. test("overriding baseUrl changes URL on all built-in models", () => {
  95. writeRawModelsJson({
  96. anthropic: overrideConfig("https://my-proxy.example.com/v1"),
  97. });
  98. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  99. const anthropicModels = getModelsForProvider(registry, "anthropic");
  100. // All models should have the new baseUrl
  101. for (const model of anthropicModels) {
  102. expect(model.baseUrl).toBe("https://my-proxy.example.com/v1");
  103. }
  104. });
  105. test("overriding headers resolves at request time", async () => {
  106. writeRawModelsJson({
  107. anthropic: overrideConfig("https://my-proxy.example.com/v1", {
  108. "X-Custom-Header": "custom-value",
  109. }),
  110. });
  111. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  112. const anthropicModels = getModelsForProvider(registry, "anthropic");
  113. for (const model of anthropicModels) {
  114. const auth = await registry.getApiKeyAndHeaders(model);
  115. expect(auth.ok).toBe(true);
  116. if (auth.ok) {
  117. expect(auth.headers?.["X-Custom-Header"]).toBe("custom-value");
  118. }
  119. }
  120. });
  121. test("headers-only override resolves at request time", async () => {
  122. writeRawModelsJson({
  123. anthropic: {
  124. headers: {
  125. "X-Custom-Header": "custom-value",
  126. },
  127. },
  128. });
  129. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  130. expect(registry.getError()).toBeUndefined();
  131. const anthropicModels = getModelsForProvider(registry, "anthropic");
  132. for (const model of anthropicModels) {
  133. const auth = await registry.getApiKeyAndHeaders(model);
  134. expect(auth.ok).toBe(true);
  135. if (auth.ok) {
  136. expect(auth.headers?.["X-Custom-Header"]).toBe("custom-value");
  137. }
  138. }
  139. });
  140. test("baseUrl-only override does not affect other providers", () => {
  141. writeRawModelsJson({
  142. anthropic: overrideConfig("https://my-proxy.example.com/v1"),
  143. });
  144. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  145. const googleModels = getModelsForProvider(registry, "google");
  146. // Google models should still have their original baseUrl
  147. expect(googleModels.length).toBeGreaterThan(0);
  148. expect(googleModels[0].baseUrl).not.toBe("https://my-proxy.example.com/v1");
  149. });
  150. test("can mix baseUrl override and models merge", () => {
  151. writeRawModelsJson({
  152. // baseUrl-only for anthropic
  153. anthropic: overrideConfig("https://anthropic-proxy.example.com/v1"),
  154. // Add custom model for google (merged with built-ins)
  155. google: providerConfig(
  156. "https://google-proxy.example.com/v1",
  157. [{ id: "gemini-custom" }],
  158. "google-generative-ai",
  159. ),
  160. });
  161. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  162. // Anthropic: multiple built-in models with new baseUrl
  163. const anthropicModels = getModelsForProvider(registry, "anthropic");
  164. expect(anthropicModels.length).toBeGreaterThan(1);
  165. expect(anthropicModels[0].baseUrl).toBe("https://anthropic-proxy.example.com/v1");
  166. // Google: built-ins plus custom model
  167. const googleModels = getModelsForProvider(registry, "google");
  168. expect(googleModels.length).toBeGreaterThan(1);
  169. expect(googleModels.some((m) => m.id === "gemini-custom")).toBe(true);
  170. });
  171. test("refresh() picks up baseUrl override changes", () => {
  172. writeRawModelsJson({
  173. anthropic: overrideConfig("https://first-proxy.example.com/v1"),
  174. });
  175. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  176. expect(getModelsForProvider(registry, "anthropic")[0].baseUrl).toBe("https://first-proxy.example.com/v1");
  177. // Update and refresh
  178. writeRawModelsJson({
  179. anthropic: overrideConfig("https://second-proxy.example.com/v1"),
  180. });
  181. registry.refresh();
  182. expect(getModelsForProvider(registry, "anthropic")[0].baseUrl).toBe("https://second-proxy.example.com/v1");
  183. });
  184. });
  185. describe("custom models merge behavior", () => {
  186. test("built-in provider custom models inherit api and baseUrl without explicit fields", () => {
  187. // Built-in providers already have api/baseUrl on every model, and auth
  188. // comes from env vars / auth storage. No need to specify them.
  189. writeRawModelsJson({
  190. openrouter: {
  191. models: [
  192. {
  193. id: "fake-provider/fake-model",
  194. name: "Fake model",
  195. reasoning: true,
  196. input: ["text"],
  197. },
  198. ],
  199. },
  200. });
  201. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  202. expect(registry.getError()).toBeUndefined();
  203. const model = registry.find("openrouter", "fake-provider/fake-model");
  204. expect(model).toBeDefined();
  205. expect(model?.api).toBe("openai-completions");
  206. expect(model?.baseUrl).toBe("https://openrouter.ai/api/v1");
  207. });
  208. test("non-built-in provider custom models still require baseUrl and apiKey", () => {
  209. writeRawModelsJson({
  210. "my-custom-provider": {
  211. models: [
  212. {
  213. id: "my-model",
  214. api: "openai-completions",
  215. reasoning: false,
  216. input: ["text"],
  217. },
  218. ],
  219. },
  220. });
  221. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  222. expect(registry.getError()).toContain("baseUrl");
  223. });
  224. test("custom provider with same name as built-in merges with built-in models", () => {
  225. writeModelsJson({
  226. anthropic: providerConfig("https://my-proxy.example.com/v1", [{ id: "claude-custom" }]),
  227. });
  228. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  229. const anthropicModels = getModelsForProvider(registry, "anthropic");
  230. expect(anthropicModels.length).toBeGreaterThan(1);
  231. expect(anthropicModels.some((m) => m.id === "claude-custom")).toBe(true);
  232. expect(anthropicModels.some((m) => m.id.includes("claude"))).toBe(true);
  233. });
  234. test("custom model with same id replaces built-in model by id", () => {
  235. writeModelsJson({
  236. openrouter: providerConfig(
  237. "https://my-proxy.example.com/v1",
  238. [{ id: "anthropic/claude-sonnet-4" }],
  239. "openai-completions",
  240. ),
  241. });
  242. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  243. const models = getModelsForProvider(registry, "openrouter");
  244. const sonnetModels = models.filter((m) => m.id === "anthropic/claude-sonnet-4");
  245. expect(sonnetModels).toHaveLength(1);
  246. expect(sonnetModels[0].baseUrl).toBe("https://my-proxy.example.com/v1");
  247. });
  248. test("custom provider with same name as built-in does not affect other built-in providers", () => {
  249. writeModelsJson({
  250. anthropic: providerConfig("https://my-proxy.example.com/v1", [{ id: "claude-custom" }]),
  251. });
  252. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  253. expect(getModelsForProvider(registry, "google").length).toBeGreaterThan(0);
  254. expect(getModelsForProvider(registry, "openai").length).toBeGreaterThan(0);
  255. });
  256. test("provider-level baseUrl applies to both built-in and custom models", () => {
  257. writeModelsJson({
  258. anthropic: providerConfig("https://merged-proxy.example.com/v1", [{ id: "claude-custom" }]),
  259. });
  260. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  261. const anthropicModels = getModelsForProvider(registry, "anthropic");
  262. for (const model of anthropicModels) {
  263. expect(model.baseUrl).toBe("https://merged-proxy.example.com/v1");
  264. }
  265. });
  266. test("provider-level compat applies to custom models", () => {
  267. writeRawModelsJson({
  268. demo: {
  269. baseUrl: "https://example.com/v1",
  270. apiKey: "DEMO_KEY",
  271. api: "openai-completions",
  272. compat: {
  273. supportsUsageInStreaming: false,
  274. maxTokensField: "max_tokens",
  275. },
  276. models: [
  277. {
  278. id: "demo-model",
  279. reasoning: false,
  280. input: ["text"],
  281. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  282. contextWindow: 1000,
  283. maxTokens: 100,
  284. },
  285. ],
  286. },
  287. });
  288. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  289. const compat = registry.find("demo", "demo-model")?.compat as OpenAICompletionsCompat | undefined;
  290. expect(compat?.supportsUsageInStreaming).toBe(false);
  291. expect(compat?.maxTokensField).toBe("max_tokens");
  292. });
  293. test("model-level compat overrides provider-level compat for custom models", () => {
  294. writeRawModelsJson({
  295. demo: {
  296. baseUrl: "https://example.com/v1",
  297. apiKey: "DEMO_KEY",
  298. api: "openai-completions",
  299. compat: {
  300. supportsUsageInStreaming: false,
  301. maxTokensField: "max_tokens",
  302. },
  303. models: [
  304. {
  305. id: "demo-model",
  306. reasoning: false,
  307. input: ["text"],
  308. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  309. contextWindow: 1000,
  310. maxTokens: 100,
  311. compat: {
  312. supportsUsageInStreaming: true,
  313. maxTokensField: "max_completion_tokens",
  314. },
  315. },
  316. ],
  317. },
  318. });
  319. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  320. const compat = registry.find("demo", "demo-model")?.compat as OpenAICompletionsCompat | undefined;
  321. expect(compat?.supportsUsageInStreaming).toBe(true);
  322. expect(compat?.maxTokensField).toBe("max_completion_tokens");
  323. });
  324. test("provider-level compat applies to built-in models", () => {
  325. writeRawModelsJson({
  326. openrouter: {
  327. compat: {
  328. supportsUsageInStreaming: false,
  329. supportsStrictMode: false,
  330. },
  331. },
  332. });
  333. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  334. const models = getModelsForProvider(registry, "openrouter");
  335. expect(models.length).toBeGreaterThan(0);
  336. for (const model of models) {
  337. const compat = model.compat as OpenAICompletionsCompat | undefined;
  338. expect(compat?.supportsUsageInStreaming).toBe(false);
  339. expect(compat?.supportsStrictMode).toBe(false);
  340. }
  341. });
  342. test("model schema accepts thinkingLevelMap and compat schema accepts supportsStrictMode and cacheControlFormat", () => {
  343. writeRawModelsJson({
  344. demo: {
  345. baseUrl: "https://example.com/v1",
  346. apiKey: "DEMO_KEY",
  347. api: "openai-completions",
  348. models: [
  349. {
  350. id: "demo-model",
  351. reasoning: true,
  352. input: ["text"],
  353. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  354. contextWindow: 1000,
  355. maxTokens: 100,
  356. thinkingLevelMap: {
  357. minimal: null,
  358. high: "max",
  359. },
  360. compat: {
  361. supportsStrictMode: false,
  362. cacheControlFormat: "anthropic",
  363. },
  364. },
  365. ],
  366. },
  367. });
  368. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  369. const model = registry.find("demo", "demo-model");
  370. const compat = model?.compat as OpenAICompletionsCompat | undefined;
  371. expect(registry.getError()).toBeUndefined();
  372. expect(model?.thinkingLevelMap).toEqual({ minimal: null, high: "max" });
  373. expect(compat?.supportsStrictMode).toBe(false);
  374. expect(compat?.cacheControlFormat).toBe("anthropic");
  375. });
  376. test("compat schema accepts Anthropic eager tool input streaming flag", () => {
  377. writeRawModelsJson({
  378. demo: {
  379. baseUrl: "https://example.com",
  380. apiKey: "DEMO_KEY",
  381. api: "anthropic-messages",
  382. compat: {
  383. supportsEagerToolInputStreaming: false,
  384. },
  385. models: [
  386. {
  387. id: "demo-model",
  388. reasoning: true,
  389. input: ["text"],
  390. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  391. contextWindow: 1000,
  392. maxTokens: 100,
  393. },
  394. ],
  395. },
  396. });
  397. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  398. const compat = registry.find("demo", "demo-model")?.compat as AnthropicMessagesCompat | undefined;
  399. expect(registry.getError()).toBeUndefined();
  400. expect(compat?.supportsEagerToolInputStreaming).toBe(false);
  401. });
  402. test("compat schema accepts long cache retention flag", () => {
  403. writeRawModelsJson({
  404. demo: {
  405. baseUrl: "https://example.com",
  406. apiKey: "DEMO_KEY",
  407. api: "anthropic-messages",
  408. compat: {
  409. supportsLongCacheRetention: false,
  410. },
  411. models: [
  412. {
  413. id: "demo-model",
  414. reasoning: true,
  415. input: ["text"],
  416. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  417. contextWindow: 1000,
  418. maxTokens: 100,
  419. },
  420. ],
  421. },
  422. });
  423. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  424. const compat = registry.find("demo", "demo-model")?.compat as AnthropicMessagesCompat | undefined;
  425. expect(registry.getError()).toBeUndefined();
  426. expect(compat?.supportsLongCacheRetention).toBe(false);
  427. });
  428. test("model-level baseUrl overrides provider-level baseUrl for custom models", () => {
  429. writeRawModelsJson({
  430. "opencode-go": {
  431. baseUrl: "https://opencode.ai/zen/go/v1",
  432. apiKey: "TEST_KEY",
  433. models: [
  434. {
  435. id: "minimax-m2.5",
  436. api: "anthropic-messages",
  437. baseUrl: "https://opencode.ai/zen/go",
  438. reasoning: true,
  439. input: ["text"],
  440. cost: { input: 0.3, output: 1.2, cacheRead: 0.03, cacheWrite: 0 },
  441. contextWindow: 204800,
  442. maxTokens: 131072,
  443. },
  444. {
  445. id: "glm-5",
  446. api: "openai-completions",
  447. reasoning: true,
  448. input: ["text"],
  449. cost: { input: 1, output: 3.2, cacheRead: 0.2, cacheWrite: 0 },
  450. contextWindow: 204800,
  451. maxTokens: 131072,
  452. },
  453. ],
  454. },
  455. });
  456. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  457. const m25 = registry.find("opencode-go", "minimax-m2.5");
  458. const glm5 = registry.find("opencode-go", "glm-5");
  459. expect(m25?.baseUrl).toBe("https://opencode.ai/zen/go");
  460. expect(glm5?.baseUrl).toBe("https://opencode.ai/zen/go/v1");
  461. });
  462. test("modelOverrides still apply when provider also defines models", () => {
  463. writeRawModelsJson({
  464. openrouter: {
  465. baseUrl: "https://my-proxy.example.com/v1",
  466. apiKey: "OPENROUTER_API_KEY",
  467. api: "openai-completions",
  468. models: [
  469. {
  470. id: "custom/openrouter-model",
  471. name: "Custom OpenRouter Model",
  472. reasoning: false,
  473. input: ["text"],
  474. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  475. contextWindow: 128000,
  476. maxTokens: 16384,
  477. },
  478. ],
  479. modelOverrides: {
  480. "anthropic/claude-sonnet-4": {
  481. name: "Overridden Built-in Sonnet",
  482. },
  483. },
  484. },
  485. });
  486. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  487. const models = getModelsForProvider(registry, "openrouter");
  488. expect(models.some((m) => m.id === "custom/openrouter-model")).toBe(true);
  489. expect(
  490. models.some((m) => m.id === "anthropic/claude-sonnet-4" && m.name === "Overridden Built-in Sonnet"),
  491. ).toBe(true);
  492. });
  493. test("refresh() reloads merged custom models from disk", () => {
  494. writeModelsJson({
  495. anthropic: providerConfig("https://first-proxy.example.com/v1", [{ id: "claude-custom" }]),
  496. });
  497. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  498. expect(getModelsForProvider(registry, "anthropic").some((m) => m.id === "claude-custom")).toBe(true);
  499. // Update and refresh
  500. writeModelsJson({
  501. anthropic: providerConfig("https://second-proxy.example.com/v1", [{ id: "claude-custom-2" }]),
  502. });
  503. registry.refresh();
  504. const anthropicModels = getModelsForProvider(registry, "anthropic");
  505. expect(anthropicModels.some((m) => m.id === "claude-custom")).toBe(false);
  506. expect(anthropicModels.some((m) => m.id === "claude-custom-2")).toBe(true);
  507. expect(anthropicModels.some((m) => m.id.includes("claude"))).toBe(true);
  508. });
  509. test("removing custom models from models.json keeps built-in provider models", () => {
  510. writeModelsJson({
  511. anthropic: providerConfig("https://proxy.example.com/v1", [{ id: "claude-custom" }]),
  512. });
  513. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  514. expect(getModelsForProvider(registry, "anthropic").some((m) => m.id === "claude-custom")).toBe(true);
  515. // Remove custom models and refresh
  516. writeModelsJson({});
  517. registry.refresh();
  518. const anthropicModels = getModelsForProvider(registry, "anthropic");
  519. expect(anthropicModels.some((m) => m.id === "claude-custom")).toBe(false);
  520. expect(anthropicModels.some((m) => m.id.includes("claude"))).toBe(true);
  521. });
  522. });
  523. describe("modelOverrides (per-model customization)", () => {
  524. test("model override applies to a single built-in model", () => {
  525. writeRawModelsJson({
  526. openrouter: {
  527. modelOverrides: {
  528. "anthropic/claude-sonnet-4": {
  529. name: "Custom Sonnet Name",
  530. },
  531. },
  532. },
  533. });
  534. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  535. const models = getModelsForProvider(registry, "openrouter");
  536. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  537. expect(sonnet?.name).toBe("Custom Sonnet Name");
  538. // Other models should be unchanged
  539. const opus = models.find((m) => m.id === "anthropic/claude-opus-4");
  540. expect(opus?.name).not.toBe("Custom Sonnet Name");
  541. });
  542. test("model override with compat.openRouterRouting", () => {
  543. writeRawModelsJson({
  544. openrouter: {
  545. modelOverrides: {
  546. "anthropic/claude-sonnet-4": {
  547. compat: {
  548. openRouterRouting: { only: ["amazon-bedrock"] },
  549. },
  550. },
  551. },
  552. },
  553. });
  554. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  555. const models = getModelsForProvider(registry, "openrouter");
  556. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  557. const compat = sonnet?.compat as OpenAICompletionsCompat | undefined;
  558. expect(compat?.openRouterRouting).toEqual({ only: ["amazon-bedrock"] });
  559. });
  560. test("model override deep merges compat settings", () => {
  561. writeRawModelsJson({
  562. openrouter: {
  563. modelOverrides: {
  564. "anthropic/claude-sonnet-4": {
  565. compat: {
  566. openRouterRouting: { order: ["anthropic", "together"] },
  567. },
  568. },
  569. },
  570. },
  571. });
  572. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  573. const models = getModelsForProvider(registry, "openrouter");
  574. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  575. // Should have both the new routing AND preserve other compat settings
  576. const compat = sonnet?.compat as OpenAICompletionsCompat | undefined;
  577. expect(compat?.openRouterRouting).toEqual({ order: ["anthropic", "together"] });
  578. });
  579. test("multiple model overrides on same provider", () => {
  580. writeRawModelsJson({
  581. openrouter: {
  582. modelOverrides: {
  583. "anthropic/claude-sonnet-4": {
  584. compat: { openRouterRouting: { only: ["amazon-bedrock"] } },
  585. },
  586. "anthropic/claude-opus-4": {
  587. compat: { openRouterRouting: { only: ["anthropic"] } },
  588. },
  589. },
  590. },
  591. });
  592. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  593. const models = getModelsForProvider(registry, "openrouter");
  594. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  595. const opus = models.find((m) => m.id === "anthropic/claude-opus-4");
  596. const sonnetCompat = sonnet?.compat as OpenAICompletionsCompat | undefined;
  597. const opusCompat = opus?.compat as OpenAICompletionsCompat | undefined;
  598. expect(sonnetCompat?.openRouterRouting).toEqual({ only: ["amazon-bedrock"] });
  599. expect(opusCompat?.openRouterRouting).toEqual({ only: ["anthropic"] });
  600. });
  601. test("model override combined with baseUrl override", () => {
  602. writeRawModelsJson({
  603. openrouter: {
  604. baseUrl: "https://my-proxy.example.com/v1",
  605. modelOverrides: {
  606. "anthropic/claude-sonnet-4": {
  607. name: "Proxied Sonnet",
  608. },
  609. },
  610. },
  611. });
  612. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  613. const models = getModelsForProvider(registry, "openrouter");
  614. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  615. // Both overrides should apply
  616. expect(sonnet?.baseUrl).toBe("https://my-proxy.example.com/v1");
  617. expect(sonnet?.name).toBe("Proxied Sonnet");
  618. // Other models should have the baseUrl but not the name override
  619. const opus = models.find((m) => m.id === "anthropic/claude-opus-4");
  620. expect(opus?.baseUrl).toBe("https://my-proxy.example.com/v1");
  621. expect(opus?.name).not.toBe("Proxied Sonnet");
  622. });
  623. test("model override for non-existent model ID is ignored", () => {
  624. writeRawModelsJson({
  625. openrouter: {
  626. modelOverrides: {
  627. "nonexistent/model-id": {
  628. name: "This should not appear",
  629. },
  630. },
  631. },
  632. });
  633. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  634. const models = getModelsForProvider(registry, "openrouter");
  635. // Should not create a new model
  636. expect(models.find((m) => m.id === "nonexistent/model-id")).toBeUndefined();
  637. // Should not crash or show error
  638. expect(registry.getError()).toBeUndefined();
  639. });
  640. test("model override can change cost fields partially", () => {
  641. writeRawModelsJson({
  642. openrouter: {
  643. modelOverrides: {
  644. "anthropic/claude-sonnet-4": {
  645. cost: { input: 99 },
  646. },
  647. },
  648. },
  649. });
  650. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  651. const models = getModelsForProvider(registry, "openrouter");
  652. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  653. // Input cost should be overridden
  654. expect(sonnet?.cost.input).toBe(99);
  655. // Other cost fields should be preserved from built-in
  656. expect(sonnet?.cost.output).toBeGreaterThan(0);
  657. });
  658. test("model override can add headers at request time", async () => {
  659. writeRawModelsJson({
  660. openrouter: {
  661. modelOverrides: {
  662. "anthropic/claude-sonnet-4": {
  663. headers: { "X-Custom-Model-Header": "value" },
  664. },
  665. },
  666. },
  667. });
  668. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  669. const models = getModelsForProvider(registry, "openrouter");
  670. const sonnet = models.find((m) => m.id === "anthropic/claude-sonnet-4");
  671. expect(sonnet).toBeDefined();
  672. const auth = await registry.getApiKeyAndHeaders(sonnet!);
  673. expect(auth.ok).toBe(true);
  674. if (auth.ok) {
  675. expect(auth.headers?.["X-Custom-Model-Header"]).toBe("value");
  676. }
  677. });
  678. test("refresh() picks up model override changes", () => {
  679. writeRawModelsJson({
  680. openrouter: {
  681. modelOverrides: {
  682. "anthropic/claude-sonnet-4": {
  683. name: "First Name",
  684. },
  685. },
  686. },
  687. });
  688. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  689. expect(
  690. getModelsForProvider(registry, "openrouter").find((m) => m.id === "anthropic/claude-sonnet-4")?.name,
  691. ).toBe("First Name");
  692. // Update and refresh
  693. writeRawModelsJson({
  694. openrouter: {
  695. modelOverrides: {
  696. "anthropic/claude-sonnet-4": {
  697. name: "Second Name",
  698. },
  699. },
  700. },
  701. });
  702. registry.refresh();
  703. expect(
  704. getModelsForProvider(registry, "openrouter").find((m) => m.id === "anthropic/claude-sonnet-4")?.name,
  705. ).toBe("Second Name");
  706. });
  707. test("removing model override restores built-in values", () => {
  708. writeRawModelsJson({
  709. openrouter: {
  710. modelOverrides: {
  711. "anthropic/claude-sonnet-4": {
  712. name: "Custom Name",
  713. },
  714. },
  715. },
  716. });
  717. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  718. const customName = getModelsForProvider(registry, "openrouter").find(
  719. (m) => m.id === "anthropic/claude-sonnet-4",
  720. )?.name;
  721. expect(customName).toBe("Custom Name");
  722. // Remove override and refresh
  723. writeRawModelsJson({});
  724. registry.refresh();
  725. const restoredName = getModelsForProvider(registry, "openrouter").find(
  726. (m) => m.id === "anthropic/claude-sonnet-4",
  727. )?.name;
  728. expect(restoredName).not.toBe("Custom Name");
  729. });
  730. });
  731. describe("dynamic provider lifecycle", () => {
  732. test("getProviderDisplayName resolves registered, OAuth, built-in, and fallback names", () => {
  733. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  734. expect(registry.getProviderDisplayName("openai")).toBe("OpenAI");
  735. expect(registry.getProviderDisplayName("github-copilot")).toBe("GitHub Copilot");
  736. expect(registry.getProviderDisplayName("unknown-provider")).toBe("unknown-provider");
  737. registry.registerProvider("named-provider", {
  738. name: "Named Provider",
  739. baseUrl: "https://provider.test/v1",
  740. apiKey: "test-key",
  741. api: "openai-completions",
  742. models: [
  743. {
  744. id: "demo-model",
  745. name: "Demo Model",
  746. reasoning: false,
  747. input: ["text"],
  748. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  749. contextWindow: 128000,
  750. maxTokens: 4096,
  751. },
  752. ],
  753. });
  754. expect(registry.getProviderDisplayName("named-provider")).toBe("Named Provider");
  755. registry.registerProvider("oauth-provider", {
  756. baseUrl: "https://provider.test/v1",
  757. api: "openai-completions",
  758. oauth: {
  759. name: "OAuth Provider",
  760. login: async () => ({ access: "access", refresh: "refresh", expires: Date.now() + 60_000 }),
  761. refreshToken: async (credentials) => credentials,
  762. getApiKey: (credentials) => credentials.access,
  763. },
  764. models: [
  765. {
  766. id: "demo-model",
  767. name: "Demo Model",
  768. reasoning: false,
  769. input: ["text"],
  770. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  771. contextWindow: 128000,
  772. maxTokens: 4096,
  773. },
  774. ],
  775. });
  776. expect(registry.getProviderDisplayName("oauth-provider")).toBe("OAuth Provider");
  777. });
  778. test("registerProvider warns and temporarily treats uppercase apiKey as an env reference", async () => {
  779. const originalEnv = process.env.CUSTOM_NAME;
  780. process.env.CUSTOM_NAME = "legacy-env-key";
  781. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  782. try {
  783. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  784. registry.registerProvider("legacy-provider", {
  785. ...providerConfig("https://provider.test/v1", [{ id: "demo-model" }], "openai-completions"),
  786. apiKey: "CUSTOM_NAME",
  787. });
  788. expect(await registry.getApiKeyForProvider("legacy-provider")).toBe("legacy-env-key");
  789. expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Pass "$CUSTOM_NAME" instead'));
  790. } finally {
  791. if (originalEnv === undefined) {
  792. delete process.env.CUSTOM_NAME;
  793. } else {
  794. process.env.CUSTOM_NAME = originalEnv;
  795. }
  796. }
  797. });
  798. test("failed registerProvider does not persist invalid streamSimple config", () => {
  799. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  800. expect(() =>
  801. registry.registerProvider("broken-provider", {
  802. streamSimple: (() => {
  803. throw new Error("should not run");
  804. }) as any,
  805. }),
  806. ).toThrow('Provider broken-provider: "api" is required when registering streamSimple.');
  807. expect(() => registry.refresh()).not.toThrow();
  808. });
  809. test("failed registerProvider does not remove existing provider models", () => {
  810. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  811. registry.registerProvider("demo-provider", {
  812. baseUrl: "https://provider.test/v1",
  813. apiKey: "test-key",
  814. api: "openai-completions",
  815. models: [
  816. {
  817. id: "demo-model",
  818. name: "Demo Model",
  819. reasoning: false,
  820. input: ["text"],
  821. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  822. contextWindow: 128000,
  823. maxTokens: 4096,
  824. },
  825. ],
  826. });
  827. expect(registry.find("demo-provider", "demo-model")).toBeDefined();
  828. expect(() =>
  829. registry.registerProvider("demo-provider", {
  830. baseUrl: "https://provider.test/v2",
  831. apiKey: "test-key",
  832. models: [
  833. {
  834. id: "broken-model",
  835. name: "Broken Model",
  836. reasoning: false,
  837. input: ["text"],
  838. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  839. contextWindow: 128000,
  840. maxTokens: 4096,
  841. },
  842. ],
  843. }),
  844. ).toThrow('Provider demo-provider, model broken-model: no "api" specified.');
  845. expect(registry.find("demo-provider", "demo-model")).toBeDefined();
  846. expect(() => registry.refresh()).not.toThrow();
  847. expect(registry.find("demo-provider", "demo-model")).toBeDefined();
  848. });
  849. test("unregisterProvider removes custom OAuth provider and restores built-in OAuth provider", () => {
  850. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  851. registry.registerProvider("anthropic", {
  852. oauth: {
  853. name: "Custom Anthropic OAuth",
  854. login: async () => ({
  855. access: "custom-access-token",
  856. refresh: "custom-refresh-token",
  857. expires: Date.now() + 60_000,
  858. }),
  859. refreshToken: async (credentials) => credentials,
  860. getApiKey: (credentials) => credentials.access,
  861. },
  862. });
  863. expect(getOAuthProvider("anthropic")?.name).toBe("Custom Anthropic OAuth");
  864. registry.unregisterProvider("anthropic");
  865. expect(getOAuthProvider("anthropic")?.name).not.toBe("Custom Anthropic OAuth");
  866. });
  867. test("unregisterProvider removes custom streamSimple override and restores built-in API stream handler", () => {
  868. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  869. registry.registerProvider("stream-override-provider", {
  870. api: "openai-completions",
  871. streamSimple: () => {
  872. throw new Error("custom streamSimple override");
  873. },
  874. });
  875. let threwCustomOverride = false;
  876. try {
  877. getApiProvider("openai-completions")?.streamSimple(openAiModel, emptyContext);
  878. } catch (error) {
  879. threwCustomOverride = error instanceof Error && error.message === "custom streamSimple override";
  880. }
  881. expect(threwCustomOverride).toBe(true);
  882. registry.unregisterProvider("stream-override-provider");
  883. let threwCustomOverrideAfterUnregister = false;
  884. try {
  885. getApiProvider("openai-completions")?.streamSimple(openAiModel, emptyContext);
  886. } catch (error) {
  887. threwCustomOverrideAfterUnregister =
  888. error instanceof Error && error.message === "custom streamSimple override";
  889. }
  890. expect(threwCustomOverrideAfterUnregister).toBe(false);
  891. });
  892. describe("dynamic provider override persistence", () => {
  893. test("baseUrl-only override keeps built-in provider models after refresh", () => {
  894. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  895. registry.registerProvider("anthropic", { baseUrl: "https://proxy.test/anthropic" });
  896. registry.refresh();
  897. const anthropicModels = getModelsForProvider(registry, "anthropic");
  898. expect(anthropicModels.length).toBeGreaterThan(1);
  899. expect(anthropicModels.every((m) => m.baseUrl === "https://proxy.test/anthropic")).toBe(true);
  900. });
  901. test("models-only override replaces built-in provider models after refresh", () => {
  902. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  903. registry.registerProvider("anthropic", {
  904. ...providerConfig("https://custom.test/anthropic", [{ id: "custom-claude" }], "anthropic-messages"),
  905. baseUrl: "https://custom.test/anthropic",
  906. });
  907. registry.refresh();
  908. expect(getModelsForProvider(registry, "anthropic").map((m) => m.id)).toEqual(["custom-claude"]);
  909. expect(registry.find("anthropic", "custom-claude")?.baseUrl).toBe("https://custom.test/anthropic");
  910. });
  911. test("models plus baseUrl override replaces built-in provider models after refresh", () => {
  912. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  913. registry.registerProvider("anthropic", {
  914. ...providerConfig("https://custom.test/anthropic", [{ id: "custom-claude" }], "anthropic-messages"),
  915. baseUrl: "https://custom.test/anthropic",
  916. });
  917. registry.registerProvider("anthropic", { baseUrl: "https://proxy.test/anthropic" });
  918. registry.refresh();
  919. expect(getModelsForProvider(registry, "anthropic").map((m) => m.id)).toEqual(["custom-claude"]);
  920. expect(registry.find("anthropic", "custom-claude")?.baseUrl).toBe("https://proxy.test/anthropic");
  921. });
  922. test("models-only custom provider registration survives refresh", () => {
  923. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  924. registry.registerProvider(
  925. "custom-provider",
  926. providerConfig("https://custom.test/v1", [{ id: "custom-a" }, { id: "custom-b" }], "openai-completions"),
  927. );
  928. registry.refresh();
  929. expect(getModelsForProvider(registry, "custom-provider").map((m) => m.id)).toEqual([
  930. "custom-a",
  931. "custom-b",
  932. ]);
  933. });
  934. test("baseUrl-only override keeps custom provider models after refresh", () => {
  935. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  936. registry.registerProvider(
  937. "custom-provider",
  938. providerConfig("https://custom.test/v1", [{ id: "custom-a" }, { id: "custom-b" }], "openai-completions"),
  939. );
  940. registry.registerProvider("custom-provider", { baseUrl: "https://proxy.test/custom" });
  941. registry.refresh();
  942. expect(getModelsForProvider(registry, "custom-provider").map((m) => m.id)).toEqual([
  943. "custom-a",
  944. "custom-b",
  945. ]);
  946. expect(
  947. getModelsForProvider(registry, "custom-provider").every(
  948. (m) => m.baseUrl === "https://proxy.test/custom",
  949. ),
  950. ).toBe(true);
  951. });
  952. test("headers-only override keeps custom provider models after refresh", async () => {
  953. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  954. registry.registerProvider(
  955. "custom-provider",
  956. providerConfig("https://custom.test/v1", [{ id: "custom-a" }, { id: "custom-b" }], "openai-completions"),
  957. );
  958. registry.registerProvider("custom-provider", { headers: { "x-proxy": "enabled" } });
  959. registry.refresh();
  960. const models = getModelsForProvider(registry, "custom-provider");
  961. expect(models.map((m) => m.id)).toEqual(["custom-a", "custom-b"]);
  962. expect(models.every((m) => m.baseUrl === "https://custom.test/v1")).toBe(true);
  963. expect(await registry.getApiKeyAndHeaders(models[0])).toMatchObject({
  964. ok: true,
  965. headers: { "x-proxy": "enabled" },
  966. });
  967. });
  968. });
  969. });
  970. describe("API key resolution", () => {
  971. /** Create provider config with custom apiKey */
  972. function providerWithApiKey(apiKey: string) {
  973. return {
  974. baseUrl: "https://example.com/v1",
  975. apiKey,
  976. api: "anthropic-messages",
  977. models: [
  978. {
  979. id: "test-model",
  980. name: "Test Model",
  981. reasoning: false,
  982. input: ["text"],
  983. cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
  984. contextWindow: 100000,
  985. maxTokens: 8000,
  986. },
  987. ],
  988. };
  989. }
  990. test("apiKey with ! prefix executes command and uses stdout", async () => {
  991. writeRawModelsJson({
  992. "custom-provider": providerWithApiKey("!echo test-api-key-from-command"),
  993. });
  994. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  995. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  996. expect(apiKey).toBe("test-api-key-from-command");
  997. });
  998. test("apiKey with ! prefix trims whitespace from command output", async () => {
  999. writeRawModelsJson({
  1000. "custom-provider": providerWithApiKey("!echo ' spaced-key '"),
  1001. });
  1002. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1003. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1004. expect(apiKey).toBe("spaced-key");
  1005. });
  1006. test("apiKey with ! prefix handles multiline output (uses trimmed result)", async () => {
  1007. writeRawModelsJson({
  1008. "custom-provider": providerWithApiKey("!printf 'line1\\nline2'"),
  1009. });
  1010. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1011. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1012. expect(apiKey).toBe("line1\nline2");
  1013. });
  1014. test("apiKey with ! prefix returns undefined on command failure", async () => {
  1015. writeRawModelsJson({
  1016. "custom-provider": providerWithApiKey("!exit 1"),
  1017. });
  1018. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1019. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1020. expect(apiKey).toBeUndefined();
  1021. });
  1022. test("apiKey with ! prefix returns undefined on nonexistent command", async () => {
  1023. writeRawModelsJson({
  1024. "custom-provider": providerWithApiKey("!nonexistent-command-12345"),
  1025. });
  1026. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1027. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1028. expect(apiKey).toBeUndefined();
  1029. });
  1030. test("apiKey with ! prefix returns undefined on empty output", async () => {
  1031. writeRawModelsJson({
  1032. "custom-provider": providerWithApiKey("!printf ''"),
  1033. });
  1034. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1035. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1036. expect(apiKey).toBeUndefined();
  1037. });
  1038. test("apiKey with $ prefix resolves to env value", async () => {
  1039. const originalEnv = process.env.TEST_API_KEY_12345;
  1040. process.env.TEST_API_KEY_12345 = "env-api-key-value";
  1041. try {
  1042. writeRawModelsJson({
  1043. "custom-provider": providerWithApiKey("$TEST_API_KEY_12345"),
  1044. });
  1045. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1046. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1047. expect(apiKey).toBe("env-api-key-value");
  1048. } finally {
  1049. if (originalEnv === undefined) {
  1050. delete process.env.TEST_API_KEY_12345;
  1051. } else {
  1052. process.env.TEST_API_KEY_12345 = originalEnv;
  1053. }
  1054. }
  1055. });
  1056. test("apiKey with braced env syntax resolves to env value", async () => {
  1057. const originalEnv = process.env.TEST_BRACED_API_KEY_12345;
  1058. process.env.TEST_BRACED_API_KEY_12345 = "braced-env-api-key-value";
  1059. const bracedKey = "$" + "{TEST_BRACED_API_KEY_12345}";
  1060. try {
  1061. writeRawModelsJson({
  1062. "custom-provider": providerWithApiKey(bracedKey),
  1063. });
  1064. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1065. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1066. expect(apiKey).toBe("braced-env-api-key-value");
  1067. } finally {
  1068. if (originalEnv === undefined) {
  1069. delete process.env.TEST_BRACED_API_KEY_12345;
  1070. } else {
  1071. process.env.TEST_BRACED_API_KEY_12345 = originalEnv;
  1072. }
  1073. }
  1074. });
  1075. test("apiKey interpolates braced env references inside literals", async () => {
  1076. const originalPartA = process.env.TEST_INTERPOLATED_PART_A_12345;
  1077. const originalPartB = process.env.TEST_INTERPOLATED_PART_B_12345;
  1078. process.env.TEST_INTERPOLATED_PART_A_12345 = "left";
  1079. process.env.TEST_INTERPOLATED_PART_B_12345 = "right";
  1080. const interpolatedKey = ["$", "{TEST_INTERPOLATED_PART_A_12345}_$", "{TEST_INTERPOLATED_PART_B_12345}"].join(
  1081. "",
  1082. );
  1083. try {
  1084. writeRawModelsJson({
  1085. "custom-provider": providerWithApiKey(interpolatedKey),
  1086. });
  1087. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1088. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1089. expect(apiKey).toBe("left_right");
  1090. } finally {
  1091. if (originalPartA === undefined) {
  1092. delete process.env.TEST_INTERPOLATED_PART_A_12345;
  1093. } else {
  1094. process.env.TEST_INTERPOLATED_PART_A_12345 = originalPartA;
  1095. }
  1096. if (originalPartB === undefined) {
  1097. delete process.env.TEST_INTERPOLATED_PART_B_12345;
  1098. } else {
  1099. process.env.TEST_INTERPOLATED_PART_B_12345 = originalPartB;
  1100. }
  1101. }
  1102. });
  1103. test("apiKey with $$ prefix escapes a leading dollar", async () => {
  1104. writeRawModelsJson({
  1105. "custom-provider": providerWithApiKey("$$TEST_API_KEY_12345"),
  1106. });
  1107. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1108. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1109. expect(apiKey).toBe("$TEST_API_KEY_12345");
  1110. });
  1111. test("apiKey with $! escapes a literal bang and still interpolates later env refs", async () => {
  1112. const originalEnv = process.env.TEST_API_KEY_12345;
  1113. process.env.TEST_API_KEY_12345 = "env-api-key-value";
  1114. try {
  1115. writeRawModelsJson({
  1116. "custom-provider": providerWithApiKey("$!literal-$TEST_API_KEY_12345"),
  1117. });
  1118. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1119. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1120. expect(apiKey).toBe("!literal-env-api-key-value");
  1121. } finally {
  1122. if (originalEnv === undefined) {
  1123. delete process.env.TEST_API_KEY_12345;
  1124. } else {
  1125. process.env.TEST_API_KEY_12345 = originalEnv;
  1126. }
  1127. }
  1128. });
  1129. test("plain apiKey is used directly even when it matches an env var", async () => {
  1130. const originalEnv = process.env.TEST_API_KEY_12345;
  1131. process.env.TEST_API_KEY_12345 = "env-api-key-value";
  1132. try {
  1133. writeRawModelsJson({
  1134. "custom-provider": providerWithApiKey("TEST_API_KEY_12345"),
  1135. });
  1136. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1137. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1138. expect(apiKey).toBe("TEST_API_KEY_12345");
  1139. } finally {
  1140. if (originalEnv === undefined) {
  1141. delete process.env.TEST_API_KEY_12345;
  1142. } else {
  1143. process.env.TEST_API_KEY_12345 = originalEnv;
  1144. }
  1145. }
  1146. });
  1147. test("apiKey as literal value is used directly when not an env var", async () => {
  1148. // Make sure this isn't an env var
  1149. delete process.env.literal_api_key_value;
  1150. writeRawModelsJson({
  1151. "custom-provider": providerWithApiKey("literal_api_key_value"),
  1152. });
  1153. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1154. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1155. expect(apiKey).toBe("literal_api_key_value");
  1156. });
  1157. test("apiKey command can use shell features like pipes", async () => {
  1158. writeRawModelsJson({
  1159. "custom-provider": providerWithApiKey("!echo 'hello world' | tr ' ' '-'"),
  1160. });
  1161. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1162. const apiKey = await registry.getApiKeyForProvider("custom-provider");
  1163. expect(apiKey).toBe("hello-world");
  1164. });
  1165. describe("request-time resolution", () => {
  1166. test("command is executed on every provider lookup", async () => {
  1167. const counterFile = join(tempDir, "counter");
  1168. writeFileSync(counterFile, "0");
  1169. const counterPath = toShPath(counterFile);
  1170. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; echo "key-value"'`;
  1171. writeRawModelsJson({
  1172. "custom-provider": providerWithApiKey(command),
  1173. });
  1174. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1175. await registry.getApiKeyForProvider("custom-provider");
  1176. await registry.getApiKeyForProvider("custom-provider");
  1177. await registry.getApiKeyForProvider("custom-provider");
  1178. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  1179. expect(count).toBe(3);
  1180. });
  1181. test("commands are re-executed across registry instances", async () => {
  1182. const counterFile = join(tempDir, "counter");
  1183. writeFileSync(counterFile, "0");
  1184. const counterPath = toShPath(counterFile);
  1185. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; echo "key-value"'`;
  1186. writeRawModelsJson({
  1187. "custom-provider": providerWithApiKey(command),
  1188. });
  1189. const registry1 = ModelRegistry.create(authStorage, modelsJsonPath);
  1190. await registry1.getApiKeyForProvider("custom-provider");
  1191. const registry2 = ModelRegistry.create(authStorage, modelsJsonPath);
  1192. await registry2.getApiKeyForProvider("custom-provider");
  1193. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  1194. expect(count).toBe(2);
  1195. });
  1196. test("different commands resolve independently", async () => {
  1197. writeRawModelsJson({
  1198. "provider-a": providerWithApiKey("!echo key-a"),
  1199. "provider-b": providerWithApiKey("!echo key-b"),
  1200. });
  1201. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1202. const keyA = await registry.getApiKeyForProvider("provider-a");
  1203. const keyB = await registry.getApiKeyForProvider("provider-b");
  1204. expect(keyA).toBe("key-a");
  1205. expect(keyB).toBe("key-b");
  1206. });
  1207. test("failed commands are retried", async () => {
  1208. const counterFile = join(tempDir, "counter");
  1209. writeFileSync(counterFile, "0");
  1210. const counterPath = toShPath(counterFile);
  1211. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; exit 1'`;
  1212. writeRawModelsJson({
  1213. "custom-provider": providerWithApiKey(command),
  1214. });
  1215. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1216. const key1 = await registry.getApiKeyForProvider("custom-provider");
  1217. const key2 = await registry.getApiKeyForProvider("custom-provider");
  1218. expect(key1).toBeUndefined();
  1219. expect(key2).toBeUndefined();
  1220. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  1221. expect(count).toBe(2);
  1222. });
  1223. test("provider auth status reports apiKey environment variables from models.json", () => {
  1224. const envVarName = "TEST_API_KEY_STATUS_TEST_98765";
  1225. const originalEnv = process.env[envVarName];
  1226. try {
  1227. process.env[envVarName] = "status-test-key";
  1228. writeRawModelsJson({
  1229. "custom-provider": providerWithApiKey(`$${envVarName}`),
  1230. });
  1231. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1232. expect(registry.getProviderAuthStatus("custom-provider")).toEqual({
  1233. configured: true,
  1234. source: "environment",
  1235. label: envVarName,
  1236. });
  1237. } finally {
  1238. if (originalEnv === undefined) {
  1239. delete process.env[envVarName];
  1240. } else {
  1241. process.env[envVarName] = originalEnv;
  1242. }
  1243. }
  1244. });
  1245. test("provider auth status reports interpolated apiKey environment variables", () => {
  1246. const envVarNameA = "TEST_API_KEY_STATUS_PART_A_98765";
  1247. const envVarNameB = "TEST_API_KEY_STATUS_PART_B_98765";
  1248. const originalEnvA = process.env[envVarNameA];
  1249. const originalEnvB = process.env[envVarNameB];
  1250. process.env[envVarNameA] = "left";
  1251. process.env[envVarNameB] = "right";
  1252. const interpolatedKey = ["$", "{", envVarNameA, "}_$", "{", envVarNameB, "}"].join("");
  1253. try {
  1254. writeRawModelsJson({
  1255. "custom-provider": providerWithApiKey(interpolatedKey),
  1256. });
  1257. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1258. expect(registry.getProviderAuthStatus("custom-provider")).toEqual({
  1259. configured: true,
  1260. source: "environment",
  1261. label: `${envVarNameA}, ${envVarNameB}`,
  1262. });
  1263. } finally {
  1264. if (originalEnvA === undefined) {
  1265. delete process.env[envVarNameA];
  1266. } else {
  1267. process.env[envVarNameA] = originalEnvA;
  1268. }
  1269. if (originalEnvB === undefined) {
  1270. delete process.env[envVarNameB];
  1271. } else {
  1272. process.env[envVarNameB] = originalEnvB;
  1273. }
  1274. }
  1275. });
  1276. test("provider auth status reports non-env apiKey values from models.json as a config key", () => {
  1277. writeRawModelsJson({
  1278. "custom-provider": providerWithApiKey("literal_api_key_value"),
  1279. });
  1280. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1281. expect(registry.getProviderAuthStatus("custom-provider")).toEqual({
  1282. configured: true,
  1283. source: "models_json_key",
  1284. });
  1285. });
  1286. test("missing explicit env apiKey keeps provider unavailable", () => {
  1287. const envVarName = "TEST_API_KEY_MISSING_TEST_98765";
  1288. const originalEnv = process.env[envVarName];
  1289. delete process.env[envVarName];
  1290. try {
  1291. writeRawModelsJson({
  1292. "custom-provider": providerWithApiKey(`$${envVarName}`),
  1293. });
  1294. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1295. expect(registry.getProviderAuthStatus("custom-provider")).toEqual({ configured: false });
  1296. expect(registry.getAvailable().some((model) => model.provider === "custom-provider")).toBe(false);
  1297. } finally {
  1298. if (originalEnv === undefined) {
  1299. delete process.env[envVarName];
  1300. } else {
  1301. process.env[envVarName] = originalEnv;
  1302. }
  1303. }
  1304. });
  1305. test("provider auth status reports command apiKey values from models.json without executing them", () => {
  1306. const counterFile = join(tempDir, "status-counter");
  1307. writeFileSync(counterFile, "0");
  1308. const counterPath = toShPath(counterFile);
  1309. const command = `!sh -c 'echo 1 > "${counterPath}"; echo key-value'`;
  1310. writeRawModelsJson({
  1311. "custom-provider": providerWithApiKey(command),
  1312. });
  1313. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1314. expect(registry.getProviderAuthStatus("custom-provider")).toEqual({
  1315. configured: true,
  1316. source: "models_json_command",
  1317. });
  1318. expect(readFileSync(counterFile, "utf-8")).toBe("0");
  1319. });
  1320. test("environment variables are not cached (changes are picked up)", async () => {
  1321. const envVarName = "TEST_API_KEY_CACHE_TEST_98765";
  1322. const originalEnv = process.env[envVarName];
  1323. try {
  1324. process.env[envVarName] = "first-value";
  1325. writeRawModelsJson({
  1326. "custom-provider": providerWithApiKey(`$${envVarName}`),
  1327. });
  1328. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1329. const key1 = await registry.getApiKeyForProvider("custom-provider");
  1330. expect(key1).toBe("first-value");
  1331. process.env[envVarName] = "second-value";
  1332. const key2 = await registry.getApiKeyForProvider("custom-provider");
  1333. expect(key2).toBe("second-value");
  1334. } finally {
  1335. if (originalEnv === undefined) {
  1336. delete process.env[envVarName];
  1337. } else {
  1338. process.env[envVarName] = originalEnv;
  1339. }
  1340. }
  1341. });
  1342. test("getAvailable does not execute command-backed apiKey resolution", async () => {
  1343. const counterFile = join(tempDir, "counter");
  1344. writeFileSync(counterFile, "0");
  1345. const counterPath = toShPath(counterFile);
  1346. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; echo "key-value"'`;
  1347. writeRawModelsJson({
  1348. "custom-provider": providerWithApiKey(command),
  1349. });
  1350. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1351. const available = registry.getAvailable();
  1352. expect(available.some((m) => m.provider === "custom-provider")).toBe(true);
  1353. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  1354. expect(count).toBe(0);
  1355. });
  1356. test("getApiKeyAndHeaders resolves authHeader on every request", async () => {
  1357. const tokenFile = join(tempDir, "token");
  1358. writeFileSync(tokenFile, "token-1");
  1359. const tokenPath = toShPath(tokenFile);
  1360. writeRawModelsJson({
  1361. "custom-provider": {
  1362. ...providerWithApiKey(`!sh -c 'cat "${tokenPath}"'`),
  1363. authHeader: true,
  1364. },
  1365. });
  1366. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1367. const model = registry.find("custom-provider", "test-model");
  1368. expect(model).toBeDefined();
  1369. const auth1 = await registry.getApiKeyAndHeaders(model!);
  1370. expect(auth1).toEqual({
  1371. ok: true,
  1372. apiKey: "token-1",
  1373. headers: { Authorization: "Bearer token-1" },
  1374. });
  1375. writeFileSync(tokenFile, "token-2");
  1376. const auth2 = await registry.getApiKeyAndHeaders(model!);
  1377. expect(auth2).toEqual({
  1378. ok: true,
  1379. apiKey: "token-2",
  1380. headers: { Authorization: "Bearer token-2" },
  1381. });
  1382. });
  1383. test("getApiKeyAndHeaders returns an error for failed authHeader resolution", async () => {
  1384. writeRawModelsJson({
  1385. "custom-provider": {
  1386. ...providerWithApiKey("!exit 1"),
  1387. authHeader: true,
  1388. },
  1389. });
  1390. const registry = ModelRegistry.create(authStorage, modelsJsonPath);
  1391. const model = registry.find("custom-provider", "test-model");
  1392. expect(model).toBeDefined();
  1393. const auth = await registry.getApiKeyAndHeaders(model!);
  1394. expect(auth.ok).toBe(false);
  1395. if (!auth.ok) {
  1396. expect(auth.error).toContain('Failed to resolve API key for provider "custom-provider"');
  1397. }
  1398. });
  1399. });
  1400. });
  1401. });