-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.test.ts
More file actions
963 lines (906 loc) · 33.4 KB
/
Copy pathconfig.test.ts
File metadata and controls
963 lines (906 loc) · 33.4 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
import { describe, test, expect } from "bun:test";
import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildBifrostSource, buildOpenAISource, buildProviderCatalog, catalogEntryAsProviderSettings, CliHelpError, CLI_HELP_TEXT, KEYLESS_API_KEY, loadConfig, providerCatalogToSettings, runtimeSettingsWithCatalog, SOURCE_MAX_TOKENS } from "./config/index.js";
import type { Config, UnconfiguredConfig } from "./config/index.js";
import { mergeProviderIntoSettings, type ResolvedProvider, type Settings } from "./config/settings.js";
import { OPENCODE_GO_BASE_URL } from "../packages/opencode-go/src/index.js";
import { generateSessionId, initSessionDir } from "./session/index.js";
import { saveState } from "./session/state.js";
function assertConfigured(config: Config | UnconfiguredConfig): asserts config is Config {
if (config.configured === false) {
throw new Error(`Expected configured Config but got UnconfiguredConfig: ${config.providerError}`);
}
}
// A global settings path guaranteed not to exist, so resolution finds no
// provider — used by the "missing provider" cases.
const NO_SETTINGS = join(tmpdir(), "corbits-tests-missing", ".corbits", "settings.json");
// Writes a minimal valid global settings file with a single provider and
// returns its path. Provider resolution reads exclusively from such files.
async function writeGlobalSettings(cwd: string): Promise<string> {
const path = join(cwd, "global.json");
await writeFile(
path,
JSON.stringify({
defaultProvider: "fireworks",
providers: {
fireworks: {
baseURL: "https://api.fireworks.ai/inference",
apiKey: "test-key",
models: ["accounts/fireworks/routers/kimi-k2p6-turbo"],
},
},
}),
);
return path;
}
// A cwd with no per-repo settings file, so local resolution is inert.
async function emptyCwd(): Promise<string> {
return mkdtemp(join(tmpdir(), "ic-config-"));
}
describe("loadConfig", () => {
test("resolves provider from the global settings file", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["--cwd", cwd, "add", "hello", "world"], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.task).toBe("add hello world");
expect(config.apiKey).toBe("test-key");
expect(config.baseURL).toBe("https://api.fireworks.ai/inference");
expect(config.model).toBe("accounts/fireworks/routers/kimi-k2p6-turbo");
expect(config.providerName).toBe("fireworks");
expect(config.globalSettingsPath).toBe(globalPath);
expect(config.globalDefaultProvider).toBe("fireworks");
expect(config.force).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("throws when no provider can be resolved (allowUnconfigured false)", async () => {
const cwd = await emptyCwd();
try {
await expect(
loadConfig(["--cwd", cwd, "do it"], { globalSettingsPath: NO_SETTINGS }),
).rejects.toThrow(/missing/);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("returns UnconfiguredConfig when allowUnconfigured is true and provider is missing", async () => {
const cwd = await emptyCwd();
try {
const result = await loadConfig(["--cwd", cwd, "do it"], {
globalSettingsPath: NO_SETTINGS,
allowUnconfigured: true,
});
expect(result.configured).toBe(false);
if (result.configured === false) {
expect(result.cwd).toBe(cwd);
expect(result.task).toBe("do it");
expect(result.providerError).toMatch(/missing/);
expect(result.globalSettingsPath).toBe(NO_SETTINGS);
}
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("threads local settings diagnostics on unconfigured early return", async () => {
const cwd = await emptyCwd();
try {
await mkdir(join(cwd, ".corbits"), { recursive: true });
await writeFile(
join(cwd, ".corbits", "settings.json"),
JSON.stringify({ unknownKey: true, anotherJunk: 1 }),
);
const result = await loadConfig(["--cwd", cwd, "do it"], {
globalSettingsPath: NO_SETTINGS,
allowUnconfigured: true,
});
expect(result.configured).toBe(false);
if (result.configured === false) {
expect(result.settingsDiagnostics).toBeDefined();
expect(result.settingsDiagnostics!.length).toBeGreaterThan(0);
expect(result.settingsDiagnostics!.some((d) => /unknown/i.test(d.message))).toBe(true);
}
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("UnconfiguredConfig.globalSettingsPath reflects --config path, not the global default", async () => {
const cwd = await emptyCwd();
try {
const configPath = join(cwd, "custom.json");
await writeFile(configPath, JSON.stringify({ providers: {} }));
const result = await loadConfig(["--cwd", cwd, "--config", configPath, "task"], {
allowUnconfigured: true,
});
expect(result.configured).toBe(false);
if (result.configured === false) {
expect(result.globalSettingsPath).toBe(configPath);
}
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("parses --force", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["--cwd", cwd, "--force", "run task"], {
globalSettingsPath: globalPath,
});
expect(config.force).toBe(true);
expect(config.task).toBe("run task");
expect(config.command).toBe("tui");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("parses exec subcommand and keeps flags", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["exec", "--cwd", cwd, "--force", "ship it"], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.command).toBe("exec");
expect(config.task).toBe("ship it");
expect(config.force).toBe(true);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("parses run as exec alias", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["run", "--cwd", cwd, "alias task"], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.command).toBe("exec");
expect(config.task).toBe("alias task");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("resume --pick opens the session picker without requiring prior sessions", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["resume", "--pick", "--cwd", cwd], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.command).toBe("tui");
expect(config.resumeMode).toBe("pick");
expect(config.resumePicker).toBe(true);
expect(config.skipInitialTask).toBe(true);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("continue is an alias of resume", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["continue", "--list", "--cwd", cwd], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.resumeMode).toBe("pick");
expect(config.resumePicker).toBe(true);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("resume last fails when this project has no sessions", async () => {
const cwd = await emptyCwd();
const home = await mkdtemp(join(tmpdir(), "ic-resume-home-"));
try {
const globalPath = await writeGlobalSettings(cwd);
await expect(
loadConfig(["resume", "--cwd", cwd], {
globalSettingsPath: globalPath,
home,
}),
).rejects.toThrow(/No previous session/);
} finally {
await rm(cwd, { recursive: true, force: true });
await rm(home, { recursive: true, force: true });
}
});
test("resume <id> reopens a known session and skips the initial task", async () => {
const cwd = await emptyCwd();
const home = await mkdtemp(join(tmpdir(), "ic-resume-home-"));
try {
const globalPath = await writeGlobalSettings(cwd);
const sessionId = generateSessionId();
await initSessionDir(cwd, sessionId, home);
await saveState(
cwd,
sessionId,
{
status: "done",
turnsUsed: 2,
task: "ship resume",
startedAt: Date.now() - 1_000,
finishedAt: Date.now(),
},
home,
);
const config = await loadConfig(["resume", sessionId, "--cwd", cwd], {
globalSettingsPath: globalPath,
home,
});
assertConfigured(config);
expect(config.resumeMode).toBe("id");
expect(config.sessionId).toBe(sessionId);
expect(config.skipInitialTask).toBe(true);
expect(config.task).toBe("ship resume");
} finally {
await rm(cwd, { recursive: true, force: true });
await rm(home, { recursive: true, force: true });
}
});
test("resume last follows the latest symlink for this project", async () => {
const cwd = await emptyCwd();
const home = await mkdtemp(join(tmpdir(), "ic-resume-home-"));
try {
const globalPath = await writeGlobalSettings(cwd);
const sessionId = generateSessionId();
await initSessionDir(cwd, sessionId, home);
await saveState(
cwd,
sessionId,
{
status: "done",
turnsUsed: 1,
task: "keep going",
startedAt: Date.now() - 500,
finishedAt: Date.now(),
},
home,
);
const config = await loadConfig(["resume", "--cwd", cwd], {
globalSettingsPath: globalPath,
home,
});
assertConfigured(config);
expect(config.resumeMode).toBe("last");
expect(config.sessionId).toBe(sessionId);
expect(config.skipInitialTask).toBe(true);
expect(config.task).toBe("keep going");
} finally {
await rm(cwd, { recursive: true, force: true });
await rm(home, { recursive: true, force: true });
}
});
test("resume <id> rejects an unknown session id for this project", async () => {
const cwd = await emptyCwd();
const home = await mkdtemp(join(tmpdir(), "ic-resume-home-"));
try {
const globalPath = await writeGlobalSettings(cwd);
const missing = generateSessionId();
await expect(
loadConfig(["resume", missing, "--cwd", cwd], {
globalSettingsPath: globalPath,
home,
}),
).rejects.toThrow(new RegExp(`No session ${missing}`));
} finally {
await rm(cwd, { recursive: true, force: true });
await rm(home, { recursive: true, force: true });
}
});
test("resume rejects a non-id positional instead of treating it as last", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
await expect(
loadConfig(["resume", "not-a-uuid", "--cwd", cwd], {
globalSettingsPath: globalPath,
}),
).rejects.toThrow(/not a session id/);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("resume rejects combining a session id with --pick", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const id = generateSessionId();
await expect(
loadConfig(["resume", id, "--pick", "--cwd", cwd], {
globalSettingsPath: globalPath,
}),
).rejects.toThrow(/cannot combine a session id with --pick/);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("resume accepts --pick after other flags", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["resume", "--cwd", cwd, "--pick"], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.resumeMode).toBe("pick");
expect(config.resumePicker).toBe(true);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("--help throws CliHelpError with exitCode 0 and full help text", async () => {
await expect(loadConfig(["--help"], { globalSettingsPath: NO_SETTINGS })).rejects.toBeInstanceOf(
CliHelpError,
);
try {
await loadConfig(["-h"], { globalSettingsPath: NO_SETTINGS });
expect.unreachable("expected CliHelpError");
} catch (err) {
expect(err).toBeInstanceOf(CliHelpError);
const help = err as CliHelpError;
expect(help.exitCode).toBe(0);
expect(help.message).toBe(CLI_HELP_TEXT);
expect(help.message).toContain("resume");
}
});
test("rejects unknown flags", async () => {
await expect(
loadConfig(["--unknown"], { globalSettingsPath: NO_SETTINGS }),
).rejects.toThrow(/unrecognized flag/);
});
test("defaults dangerouslySkipPermissions to false", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(["--cwd", cwd, "do something"], {
globalSettingsPath: globalPath,
});
expect(config.dangerouslySkipPermissions).toBe(false);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("parses --dangerously-skip-permissions", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
const config = await loadConfig(
["--cwd", cwd, "--dangerously-skip-permissions", "do something"],
{ globalSettingsPath: globalPath },
);
expect(config.dangerouslySkipPermissions).toBe(true);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("reads provider and model from a --config settings file", async () => {
const cwd = await emptyCwd();
try {
const settingsPath = join(cwd, "settings.json");
await writeFile(
settingsPath,
JSON.stringify({
defaultProvider: "firepass",
providers: {
firepass: {
baseURL: "https://firepass.example/v1",
apiKey: "fp-key",
models: ["fp-large", "fp-small"],
defaultModel: "fp-large",
},
},
}),
);
const config = await loadConfig(["--cwd", cwd, "--config", settingsPath, "task"]);
assertConfigured(config);
expect(config.providerName).toBe("firepass");
expect(config.baseURL).toBe("https://firepass.example/v1");
expect(config.apiKey).toBe("fp-key");
expect(config.model).toBe("fp-large");
expect(config.globalDefaultProvider).toBe("firepass");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("--model overrides the provider default model", async () => {
const cwd = await emptyCwd();
try {
const settingsPath = join(cwd, "settings.json");
await writeFile(
settingsPath,
JSON.stringify({
defaultProvider: "firepass",
providers: {
firepass: {
baseURL: "https://firepass.example/v1",
apiKey: "fp-key",
models: ["fp-large", "fp-small"],
defaultModel: "fp-large",
},
},
}),
);
const config = await loadConfig([
"--cwd",
cwd,
"--config",
settingsPath,
"--model",
"fp-small",
"task",
]);
assertConfigured(config);
expect(config.model).toBe("fp-small");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("--config pointing at a missing file throws", async () => {
const cwd = await emptyCwd();
try {
await expect(
loadConfig(["--cwd", cwd, "--config", join(cwd, "nope.json"), "task"]),
).rejects.toThrow(/not found or empty/);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("--profile flag surfaces profile name and model from project profile.json", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
await mkdir(join(cwd, ".corbits"), { recursive: true });
await writeFile(
join(cwd, ".corbits", "profile.json"),
JSON.stringify({ model: "profile-model", maxTurns: 25, systemPromptExtensions: ["ext1"] }),
);
const config = await loadConfig(["--cwd", cwd, "task"], { globalSettingsPath: globalPath });
assertConfigured(config);
expect(config.model).toBe("profile-model");
expect(config.maxTurns).toBe(25);
expect(config.systemPromptExtensions).toEqual(["ext1"]);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("--model flag overrides profile model", async () => {
const cwd = await emptyCwd();
try {
const globalPath = await writeGlobalSettings(cwd);
await mkdir(join(cwd, ".corbits"), { recursive: true });
await writeFile(
join(cwd, ".corbits", "profile.json"),
JSON.stringify({ model: "profile-model" }),
);
const config = await loadConfig(["--cwd", cwd, "--model", "accounts/fireworks/routers/kimi-k2p6-turbo", "task"], {
globalSettingsPath: globalPath,
});
assertConfigured(config);
expect(config.model).toBe("accounts/fireworks/routers/kimi-k2p6-turbo");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("per-repo local settings select the provider", async () => {
const cwd = await emptyCwd();
try {
await mkdir(join(cwd, ".corbits"), { recursive: true });
await writeFile(
join(cwd, ".corbits", "settings.json"),
JSON.stringify({ provider: "b", model: "b-model" }),
);
const globalPath = join(cwd, "global.json");
await writeFile(
globalPath,
JSON.stringify({
defaultProvider: "a",
providers: {
a: { baseURL: "https://a/v1", apiKey: "a-key", models: ["a-model"] },
b: { baseURL: "https://b/v1", apiKey: "b-key", models: ["b-model"] },
},
}),
);
const config = await loadConfig(["--cwd", cwd, "task"], { globalSettingsPath: globalPath });
assertConfigured(config);
expect(config.providerName).toBe("b");
expect(config.model).toBe("b-model");
expect(config.apiKey).toBe("b-key");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
test("rejects a local reasoningEffort unsupported by the selected model", async () => {
const cwd = await emptyCwd();
try {
await mkdir(join(cwd, ".corbits"), { recursive: true });
await writeFile(
join(cwd, ".corbits", "settings.json"),
JSON.stringify({ provider: "a", model: "a-model", reasoningEffort: "xhigh" }),
);
const globalPath = join(cwd, "global.json");
await writeFile(
globalPath,
JSON.stringify({ providers: { a: { baseURL: "https://a/v1", apiKey: "a-key", models: ["a-model"] } } }),
);
await expect(
loadConfig(["--cwd", cwd, "task"], { globalSettingsPath: globalPath }),
).rejects.toThrow(/reasoningEffort/);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
});
describe("buildOpenAISource", () => {
test("normalizes the runtime source baseURL", () => {
const source = buildOpenAISource({
id: "fp",
baseURL: "https://fp/v1/chat/completions",
apiKey: "fp-key",
model: "fp-large",
});
expect(source.baseURL).toBe("https://fp/v1");
});
test("omits reasoning_effort when effort is absent", () => {
const source = buildOpenAISource({ id: "fp", baseURL: "https://fp/v1", apiKey: "k", model: "m" });
expect(source.defaults).toEqual({ maxTokens: SOURCE_MAX_TOKENS });
});
test("sets providerOptions.reasoning_effort when effort is present", () => {
const source = buildOpenAISource({
id: "fp",
baseURL: "https://fp/v1",
apiKey: "k",
model: "gpt-5.1",
reasoningEffort: "high",
});
expect(source.defaults).toEqual({
maxTokens: SOURCE_MAX_TOKENS,
providerOptions: { reasoning_effort: "high" },
});
});
test("substitutes a placeholder apiKey when none is provided (keyless)", () => {
const source = buildOpenAISource({ id: "ollama", baseURL: "http://localhost:11434/v1", model: "llama3" });
expect(source.apiKey).toBe(KEYLESS_API_KEY);
});
});
describe("buildBifrostSource", () => {
test("sets provider to bifrost and normalizes baseURL", () => {
const source = buildBifrostSource({
id: "bf",
baseURL: "http://localhost:8080/v1/chat/completions",
apiKey: "sk-bf-abc",
model: "gpt-4o",
});
expect(source.provider).toBe("bifrost");
expect(source.baseURL).toBe("http://localhost:8080/v1");
expect(source.model).toBe("gpt-4o");
});
test("embeds reasoning effort", () => {
const source = buildBifrostSource({
id: "bf",
baseURL: "https://b/v1",
apiKey: "k",
model: "m",
reasoningEffort: "low",
});
expect(source.defaults?.providerOptions).toEqual({ reasoning_effort: "low" });
});
});
describe("buildProviderCatalog", () => {
const resolved: ResolvedProvider = {
providerName: "fp",
baseURL: "https://fp/v1",
apiKey: "fp-key",
model: "fp-large",
};
test("lists every provider from the settings file", () => {
const settings: Settings = {
defaultProvider: "fp",
providers: {
fp: { baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large", "fp-small"], defaultModel: "fp-large" },
oa: { baseURL: "https://oa/v1", apiKey: "oa-key", models: ["o-1"] },
},
};
const catalog = buildProviderCatalog(settings, resolved);
expect(catalog.map((c) => c.name).sort()).toEqual(["fp", "oa"]);
const fp = catalog.find((c) => c.name === "fp")!;
expect(fp.models).toEqual(["fp-large", "fp-small"]);
expect(fp.defaultModel).toBe("fp-large");
expect(catalog.find((c) => c.name === "oa")!.defaultModel).toBeUndefined();
});
test("normalizes provider base URLs from the settings file", () => {
const settings: Settings = {
providers: {
fp: {
baseURL: "https://fp/v1/chat/completions/",
apiKey: "fp-key",
models: ["fp-large"],
},
},
};
const catalog = buildProviderCatalog(settings, resolved);
expect(catalog[0]?.baseURL).toBe("https://fp/v1");
});
test("preserves bifrostVirtualKey flag from settings", () => {
const settings: Settings = {
providers: {
bf: { baseURL: "http://b:8080/v1", apiKey: "sk-bf-k", models: ["m"], bifrostVirtualKey: true },
},
};
const catalog = buildProviderCatalog(settings, resolved);
const bf = catalog.find((c) => c.name === "bf")!;
expect(bf.bifrostVirtualKey).toBe(true);
});
test("falls back to the single resolved provider when there is no settings file", () => {
const catalog = buildProviderCatalog(null, resolved);
expect(catalog).toEqual([
{ name: "fp", baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large"] },
]);
});
test("preserves keyless flag and omits apiKey for keyless providers", () => {
const settings: Settings = {
providers: {
ollama: { baseURL: "http://localhost:11434/v1", keyless: true, models: ["llama3"] },
fp: { baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large"] },
},
};
const catalog = buildProviderCatalog(settings, resolved);
const ollama = catalog.find((c) => c.name === "ollama")!;
expect(ollama.keyless).toBe(true);
expect(ollama.apiKey).toBeUndefined();
const fp = catalog.find((c) => c.name === "fp")!;
expect(fp.keyless).toBeUndefined();
expect(fp.apiKey).toBe("fp-key");
});
test("converts a provider catalog back to global settings", () => {
const settings = providerCatalogToSettings(
[
{
name: "fp",
baseURL: "https://fp/v1",
apiKey: "fp-key",
models: ["fp-large", "fp-small"],
defaultModel: "fp-large",
},
{ name: "oa", baseURL: "https://oa/v1", apiKey: "oa-key", models: ["o-1"] },
],
"oa",
);
expect(settings).toEqual({
defaultProvider: "oa",
providers: {
fp: {
baseURL: "https://fp/v1",
apiKey: "fp-key",
models: ["fp-large", "fp-small"],
defaultModel: "fp-large",
},
oa: { baseURL: "https://oa/v1", apiKey: "oa-key", models: ["o-1"] },
},
});
});
test("runtimeSettingsWithCatalog overlays OAuth catalog entries for provider resolution", () => {
const disk = {
providers: {
openai: { baseURL: "https://api.openai.com/v1", apiKey: "sk", models: ["gpt-4o"] },
},
};
const catalog = [
{
name: "openai",
baseURL: "https://api.openai.com/v1",
apiKey: "sk",
models: ["gpt-4o"],
},
{
name: "xai/work",
baseURL: "https://api.x.ai/v1",
apiKey: "xai-token",
models: ["grok-4"],
xaiProfile: "work",
},
];
const runtime = runtimeSettingsWithCatalog(disk, catalog);
expect(runtime.providers["xai/work"]).toEqual({
baseURL: "https://api.x.ai/v1",
apiKey: "xai-token",
models: ["grok-4"],
});
// Disk persist path still strips OAuth.
expect(providerCatalogToSettings(catalog, "openai", disk).providers["xai/work"]).toBeUndefined();
});
test("normalizes provider catalog URLs when converting back to settings", () => {
const settings = providerCatalogToSettings(
[{ name: "fp", baseURL: "https://fp/v1/chat/completions", apiKey: "fp-key", models: ["fp-large"] }],
undefined,
);
expect(settings.providers.fp?.baseURL).toBe("https://fp/v1");
});
test("rejects invalid provider catalog URLs when converting back to settings", () => {
expect(() =>
providerCatalogToSettings(
[{ name: "fp", baseURL: "fp/v1", apiKey: "fp-key", models: ["fp-large"] }],
undefined,
),
).toThrow(/Invalid OpenAI-compatible baseURL/);
});
test("omits defaultProvider when no global default is known", () => {
const settings = providerCatalogToSettings(
[{ name: "fp", baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large"] }],
undefined,
);
expect(settings).toEqual({
providers: {
fp: { baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large"] },
},
});
});
test("persists bifrostVirtualKey flag for virtual-key providers", () => {
const catalog = [
{ name: "bf-prod", baseURL: "http://b:8080/v1", apiKey: "sk-bf-xyz", models: ["m1"], bifrostVirtualKey: true as const },
];
const settings = providerCatalogToSettings(catalog, "bf-prod");
expect(settings.providers["bf-prod"]).toEqual({
baseURL: "http://b:8080/v1",
apiKey: "sk-bf-xyz",
models: ["m1"],
bifrostVirtualKey: true,
});
});
test("preserves non-provider fields from existing settings", () => {
// Full non-provider surface: provider saves must not re-own a subset of
// Settings keys (an allowlist previously dropped sessionMode/shell/tools/…).
const existing: Settings = {
defaultProvider: "fp",
providers: { fp: { baseURL: "https://fp/v1", apiKey: "old-key", models: ["fp-small"] } },
mcpServers: [{ name: "linear", type: "http", url: "https://mcp.linear.app/mcp" }],
plugins: { exa: { enabled: true, credentials: { apiKey: "k" } } },
pluginPaths: ["/abs/plugins/exa"],
web: "exa",
hiddenCommands: ["help"],
onboarded: true,
compactionMode: "pruning",
subagentMaxTurns: 40,
sessionMode: "orchestrator",
agentModelFallback: "none",
shell: { timeoutMs: 30_000, maxTimeoutMs: 120_000 },
tools: { timeoutMs: 60_000 },
workflowProfiles: { fast: { implement: "fp-large" } },
};
const settings = providerCatalogToSettings(
[
{ name: "fp", baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large", "fp-small"], defaultModel: "fp-large" },
{ name: "oa", baseURL: "https://oa/v1", apiKey: "oa-key", models: ["o-1"] },
],
"oa",
existing,
);
const { providers: _ep, defaultProvider: _ed, ...restExisting } = existing;
const { providers: outProviders, defaultProvider: outDefault, ...restOut } = settings;
expect(outDefault).toBe("oa");
expect(outProviders).toEqual({
fp: { baseURL: "https://fp/v1", apiKey: "fp-key", models: ["fp-large", "fp-small"], defaultModel: "fp-large" },
oa: { baseURL: "https://oa/v1", apiKey: "oa-key", models: ["o-1"] },
});
expect(restOut).toEqual(restExisting);
});
test("round-trips every ProviderSettings field a catalog entry can carry through buildProviderCatalog and back", () => {
// ProviderCatalogEntry is defined as Omit<ProviderSettings, "name" | "contextWindow">.
// This exercises every field that relationship carries over, so a field
// added to ProviderSettings and forgotten in the two conversion sites
// below fails here instead of being silently dropped at runtime.
// `anthropic` and `opencodeGo` are exercised separately below: both are
// protocol markers that also normalize `baseURL` in buildProviderCatalog,
// so a provider combining them with an arbitrary baseURL isn't a real
// round trip (the healing logic rewrites baseURL by design).
const provider: Settings["providers"][string] = {
baseURL: "https://fp/v1",
apiKey: "fp-key",
models: ["fp-large"],
defaultModel: "fp-large",
free: true,
keyless: true,
bifrostVirtualKey: true,
};
const settings: Settings = { providers: { fp: provider } };
const catalog = buildProviderCatalog(settings, {
providerName: "fp",
baseURL: provider.baseURL,
apiKey: "fp-key",
model: "fp-large",
} as ResolvedProvider);
const entry = catalog.find((c) => c.name === "fp")!;
const roundTripped = { fp: catalogEntryAsProviderSettings(entry) };
expect(roundTripped).toEqual({ fp: provider });
});
test("round-trips the anthropic protocol marker", () => {
const provider: Settings["providers"][string] = {
baseURL: "https://api.anthropic.com/v1",
apiKey: "an-key",
models: ["claude"],
anthropic: true,
};
const settings: Settings = { providers: { an: provider } };
const catalog = buildProviderCatalog(settings, {
providerName: "an",
baseURL: provider.baseURL,
apiKey: "an-key",
model: "claude",
} as ResolvedProvider);
const entry = catalog.find((c) => c.name === "an")!;
const roundTripped = { an: catalogEntryAsProviderSettings(entry) };
expect(roundTripped).toEqual({ an: provider });
});
test("round-trips the opencodeGo protocol marker", () => {
const provider: Settings["providers"][string] = {
baseURL: OPENCODE_GO_BASE_URL,
apiKey: "go-key",
models: ["go-model"],
opencodeGo: true,
};
const settings: Settings = { providers: { go: provider } };
const catalog = buildProviderCatalog(settings, {
providerName: "go",
baseURL: provider.baseURL,
apiKey: "go-key",
model: "go-model",
} as ResolvedProvider);
const entry = catalog.find((c) => c.name === "go")!;
const roundTripped = { go: catalogEntryAsProviderSettings(entry) };
expect(roundTripped).toEqual({ go: provider });
});
});
describe("mergeProviderIntoSettings", () => {
test("preserves plugins and non-provider fields when upserting a provider", () => {
const existing: Settings = {
providers: { old: { baseURL: "https://old/v1", apiKey: "k", models: ["m"] } },
plugins: { cmd: { enabled: true } },
pluginPaths: ["/abs/cmd"],
sessionMode: "orchestrator",
shell: { timeoutMs: 10_000 },
onboarded: true,
};
const merged = mergeProviderIntoSettings(existing, "new", {
baseURL: "https://new/v1",
apiKey: "nk",
models: ["n1"],
defaultModel: "n1",
});
expect(merged.defaultProvider).toBe("new");
expect(merged.providers.old).toEqual(existing.providers.old);
expect(merged.providers.new).toEqual({
baseURL: "https://new/v1",
apiKey: "nk",
models: ["n1"],
defaultModel: "n1",
});
expect(merged.plugins).toEqual({ cmd: { enabled: true } });
expect(merged.pluginPaths).toEqual(["/abs/cmd"]);
expect(merged.sessionMode).toBe("orchestrator");
expect(merged.shell).toEqual({ timeoutMs: 10_000 });
expect(merged.onboarded).toBe(true);
});
test("creates settings from null existing", () => {
const merged = mergeProviderIntoSettings(null, "only", {
baseURL: "https://only/v1",
keyless: true,
models: ["m"],
});
expect(merged).toEqual({
defaultProvider: "only",
providers: {
only: { baseURL: "https://only/v1", keyless: true, models: ["m"] },
},
});
});
});