mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-27 02:12:19 +03:00
Compare commits
3850 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de60b4b171 | ||
|
|
b6c65efd28 | ||
|
|
9350a5d6c6 | ||
|
|
99397b4f41 | ||
|
|
a32e52eed6 | ||
|
|
88857237a2 | ||
|
|
c315a2394c | ||
|
|
4bfd9e2845 | ||
|
|
d6f008cdaf | ||
|
|
bf8b56b29f | ||
|
|
630680067c | ||
|
|
6a7a36c09e | ||
|
|
d65d8bb54f | ||
|
|
68e4d0c599 | ||
|
|
8169b97d84 | ||
|
|
50ce13bce6 | ||
|
|
e1a9c61179 | ||
|
|
2441a4f441 | ||
|
|
6ebc493770 | ||
|
|
259486afb5 | ||
|
|
500197846d | ||
|
|
ee0fdcb6c8 | ||
|
|
5c3545b045 | ||
|
|
1cc2313a4f | ||
|
|
49c11f0cea | ||
|
|
4f38167964 | ||
|
|
ff65652cdf | ||
|
|
cc850122e3 | ||
|
|
42887b65b2 | ||
|
|
1a98dfe8ed | ||
|
|
003e6a80b7 | ||
|
|
617a648088 | ||
|
|
1322411343 | ||
|
|
da273d37e2 | ||
|
|
dbd70ddd1f | ||
|
|
89a76d8c1c | ||
|
|
a00366602b | ||
|
|
96e5ec9269 | ||
|
|
858b6742e8 | ||
|
|
3c98e9f1ef | ||
|
|
2427df2f2c | ||
|
|
07a81c8a40 | ||
|
|
ea0c0d8499 | ||
|
|
23f31faf38 | ||
|
|
1e4185edac | ||
|
|
b3372e46c4 | ||
|
|
fc437ddecd | ||
|
|
70c6610fa8 | ||
|
|
d3ff0b3bde | ||
|
|
f01a0b0c6d | ||
|
|
de2420a35c | ||
|
|
eb8651780d | ||
|
|
c0dcdcc12f | ||
|
|
ea9d22beda | ||
|
|
60fc41f638 | ||
|
|
ac4fd7e078 | ||
|
|
85351bc63d | ||
|
|
ed3c188881 | ||
|
|
11bd96ec5c | ||
|
|
f112bc966f | ||
|
|
b60839b90c | ||
|
|
717f56bf93 | ||
|
|
3ea416350e | ||
|
|
1012603a1b | ||
|
|
b480e6c916 | ||
|
|
6ec4ca3f67 | ||
|
|
b145e41a42 | ||
|
|
e328e257d1 | ||
|
|
67d79f6c44 | ||
|
|
e0615a8194 | ||
|
|
f688d1150f | ||
|
|
fd6a2a7f95 | ||
|
|
ecdd5a36eb | ||
|
|
71f6e8d312 | ||
|
|
c9663d4f84 | ||
|
|
4c420b015d | ||
|
|
452e6cc937 | ||
|
|
48ed42c6c3 | ||
|
|
6df38155a4 | ||
|
|
5b72dc6250 | ||
|
|
4adc1d087f | ||
|
|
ee061d7a6d | ||
|
|
ed275bb54b | ||
|
|
8505e0f2b7 | ||
|
|
765964242c | ||
|
|
fc37c93a20 | ||
|
|
a471d70c3c | ||
|
|
b4437dcee4 | ||
|
|
a8522cc13a | ||
|
|
929caeb910 | ||
|
|
000d60b907 | ||
|
|
591084052a | ||
|
|
35a30609dd | ||
|
|
7db430a352 | ||
|
|
630baa6c18 | ||
|
|
df2379053e | ||
|
|
9535fa52a6 | ||
|
|
cd89ce3cfa | ||
|
|
a25d5f1ef6 | ||
|
|
78454eed5e | ||
|
|
5bebf0e53c | ||
|
|
7ab1ad85a1 | ||
|
|
a8668ebd77 | ||
|
|
27f6ea85f9 | ||
|
|
1bc88d97ee | ||
|
|
3086894704 | ||
|
|
e1622ed88b | ||
|
|
1344843a45 | ||
|
|
ba734b01b2 | ||
|
|
1c8f3bee97 | ||
|
|
7abb40c64c | ||
|
|
a7e445edea | ||
|
|
36932b62a7 | ||
|
|
a5d19bf4b9 | ||
|
|
a19cfd4036 | ||
|
|
e478ab23af | ||
|
|
80c546eba9 | ||
|
|
41eb0091a2 | ||
|
|
30ebe0ae2e | ||
|
|
5d8f265192 | ||
|
|
6674f6a4f2 | ||
|
|
6bfba384d8 | ||
|
|
2ad2bcb13f | ||
|
|
07d9010668 | ||
|
|
2db8de8232 | ||
|
|
583bceb53d | ||
|
|
e364764dc7 | ||
|
|
925d838d3b | ||
|
|
c2520bf5b7 | ||
|
|
1d28c0f13d | ||
|
|
452e152703 | ||
|
|
404cfcbbac | ||
|
|
c2d46776fd | ||
|
|
396a79f02a | ||
|
|
75bccccbef | ||
|
|
4fcc16fc6a | ||
|
|
62e6336aad | ||
|
|
9c13d44cca | ||
|
|
cf7f684bd8 | ||
|
|
b413774bdf | ||
|
|
d985dace79 | ||
|
|
c222143071 | ||
|
|
5ec8fa222a | ||
|
|
8cdfee5d90 | ||
|
|
af7a8b3b45 | ||
|
|
2942ba874e | ||
|
|
0ac8539200 | ||
|
|
fea2991fc0 | ||
|
|
4dbbbaacf1 | ||
|
|
dfcaeba6d9 | ||
|
|
5179b16596 | ||
|
|
b2887da1ca | ||
|
|
b4d5610d86 | ||
|
|
e0c6fb9f8c | ||
|
|
5a2e93d20a | ||
|
|
7786aa2c0e | ||
|
|
ec4f8c4d42 | ||
|
|
c116bfbc7f | ||
|
|
5afb984425 | ||
|
|
6fe7c6b5b1 | ||
|
|
143fb2ace4 | ||
|
|
9032a5a4ab | ||
|
|
fa0aa1e25d | ||
|
|
9bc2c89924 | ||
|
|
d3422c1c4d | ||
|
|
422b7b747c | ||
|
|
005ee10a1e | ||
|
|
7b4bda13b1 | ||
|
|
0ea925ac20 | ||
|
|
c48e0851f7 | ||
|
|
de5c842301 | ||
|
|
d8363a51f2 | ||
|
|
4a5e123bad | ||
|
|
ccc4425744 | ||
|
|
ee62c4c38b | ||
|
|
a7494e415e | ||
|
|
264a2ccbc7 | ||
|
|
37218fd517 | ||
|
|
c27a32d432 | ||
|
|
68d5a0ab27 | ||
|
|
506a701a1a | ||
|
|
5057454d21 | ||
|
|
6ce96cb664 | ||
|
|
796267df3f | ||
|
|
49dedecc42 | ||
|
|
872895c172 | ||
|
|
b6bda19919 | ||
|
|
223374221f | ||
|
|
74ce4fd76d | ||
|
|
dd85309e64 | ||
|
|
bb87a59125 | ||
|
|
dff836ae26 | ||
|
|
27229aa7eb | ||
|
|
e1007acb7e | ||
|
|
f1c42359a2 | ||
|
|
20331afeec | ||
|
|
838c2cab88 | ||
|
|
8dd9749a93 | ||
|
|
49bfe982c2 | ||
|
|
cad93f35ce | ||
|
|
652faeefc7 | ||
|
|
8dc93ade6d | ||
|
|
80c9ca7096 | ||
|
|
a718558d68 | ||
|
|
51345bf2e9 | ||
|
|
84b5caeeb9 | ||
|
|
656e73e1f0 | ||
|
|
27b822e412 | ||
|
|
50896699d3 | ||
|
|
0594af6a6c | ||
|
|
0331e8126d | ||
|
|
261a910820 | ||
|
|
ed170229e7 | ||
|
|
c9620eb741 | ||
|
|
0231fbb335 | ||
|
|
e390a8d633 | ||
|
|
5efeeb183f | ||
|
|
b7fdcdddf8 | ||
|
|
5b484737bb | ||
|
|
03b8aa1f6d | ||
|
|
27c08178d7 | ||
|
|
05c6335292 | ||
|
|
277f530f0e | ||
|
|
aa647768c4 | ||
|
|
d5f2586513 | ||
|
|
b57afb5bbe | ||
|
|
f0f776c310 | ||
|
|
5f7f74dc6a | ||
|
|
5f3b1e8cde | ||
|
|
8a25d9e229 | ||
|
|
365c29a115 | ||
|
|
7042d562c4 | ||
|
|
470df2df77 | ||
|
|
948f232517 | ||
|
|
42821ee620 | ||
|
|
51d2ca8151 | ||
|
|
a296c34a95 | ||
|
|
28116c71f8 | ||
|
|
3c8646a400 | ||
|
|
e6db182dcf | ||
|
|
c4fa7add1b | ||
|
|
9db306e2f8 | ||
|
|
e7f064d916 | ||
|
|
8a5feacc88 | ||
|
|
6999566ce1 | ||
|
|
43b1392876 | ||
|
|
9141e98458 | ||
|
|
c42591f400 | ||
|
|
d37693de98 | ||
|
|
b9da7d3176 | ||
|
|
5943e5d528 | ||
|
|
0f900f1d56 | ||
|
|
705ab8e690 | ||
|
|
a907ae714c | ||
|
|
5e94e595aa | ||
|
|
fc77100c3f | ||
|
|
b80e6c26ac | ||
|
|
5b62a4be88 | ||
|
|
656b2e5e7c | ||
|
|
1533286726 | ||
|
|
326a219620 | ||
|
|
72b4804c1b | ||
|
|
34e0eab099 | ||
|
|
e176d0abd4 | ||
|
|
f5acb60cac | ||
|
|
7c2dc1cde6 | ||
|
|
146244b8f5 | ||
|
|
e438139b03 | ||
|
|
c4a993184e | ||
|
|
ccaa0b5f79 | ||
|
|
8277b98003 | ||
|
|
8086d2878b | ||
|
|
512e980a9e | ||
|
|
62f08de540 | ||
|
|
f8c1213722 | ||
|
|
831f82858f | ||
|
|
11eb74c828 | ||
|
|
fdbaae4734 | ||
|
|
7b87d2f169 | ||
|
|
dee20ac665 | ||
|
|
66ddbb0f5a | ||
|
|
3dca2bb3f1 | ||
|
|
8386ab3084 | ||
|
|
c711ac62a7 | ||
|
|
76d697bb88 | ||
|
|
65195dcd7a | ||
|
|
a5f3c998c1 | ||
|
|
08c70572fb | ||
|
|
5350b5e7f5 | ||
|
|
39a673b7d6 | ||
|
|
8f0615fd04 | ||
|
|
2a8954663c | ||
|
|
a1c743ddb0 | ||
|
|
9e7f3cad10 | ||
|
|
20c31493af | ||
|
|
89c52d4f04 | ||
|
|
482e4690eb | ||
|
|
fd26e601a2 | ||
|
|
4e4e89759a | ||
|
|
6b7ae9ad2e | ||
|
|
e11366b647 | ||
|
|
6561548687 | ||
|
|
b20748a73e | ||
|
|
baa4e56997 | ||
|
|
57dfa25312 | ||
|
|
aa8033dae9 | ||
|
|
c34285f676 | ||
|
|
8ef8a9b5a7 | ||
|
|
dd42b1564f | ||
|
|
e4eeb6dc7f | ||
|
|
4de674e0fc | ||
|
|
099cb67317 | ||
|
|
a332b659c2 | ||
|
|
6fd7098c21 | ||
|
|
df7b1e83c2 | ||
|
|
6848636351 | ||
|
|
3c8e84d702 | ||
|
|
46c482ca98 | ||
|
|
ac5ac0c2a7 | ||
|
|
b64489b3ad | ||
|
|
881a8e9b56 | ||
|
|
342f12b77a | ||
|
|
e5392a7eaa | ||
|
|
e694674851 | ||
|
|
bf96769db7 | ||
|
|
74e290bc70 | ||
|
|
a0b435bcae | ||
|
|
4b3987e190 | ||
|
|
7f6e7a80e3 | ||
|
|
58a7d97b3f | ||
|
|
137d77cf12 | ||
|
|
5d84a8fa7a | ||
|
|
efa8f0af23 | ||
|
|
eac24ca458 | ||
|
|
9863000ab1 | ||
|
|
e9cc53b17f | ||
|
|
6d2e695882 | ||
|
|
fc6692925e | ||
|
|
cb1a18fa1a | ||
|
|
1eff658678 | ||
|
|
727616b2c0 | ||
|
|
7cb77a9083 | ||
|
|
1ba24c67df | ||
|
|
7b6007bc2d | ||
|
|
9f254a6e19 | ||
|
|
2ec803bbad | ||
|
|
029e4f6943 | ||
|
|
ddd129f3f9 | ||
|
|
7ec85ce054 | ||
|
|
254c8bf335 | ||
|
|
98cc1df3b5 | ||
|
|
a9332f868f | ||
|
|
a6de2a58c5 | ||
|
|
fa038e069d | ||
|
|
bc46eba8f6 | ||
|
|
3c21a1ae44 | ||
|
|
abb77879db | ||
|
|
57930bae93 | ||
|
|
1543a4ba77 | ||
|
|
73075f9fb3 | ||
|
|
54ca6ba9b6 | ||
|
|
be77a03aa0 | ||
|
|
c6cc8bb334 | ||
|
|
10fa5e8903 | ||
|
|
cb45d9dfe9 | ||
|
|
5acf6bd9cd | ||
|
|
aa6091aa14 | ||
|
|
5208cd5936 | ||
|
|
99f615c7e0 | ||
|
|
51d66eadee | ||
|
|
c2d7ac9359 | ||
|
|
8c11acaa33 | ||
|
|
b1e1f5e5f6 | ||
|
|
18b615f5f0 | ||
|
|
d4045e74b5 | ||
|
|
d490a30b58 | ||
|
|
4157fbe7a9 | ||
|
|
687c28474d | ||
|
|
17b58f8f5f | ||
|
|
2521c09119 | ||
|
|
bbc4c575e0 | ||
|
|
767fad3d5c | ||
|
|
009ad13a91 | ||
|
|
c4a359ef5f | ||
|
|
c455a360ab | ||
|
|
6ff3238e8d | ||
|
|
b2e1e6c1e9 | ||
|
|
d0a87970c6 | ||
|
|
8e9b3e217a | ||
|
|
81bf13e866 | ||
|
|
8151c46139 | ||
|
|
933121b082 | ||
|
|
4b6d6c7670 | ||
|
|
d0e5b97d10 | ||
|
|
bc7ab44f74 | ||
|
|
2d627a3433 | ||
|
|
f5d74cd76d | ||
|
|
923b8fe14f | ||
|
|
1a701292b6 | ||
|
|
cf9a78ad32 | ||
|
|
86a22d64c7 | ||
|
|
ef58d83adc | ||
|
|
ca7756e990 | ||
|
|
0e35292e0e | ||
|
|
559252aee4 | ||
|
|
d22564df4d | ||
|
|
a365706d65 | ||
|
|
71bfe084ae | ||
|
|
209d0b5ae4 | ||
|
|
a9f1e7f5b4 | ||
|
|
bfe4e398ac | ||
|
|
778f74c4cb | ||
|
|
a17f5df0da | ||
|
|
a06054ad34 | ||
|
|
b647cf3930 | ||
|
|
380d558586 | ||
|
|
20a91c08ed | ||
|
|
eb7348aeb9 | ||
|
|
816ba12599 | ||
|
|
d07d3dcdaf | ||
|
|
009c928d0a | ||
|
|
0fe97ab8e9 | ||
|
|
e63fbed64b | ||
|
|
729252008b | ||
|
|
bafcf72be7 | ||
|
|
b5d03ed3f2 | ||
|
|
bc6332310d | ||
|
|
f14722315d | ||
|
|
f6d68a7bf3 | ||
|
|
0a09fa5a11 | ||
|
|
672398e86f | ||
|
|
5c340ea813 | ||
|
|
d5b163558d | ||
|
|
74ba399e04 | ||
|
|
b93cde7507 | ||
|
|
2f707e08e0 | ||
|
|
acd517eb1e | ||
|
|
2fd12711bb | ||
|
|
9430a532ed | ||
|
|
e5a624d0ec | ||
|
|
8adc0a0d9a | ||
|
|
428947207f | ||
|
|
69acd664d7 | ||
|
|
2300db6cc5 | ||
|
|
e2ad12d090 | ||
|
|
62de5a83b8 | ||
|
|
4536aabe23 | ||
|
|
ff255c4582 | ||
|
|
c90bed0043 | ||
|
|
fa4bd6c68c | ||
|
|
4e51bc686c | ||
|
|
1a9b2bfd85 | ||
|
|
266c145ee4 | ||
|
|
8dafe78d79 | ||
|
|
606b7092b6 | ||
|
|
cf3600de11 | ||
|
|
856603ecb7 | ||
|
|
3dd4a3b6f8 | ||
|
|
6a14c31280 | ||
|
|
3742afcd64 | ||
|
|
78c5a30cf9 | ||
|
|
49f6092099 | ||
|
|
ba340f18a5 | ||
|
|
e7870132db | ||
|
|
e51ab949fa | ||
|
|
ec7233042c | ||
|
|
4c38961b72 | ||
|
|
2b613d9fb8 | ||
|
|
697946381d | ||
|
|
8b074d2c29 | ||
|
|
2fb5979118 | ||
|
|
af8e134af6 | ||
|
|
7a0e803c01 | ||
|
|
847799092e | ||
|
|
52503064a8 | ||
|
|
379b72c157 | ||
|
|
38221f2040 | ||
|
|
b778ad2614 | ||
|
|
187bc509bb | ||
|
|
6214ea6768 | ||
|
|
a921300a53 | ||
|
|
8316c618b2 | ||
|
|
c29d6ed7a4 | ||
|
|
8dff29c760 | ||
|
|
58eb093a2e | ||
|
|
8cd77b0f49 | ||
|
|
0c9345f75e | ||
|
|
ff7a9069f0 | ||
|
|
51b586c2af | ||
|
|
6b0e89fb42 | ||
|
|
270c2eb925 | ||
|
|
5a61ae9a98 | ||
|
|
6095842ef0 | ||
|
|
a91f352fde | ||
|
|
6cdf69e077 | ||
|
|
b4c0ce6519 | ||
|
|
f1d0416d72 | ||
|
|
664a606bfb | ||
|
|
99d673fe5b | ||
|
|
36c276a6d7 | ||
|
|
8eacd78be4 | ||
|
|
a03d7b40d7 | ||
|
|
a59a90e6a1 | ||
|
|
d698e957fb | ||
|
|
dd6104ea38 | ||
|
|
a1e0bc7469 | ||
|
|
31a734966c | ||
|
|
ce039778da | ||
|
|
27e56f6bb2 | ||
|
|
cad06d85a6 | ||
|
|
23dad7d93d | ||
|
|
57aff12781 | ||
|
|
3b2d075402 | ||
|
|
468354f8ff | ||
|
|
31e11aa8d8 | ||
|
|
7e7faad079 | ||
|
|
c6f17d8e78 | ||
|
|
37890ba007 | ||
|
|
7ffc56b7e0 | ||
|
|
d25e32326d | ||
|
|
2b99d7ba7f | ||
|
|
a7330b4fb1 | ||
|
|
3767e130ea | ||
|
|
5600dcd2d2 | ||
|
|
bd1098de16 | ||
|
|
54cec88989 | ||
|
|
9515375114 | ||
|
|
18641c9d87 | ||
|
|
ac0e9d5272 | ||
|
|
b7242579f4 | ||
|
|
dd8f7aa6a1 | ||
|
|
6253f31166 | ||
|
|
f4605828b1 | ||
|
|
1ee177d065 | ||
|
|
db27ae5006 | ||
|
|
da527508db | ||
|
|
275018ffce | ||
|
|
968addf54f | ||
|
|
d024365410 | ||
|
|
0b405d51f0 | ||
|
|
dcba31a6ed | ||
|
|
ef6e6c74a5 | ||
|
|
715809a150 | ||
|
|
1b0d3c75e9 | ||
|
|
5cb23b4e71 | ||
|
|
8eff0bda01 | ||
|
|
53c8ffcc34 | ||
|
|
150869198b | ||
|
|
dad82d59f7 | ||
|
|
7720d5bd47 | ||
|
|
191009dd23 | ||
|
|
5d2d10d281 | ||
|
|
edf89b2d6e | ||
|
|
81579ac052 | ||
|
|
8264dfe608 | ||
|
|
d39d2719bb | ||
|
|
a9bc0e8685 | ||
|
|
87569d6a82 | ||
|
|
cdb1a6b3a0 | ||
|
|
ad14d99580 | ||
|
|
95023d6eb1 | ||
|
|
ddb61686c2 | ||
|
|
4b15a992d6 | ||
|
|
a086862c97 | ||
|
|
94682d2a76 | ||
|
|
a1a225209c | ||
|
|
fbe140c231 | ||
|
|
8b74fb48ca | ||
|
|
efcd062002 | ||
|
|
a15750d968 | ||
|
|
f59f8daa94 | ||
|
|
f86f24af5f | ||
|
|
6fdd312019 | ||
|
|
65c7ab8802 | ||
|
|
e73a2eaca9 | ||
|
|
7d398d1af3 | ||
|
|
2483b2d08e | ||
|
|
067e0496cf | ||
|
|
d78088fd84 | ||
|
|
10111aef1b | ||
|
|
e834279790 | ||
|
|
5ac1e997a8 | ||
|
|
1682dcbf87 | ||
|
|
7714b09e6f | ||
|
|
87564304e1 | ||
|
|
5f0cf313a5 | ||
|
|
fd0b993c6e | ||
|
|
dc3915a4e3 | ||
|
|
fb7a9f2ba8 | ||
|
|
f1eb08c7b5 | ||
|
|
dd5098bf67 | ||
|
|
1bf73fe492 | ||
|
|
9ff906b80b | ||
|
|
ebae877aa3 | ||
|
|
1f5c215cc0 | ||
|
|
1461a78d07 | ||
|
|
d96eeef9c1 | ||
|
|
a9b5a7cc8c | ||
|
|
2355bf9419 | ||
|
|
a7e71ae494 | ||
|
|
a8b4dc3e8c | ||
|
|
cccc53cade | ||
|
|
8f4fc8bcda | ||
|
|
53ac23cfe6 | ||
|
|
e3d5bc2d61 | ||
|
|
a928d9f56c | ||
|
|
a1261ccf80 | ||
|
|
dbaf25079c | ||
|
|
82999c021f | ||
|
|
6d157e481f | ||
|
|
b971db8e77 | ||
|
|
e510a57555 | ||
|
|
c02b6ea008 | ||
|
|
ed36bd7264 | ||
|
|
2428ad2bcd | ||
|
|
517c3c6e44 | ||
|
|
f270d20de0 | ||
|
|
1d55f96e01 | ||
|
|
1442e086e4 | ||
|
|
c9251f9326 | ||
|
|
32adf6275a | ||
|
|
9dfe482c1c | ||
|
|
1a4c4f8d94 | ||
|
|
dd10b4b94c | ||
|
|
dbe7b62cbe | ||
|
|
b741bd6b23 | ||
|
|
c216085e92 | ||
|
|
fee1c17d51 | ||
|
|
283c05d3d0 | ||
|
|
0a101b95b3 | ||
|
|
01041967de | ||
|
|
5f886dc73a | ||
|
|
b677dd6b25 | ||
|
|
18dae1ab95 | ||
|
|
25db3dee59 | ||
|
|
94a34899b2 | ||
|
|
f3404227d2 | ||
|
|
0c9740c771 | ||
|
|
05276bc549 | ||
|
|
1b7cc370a3 | ||
|
|
4295ecc5a7 | ||
|
|
b0191f1237 | ||
|
|
12bacb03d4 | ||
|
|
4c48730e43 | ||
|
|
39dcfd7307 | ||
|
|
7c16f75f99 | ||
|
|
5b39527e11 | ||
|
|
00bb0416d3 | ||
|
|
fbc09af6c9 | ||
|
|
516a7e5520 | ||
|
|
5a32e42508 | ||
|
|
feb0e983eb | ||
|
|
139581dc80 | ||
|
|
0f192cae2b | ||
|
|
e32abf5802 | ||
|
|
e06d72e270 | ||
|
|
59c983e201 | ||
|
|
9f5db36af8 | ||
|
|
976a048255 | ||
|
|
a7d9c803d6 | ||
|
|
1cb833acc4 | ||
|
|
b34e2cc4e3 | ||
|
|
51740a7279 | ||
|
|
1a0aca9b94 | ||
|
|
fab36115bc | ||
|
|
4e58a86cf8 | ||
|
|
6991b9a8ea | ||
|
|
1d925fb72b | ||
|
|
471a5bed00 | ||
|
|
68e2f2a2cd | ||
|
|
a5e3875fe0 | ||
|
|
a9a663cc40 | ||
|
|
c89d27ada6 | ||
|
|
f2ce163b2b | ||
|
|
1d62feaf7a | ||
|
|
f761957aca | ||
|
|
907075f704 | ||
|
|
f6ed411c62 | ||
|
|
69cc148543 | ||
|
|
669b5fe4f5 | ||
|
|
bcfc87f31b | ||
|
|
0d52125ca6 | ||
|
|
053e62dcf8 | ||
|
|
eaa6aa8b12 | ||
|
|
6dc6282102 | ||
|
|
0f1bbc58a4 | ||
|
|
f0cdc3622e | ||
|
|
fa655ab4df | ||
|
|
d779707b3a | ||
|
|
9df7cad803 | ||
|
|
cc22ca0088 | ||
|
|
dfa17ef621 | ||
|
|
46b451c5fa | ||
|
|
958418f9d9 | ||
|
|
f2306942a3 | ||
|
|
796145d6da | ||
|
|
f7211a75fa | ||
|
|
16c5dfecba | ||
|
|
bd1ef1a685 | ||
|
|
944ff0c63e | ||
|
|
a1399effab | ||
|
|
5e79f1e656 | ||
|
|
e7014ffaa0 | ||
|
|
9ec7e4bebf | ||
|
|
60a91c1163 | ||
|
|
533db63a86 | ||
|
|
eab8b12171 | ||
|
|
27d4a7aeac | ||
|
|
33c79a8c30 | ||
|
|
e83696a49c | ||
|
|
c73a90134b | ||
|
|
bf528b2b65 | ||
|
|
01d49f5373 | ||
|
|
d002288266 | ||
|
|
b1fb1509ff | ||
|
|
088aa6e7c8 | ||
|
|
517385e789 | ||
|
|
3528ad4515 | ||
|
|
083d5c0fb9 | ||
|
|
3c9dcf2475 | ||
|
|
5377f6f0c4 | ||
|
|
cd46090b75 | ||
|
|
72fd52db83 | ||
|
|
5f065a20e5 | ||
|
|
2406e392d8 | ||
|
|
52af5a13f0 | ||
|
|
401632d925 | ||
|
|
2a0b318b72 | ||
|
|
77b055aba0 | ||
|
|
93f91fc1ef | ||
|
|
0adcdaa1e5 | ||
|
|
0de8c6aef4 | ||
|
|
3f3e64a800 | ||
|
|
33d826f625 | ||
|
|
29e79764d4 | ||
|
|
9e89638c25 | ||
|
|
8f0beb99a0 | ||
|
|
6f8bc10850 | ||
|
|
807f8b63c1 | ||
|
|
2acbc79260 | ||
|
|
9c8cffa5f2 | ||
|
|
22aa276b3c | ||
|
|
75f5f2a0dd | ||
|
|
27fb856a8e | ||
|
|
b1e64480d2 | ||
|
|
8771e7232e | ||
|
|
a01c8482fd | ||
|
|
becf55ddb1 | ||
|
|
826d436abb | ||
|
|
000a529744 | ||
|
|
f78713d733 | ||
|
|
22d2633773 | ||
|
|
397ff0ace5 | ||
|
|
5e6e513c02 | ||
|
|
841e546953 | ||
|
|
858d8c3103 | ||
|
|
bff01d6fe3 | ||
|
|
566ebb9531 | ||
|
|
f8bf164180 | ||
|
|
2f3cbdb9fe | ||
|
|
f37148903d | ||
|
|
699053fe80 | ||
|
|
8dbc3ae551 | ||
|
|
630572c394 | ||
|
|
953f795b15 | ||
|
|
8526e5e4c3 | ||
|
|
c86fb0b5a2 | ||
|
|
6563fd578e | ||
|
|
2eb20fa3cd | ||
|
|
fb87dcf493 | ||
|
|
061260ec3e | ||
|
|
c658602d20 | ||
|
|
69dfc5e2d2 | ||
|
|
7b744c0798 | ||
|
|
604cb60d2e | ||
|
|
8af0c8d36f | ||
|
|
3d0bebff50 | ||
|
|
5e51436ff3 | ||
|
|
8e518ae008 | ||
|
|
785f8e4117 | ||
|
|
3d65f87f63 | ||
|
|
9cc85f4864 | ||
|
|
bdd65cdd5e | ||
|
|
9c475f0a25 | ||
|
|
e7e16b416d | ||
|
|
d516cf0506 | ||
|
|
6e15911f1e | ||
|
|
58aa0b5040 | ||
|
|
331cc68e45 | ||
|
|
05a0dceba7 | ||
|
|
52d733946d | ||
|
|
e20330af69 | ||
|
|
cc243a9d47 | ||
|
|
6435a3376d | ||
|
|
7e0c58b5cb | ||
|
|
44709df885 | ||
|
|
d899a30777 | ||
|
|
3c2022a13d | ||
|
|
fd9c9e0f4c | ||
|
|
b1d07a1604 | ||
|
|
da1c4fecd9 | ||
|
|
2b0a92d5f5 | ||
|
|
9f1fbdebf5 | ||
|
|
919043a049 | ||
|
|
5b56704538 | ||
|
|
53754ae93c | ||
|
|
3cb3b88c9d | ||
|
|
80910714a3 | ||
|
|
24e251fff2 | ||
|
|
d2a0097f86 | ||
|
|
6f7b051289 | ||
|
|
edaa05783d | ||
|
|
997ece8ef0 | ||
|
|
4640f0a77b | ||
|
|
44cddf8c4a | ||
|
|
bc0301503c | ||
|
|
1974628190 | ||
|
|
5e8c17d0f5 | ||
|
|
bcfb8968bb | ||
|
|
9a36d9ecf5 | ||
|
|
f24406dcf4 | ||
|
|
e2a22c57b0 | ||
|
|
68ec69a9c5 | ||
|
|
b209387d9f | ||
|
|
471df45bcb | ||
|
|
8926c8bf98 | ||
|
|
48c31c4ce5 | ||
|
|
5ff220b655 | ||
|
|
7a33af8ef7 | ||
|
|
76fa6688ae | ||
|
|
12cc1bb79c | ||
|
|
70c9bf279a | ||
|
|
bbf8d4ccb9 | ||
|
|
ecb0d1dbac | ||
|
|
b414df62d5 | ||
|
|
f78ede0324 | ||
|
|
8f6651d053 | ||
|
|
a4ee78322f | ||
|
|
c21bfd5a36 | ||
|
|
4cb50a733e | ||
|
|
bd2cf82e0a | ||
|
|
c7ee32186c | ||
|
|
ec876883b2 | ||
|
|
160f0693f3 | ||
|
|
6f62311778 | ||
|
|
bb90dda1ca | ||
|
|
039ff0abd9 | ||
|
|
017c16c80a | ||
|
|
07d40ef035 | ||
|
|
37e6570bdb | ||
|
|
0107beb86b | ||
|
|
1e652869d7 | ||
|
|
043f3c412b | ||
|
|
9dfea1e7ad | ||
|
|
0a398002bf | ||
|
|
cd768b8902 | ||
|
|
5197d10636 | ||
|
|
e6bfe147d5 | ||
|
|
1c0015a9ab | ||
|
|
105d2586b0 | ||
|
|
bd31823259 | ||
|
|
98c5fefed4 | ||
|
|
d73273ca20 | ||
|
|
442457af75 | ||
|
|
4a802e84bd | ||
|
|
389b035bee | ||
|
|
e5a0d3df22 | ||
|
|
2502993581 | ||
|
|
b9c8fc2f6e | ||
|
|
f41845afb7 | ||
|
|
f3bf280e7f | ||
|
|
b4fa23f619 | ||
|
|
a89785f25b | ||
|
|
0b15624ca4 | ||
|
|
72823246c1 | ||
|
|
c791af7db3 | ||
|
|
55add3b6e4 | ||
|
|
d28da844c1 | ||
|
|
431d31a713 | ||
|
|
b6a6586bf8 | ||
|
|
1290f3a4c1 | ||
|
|
2568e9f1f5 | ||
|
|
d9f4035d2c | ||
|
|
9f88f39f6a | ||
|
|
4797c08018 | ||
|
|
76a35883c6 | ||
|
|
6facf168e4 | ||
|
|
69394a906e | ||
|
|
649a2219f0 | ||
|
|
caf68872ec | ||
|
|
f6f5d8da7d | ||
|
|
5046bff067 | ||
|
|
dcb9685aa8 | ||
|
|
91e3d9c965 | ||
|
|
192e6286da | ||
|
|
5c79c1a32d | ||
|
|
bdaa045d5d | ||
|
|
5f07341998 | ||
|
|
1d9cb7eb03 | ||
|
|
668010bcf2 | ||
|
|
c16ce8a9e1 | ||
|
|
ef79eab224 | ||
|
|
1d6fcfd0c4 | ||
|
|
5508dc4e3c | ||
|
|
b54de3278a | ||
|
|
a430039ef0 | ||
|
|
914583d580 | ||
|
|
2ee80c6702 | ||
|
|
712b00346c | ||
|
|
e7a1bf1c24 | ||
|
|
02bc079ef9 | ||
|
|
4b0bda9b91 | ||
|
|
cf88675917 | ||
|
|
2e756b8789 | ||
|
|
c4853a4ce1 | ||
|
|
52b9192d83 | ||
|
|
9a8554de9e | ||
|
|
0820ec453b | ||
|
|
0c38ed57ec | ||
|
|
19c4ff9bb0 | ||
|
|
3852656e8b | ||
|
|
3a535625b5 | ||
|
|
029a1f8e5b | ||
|
|
02d5dfb61f | ||
|
|
5778043444 | ||
|
|
2d58519ca9 | ||
|
|
2cc0f5bb5b | ||
|
|
06210da48f | ||
|
|
a180725f56 | ||
|
|
c708b1f40c | ||
|
|
2f92399e23 | ||
|
|
8b430bfcc9 | ||
|
|
f4571094c2 | ||
|
|
591d99ca36 | ||
|
|
2e1862192e | ||
|
|
bb312062ea | ||
|
|
d12ce14168 | ||
|
|
6ba76aa500 | ||
|
|
371a7d8dbc | ||
|
|
b9f93a5c07 | ||
|
|
5dd75be1b9 | ||
|
|
79797cd450 | ||
|
|
ca6413917a | ||
|
|
c36ba1f864 | ||
|
|
cb6a8c1641 | ||
|
|
6a5304b79a | ||
|
|
d380883a6e | ||
|
|
afd68eec71 | ||
|
|
4cf36ccdce | ||
|
|
6236b604ec | ||
|
|
9343451ca8 | ||
|
|
0a4a7fabce | ||
|
|
e77544876e | ||
|
|
5847c3b50e | ||
|
|
b30a36fcf1 | ||
|
|
78c846d219 | ||
|
|
1196d08aad | ||
|
|
1ca703657a | ||
|
|
f211fcf509 | ||
|
|
c04aec0550 | ||
|
|
14436c6051 | ||
|
|
d78e33858d | ||
|
|
891cd0b256 | ||
|
|
6d81a048b6 | ||
|
|
2b47a81d54 | ||
|
|
0e357a9cc7 | ||
|
|
95312401b6 | ||
|
|
1d44f5d35d | ||
|
|
8ed2c02808 | ||
|
|
0181348cee | ||
|
|
d80e1b63eb | ||
|
|
3a711d1c0d | ||
|
|
07605d05cb | ||
|
|
56d1418de7 | ||
|
|
14d4c7cbcd | ||
|
|
d27b86568b | ||
|
|
0d89630a31 | ||
|
|
1aaf43d89e | ||
|
|
dff8524d3d | ||
|
|
9607225a16 | ||
|
|
1b0f22fbf8 | ||
|
|
bec422726b | ||
|
|
a4200186e2 | ||
|
|
e404649d43 | ||
|
|
c45781f0d6 | ||
|
|
2cf40cafcc | ||
|
|
ec3aa40aae | ||
|
|
e75bad3cbf | ||
|
|
319f52b988 | ||
|
|
6a19882646 | ||
|
|
fb54bcd994 | ||
|
|
4a97b419ae | ||
|
|
a7a093d066 | ||
|
|
d96e74bc15 | ||
|
|
fb0ac17835 | ||
|
|
d1d0ddda0f | ||
|
|
ca41880bb3 | ||
|
|
f86e905efb | ||
|
|
b7efba4727 | ||
|
|
ccda3cf0f0 | ||
|
|
d1160120c0 | ||
|
|
754806e0f8 | ||
|
|
c91decf543 | ||
|
|
6bad368dcb | ||
|
|
75b3e916bc | ||
|
|
c5f697dbc6 | ||
|
|
62f2fdc4c1 | ||
|
|
482cfbcdad | ||
|
|
c1952db4cb | ||
|
|
a0e9535769 | ||
|
|
4d5328dca4 | ||
|
|
6347cbfe5d | ||
|
|
304dcac4cc | ||
|
|
bed254954c | ||
|
|
316e3b39f3 | ||
|
|
6c7242cca3 | ||
|
|
1a99f0058e | ||
|
|
52c2d1cb75 | ||
|
|
3c3a02ed42 | ||
|
|
bda03ce5dc | ||
|
|
25613e6176 | ||
|
|
f27911fd4a | ||
|
|
44b248314b | ||
|
|
f730161c74 | ||
|
|
b1a127a732 | ||
|
|
33c9b2b96c | ||
|
|
99ccc35b93 | ||
|
|
dfd2182c41 | ||
|
|
b9e5d940a4 | ||
|
|
fb519b2002 | ||
|
|
de7c0c6bba | ||
|
|
d7372dea3f | ||
|
|
22123013be | ||
|
|
d5d9b5c839 | ||
|
|
c647f854e8 | ||
|
|
4d825ad482 | ||
|
|
23f5b6f8b8 | ||
|
|
c3c0817c3b | ||
|
|
9905d92244 | ||
|
|
67548034be | ||
|
|
4bb44b10d3 | ||
|
|
ca85652bab | ||
|
|
8a10b3ecd8 | ||
|
|
15838348c3 | ||
|
|
0a95372746 | ||
|
|
a0cc22be73 | ||
|
|
78de1d2455 | ||
|
|
c06d1e16b5 | ||
|
|
8dbd0a9d1c | ||
|
|
150fe98ddd | ||
|
|
bb200cd0ba | ||
|
|
88899971d1 | ||
|
|
c0db545811 | ||
|
|
e98ba91928 | ||
|
|
193bf1a766 | ||
|
|
c5183ed55a | ||
|
|
269fce6f0b | ||
|
|
ddf6b0ef63 | ||
|
|
648415d4cf | ||
|
|
97d607e7c5 | ||
|
|
96b6000f40 | ||
|
|
411a6d85d1 | ||
|
|
898f2f21c4 | ||
|
|
ae0941464f | ||
|
|
3c50ebce8f | ||
|
|
282bffcea7 | ||
|
|
80fa37f30f | ||
|
|
47c0dce062 | ||
|
|
9fcfc2bd0b | ||
|
|
45f602606b | ||
|
|
89d3304a93 | ||
|
|
bf764dc529 | ||
|
|
612cf63de7 | ||
|
|
aed1bd02d2 | ||
|
|
051ce5e786 | ||
|
|
e827ac125a | ||
|
|
75b02f6419 | ||
|
|
adb7f2dbe4 | ||
|
|
44e49f635b | ||
|
|
1721cf7b32 | ||
|
|
83790b6c6a | ||
|
|
07d6a17643 | ||
|
|
4f149fb5a3 | ||
|
|
b2cd0d69bb | ||
|
|
9d9eff684a | ||
|
|
2c4f26d726 | ||
|
|
617d761948 | ||
|
|
088ad53d79 | ||
|
|
1b0282ed32 | ||
|
|
258c676df4 | ||
|
|
7a5166621d | ||
|
|
93091fbb0a | ||
|
|
70b9cc7831 | ||
|
|
5b16156ba1 | ||
|
|
9926a28e50 | ||
|
|
1c67d4a2db | ||
|
|
8958ac2b96 | ||
|
|
0156e03780 | ||
|
|
45077e211b | ||
|
|
722e9f41cd | ||
|
|
52a43d65d3 | ||
|
|
0e9aed4d03 | ||
|
|
87fad5d171 | ||
|
|
f1e4c001a9 | ||
|
|
83445a96b8 | ||
|
|
0c6c5e212e | ||
|
|
aac17c01c3 | ||
|
|
619463c573 | ||
|
|
72a46581b6 | ||
|
|
722aa32939 | ||
|
|
80f8dd7863 | ||
|
|
3c016ce4dc | ||
|
|
7042460292 | ||
|
|
10ecf693a9 | ||
|
|
d718a6cbfb | ||
|
|
f32f6b841c | ||
|
|
7117cea835 | ||
|
|
c765a987e6 | ||
|
|
a00af74279 | ||
|
|
1d28fbc6f2 | ||
|
|
a7e1124f64 | ||
|
|
4cefed33f7 | ||
|
|
02494051af | ||
|
|
1f1336aa7a | ||
|
|
f40a20e5f8 | ||
|
|
13de1c4675 | ||
|
|
e9ead52a42 | ||
|
|
ade053c78b | ||
|
|
0700705040 | ||
|
|
3a5ad60eb2 | ||
|
|
e6ea8f13d9 | ||
|
|
279e9c47bc | ||
|
|
af96e33184 | ||
|
|
9e57148b60 | ||
|
|
ec4d0368df | ||
|
|
6cfdf78900 | ||
|
|
b5cc0993df | ||
|
|
cd9e03bf7a | ||
|
|
fd19ffa436 | ||
|
|
97cdf039b2 | ||
|
|
b93c18da5f | ||
|
|
9ce9ddcc3e | ||
|
|
f70296232c | ||
|
|
e12cf77857 | ||
|
|
f8e726fd1c | ||
|
|
a88d7d55a8 | ||
|
|
af5635e422 | ||
|
|
30753d4dd5 | ||
|
|
84a2bc5fbc | ||
|
|
744039403d | ||
|
|
07fd7f20cc | ||
|
|
5373b97ced | ||
|
|
4321dc69af | ||
|
|
1a157193dc | ||
|
|
a80bb55cea | ||
|
|
48070ae768 | ||
|
|
9145339a06 | ||
|
|
8f2b72315d | ||
|
|
e65633f9ff | ||
|
|
b91ffa7f72 | ||
|
|
1b6deb815a | ||
|
|
68cb9f7992 | ||
|
|
bb18a049e9 | ||
|
|
d25394b2c5 | ||
|
|
212d0466e5 | ||
|
|
f6b140a6ed | ||
|
|
5901a27224 | ||
|
|
beaa7267b6 | ||
|
|
b89faf1e4d | ||
|
|
e62fbb7a75 | ||
|
|
89aa761e66 | ||
|
|
26b007e861 | ||
|
|
08d30b1e9b | ||
|
|
3e6609a853 | ||
|
|
6a5d1c1479 | ||
|
|
75d9a83c25 | ||
|
|
ebe0b6607c | ||
|
|
c8a20b1107 | ||
|
|
34e62d8725 | ||
|
|
1ea91b6c71 | ||
|
|
5abaa7e0f4 | ||
|
|
f702cbbd38 | ||
|
|
91b6983564 | ||
|
|
a224bf6530 | ||
|
|
39526b2b8c | ||
|
|
a8cfe243e1 | ||
|
|
a3ae2c422d | ||
|
|
87175d6c16 | ||
|
|
527ab764dd | ||
|
|
460e4e733f | ||
|
|
b50dfb98bc | ||
|
|
f5073604b3 | ||
|
|
0e6af20c2a | ||
|
|
428dfcdf2d | ||
|
|
b654a1ebe7 | ||
|
|
50f5d95a2f | ||
|
|
c5f15f6725 | ||
|
|
c5458e4c08 | ||
|
|
0912ade9e1 | ||
|
|
249b0ce759 | ||
|
|
29c2f1bdc2 | ||
|
|
dd790c38a2 | ||
|
|
6248699ce5 | ||
|
|
5735b4d4db | ||
|
|
78c344b3a2 | ||
|
|
cd9d684960 | ||
|
|
8536593bdc | ||
|
|
7dfcd0a4fd | ||
|
|
a9cef6dbad | ||
|
|
ae94b268f0 | ||
|
|
8bd125ed2f | ||
|
|
ec23a0461d | ||
|
|
fbf37ae0da | ||
|
|
3ff3e3dd15 | ||
|
|
49fe356b91 | ||
|
|
5ef3482254 | ||
|
|
8a44ed57d7 | ||
|
|
6e1105e2c2 | ||
|
|
c0c2efff97 | ||
|
|
546d7e95da | ||
|
|
42e1466cf4 | ||
|
|
16277bd6df | ||
|
|
55913d1c42 | ||
|
|
f8d9873e27 | ||
|
|
8d34f4c650 | ||
|
|
5f37f0f804 | ||
|
|
ef800eee40 | ||
|
|
29c5a03efe | ||
|
|
b9af4553cd | ||
|
|
61683e0c3d | ||
|
|
db674c8be0 | ||
|
|
5040c8b254 | ||
|
|
bfe90c0d0d | ||
|
|
4bc6b33f16 | ||
|
|
3b9cb7d568 | ||
|
|
e7eb777969 | ||
|
|
8b8bb3da1b | ||
|
|
e57cf437db | ||
|
|
6756006b4f | ||
|
|
3355920db9 | ||
|
|
f04c02c221 | ||
|
|
ae07f437b1 | ||
|
|
2ae523b12c | ||
|
|
6959e067fa | ||
|
|
81fb3f50e8 | ||
|
|
4b2e9b780a | ||
|
|
ca42874098 | ||
|
|
266dd038f1 | ||
|
|
6f6837d070 | ||
|
|
7c11b952a7 | ||
|
|
2e3b6d0bc6 | ||
|
|
639061ac2f | ||
|
|
1110ec9d37 | ||
|
|
d3c187a62f | ||
|
|
48c2d675fb | ||
|
|
f74d276e50 | ||
|
|
48235a3c66 | ||
|
|
3fbec5065e | ||
|
|
8cca3630ae | ||
|
|
22400a4f86 | ||
|
|
6b05fb7906 | ||
|
|
b34dc46bd0 | ||
|
|
b9c78d192a | ||
|
|
4b3009ad7d | ||
|
|
cfd2e19267 | ||
|
|
7ba05fdae5 | ||
|
|
3957c4d76b | ||
|
|
5fcccc7364 | ||
|
|
70d55664ee | ||
|
|
1410c50fa1 | ||
|
|
e1cde147df | ||
|
|
2ebc84ea77 | ||
|
|
61de0c709a | ||
|
|
e463d7945f | ||
|
|
10c8f32bd9 | ||
|
|
cfa948fd9a | ||
|
|
6fcc99ba26 | ||
|
|
65105feeaf | ||
|
|
205ef64ac4 | ||
|
|
595e9e3b1f | ||
|
|
12b34d4a93 | ||
|
|
fec6164e92 | ||
|
|
c24b0f9569 | ||
|
|
0de964d42b | ||
|
|
f43badc3d4 | ||
|
|
3394ded6bb | ||
|
|
fa3ee31f06 | ||
|
|
3470be891e | ||
|
|
1c4d850441 | ||
|
|
62f609755a | ||
|
|
c9dc205c74 | ||
|
|
7e02b445b2 | ||
|
|
62652b1fc1 | ||
|
|
44d9abac96 | ||
|
|
eb83eaf25f | ||
|
|
0c4d50a6f5 | ||
|
|
d291834481 | ||
|
|
04d44f6262 | ||
|
|
72900bead3 | ||
|
|
5ce3f7f4d6 | ||
|
|
985973b35a | ||
|
|
5098d8fd7e | ||
|
|
b7316d56e8 | ||
|
|
5ed96f5072 | ||
|
|
85a4bacf31 | ||
|
|
6401faf9f0 | ||
|
|
32b3549425 | ||
|
|
55160bc52a | ||
|
|
57354ac6d7 | ||
|
|
0c44185d0d | ||
|
|
e50126e639 | ||
|
|
531c9de8ca | ||
|
|
b17fd87470 | ||
|
|
f2e368830a | ||
|
|
06b34cc12c | ||
|
|
400dbc386a | ||
|
|
775c87bb8f | ||
|
|
33928afec0 | ||
|
|
9c5b75e3bf | ||
|
|
d62b128144 | ||
|
|
fe3ab7a836 | ||
|
|
2af324f6ee | ||
|
|
5da9b1b778 | ||
|
|
b464946b1b | ||
|
|
c4fe3d63be | ||
|
|
dd24571949 | ||
|
|
41b7f13b27 | ||
|
|
6c488d6d2a | ||
|
|
2bbd0fff45 | ||
|
|
1dae73cfef | ||
|
|
f67c7d9383 | ||
|
|
0b2085db83 | ||
|
|
b9126e51f7 | ||
|
|
1e709fdef1 | ||
|
|
855dc86ea8 | ||
|
|
b3cb5b68d8 | ||
|
|
75c1d2ead2 | ||
|
|
877aafdb99 | ||
|
|
3786e929d6 | ||
|
|
c6a51605ce | ||
|
|
09fb5cdf34 | ||
|
|
4eb5ba5fb8 | ||
|
|
f6364427ce | ||
|
|
7a40e0f547 | ||
|
|
6d4ee4f85a | ||
|
|
749b945fdf | ||
|
|
d6d585e200 | ||
|
|
db8a2dc735 | ||
|
|
9b8dc4d6db | ||
|
|
1be18f5530 | ||
|
|
193e7a6417 | ||
|
|
b191173ae1 | ||
|
|
1f27c344d4 | ||
|
|
aefd9bbbc7 | ||
|
|
c2451038a0 | ||
|
|
749197466f | ||
|
|
0e2d04526c | ||
|
|
696e16b361 | ||
|
|
0f15797e01 | ||
|
|
891a9e4125 | ||
|
|
9c69a20ea5 | ||
|
|
3748b0238d | ||
|
|
6e6cb5a0b5 | ||
|
|
3227c9ffe3 | ||
|
|
cf0006fd7b | ||
|
|
25f3fe1ac5 | ||
|
|
072e38e552 | ||
|
|
8a6d681c15 | ||
|
|
de5434a0a6 | ||
|
|
634f50a04e | ||
|
|
02564d5a5b | ||
|
|
fc9f8d91f7 | ||
|
|
a45d9190db | ||
|
|
ca8f492240 | ||
|
|
84cde3d009 | ||
|
|
f57dcba59f | ||
|
|
b2fe307128 | ||
|
|
6fa745efcb | ||
|
|
440ca8e3cc | ||
|
|
43d4ea092c | ||
|
|
ee2a698dcb | ||
|
|
317d146302 | ||
|
|
a4a870cda3 | ||
|
|
2b624b1bf3 | ||
|
|
cf3262aee8 | ||
|
|
926ff2b5db | ||
|
|
5a7df8ac29 | ||
|
|
7fdcba9e05 | ||
|
|
42011abc69 | ||
|
|
fd28e772a8 | ||
|
|
8a23c5527e | ||
|
|
13ca2cc62a | ||
|
|
8afaca4b9f | ||
|
|
3757e6dc30 | ||
|
|
801f3c9c22 | ||
|
|
8669bf69ec | ||
|
|
debf7cb283 | ||
|
|
7e9efe7cb0 | ||
|
|
d7dcd233a2 | ||
|
|
b83d1a0fc8 | ||
|
|
08f03a0fa6 | ||
|
|
56b0ea91c9 | ||
|
|
bbfd3865a5 | ||
|
|
dae0501d75 | ||
|
|
8eb721ec31 | ||
|
|
ebef1648be | ||
|
|
1640530ec8 | ||
|
|
4913439d91 | ||
|
|
789a263967 | ||
|
|
f224b9f104 | ||
|
|
f80de415ec | ||
|
|
ec138c6fee | ||
|
|
b3b006b630 | ||
|
|
04335c5a6b | ||
|
|
c15ea65a26 | ||
|
|
2af6923e6e | ||
|
|
9ccb7b1c1e | ||
|
|
51918cb5d4 | ||
|
|
91af593bb2 | ||
|
|
9efad44fc9 | ||
|
|
367497958f | ||
|
|
b3baa0e9f4 | ||
|
|
56d6ad604c | ||
|
|
52222aaf76 | ||
|
|
124ed82f02 | ||
|
|
50ad3b0e22 | ||
|
|
beb43a8bea | ||
|
|
3046705c22 | ||
|
|
5848fe3948 | ||
|
|
718637c5cd | ||
|
|
132658d009 | ||
|
|
06bdc31a50 | ||
|
|
6a51b96a47 | ||
|
|
c9c6c63216 | ||
|
|
dc6c276992 | ||
|
|
8b555d7ee6 | ||
|
|
feb263ff4d | ||
|
|
a0d766de8a | ||
|
|
00e19f3941 | ||
|
|
dc6e7b00d0 | ||
|
|
5c41961351 | ||
|
|
72afecffeb | ||
|
|
5221a81a75 | ||
|
|
8db3fec05a | ||
|
|
baefcd06f0 | ||
|
|
b060ebb05b | ||
|
|
acc9a8780d | ||
|
|
cfc6be6a12 | ||
|
|
15d20b7b59 | ||
|
|
35cb91c3a9 | ||
|
|
da8218856b | ||
|
|
523f674fff | ||
|
|
7b73ac47da | ||
|
|
07f3b71fc9 | ||
|
|
a5f33017fd | ||
|
|
8e5c1d9ead | ||
|
|
a045ddca56 | ||
|
|
1daf15efbd | ||
|
|
93526e3d9c | ||
|
|
b653cfd160 | ||
|
|
79e19b5466 | ||
|
|
b39d0d8861 | ||
|
|
3975d2c10f | ||
|
|
58c2cfccd9 | ||
|
|
291c1ffaf8 | ||
|
|
68ca8bf1e9 | ||
|
|
4f01a8995b | ||
|
|
fa1d1fe7eb | ||
|
|
a6af54a047 | ||
|
|
4fde71a4b1 | ||
|
|
149e901514 | ||
|
|
69f0735c7a | ||
|
|
0f656571d5 | ||
|
|
875c8f77c1 | ||
|
|
79d03575ee | ||
|
|
4d000f1eb0 | ||
|
|
d0d8638a02 | ||
|
|
0d09858526 | ||
|
|
855eeb3d2d | ||
|
|
0edf90bb5a | ||
|
|
634b4fe0ce | ||
|
|
bb0ec76f24 | ||
|
|
1c949c248b | ||
|
|
9a9561f630 | ||
|
|
0cc6fec85e | ||
|
|
eba07d8918 | ||
|
|
f320caa724 | ||
|
|
5e949276d4 | ||
|
|
69a2b27a33 | ||
|
|
09db1129a1 | ||
|
|
e3e962dbda | ||
|
|
2faf3608b2 | ||
|
|
dcc21f1052 | ||
|
|
8a471e712c | ||
|
|
d8445caf90 | ||
|
|
d577759002 | ||
|
|
956208c251 | ||
|
|
1dd17260ac | ||
|
|
b3e5ee3333 | ||
|
|
cd62899f31 | ||
|
|
d28d756e80 | ||
|
|
79438ef391 | ||
|
|
59128b6742 | ||
|
|
b3cfac3c14 | ||
|
|
5072b82e93 | ||
|
|
27f7e5c4fe | ||
|
|
b329cfc84a | ||
|
|
151528735b | ||
|
|
ed19c824c0 | ||
|
|
47de3bf60f | ||
|
|
4a84ab9c1b | ||
|
|
133dd0026d | ||
|
|
4f80be1f2f | ||
|
|
fe6cffb54b | ||
|
|
76c20240f1 | ||
|
|
96e528e3e2 | ||
|
|
853c9574e1 | ||
|
|
7a2682efb5 | ||
|
|
23c10916e0 | ||
|
|
7648e4b16e | ||
|
|
2f2583a02f | ||
|
|
fc45ff1bdd | ||
|
|
145fcae0e9 | ||
|
|
f4370ca15f | ||
|
|
92b2f20d32 | ||
|
|
931024eb5a | ||
|
|
761ff3e781 | ||
|
|
54be51a664 | ||
|
|
379e0bbd3a | ||
|
|
582e89840d | ||
|
|
d1880f1d4a | ||
|
|
3cfba85461 | ||
|
|
f79ab2c3d1 | ||
|
|
55659d92be | ||
|
|
23b1bd1ffe | ||
|
|
b8707dbbb4 | ||
|
|
76362c4efe | ||
|
|
8c48abc40c | ||
|
|
28629bf7f0 | ||
|
|
2468ebf8f7 | ||
|
|
33ad5012c6 | ||
|
|
6e392932c2 | ||
|
|
ba14064ea4 | ||
|
|
302ea853d5 | ||
|
|
85489a0295 | ||
|
|
993cd32829 | ||
|
|
18e5bf26a6 | ||
|
|
7c128b0f4e | ||
|
|
685954c0dd | ||
|
|
6c6e8d3f2f | ||
|
|
a5fa94bdcb | ||
|
|
6b63aa3948 | ||
|
|
8f915b18b0 | ||
|
|
0bb1ae7240 | ||
|
|
9da0e704a7 | ||
|
|
af80efe75a | ||
|
|
ab911265ed | ||
|
|
162e2f4b98 | ||
|
|
22d27ca273 | ||
|
|
8dcc21476b | ||
|
|
1887483c0f | ||
|
|
7fb5505b12 | ||
|
|
77a4429bf4 | ||
|
|
4ed8e4e673 | ||
|
|
31031422d3 | ||
|
|
2e494f8f07 | ||
|
|
e007fc11aa | ||
|
|
e7a4ea8c7f | ||
|
|
cfc83e2fd8 | ||
|
|
bd292b1e80 | ||
|
|
c6b269a4d5 | ||
|
|
aa0e312d8a | ||
|
|
3ce114af44 | ||
|
|
24b2e77aae | ||
|
|
955049186f | ||
|
|
4fe2ef8887 | ||
|
|
4b1e57443a | ||
|
|
d9b85704e4 | ||
|
|
dd06e64207 | ||
|
|
d9c2c13851 | ||
|
|
f3f1f9f36e | ||
|
|
67f713d3a5 | ||
|
|
4a31a795b9 | ||
|
|
83f242fa4d | ||
|
|
2f794d92a4 | ||
|
|
e9904f1394 | ||
|
|
eff7de2284 | ||
|
|
bbf3ba0138 | ||
|
|
d2b413c9ab | ||
|
|
ed1993d5bf | ||
|
|
1d21eb1686 | ||
|
|
e1a6ecf238 | ||
|
|
57a80b6c1a | ||
|
|
7210a73e1f | ||
|
|
f63f29830f | ||
|
|
e84e1b41bf | ||
|
|
5ce332d2ee | ||
|
|
7ab68365ba | ||
|
|
190e273d5b | ||
|
|
242c50cb0c | ||
|
|
f56485f3cf | ||
|
|
037f4e8d50 | ||
|
|
e244fd51d4 | ||
|
|
7c89858797 | ||
|
|
871f0520bb | ||
|
|
1a39c31ff4 | ||
|
|
153a421354 | ||
|
|
18ab2e9259 | ||
|
|
c6f5b394f8 | ||
|
|
c49d817a68 | ||
|
|
26758b3ed9 | ||
|
|
678dee2ede | ||
|
|
da939ca2ba | ||
|
|
6c976a6b68 | ||
|
|
c2bf5c7db5 | ||
|
|
4726dea901 | ||
|
|
72dd7c9b49 | ||
|
|
18ef28ea77 | ||
|
|
35a55d73f3 | ||
|
|
fe9efd2191 | ||
|
|
bcbc095798 | ||
|
|
52f3285dcd | ||
|
|
ebed308fbb | ||
|
|
52285d8a7a | ||
|
|
1b14b5b012 | ||
|
|
2d601ea459 | ||
|
|
831f64ed38 | ||
|
|
0c3d33899d | ||
|
|
0caca472d4 | ||
|
|
ce746d4f5b | ||
|
|
b9db934e39 | ||
|
|
bf83aa55de | ||
|
|
22f2c033da | ||
|
|
30130d6c2c | ||
|
|
44a04df4f6 | ||
|
|
253f5e5904 | ||
|
|
e2b4c2b06e | ||
|
|
9ae31e7f05 | ||
|
|
bbdcb97a06 | ||
|
|
29b9f27919 | ||
|
|
46df8470a9 | ||
|
|
8c4d726c7b | ||
|
|
81928cccc5 | ||
|
|
14884568a9 | ||
|
|
788f8e1794 | ||
|
|
6a0b19c535 | ||
|
|
2eb4b1ac3b | ||
|
|
8b93dd5583 | ||
|
|
a249724777 | ||
|
|
078f687592 | ||
|
|
6f93d81e58 | ||
|
|
e584fe9e33 | ||
|
|
7d0e51a7a7 | ||
|
|
799959432b | ||
|
|
9fcc8648e9 | ||
|
|
91b457a802 | ||
|
|
e022335b60 | ||
|
|
b23127e53c | ||
|
|
52f29f2347 | ||
|
|
acf6b93df2 | ||
|
|
3796fc0925 | ||
|
|
8aa2c9461a | ||
|
|
0ccc1f0d60 | ||
|
|
9668b5fd34 | ||
|
|
9638a88145 | ||
|
|
caa262a4c5 | ||
|
|
8a26128e93 | ||
|
|
5592b25243 | ||
|
|
7b97b01fe6 | ||
|
|
fd65db99c8 | ||
|
|
352b87bd30 | ||
|
|
31b1985c64 | ||
|
|
fb963154ea | ||
|
|
55111efcb5 | ||
|
|
399b9f8d9d | ||
|
|
ae3d73a2e7 | ||
|
|
dfe9a3e288 | ||
|
|
58b70de654 | ||
|
|
afeee02e4a | ||
|
|
c86f60b1d3 | ||
|
|
eb62ad72f1 | ||
|
|
4968de9405 | ||
|
|
afe2a67c76 | ||
|
|
6991024935 | ||
|
|
82784a6f41 | ||
|
|
ee97583e02 | ||
|
|
519fdf41b8 | ||
|
|
675668c430 | ||
|
|
2c7af9fc45 | ||
|
|
8a1d9beb55 | ||
|
|
c044cfdefb | ||
|
|
ac39badc2e | ||
|
|
eb02fda327 | ||
|
|
b4665fc852 | ||
|
|
b43ab4d4c3 | ||
|
|
25f794affa | ||
|
|
46932961d4 | ||
|
|
a7a42140a0 | ||
|
|
0a800d87e1 | ||
|
|
ddf1ba21b3 | ||
|
|
f3b944a55a | ||
|
|
6f2b360ce8 | ||
|
|
ca6916a867 | ||
|
|
918a539baf | ||
|
|
26d6b7a76f | ||
|
|
4437b0040e | ||
|
|
20cb648ea9 | ||
|
|
204e15628c | ||
|
|
46e5aa5522 | ||
|
|
c89663d774 | ||
|
|
20b35c4d20 | ||
|
|
6fa2d5e84f | ||
|
|
dbe9d84649 | ||
|
|
9e49baefa4 | ||
|
|
75b979282f | ||
|
|
e354d942e3 | ||
|
|
c53587ef2d | ||
|
|
d94b6b5012 | ||
|
|
15d6fc35da | ||
|
|
da982d31be | ||
|
|
a260795327 | ||
|
|
4f20fbc36c | ||
|
|
4ac6e58360 | ||
|
|
fc620514a9 | ||
|
|
e6aee3d26c | ||
|
|
061c0c29fe | ||
|
|
af7d056f7e | ||
|
|
a408b30896 | ||
|
|
13f7ebce5a | ||
|
|
5c11b57542 | ||
|
|
340f68bbee | ||
|
|
b23b624f82 | ||
|
|
607ae5ca5e | ||
|
|
007e19fe30 | ||
|
|
5455bf9b77 | ||
|
|
a6d4c012ae | ||
|
|
4f87062f3e | ||
|
|
be76707452 | ||
|
|
08b95863a2 | ||
|
|
ed1554b7a1 | ||
|
|
dd51a261e0 | ||
|
|
ff730b372e | ||
|
|
08d88d40a5 | ||
|
|
95944dad92 | ||
|
|
2638c92fba | ||
|
|
41946c44c9 | ||
|
|
704f686396 | ||
|
|
5c4c0a94ff | ||
|
|
191bcff0ac | ||
|
|
dcb32a6ba0 | ||
|
|
0ffbbd631e | ||
|
|
b3fe7ddcb1 | ||
|
|
d8277a4ba0 | ||
|
|
e5974c4ae3 | ||
|
|
49b8f9b911 | ||
|
|
25199b20fe | ||
|
|
5da471bf15 | ||
|
|
d995713e21 | ||
|
|
f188e76b8c | ||
|
|
6d722ecd27 | ||
|
|
90cf685165 | ||
|
|
c52b365e1d | ||
|
|
a14802fe2c | ||
|
|
2777c0541c | ||
|
|
51c4e1cdc2 | ||
|
|
f946f6e0a7 | ||
|
|
52143d2c8e | ||
|
|
0594b1d2ea | ||
|
|
5925f313f9 | ||
|
|
78b084502a | ||
|
|
c1b004c74e | ||
|
|
8b1da7b92c | ||
|
|
992848431b | ||
|
|
c83792a8cd | ||
|
|
83f25922b0 | ||
|
|
05212b0a3f | ||
|
|
4ee9ba9766 | ||
|
|
970e14725b | ||
|
|
ef1022e9c8 | ||
|
|
fa3b6d18ac | ||
|
|
7395d71e1d | ||
|
|
21ca713af4 | ||
|
|
08de5a1bbb | ||
|
|
fea8e5a1e9 | ||
|
|
f632da7943 | ||
|
|
2880155772 | ||
|
|
e4c8c14fb3 | ||
|
|
d3e0353203 | ||
|
|
6fc66eaba7 | ||
|
|
6e2c5e2d4c | ||
|
|
fca89049c9 | ||
|
|
1814d2bde0 | ||
|
|
fdb4c63244 | ||
|
|
19c15a5139 | ||
|
|
bbecbccb0a | ||
|
|
66d5808d4a | ||
|
|
360a97b654 | ||
|
|
66d5d40a7d | ||
|
|
7d8b783195 | ||
|
|
966e411ecb | ||
|
|
602f897c50 | ||
|
|
67af6c303f | ||
|
|
c5967381d6 | ||
|
|
4e53fba8b9 | ||
|
|
0f748cb732 | ||
|
|
f8812b95c7 | ||
|
|
fa1295d3cf | ||
|
|
8b3f170b38 | ||
|
|
110fa35d04 | ||
|
|
ee408653dd | ||
|
|
82a5bb3778 | ||
|
|
40bd60959e | ||
|
|
9e7cb90a01 | ||
|
|
bff9a0c4a6 | ||
|
|
9f79a6bb94 | ||
|
|
5caee79f43 | ||
|
|
72fb5460d0 | ||
|
|
cb489d155c | ||
|
|
c061f347f2 | ||
|
|
ed19e0f43e | ||
|
|
dc8dc941e8 | ||
|
|
87dfbcca62 | ||
|
|
ec6456ba73 | ||
|
|
e58aea9df7 | ||
|
|
4aea2c8b30 | ||
|
|
f7279b3e19 | ||
|
|
fbb4dfaf37 | ||
|
|
e1ab7c9273 | ||
|
|
88e03caff1 | ||
|
|
8e4d28097a | ||
|
|
9ddcd8bda8 | ||
|
|
c14e43a52f | ||
|
|
f8322b3bd7 | ||
|
|
ee228e6657 | ||
|
|
4ea2a96e13 | ||
|
|
5d006f7bee | ||
|
|
2b83552668 | ||
|
|
61f5866ecc | ||
|
|
7c569e9cfe | ||
|
|
86db9bcf47 | ||
|
|
8bcbbcdfcb | ||
|
|
1966215b92 | ||
|
|
fa07fbedbc | ||
|
|
1c7d002031 | ||
|
|
a3e9934fa0 | ||
|
|
35c6db05bf | ||
|
|
12b254097b | ||
|
|
58e5ce3900 | ||
|
|
0da32bdfec | ||
|
|
883317e58c | ||
|
|
4c9fe12832 | ||
|
|
cc79237af7 | ||
|
|
01aafd348c | ||
|
|
e0928f6b37 | ||
|
|
73bda23c60 | ||
|
|
5731541bad | ||
|
|
75f4343881 | ||
|
|
abf7a3d5e3 | ||
|
|
6eee061c0e | ||
|
|
887926e0ad | ||
|
|
7e13bd36f5 | ||
|
|
9d663db3f0 | ||
|
|
bc941d3dd9 | ||
|
|
fa29e19863 | ||
|
|
3d75fb3fae | ||
|
|
7d6854e925 | ||
|
|
a8106bbadd | ||
|
|
73fc6e3ca6 | ||
|
|
503446c463 | ||
|
|
d06d1ae49c | ||
|
|
09733e4906 | ||
|
|
149d13cb9c | ||
|
|
7f0da3d0b2 | ||
|
|
75008d8098 | ||
|
|
bfb5ab0f58 | ||
|
|
f5e155b7c8 | ||
|
|
cdd71ab211 | ||
|
|
4a6865650d | ||
|
|
4f202f3fa5 | ||
|
|
043d345647 | ||
|
|
862a9c2c89 | ||
|
|
e38333e627 | ||
|
|
9f24404ab8 | ||
|
|
3de0c84d1d | ||
|
|
ad2600b4d0 | ||
|
|
7b80e80a1e | ||
|
|
32f3f3d94f | ||
|
|
276e5da137 | ||
|
|
a52c9ceb45 | ||
|
|
a21aa1f53c | ||
|
|
aacd43bb45 | ||
|
|
e26f79f052 | ||
|
|
13ce9d69cb | ||
|
|
831829dbc3 | ||
|
|
deb2180c9b | ||
|
|
60bb00be41 | ||
|
|
a47bb90388 | ||
|
|
bc6d0a3641 | ||
|
|
39ae0314b6 | ||
|
|
dc94613e6a | ||
|
|
56ccf4f8dd | ||
|
|
ad966b15f2 | ||
|
|
640ed6d2bc | ||
|
|
43553646ed | ||
|
|
4331e129ab | ||
|
|
ef23e702af | ||
|
|
80d52d9a77 | ||
|
|
fc84e5a34a | ||
|
|
962faa84e9 | ||
|
|
afdebbc793 | ||
|
|
9875b40420 | ||
|
|
23ec2f9fa8 | ||
|
|
3662f90095 | ||
|
|
1e80366b42 | ||
|
|
9d3eb480a2 | ||
|
|
1929b44235 | ||
|
|
f09c2d6b87 | ||
|
|
16febc0510 | ||
|
|
cababfe58a | ||
|
|
eeb836d62a | ||
|
|
31da6a09a1 | ||
|
|
e7753698c9 | ||
|
|
f1af90e97e | ||
|
|
321f6070ac | ||
|
|
57d37869c9 | ||
|
|
0e844570dc | ||
|
|
7330947ce2 | ||
|
|
72d0e1ff1b | ||
|
|
61fb2ac36d | ||
|
|
a430381434 | ||
|
|
4cd7ee1134 | ||
|
|
40cc0d116a | ||
|
|
e9d96fa3ff | ||
|
|
7214efa86e | ||
|
|
eb2579ec0a | ||
|
|
d96f0c2fda | ||
|
|
a13d2f9aff | ||
|
|
312f2f3aeb | ||
|
|
84955146d0 | ||
|
|
a7e00fbe4a | ||
|
|
b4ba8379de | ||
|
|
d1ff4a6905 | ||
|
|
3dc7542eca | ||
|
|
c5dded8992 | ||
|
|
aace2fcbd0 | ||
|
|
5c67df5508 | ||
|
|
e0613e6600 | ||
|
|
269186b9d1 | ||
|
|
76326c6497 | ||
|
|
23aa213cef | ||
|
|
ffde066951 | ||
|
|
667ce4db06 | ||
|
|
a591b4fc4b | ||
|
|
fb0361fc8c | ||
|
|
f1cd77472c | ||
|
|
770aa1b123 | ||
|
|
0ab613e57f | ||
|
|
8a9d0d3504 | ||
|
|
dda5269e77 | ||
|
|
e7b5ced09c | ||
|
|
22d562782b | ||
|
|
1064b85a7d | ||
|
|
1985af8965 | ||
|
|
d7eb92be5a | ||
|
|
90898172bf | ||
|
|
08e18867fd | ||
|
|
811a3ab577 | ||
|
|
7166d0f106 | ||
|
|
171081dbbb | ||
|
|
28b7172c0a | ||
|
|
7665ad3950 | ||
|
|
dfd83bacd1 | ||
|
|
2839ed9c20 | ||
|
|
55ae7a2409 | ||
|
|
c50c398a81 | ||
|
|
40d29cab55 | ||
|
|
eb3520ab73 | ||
|
|
e9175b2f8c | ||
|
|
cd4f4084c0 | ||
|
|
913b8b84bc | ||
|
|
fc354a44cc | ||
|
|
c737007879 | ||
|
|
c63c5d5008 | ||
|
|
d4e68cfcf9 | ||
|
|
7dab1fb731 | ||
|
|
8077e9b62b | ||
|
|
2082ffbad5 | ||
|
|
64b1a20010 | ||
|
|
3d769e6a73 | ||
|
|
afe4b19588 | ||
|
|
bf96e704ff | ||
|
|
da089b09f6 | ||
|
|
d07313333f | ||
|
|
52e031b849 | ||
|
|
bc7226ae95 | ||
|
|
0d1e332217 | ||
|
|
fe7775c384 | ||
|
|
89b740d9f7 | ||
|
|
6a45ea2c97 | ||
|
|
3f900a833e | ||
|
|
8f3d9e2ec7 | ||
|
|
5ad6df52e0 | ||
|
|
7985f6818e | ||
|
|
3b473082e5 | ||
|
|
d775dd31f5 | ||
|
|
baeaaee0f7 | ||
|
|
d4408add04 | ||
|
|
4dc959c1f2 | ||
|
|
0024d20e28 | ||
|
|
c74657f29a | ||
|
|
b048d62ad0 | ||
|
|
a1d40035df | ||
|
|
55785f5919 | ||
|
|
3e3ba607b5 | ||
|
|
a15b6964b7 | ||
|
|
223560a7ec | ||
|
|
773d71204f | ||
|
|
291ad52891 | ||
|
|
adf99811fa | ||
|
|
37058ad3d2 | ||
|
|
ec0ce5bed7 | ||
|
|
9577a8d9e8 | ||
|
|
3f063e5c52 | ||
|
|
372c887ca3 | ||
|
|
802a92e92f | ||
|
|
72e31e6329 | ||
|
|
0d5885fff0 | ||
|
|
0083d643bc | ||
|
|
3c42c9aac3 | ||
|
|
99c6dc7fd6 | ||
|
|
1a342ae5dc | ||
|
|
88972bf92a | ||
|
|
f6fdfea3ae | ||
|
|
d3c1abc6e1 | ||
|
|
b73f3610fc | ||
|
|
0c27b89c63 | ||
|
|
b8746b1464 | ||
|
|
fb2fb7c6f4 | ||
|
|
9e1d4885b5 | ||
|
|
0e8148d602 | ||
|
|
1d38900f17 | ||
|
|
9dc377e1d8 | ||
|
|
dc8b85611f | ||
|
|
d7a14cecde | ||
|
|
53fd36e4f2 | ||
|
|
879eda9379 | ||
|
|
6b7f33183c | ||
|
|
2bd8e05824 | ||
|
|
37a4a66e93 | ||
|
|
6424c82570 | ||
|
|
d8baf4434d | ||
|
|
6e38bd5393 | ||
|
|
dde74281de | ||
|
|
a7233d1bf1 | ||
|
|
970f6a3ae7 | ||
|
|
743be29852 | ||
|
|
aa40bc34f5 | ||
|
|
0f35c148ea | ||
|
|
a2d0db2a86 | ||
|
|
fe25fdcfdc | ||
|
|
f64b209750 | ||
|
|
c49929327a | ||
|
|
5aff529f0b | ||
|
|
0cf33fdaa3 | ||
|
|
476ef48fa5 | ||
|
|
4b9c129e1c | ||
|
|
b75b52eefb | ||
|
|
230f0410f7 | ||
|
|
59f4d42795 | ||
|
|
ebbd7c34c8 | ||
|
|
1e3c08565c | ||
|
|
e4beb49c6d | ||
|
|
8400dbea7d | ||
|
|
c12b7546a8 | ||
|
|
01092fa349 | ||
|
|
41ff569260 | ||
|
|
1b2a4fd659 | ||
|
|
00182afb2f | ||
|
|
a10a4bf491 | ||
|
|
399a911675 | ||
|
|
7ec572ca47 | ||
|
|
66193a2ac8 | ||
|
|
95a43597c9 | ||
|
|
3d78cd6848 | ||
|
|
e21ebaa389 | ||
|
|
d2ce20dc5c | ||
|
|
c766aa5403 | ||
|
|
35d56358b8 | ||
|
|
29c170f83a | ||
|
|
64b8194210 | ||
|
|
f8a23f41a6 | ||
|
|
cf703138f2 | ||
|
|
abe8cae083 | ||
|
|
fa950a8a49 | ||
|
|
a906bda7fc | ||
|
|
8f14452614 | ||
|
|
2666043daf | ||
|
|
20358bc8bf | ||
|
|
b44d1d9b90 | ||
|
|
eadcf43ca0 | ||
|
|
4e79d4708c | ||
|
|
a7df2b0b55 | ||
|
|
7b575f38aa | ||
|
|
f7d45ef31f | ||
|
|
85f2f8d8d8 | ||
|
|
1f9b340d13 | ||
|
|
fb95689601 | ||
|
|
d8e977cb42 | ||
|
|
89886e69a9 | ||
|
|
8ad5f0dbcc | ||
|
|
e9bb874ddc | ||
|
|
9042d5049d | ||
|
|
3a8defed09 | ||
|
|
0428943d84 | ||
|
|
373181dade | ||
|
|
f44fb3d9b7 | ||
|
|
32e0a7cb16 | ||
|
|
4ac29c4d9b | ||
|
|
3d70ad414e | ||
|
|
21f4f8ddce | ||
|
|
f3226b7f8d | ||
|
|
ea9d9e09ba | ||
|
|
ea6f556ed2 | ||
|
|
10b125115e | ||
|
|
ce6706f3e9 | ||
|
|
ec863041f9 | ||
|
|
3ff2f6a7c9 | ||
|
|
983263e45e | ||
|
|
f8c7e7904e | ||
|
|
934c133103 | ||
|
|
8ebddc2ca3 | ||
|
|
9aa89b17a5 | ||
|
|
94ba3b3a23 | ||
|
|
8ca5902a98 | ||
|
|
de4cbe2e3f | ||
|
|
fa0f3cc8be | ||
|
|
eaeab62373 | ||
|
|
7b21e04604 | ||
|
|
dc23c2c0d1 | ||
|
|
5e0d6263ed | ||
|
|
89ef91ca1b | ||
|
|
4597cfd54e | ||
|
|
595b5dc642 | ||
|
|
e0a4f703cb | ||
|
|
16f14b76a9 | ||
|
|
e9d2ebb4f9 | ||
|
|
e929559e9a | ||
|
|
6c172df547 | ||
|
|
902d0b9f41 | ||
|
|
cd27c5cf33 | ||
|
|
1b26018534 | ||
|
|
cc460b36b9 | ||
|
|
d26b92b551 | ||
|
|
3963575529 | ||
|
|
294751d8a3 | ||
|
|
3ec9ca11b1 | ||
|
|
24ffdde03d | ||
|
|
c7b7b847f0 | ||
|
|
e12814fb98 | ||
|
|
90873cd3e2 | ||
|
|
ff80f03953 | ||
|
|
ce3e4ba618 | ||
|
|
71702a086c | ||
|
|
6d6a4abb8a | ||
|
|
9e0d2f6a70 | ||
|
|
0cd388efb8 | ||
|
|
4cdd0dfd1a | ||
|
|
d7cfb626bb | ||
|
|
8053ebe798 | ||
|
|
57e55268e5 | ||
|
|
4f7a0c265d | ||
|
|
1292465a5b | ||
|
|
ae8a7d2dc5 | ||
|
|
2f1c904d74 | ||
|
|
aa535748ef | ||
|
|
42952ee42f | ||
|
|
8a0ca60e4b | ||
|
|
e6e7f8d402 | ||
|
|
edd6941de4 | ||
|
|
6bf7b9601d | ||
|
|
dc103318ab | ||
|
|
1194a1a5a5 | ||
|
|
70d7fc71b3 | ||
|
|
96fa89052b | ||
|
|
97505e200a | ||
|
|
a16e47c593 | ||
|
|
4080eb9312 | ||
|
|
c9538194aa | ||
|
|
73022ff3b3 | ||
|
|
58fb988c52 | ||
|
|
95f7c69e36 | ||
|
|
b3d928c593 | ||
|
|
ea691bfd41 | ||
|
|
00ae48f58d | ||
|
|
d5ea907d69 | ||
|
|
8100b53fd7 | ||
|
|
f23f301547 | ||
|
|
bda1f290ac | ||
|
|
2f905598e8 | ||
|
|
f769ce93cc | ||
|
|
9c9ba8f2bd | ||
|
|
67bce7721b | ||
|
|
84fbfa36c6 | ||
|
|
a46e920148 | ||
|
|
cf959c768d | ||
|
|
34b0cda024 | ||
|
|
e93721162d | ||
|
|
013e33e1a5 | ||
|
|
084f2c53ce | ||
|
|
9e198184a7 | ||
|
|
7f3dccf6dd | ||
|
|
0274af8c9c | ||
|
|
905b7555c2 | ||
|
|
b1974dac12 | ||
|
|
610b6fda3b | ||
|
|
1a5010b2c6 | ||
|
|
3ee0150367 | ||
|
|
4ecddaacd9 | ||
|
|
819c0762b9 | ||
|
|
26edd01ca3 | ||
|
|
a5e32a6d32 | ||
|
|
caeba1fd91 | ||
|
|
cd67c18049 | ||
|
|
c7074761c5 | ||
|
|
f399ece9f9 | ||
|
|
eace1dc44d | ||
|
|
4b475df5b2 | ||
|
|
c0d92f3569 | ||
|
|
88dbefa141 | ||
|
|
74a37bcf78 | ||
|
|
8a8e6ca349 | ||
|
|
ed9a7e5495 | ||
|
|
ccda2fbe44 | ||
|
|
cc07e5f7f6 | ||
|
|
31a0628cf1 | ||
|
|
18a25e4e4c | ||
|
|
778a7170a5 | ||
|
|
1c6d54ef57 | ||
|
|
da4c3660f4 | ||
|
|
665b3e2d5d | ||
|
|
b1e13668f2 | ||
|
|
b5f6bea880 | ||
|
|
5666950929 | ||
|
|
021cfd791f | ||
|
|
cdb271ea23 | ||
|
|
ba6a8602fb | ||
|
|
d4a92830be | ||
|
|
03ec5808ff | ||
|
|
6eb5d663b0 | ||
|
|
6e0b801b6a | ||
|
|
6747e22757 | ||
|
|
6dd883e5f4 | ||
|
|
4671a1eb98 | ||
|
|
845e2b3d01 | ||
|
|
bc91fb9e54 | ||
|
|
9d334c82b9 | ||
|
|
98e70a706e | ||
|
|
eec5fa3feb | ||
|
|
712f1ea3e9 | ||
|
|
388b84de3c | ||
|
|
9881e190bf | ||
|
|
4ac4ac3fd4 | ||
|
|
cf0f947adb | ||
|
|
ae77d1370e | ||
|
|
4d48454c11 | ||
|
|
c9fc36ca14 | ||
|
|
3ff6137767 | ||
|
|
cbe7358dc8 | ||
|
|
3008ba9a13 | ||
|
|
f14679f7a5 | ||
|
|
97912c7d9c | ||
|
|
725ec7f2a9 | ||
|
|
c26c3a46a9 | ||
|
|
19edb8efa4 | ||
|
|
52d5b86e88 | ||
|
|
738e108d06 | ||
|
|
78b845b68c | ||
|
|
56ae1b8246 | ||
|
|
314cad79ba | ||
|
|
4eef082cf3 | ||
|
|
acf6ad4ba0 | ||
|
|
2601e0e49d | ||
|
|
f00e9a1272 | ||
|
|
cabdfb04e7 | ||
|
|
6dcbdfd605 | ||
|
|
d60a5465db | ||
|
|
d2f32090b7 | ||
|
|
0fb535db8e | ||
|
|
f0a750c8a3 | ||
|
|
29c92c38fb | ||
|
|
cb89abc53a | ||
|
|
a71dd1aee6 | ||
|
|
fec0deb758 | ||
|
|
ff28b1a990 | ||
|
|
e30969fecd | ||
|
|
dbd4b0a7d2 | ||
|
|
71745820ed | ||
|
|
abeb78b95c | ||
|
|
4692621e4f | ||
|
|
1c86cd5fec | ||
|
|
fbf129da56 | ||
|
|
0c90c9768b | ||
|
|
dd67b25df1 | ||
|
|
accb58f5b2 | ||
|
|
d08301de8c | ||
|
|
9c9f2b9d45 | ||
|
|
05a50fcf53 | ||
|
|
744a5606e4 | ||
|
|
aa6b2f7567 | ||
|
|
167404f19e | ||
|
|
a691893413 | ||
|
|
213d38cd50 | ||
|
|
d179ace708 | ||
|
|
6df01aeb34 | ||
|
|
e30b706e66 | ||
|
|
6dc5bb9437 | ||
|
|
ead269d30d | ||
|
|
72afe8fe04 | ||
|
|
abaf2e9704 | ||
|
|
3547258282 | ||
|
|
77373ef9af | ||
|
|
a6c96257a5 | ||
|
|
091b1238da | ||
|
|
8a8fcc77a8 | ||
|
|
13495d4d13 | ||
|
|
df76aaef96 | ||
|
|
1e9e6d4349 | ||
|
|
b9c20b2b06 | ||
|
|
d9120c7b56 | ||
|
|
3dba954900 | ||
|
|
7c56918787 | ||
|
|
fa8ca5dcde | ||
|
|
94ae0f1921 | ||
|
|
f9e799d089 | ||
|
|
ce9dc8e851 | ||
|
|
604d55ed42 | ||
|
|
1beb372057 | ||
|
|
9325553ff9 | ||
|
|
17b5a8540e | ||
|
|
1f66b67309 | ||
|
|
cb4ad33703 | ||
|
|
7775c8cc50 | ||
|
|
e766fb1f13 | ||
|
|
a42da2af01 | ||
|
|
99331f777e | ||
|
|
35a1f6a529 | ||
|
|
d403186e6e | ||
|
|
50097b1fb1 | ||
|
|
3478ac6538 | ||
|
|
a5be284f1d | ||
|
|
1dd7ec91fe | ||
|
|
fc80a986f2 | ||
|
|
299793e788 | ||
|
|
8684d43ebd | ||
|
|
e4a27c41a6 | ||
|
|
43d7f0c312 | ||
|
|
9eac8c2efe | ||
|
|
e64dc3b431 | ||
|
|
872e597512 | ||
|
|
f5df0d337d | ||
|
|
eada1321ff | ||
|
|
57b926f739 | ||
|
|
f4d3cf3576 | ||
|
|
1f962a2167 | ||
|
|
0e15988233 | ||
|
|
af5d800759 | ||
|
|
1e60f0ce51 | ||
|
|
c9aef0e595 | ||
|
|
31acf52d0a | ||
|
|
5b5e21a99e | ||
|
|
7ed15c742f | ||
|
|
7d34b6a7e1 | ||
|
|
619d8c937d | ||
|
|
35c29faf99 | ||
|
|
15b4a54454 | ||
|
|
1b84c04dcd | ||
|
|
5b8e41c1b2 | ||
|
|
7073928abb | ||
|
|
76e34f093d | ||
|
|
4f6f97b369 | ||
|
|
a972293151 | ||
|
|
78531fe033 | ||
|
|
b10b724d17 | ||
|
|
80e3858ae4 | ||
|
|
c656123db9 | ||
|
|
3a0bc955be | ||
|
|
e2469b8f6d | ||
|
|
4057fe55a2 | ||
|
|
968cbfeb15 | ||
|
|
01dd72cf1f | ||
|
|
9a8404b733 | ||
|
|
47468636e4 | ||
|
|
05005acabd | ||
|
|
a42ef13b61 | ||
|
|
49a5a552a3 | ||
|
|
19bf03542c | ||
|
|
ee55ab522f | ||
|
|
bbfcd65855 | ||
|
|
25e1be8001 | ||
|
|
18f2f0446d | ||
|
|
550d15b49e | ||
|
|
4920295e3e | ||
|
|
c5dcf35281 | ||
|
|
34bdd1e8d0 | ||
|
|
1568c53faa | ||
|
|
6b86fb9966 | ||
|
|
2a58543b4d | ||
|
|
0f95330bc1 | ||
|
|
bdfcec7cf7 | ||
|
|
7388623244 | ||
|
|
fff025ca0f | ||
|
|
331e1b7d61 | ||
|
|
16b0499192 | ||
|
|
fe09fe485f | ||
|
|
d52a5af87d | ||
|
|
d539a21f69 | ||
|
|
128f242808 | ||
|
|
66bf8054f9 | ||
|
|
d99cf6350f | ||
|
|
9bd7cb7d00 | ||
|
|
f804a5f443 | ||
|
|
7549a68d6c | ||
|
|
1ef354465a | ||
|
|
a7b6dfb06e | ||
|
|
98c5b250b9 | ||
|
|
098639e146 | ||
|
|
a7d30d9c6f | ||
|
|
0937c5a8a3 | ||
|
|
56608a4654 | ||
|
|
8bb1c83479 | ||
|
|
b709dca2d6 | ||
|
|
b925be2758 | ||
|
|
2e36599d40 | ||
|
|
0d852ab3e0 | ||
|
|
495ca290e0 | ||
|
|
de1bea8227 | ||
|
|
9cd36af3e8 | ||
|
|
3502c5afd1 | ||
|
|
03769eb0ea | ||
|
|
76b0f077a4 | ||
|
|
1dae161823 | ||
|
|
25e22df2cf | ||
|
|
96d0f57558 | ||
|
|
f651a27418 | ||
|
|
3834768b72 | ||
|
|
0d86244c90 | ||
|
|
a389f2699a | ||
|
|
3478dea5de | ||
|
|
0c24ab45af | ||
|
|
cde6f56014 | ||
|
|
9754b04bd6 | ||
|
|
d19b8d83e8 | ||
|
|
496114ae8b | ||
|
|
ceca26ae87 | ||
|
|
20f04574e5 | ||
|
|
1d3d99bb9e | ||
|
|
b38e57d452 | ||
|
|
763d353f5c | ||
|
|
eaa74afb42 | ||
|
|
3245779c11 | ||
|
|
a2a7eb5630 | ||
|
|
bd5dd7cb21 | ||
|
|
9311f2a627 | ||
|
|
bfe64156bf | ||
|
|
333f0b9f2d | ||
|
|
d6cbdc1580 | ||
|
|
77f326e0dd | ||
|
|
881f59354d | ||
|
|
08d0e9f8b4 | ||
|
|
3432dfd280 | ||
|
|
5be86907d7 | ||
|
|
b191842d98 | ||
|
|
293290e12a | ||
|
|
bb1e70acab | ||
|
|
97fe1a1b57 | ||
|
|
860d596c3b | ||
|
|
b909013058 | ||
|
|
f979c606fe | ||
|
|
4a50b2eb6a | ||
|
|
f3ae67473b | ||
|
|
9d32b65a82 | ||
|
|
e57126af4f | ||
|
|
8d1c30ad17 | ||
|
|
ecab0edad1 | ||
|
|
d42842ba25 | ||
|
|
c1659a1c5e | ||
|
|
4a560c0b1c | ||
|
|
891189bbf3 | ||
|
|
01ae037205 | ||
|
|
f53caa93b6 | ||
|
|
c8679b0c79 | ||
|
|
7bc4ac1833 | ||
|
|
c03a5a4443 | ||
|
|
7e1e0e362e | ||
|
|
4a930e7966 | ||
|
|
0307950dc6 | ||
|
|
6d9ba007e5 | ||
|
|
15abfe61ec | ||
|
|
4734d53322 | ||
|
|
71b256aad5 | ||
|
|
e5c4e450c0 | ||
|
|
857b692aac | ||
|
|
738353a0e7 | ||
|
|
4a6e915ebd | ||
|
|
004ed83689 | ||
|
|
4ea123a2c0 | ||
|
|
c8828b8a42 | ||
|
|
3ae6938d1f | ||
|
|
be2ff98f25 | ||
|
|
0357a18cea | ||
|
|
e4e7bdebc6 | ||
|
|
eff2c0beb7 | ||
|
|
fceb9d4145 | ||
|
|
447c13592f | ||
|
|
0afd304949 | ||
|
|
a3d1dc6cf9 | ||
|
|
2fe67ada97 | ||
|
|
949a7a618f | ||
|
|
6034df36b8 | ||
|
|
ea67216bf2 | ||
|
|
38f66917ae | ||
|
|
1e3ac5fff7 | ||
|
|
792a1cb2ab | ||
|
|
5ead25829f | ||
|
|
8cf78ddf00 | ||
|
|
4ae488b25b | ||
|
|
dc6d9e2e4b | ||
|
|
14d18d27b1 | ||
|
|
7b51ccd9e4 | ||
|
|
ce8e9b96ca | ||
|
|
a5982579ac | ||
|
|
46c0a32357 | ||
|
|
21bccce4a1 | ||
|
|
d868124c36 | ||
|
|
bd1ead2237 | ||
|
|
689bf7fbc5 | ||
|
|
25f9a1339f | ||
|
|
bbc0a8d534 | ||
|
|
22492b5707 | ||
|
|
55da8fda74 | ||
|
|
661a63cc45 | ||
|
|
f5700f2b4c | ||
|
|
a5c258ac32 | ||
|
|
a0654b4643 | ||
|
|
adf59ddce7 | ||
|
|
438f25214c | ||
|
|
6902fa34bb | ||
|
|
5cbc08a6a2 | ||
|
|
79c63d1a4f | ||
|
|
01bd0d6760 | ||
|
|
bc7fb96184 | ||
|
|
03b8e21f23 | ||
|
|
68060d636d | ||
|
|
bf04aa3927 | ||
|
|
732a3116ff | ||
|
|
6e9b23c8e2 | ||
|
|
c4570a1387 | ||
|
|
3843751c58 | ||
|
|
ca944f280f | ||
|
|
b140181257 | ||
|
|
4eedf4d1cd | ||
|
|
37cc61e6a3 | ||
|
|
d1ca9c2d51 | ||
|
|
57395ed05c | ||
|
|
8d52a6cc7a | ||
|
|
2206fed7e4 | ||
|
|
67fc68683d | ||
|
|
fb2141382f | ||
|
|
c11c5a866d | ||
|
|
f86754f437 | ||
|
|
b3909b4af5 | ||
|
|
29738cc6f6 | ||
|
|
ee024b34da | ||
|
|
f422493694 | ||
|
|
071fde11d2 | ||
|
|
5c81aba90e | ||
|
|
6007a31380 | ||
|
|
c7a11eea4c | ||
|
|
be6c3ac662 | ||
|
|
9a54e09d15 | ||
|
|
f07c7aea2f | ||
|
|
cba6524926 | ||
|
|
1992516be9 | ||
|
|
cb71fb6907 | ||
|
|
33e7167090 | ||
|
|
f10474548b | ||
|
|
9bfbbd65f5 | ||
|
|
813191beef | ||
|
|
9e45baae58 | ||
|
|
c591922ae6 | ||
|
|
c89d06df18 | ||
|
|
97dca71c2c | ||
|
|
eaec3279ab | ||
|
|
195c313628 | ||
|
|
eb62d6368b | ||
|
|
4655a8504d | ||
|
|
44e4ae2d94 | ||
|
|
5fa5be2136 | ||
|
|
3e83402470 | ||
|
|
e7c2998cf9 | ||
|
|
9ef3dcd581 | ||
|
|
8cfd26c21e | ||
|
|
2d88469761 | ||
|
|
f3e53a108b | ||
|
|
a2436bc50b | ||
|
|
cd56ea7040 | ||
|
|
7efa672976 | ||
|
|
0856854c81 | ||
|
|
488f9653e6 | ||
|
|
48467bc514 | ||
|
|
56f7a5baae | ||
|
|
ee5a1f0e7a | ||
|
|
625bcf105c | ||
|
|
3e3ea37aba | ||
|
|
5049cc6e1d | ||
|
|
b142145a4e | ||
|
|
7eb3056856 | ||
|
|
d8e9c16d83 | ||
|
|
a58db791e1 | ||
|
|
fa2cfe36d4 | ||
|
|
b8c9880a2e | ||
|
|
3b4e7b0e5f | ||
|
|
ed27ef4cee | ||
|
|
1e2b7e728d | ||
|
|
1e9fbd216f | ||
|
|
139cd337a3 | ||
|
|
531d49fa00 | ||
|
|
b17c9a067a | ||
|
|
4d67a4a811 | ||
|
|
c286fdc96a | ||
|
|
b65caf82b4 | ||
|
|
25bd04e400 | ||
|
|
9944d136e4 | ||
|
|
816db26a75 | ||
|
|
25815ae53d | ||
|
|
ea61d00cf7 | ||
|
|
f15576fd98 | ||
|
|
6b64702054 | ||
|
|
0887d544ce | ||
|
|
af57d67320 | ||
|
|
4d460109dd | ||
|
|
10288f87c1 | ||
|
|
05bfe0a7b2 | ||
|
|
6e521af3b3 | ||
|
|
d833cc9c54 | ||
|
|
4e0d926f61 | ||
|
|
9e4ce3ae72 | ||
|
|
7a8e6f8e8c | ||
|
|
e137d63886 | ||
|
|
5e16ef73f9 | ||
|
|
9e4495b85b | ||
|
|
b5e1c8e47b | ||
|
|
36a05831ab | ||
|
|
12b895f94a | ||
|
|
e89015649e | ||
|
|
86fc7841b8 | ||
|
|
76e920fc1a | ||
|
|
99591a2b0f | ||
|
|
770b70a135 | ||
|
|
6845ef6bde | ||
|
|
d4609762bb | ||
|
|
ebf63a75d5 | ||
|
|
3effbe5f06 | ||
|
|
c742433d34 | ||
|
|
bd33b53805 | ||
|
|
1d6739b683 | ||
|
|
e75baed4b6 | ||
|
|
55f73d34e1 | ||
|
|
557157c2d6 | ||
|
|
0bae35d387 | ||
|
|
c7062bc560 | ||
|
|
a344352365 | ||
|
|
33d86ad3b5 | ||
|
|
8bacde0262 | ||
|
|
87c82071c0 | ||
|
|
1f72810649 | ||
|
|
6711095dd6 | ||
|
|
e39a42464e | ||
|
|
515674b6cf | ||
|
|
37cc63e493 | ||
|
|
4cd43f9c93 | ||
|
|
691d83e596 | ||
|
|
4bca25d783 | ||
|
|
74a5bcb3a9 | ||
|
|
9f55159bd5 | ||
|
|
f118082f6b | ||
|
|
586e9f328f | ||
|
|
fb9d52a19b | ||
|
|
815a7b6e1d | ||
|
|
336d889034 | ||
|
|
bba7479688 | ||
|
|
46a532540c | ||
|
|
1442c47bbb | ||
|
|
bb4e0be5f4 | ||
|
|
33aa182757 | ||
|
|
7bd8ace1a2 | ||
|
|
d9f4166418 | ||
|
|
02128618b0 | ||
|
|
f5cd841056 | ||
|
|
804e054bf8 | ||
|
|
3eebfdd349 | ||
|
|
581ff5fc73 | ||
|
|
3c50ffa18e | ||
|
|
4af7a1896c | ||
|
|
e1df1e7350 | ||
|
|
e156cc04c0 | ||
|
|
e0011d8372 | ||
|
|
0da777683f | ||
|
|
39eb5a50ab | ||
|
|
c04a7af39a | ||
|
|
67740a00bd | ||
|
|
6fada51fe8 | ||
|
|
eec2db0590 | ||
|
|
26316d8d76 | ||
|
|
6ea545df05 | ||
|
|
7674059899 | ||
|
|
c1f363fde2 | ||
|
|
ab2d174a0b | ||
|
|
6635540a6d | ||
|
|
a792858793 | ||
|
|
5f6f830d77 | ||
|
|
ba77125052 | ||
|
|
48b44efd67 | ||
|
|
4d9312259c | ||
|
|
7ede1ec4b0 | ||
|
|
b80d97dc38 | ||
|
|
6ee834279d | ||
|
|
c37fb0917f | ||
|
|
9d3986e06e | ||
|
|
dbcc1f4535 | ||
|
|
6c2b37c595 | ||
|
|
b338cc88fb | ||
|
|
58c5f7e373 | ||
|
|
47d188541b | ||
|
|
eb704d6420 | ||
|
|
3d9503658b | ||
|
|
5a1ffbc904 | ||
|
|
14f3a356e8 | ||
|
|
60b75b91bd | ||
|
|
4fa4737982 | ||
|
|
48c777be11 | ||
|
|
84a50beefc | ||
|
|
ab7908e012 | ||
|
|
388e0fe845 | ||
|
|
60b632418f | ||
|
|
89c81bd88b | ||
|
|
99b9b99343 | ||
|
|
0b5dbd6f5c | ||
|
|
726673f926 | ||
|
|
6a522b381c | ||
|
|
1882d263b9 | ||
|
|
b0683f77c2 | ||
|
|
7aceabed07 | ||
|
|
11c51500b3 | ||
|
|
fa886231d3 | ||
|
|
5085dcf96f | ||
|
|
34bcb2b609 | ||
|
|
c608742b84 | ||
|
|
d33c0ed1b5 | ||
|
|
d34618003d | ||
|
|
a24854a3cc | ||
|
|
f1e30dfba2 | ||
|
|
7b75476c4a | ||
|
|
b7bd41942d | ||
|
|
78db90e4bf | ||
|
|
592ca9b5c4 | ||
|
|
9981394557 | ||
|
|
b100325fe0 | ||
|
|
0ddfb48a98 | ||
|
|
d6610b7f8f | ||
|
|
ea540569ed | ||
|
|
e91d19e132 | ||
|
|
bd281e5753 | ||
|
|
7c59f05681 | ||
|
|
6dcde9fcbe | ||
|
|
cc048e55bf | ||
|
|
dd556b44e8 | ||
|
|
c62145af31 | ||
|
|
9148dc9e03 | ||
|
|
606824d282 | ||
|
|
231ca8a935 | ||
|
|
c96221c705 | ||
|
|
19f46eb817 | ||
|
|
185d53da6a | ||
|
|
07c1071c36 | ||
|
|
a9d0453811 | ||
|
|
54ef217de4 | ||
|
|
0ebfa89783 | ||
|
|
2a8b155a16 | ||
|
|
dd814d1591 | ||
|
|
1ba9ff8153 | ||
|
|
1121b81f12 | ||
|
|
f7fbe3946d | ||
|
|
921bfbbe3c | ||
|
|
bca3cb8303 | ||
|
|
fb03687802 | ||
|
|
c0e6a85ffd | ||
|
|
7f723a6bd5 | ||
|
|
02bc2e3ddb | ||
|
|
3c8e448ffb | ||
|
|
7885153933 | ||
|
|
f5161404cb | ||
|
|
a668ac7235 | ||
|
|
2610a286ca | ||
|
|
6daa065b1e | ||
|
|
1b873d3bad | ||
|
|
a0cfae214d | ||
|
|
db0af86085 | ||
|
|
be2f7cb3e5 | ||
|
|
082cb86a23 | ||
|
|
0420144104 | ||
|
|
22656c8699 | ||
|
|
c1c78164d2 | ||
|
|
08f1f05d58 | ||
|
|
c40b67fe77 | ||
|
|
81ebcc9a72 | ||
|
|
9ccc7feb58 | ||
|
|
7706adc444 | ||
|
|
7c76f7443e | ||
|
|
314ef361b6 | ||
|
|
ef401a1a2c | ||
|
|
a0877e484d | ||
|
|
067e0220bd | ||
|
|
da6481f96b | ||
|
|
7dea0441ac | ||
|
|
34c41d5f3d | ||
|
|
77d8dce81c | ||
|
|
d3058cbe07 | ||
|
|
587bab3eb1 | ||
|
|
a36a38bd8d | ||
|
|
629a6936fa | ||
|
|
4e7e50754d | ||
|
|
0288bc681b | ||
|
|
d46e3f07c3 | ||
|
|
d512ab5ddf | ||
|
|
2a052b2db1 | ||
|
|
3ada6d1bff | ||
|
|
86030a0fab | ||
|
|
954c40067e | ||
|
|
6a36606bd5 | ||
|
|
20a72a0f45 | ||
|
|
bcc374eb31 | ||
|
|
f0e1f18c79 | ||
|
|
61b7203062 | ||
|
|
a7e95d00cf | ||
|
|
83c358deb1 | ||
|
|
7dd214f3db | ||
|
|
6698d33f04 | ||
|
|
6dcd5b77aa | ||
|
|
80f2c797c9 | ||
|
|
910471a26f | ||
|
|
ccab588948 | ||
|
|
50683e6600 | ||
|
|
75daf98112 | ||
|
|
9a681a27ad | ||
|
|
25c63c8b10 | ||
|
|
a069df41b8 | ||
|
|
b1183c2c9d | ||
|
|
b777b15ee8 | ||
|
|
35061dfc53 | ||
|
|
a65bca6e49 | ||
|
|
72203f2721 | ||
|
|
03ff03ed52 | ||
|
|
488d50b97e | ||
|
|
88cbd1bd83 | ||
|
|
27fe556bab | ||
|
|
3191b7a991 | ||
|
|
f8d045c275 | ||
|
|
0038fe5ff1 | ||
|
|
3ae810a18e | ||
|
|
afe72c8029 | ||
|
|
2341bba973 | ||
|
|
c0da968af2 | ||
|
|
03fb04f4c5 | ||
|
|
d71c4a0ea7 | ||
|
|
df206d9792 | ||
|
|
49ad44dcaf | ||
|
|
7f785b8fa5 | ||
|
|
b4e674aeb0 | ||
|
|
8ed091703f | ||
|
|
464fd6d4d3 | ||
|
|
a96dfdda67 | ||
|
|
5b140d26c3 | ||
|
|
125fb81fa3 | ||
|
|
ee14372e20 | ||
|
|
5c27e0f9ef | ||
|
|
7607cec7a2 | ||
|
|
5f9c93369e | ||
|
|
9e4132fd3f | ||
|
|
0ae31e0acc | ||
|
|
24721cf2fa | ||
|
|
2ab41a359e | ||
|
|
c87167cac4 | ||
|
|
46311dfaba | ||
|
|
03720bbb81 | ||
|
|
3319fd6a21 | ||
|
|
0f75387f41 | ||
|
|
9fd5d8241e | ||
|
|
0bfee823dd | ||
|
|
668b235b07 | ||
|
|
ea6d0f573d | ||
|
|
d1b8afd3b8 | ||
|
|
0f8b9ca55b | ||
|
|
b5c84a91fb | ||
|
|
cc902db4ab | ||
|
|
faae82eae1 | ||
|
|
49ac0cadfb | ||
|
|
bd5f39e1c6 | ||
|
|
325d048340 | ||
|
|
f1805c8536 | ||
|
|
305545623a | ||
|
|
aac99f6ee2 | ||
|
|
4feea2e721 | ||
|
|
0e73b3b8e1 | ||
|
|
4b0bcf4464 | ||
|
|
57ef0ad41d | ||
|
|
a92d6b75bf | ||
|
|
763da979a8 | ||
|
|
8c58f7a04e | ||
|
|
e1868bdb78 | ||
|
|
f279368531 | ||
|
|
ed72ddc4d3 | ||
|
|
a7fa34c2fc | ||
|
|
51c734e438 | ||
|
|
ad676af3f0 | ||
|
|
1251353694 | ||
|
|
4d97023938 | ||
|
|
adf77053c5 | ||
|
|
9c57888524 | ||
|
|
dd33dc1f9b | ||
|
|
90ed6163f5 | ||
|
|
8f162cd57c | ||
|
|
e7e4bf39fe | ||
|
|
d9341e033b | ||
|
|
bf7d4ebea5 | ||
|
|
8d4a4dc526 | ||
|
|
2a3a0c758a | ||
|
|
94eb7b155e | ||
|
|
50f12869bf | ||
|
|
c81c79ad52 | ||
|
|
f2f6f2f5a8 | ||
|
|
2e2afa616d | ||
|
|
d82a7040f1 | ||
|
|
8fc97a7f91 | ||
|
|
5789c1ae7d | ||
|
|
520a89f5f6 | ||
|
|
15379384dd | ||
|
|
4cc44b37bb | ||
|
|
e121fec599 | ||
|
|
6c669abb23 | ||
|
|
622c4f9f6f | ||
|
|
b7316353f4 | ||
|
|
902a2723ae | ||
|
|
57f3c67e28 | ||
|
|
6a2bc1ef2b | ||
|
|
0b677677d1 | ||
|
|
41f9f96819 | ||
|
|
49f9fee446 | ||
|
|
9588c1ea3e | ||
|
|
c665b01e89 | ||
|
|
5c2db0134f | ||
|
|
de162eb719 | ||
|
|
33297e0226 | ||
|
|
a07e643020 | ||
|
|
304664b318 | ||
|
|
8372a3c7ca | ||
|
|
69bbc0a2a1 | ||
|
|
5bfe881fc8 | ||
|
|
44f691bea4 | ||
|
|
e59db45f5b | ||
|
|
f4087694b1 | ||
|
|
2c63e0fdd6 | ||
|
|
29bb71373e | ||
|
|
ed48858635 | ||
|
|
6f5c8389eb | ||
|
|
52bd72f449 | ||
|
|
b82f26366c | ||
|
|
758057131b | ||
|
|
e37adcd67e | ||
|
|
4e08656422 | ||
|
|
d10e70a77b | ||
|
|
0aa80f1459 | ||
|
|
26732265f0 | ||
|
|
c214c6c120 | ||
|
|
485eb60dde | ||
|
|
7e5e029559 | ||
|
|
116fd7b829 | ||
|
|
1a2b46f00c | ||
|
|
557509ef84 | ||
|
|
56f1c53084 | ||
|
|
afefee2357 | ||
|
|
bfeb1693d6 | ||
|
|
3f82b05f4f | ||
|
|
1fca80e27d | ||
|
|
7928bede1e | ||
|
|
3e62300f9c | ||
|
|
49c9eaa6e1 | ||
|
|
58db8a838a | ||
|
|
5509c65a6f | ||
|
|
fb3ba8bf92 | ||
|
|
667bda6afb | ||
|
|
a381e9aa3b | ||
|
|
32dc3b36ab | ||
|
|
190f02a939 | ||
|
|
aa2027f1b5 | ||
|
|
f665da9348 | ||
|
|
fdc2baab2b | ||
|
|
f4fc0e17da | ||
|
|
b5389cadc8 | ||
|
|
3641869332 | ||
|
|
d570a55ce6 | ||
|
|
fe77e05aff | ||
|
|
906ad8c7c1 | ||
|
|
e5d0a68d70 | ||
|
|
a17adfe366 | ||
|
|
ff158282e7 | ||
|
|
5df8abcddf | ||
|
|
3fad8479ca | ||
|
|
c7da922383 | ||
|
|
c4e2627b43 | ||
|
|
60968a926f | ||
|
|
93001377bf | ||
|
|
b912116a2f | ||
|
|
5899b0f1e4 | ||
|
|
e6e54822f5 | ||
|
|
db5adef813 | ||
|
|
adb8127a30 | ||
|
|
a4d2b8862b | ||
|
|
ad153c226e | ||
|
|
39ce0af4bf | ||
|
|
2e132e47e4 | ||
|
|
8b2cd11e9f | ||
|
|
a69f7c9dfd | ||
|
|
671ac562e7 | ||
|
|
89cb4bbb8c | ||
|
|
a91f8c4d51 | ||
|
|
8ea614266c | ||
|
|
1c0ba24e48 | ||
|
|
3d4b3bd089 | ||
|
|
31783c0d0a | ||
|
|
d244affa6c | ||
|
|
82a999e6e9 | ||
|
|
74fdb728b4 | ||
|
|
be6a53b3eb | ||
|
|
ff00af60ae | ||
|
|
ccabd09742 | ||
|
|
f784729e67 | ||
|
|
9771e956f4 | ||
|
|
5bd209aded | ||
|
|
a9554779ea | ||
|
|
fc90ad5949 | ||
|
|
3f7765fdc8 | ||
|
|
ee58871f65 | ||
|
|
b2b6472222 | ||
|
|
1c8fb4139d | ||
|
|
50057ce9c8 | ||
|
|
51dd7c9abd | ||
|
|
f250cd246c | ||
|
|
0b871b3fa5 | ||
|
|
e00a95bf02 | ||
|
|
2d3b7da4cd | ||
|
|
5083128774 | ||
|
|
e2d1b19216 | ||
|
|
e2287fae58 | ||
|
|
ef519ac5ff | ||
|
|
e7d978e027 | ||
|
|
b6d4442800 | ||
|
|
895e3931bd | ||
|
|
27ff33f93b | ||
|
|
a987425f4a | ||
|
|
971d2dfc31 | ||
|
|
5bb99f941c | ||
|
|
86334452c0 | ||
|
|
8c224878dc | ||
|
|
603db8ce6a | ||
|
|
d4b64ba26b | ||
|
|
0f0a3474fd | ||
|
|
b1de2b1a4a | ||
|
|
87ed178e27 | ||
|
|
5bae4dbf9d | ||
|
|
89eb5b7eb9 | ||
|
|
fbd30dc4ee | ||
|
|
fb9f72fc90 | ||
|
|
30558764ba | ||
|
|
fe2aaa81ca | ||
|
|
b38351a470 | ||
|
|
1d47cadae8 | ||
|
|
47cb9e8e44 | ||
|
|
ac10d25f5f | ||
|
|
597a0f21e0 | ||
|
|
4c15a83e9c | ||
|
|
2df8b234fe | ||
|
|
d852a51672 | ||
|
|
5ec8d943a3 | ||
|
|
9b4a5523cc | ||
|
|
70a4d38d04 | ||
|
|
0ad8576ae5 | ||
|
|
e712883ce1 | ||
|
|
c0f9b33bba | ||
|
|
6de76ea5d1 | ||
|
|
262e72d541 | ||
|
|
2f765529e5 | ||
|
|
bcea92e313 | ||
|
|
56ef849868 | ||
|
|
2a0c4d2b0d | ||
|
|
d4ad9b3778 | ||
|
|
df972b9ae9 | ||
|
|
f695559379 | ||
|
|
3fa7828324 | ||
|
|
dbe17b4b16 | ||
|
|
ee4df2806f | ||
|
|
a405f2e81e | ||
|
|
afc0bc9323 | ||
|
|
ce28dcc630 | ||
|
|
892830e125 | ||
|
|
75425ab1a9 | ||
|
|
2722847a59 | ||
|
|
641f84e9f8 | ||
|
|
1f0a5842f9 | ||
|
|
28c2fb92a8 | ||
|
|
715101cf5e | ||
|
|
ac37a44ffa | ||
|
|
ae3d2bebbe | ||
|
|
f8d4e1a307 | ||
|
|
b98d6984a1 | ||
|
|
8f5c9a3c72 | ||
|
|
e071393eb5 | ||
|
|
6f9fec658f | ||
|
|
9227964cb6 | ||
|
|
cf6056cede | ||
|
|
4397612349 | ||
|
|
cf3719a663 | ||
|
|
77bf35d728 | ||
|
|
e7addec0a1 | ||
|
|
243d61d95f | ||
|
|
028874fd05 | ||
|
|
6d366fe80f | ||
|
|
0924f767e9 | ||
|
|
173b5a1cd1 | ||
|
|
49e1d51be9 | ||
|
|
23e47a74ee | ||
|
|
fce7f6ce47 | ||
|
|
f3b47a16dd | ||
|
|
aa7b754693 | ||
|
|
397b13e2d8 | ||
|
|
b2c203e8c1 | ||
|
|
6afb314d26 | ||
|
|
28123355b4 | ||
|
|
bcb87f5d55 | ||
|
|
981c1c1263 | ||
|
|
67b9a3bc0e | ||
|
|
ab4914ee6a | ||
|
|
e7c73c76dd | ||
|
|
3591a3fe5c | ||
|
|
fbdce049b2 | ||
|
|
9a8520a2de | ||
|
|
a315ab29bc | ||
|
|
5437d691b5 | ||
|
|
f99c90dc85 | ||
|
|
d838388443 | ||
|
|
0b2c488a61 | ||
|
|
e2eb4ef29d | ||
|
|
76e135077b | ||
|
|
6078cd2eab | ||
|
|
3482dade71 | ||
|
|
ff73de5716 | ||
|
|
04d0c350db | ||
|
|
b6a5c91045 | ||
|
|
7a37c79ebc | ||
|
|
ba227c5ec3 | ||
|
|
7ab75dd15a | ||
|
|
df23162e9d | ||
|
|
2c12f18b44 | ||
|
|
eaeb28b4e1 | ||
|
|
d5647eab33 | ||
|
|
89eb8885b1 | ||
|
|
a5dc5687f8 | ||
|
|
6780485051 | ||
|
|
d043e7a242 | ||
|
|
c5d9b5f51d | ||
|
|
35e2892b98 | ||
|
|
b492c5ac1a | ||
|
|
df38b3c62a | ||
|
|
03a860dd6f | ||
|
|
fec585e44b | ||
|
|
11dfdbb7a3 | ||
|
|
ae1a0f411b | ||
|
|
007b5d7f50 | ||
|
|
c6eadc504b | ||
|
|
a864258cb8 | ||
|
|
8a9c15c874 | ||
|
|
7a666526b7 | ||
|
|
3fc1cac015 | ||
|
|
04a0b07bf6 | ||
|
|
59e48ca91a | ||
|
|
8ff562c5af | ||
|
|
b502a93728 | ||
|
|
b6afa6c2c7 | ||
|
|
5887da0229 | ||
|
|
a7d833d96a | ||
|
|
db3753d611 | ||
|
|
f810b13bca | ||
|
|
5ad687c6d8 | ||
|
|
6ad0910790 | ||
|
|
4d8c0546cf | ||
|
|
35f96d4a40 | ||
|
|
ae96fb6f63 | ||
|
|
67592d80aa | ||
|
|
94a5e43e5d | ||
|
|
26958f8f70 | ||
|
|
a427d215e3 | ||
|
|
271cf37b8a | ||
|
|
179c03e79d | ||
|
|
0a1b68639b | ||
|
|
d69e7ec850 | ||
|
|
76a6d8292c | ||
|
|
8f09c444b6 | ||
|
|
9032e6abb8 | ||
|
|
1c070d16a6 | ||
|
|
7837fcc657 | ||
|
|
f9690d40d3 | ||
|
|
5de6cd77dc | ||
|
|
aa5ab55b14 | ||
|
|
9195b18981 | ||
|
|
b812d6efb8 | ||
|
|
231a02eb10 | ||
|
|
6736806361 | ||
|
|
8e17756bf8 | ||
|
|
0b133fe55e | ||
|
|
d01266c642 | ||
|
|
fe3f9c86d5 | ||
|
|
14bf3645d6 | ||
|
|
0f4a7b2405 | ||
|
|
681e49a4cc | ||
|
|
6e9c97fbff | ||
|
|
370070f489 | ||
|
|
7168f4014d | ||
|
|
f0912feefb | ||
|
|
e90c9c171a | ||
|
|
d0c172830c | ||
|
|
d5bf0d1199 | ||
|
|
d3a24446b8 | ||
|
|
aa93276e6e | ||
|
|
cf36972969 | ||
|
|
40862f26e6 | ||
|
|
4083447c3f | ||
|
|
3cb34ad827 | ||
|
|
61d7566ca1 | ||
|
|
af338d447b | ||
|
|
6fad06f659 | ||
|
|
1d51d8ff27 | ||
|
|
82dd4aa403 | ||
|
|
8af9bd1ac3 | ||
|
|
9fc3845d92 | ||
|
|
93bbe8e7a8 | ||
|
|
46acd16999 | ||
|
|
5ad2c6abf6 | ||
|
|
d5781d60bd | ||
|
|
e464a95c5a | ||
|
|
a50ea4bb9e | ||
|
|
aa11bb6d93 | ||
|
|
319018f055 | ||
|
|
394b986ccb | ||
|
|
26f7b36ce4 | ||
|
|
f0daad10ce | ||
|
|
0bc557fb8b | ||
|
|
3571421a0e | ||
|
|
aed80f3e4f | ||
|
|
b84e79362e | ||
|
|
dc077bc309 | ||
|
|
0fd634ef43 | ||
|
|
d352b6b509 | ||
|
|
fcc48cc738 | ||
|
|
ec06a345cc | ||
|
|
7690b364e7 | ||
|
|
b94c0c7d04 | ||
|
|
500bfdf588 | ||
|
|
d23b19c466 | ||
|
|
3a5450039d | ||
|
|
b582ddf090 | ||
|
|
ef8b470e8b | ||
|
|
5a0841a994 | ||
|
|
bd462c4e0b | ||
|
|
f11ec4e142 | ||
|
|
a5393a3ec4 | ||
|
|
bf76da3222 | ||
|
|
f171b7de96 | ||
|
|
c0cbf00199 | ||
|
|
0cd6e59fb9 | ||
|
|
11a8adc71c | ||
|
|
b9c7fd879f | ||
|
|
2fc4c7ea33 | ||
|
|
c5003665c3 | ||
|
|
538028c150 | ||
|
|
fb8d187f8d | ||
|
|
1a11301e1a | ||
|
|
4c6cdd5c23 | ||
|
|
30a64b0dd3 | ||
|
|
04de492019 | ||
|
|
07890df6cb | ||
|
|
2f23cfdf1c | ||
|
|
1832946d41 | ||
|
|
6ec8745d2e | ||
|
|
b6bbfe063b | ||
|
|
48182edbd5 | ||
|
|
94a00cb6d6 | ||
|
|
fc24361aa6 | ||
|
|
cec833afc6 | ||
|
|
f1cddba938 | ||
|
|
a0acdfdcb9 | ||
|
|
6637f294df | ||
|
|
ad8a444105 | ||
|
|
877cfa0071 | ||
|
|
e6f0a780b7 | ||
|
|
dd9de2efa9 | ||
|
|
f6b0811f78 | ||
|
|
eba9d854a9 | ||
|
|
437cf9bab0 | ||
|
|
fdaeccf1e5 | ||
|
|
7723e46c26 | ||
|
|
dce355cce6 | ||
|
|
213e7b7093 | ||
|
|
fe7d8f93a1 | ||
|
|
9e2f4216f9 | ||
|
|
a48f7b2222 | ||
|
|
0b85d8a9bc | ||
|
|
58d6938065 | ||
|
|
a536a2b822 | ||
|
|
9ffad1005e | ||
|
|
65edddd62e | ||
|
|
a7cdcd8b3a | ||
|
|
3d6b85ed20 | ||
|
|
7abea2020c | ||
|
|
e16c34f0e3 | ||
|
|
4bfda6a145 | ||
|
|
98470e8551 | ||
|
|
df558ab8d6 | ||
|
|
c07372b58c | ||
|
|
00f59b95ae | ||
|
|
8915a7c2cd | ||
|
|
8595964ab8 | ||
|
|
922dae8546 | ||
|
|
69b3e23400 | ||
|
|
55325773dc | ||
|
|
b84c915b23 | ||
|
|
cfb390936a | ||
|
|
c5f344f333 | ||
|
|
ba4b496306 | ||
|
|
c48554589c | ||
|
|
da0851e21d | ||
|
|
d2d05abac0 | ||
|
|
de3e0423cc | ||
|
|
8d742d7938 | ||
|
|
682fd550fa | ||
|
|
abcf836a0c | ||
|
|
b123fb2cc7 | ||
|
|
0da3621a68 | ||
|
|
8ed452d9ea | ||
|
|
f380d44697 | ||
|
|
86d377a2f0 | ||
|
|
508a6d99f5 | ||
|
|
63e42047e3 | ||
|
|
769be46bf9 | ||
|
|
13829de0d9 | ||
|
|
ad7f570be5 | ||
|
|
9ba4f966db | ||
|
|
ae8d2ac2e1 | ||
|
|
93beb068a3 | ||
|
|
e88d260acd | ||
|
|
8121238872 | ||
|
|
161e377ec1 | ||
|
|
ad4bd800aa | ||
|
|
2fba6f65f4 | ||
|
|
a754ab4f10 | ||
|
|
86cfc468bd | ||
|
|
7df0c1607e | ||
|
|
6acd36e374 | ||
|
|
af51eecbac | ||
|
|
3a23dc8b04 | ||
|
|
ba13e44720 | ||
|
|
e80420f6db | ||
|
|
21ddcfc866 | ||
|
|
20f82cb22c | ||
|
|
7ef75bab23 | ||
|
|
7224e03590 | ||
|
|
cf4f2991a5 | ||
|
|
9eb3c23494 | ||
|
|
c80d8898cc | ||
|
|
bc74dd88e0 | ||
|
|
da87c461ef | ||
|
|
bf2e694f2c | ||
|
|
e5150487c4 | ||
|
|
9ff6353b88 | ||
|
|
926fd8abf4 | ||
|
|
211a7a4cfe | ||
|
|
c1835cd9cc | ||
|
|
5700044393 | ||
|
|
36fbd3d018 | ||
|
|
d1178390a9 | ||
|
|
8182825e92 | ||
|
|
2392006246 | ||
|
|
a6e78cd5dc | ||
|
|
8752790352 | ||
|
|
3976c79e12 | ||
|
|
5c1cf7f4ac | ||
|
|
7e90b8b7be | ||
|
|
912321a030 | ||
|
|
ab0a905499 | ||
|
|
3c6b3c02df | ||
|
|
bcb2e91d97 | ||
|
|
766ef94605 | ||
|
|
e3f016e262 | ||
|
|
65833f1ae0 | ||
|
|
2602cd9ab2 | ||
|
|
8333f3d9de | ||
|
|
dee1d9ba74 | ||
|
|
ed2e0c5080 | ||
|
|
7db810d7d0 | ||
|
|
8dae4e5038 | ||
|
|
b9b28edefe | ||
|
|
58120f435f | ||
|
|
027b8e52da | ||
|
|
aad510a9d5 | ||
|
|
9852a805a1 | ||
|
|
b2cabf0122 | ||
|
|
521ce15f86 | ||
|
|
fb97c11140 | ||
|
|
1c5c62e311 | ||
|
|
77148f7f97 | ||
|
|
a329d2f2bc | ||
|
|
39e9e4446b | ||
|
|
b32de54944 | ||
|
|
071b874e1b | ||
|
|
9ba65d3323 | ||
|
|
890a851bbf | ||
|
|
5f6ca23da4 | ||
|
|
58df1c06ee | ||
|
|
95f8599dc2 | ||
|
|
8a11242d7f | ||
|
|
948513ef5f | ||
|
|
c497a35d21 | ||
|
|
e0a539bc64 | ||
|
|
44b8395ead | ||
|
|
1bc8878490 | ||
|
|
ded2ac493d | ||
|
|
57b3319ac0 | ||
|
|
eba7ba25b8 | ||
|
|
df774892c8 | ||
|
|
f3b4ce6b67 | ||
|
|
bb8545b3e1 | ||
|
|
600149fc2b | ||
|
|
f4de3c8748 | ||
|
|
6e7e04839f | ||
|
|
f62dcc12a0 | ||
|
|
bef591c2e6 | ||
|
|
5907296d36 | ||
|
|
aa2a7d12be | ||
|
|
33fee5dcc5 | ||
|
|
e9ae50be0c | ||
|
|
5886c0fd5e | ||
|
|
ed146fcf07 | ||
|
|
35538e6f77 | ||
|
|
ea924f3bbf | ||
|
|
7bc15a2fc9 | ||
|
|
2bf7db92ee | ||
|
|
95260f56ba | ||
|
|
c5ace0376a | ||
|
|
7ee09388fa | ||
|
|
a15b0ef060 | ||
|
|
57cfd9a315 | ||
|
|
5fb4149c32 | ||
|
|
03d97ba617 | ||
|
|
5205f5f4b4 | ||
|
|
6eda0f4d00 | ||
|
|
9e640cac6b | ||
|
|
061521f87f | ||
|
|
b15eb278e1 | ||
|
|
142ac8eb96 | ||
|
|
88705bb6e9 | ||
|
|
60d4fcfe7e | ||
|
|
038d19ec98 | ||
|
|
e1b98768c7 | ||
|
|
b82af2b849 | ||
|
|
703591d76a | ||
|
|
7142688a77 | ||
|
|
a12622b3d8 | ||
|
|
9248ab4dfd | ||
|
|
5a8c6440f0 | ||
|
|
74b694a4dd | ||
|
|
896b52d5fb | ||
|
|
1429fea27a | ||
|
|
3218563f32 | ||
|
|
d412edbbe1 | ||
|
|
968159a85d | ||
|
|
18a3741fc2 | ||
|
|
f1be3e6bb0 | ||
|
|
b717a02394 | ||
|
|
d68143e63d | ||
|
|
0d306b8b1c | ||
|
|
a655863855 | ||
|
|
58264c80dd | ||
|
|
6f9f1aec65 | ||
|
|
97b1ee5b02 | ||
|
|
fe033cd0b3 | ||
|
|
afbd07c62a | ||
|
|
9b15996545 | ||
|
|
1dbbd7241d | ||
|
|
6c0ef48d45 | ||
|
|
8b57f88ca3 | ||
|
|
3e9fdc777e | ||
|
|
a8ca88797a | ||
|
|
71540b5dc0 | ||
|
|
b5a145d7b3 | ||
|
|
21d6a0a2dd | ||
|
|
80cc7340ac | ||
|
|
45b272ee2f | ||
|
|
f765664580 | ||
|
|
10b44f036d | ||
|
|
1bf4ee3a3c | ||
|
|
5d82ffa503 | ||
|
|
5dc3fd2ec0 | ||
|
|
4562fdda92 | ||
|
|
18258b9b0d | ||
|
|
92e0f242c7 | ||
|
|
428fa9404c | ||
|
|
3cccc480fb | ||
|
|
acb94216c8 | ||
|
|
5fa97841b2 | ||
|
|
4ad66bf7b9 | ||
|
|
64860ed5e5 | ||
|
|
b17faf6e1e | ||
|
|
0ea73bd527 | ||
|
|
b2f0820560 | ||
|
|
7ad5d42982 | ||
|
|
3912734498 | ||
|
|
0fa3f9a057 | ||
|
|
0fbabdcf25 | ||
|
|
67b7ae98a6 | ||
|
|
0f703c95dd | ||
|
|
c34b3f41bd | ||
|
|
e003b17280 | ||
|
|
e003d58c60 | ||
|
|
0546d06c0a | ||
|
|
5337111990 | ||
|
|
bb06f8eb0c | ||
|
|
23e3a1c269 | ||
|
|
e47740e02e | ||
|
|
d9ff0035f5 | ||
|
|
7a7f3be0d2 | ||
|
|
91e45fbe95 | ||
|
|
7d7e9da28c | ||
|
|
24a9739604 | ||
|
|
4fb9687782 | ||
|
|
95ffc21b60 | ||
|
|
f3c5e55b26 | ||
|
|
40183c6a5c | ||
|
|
457c59e38a | ||
|
|
aa93a3f2e2 | ||
|
|
8b9abcb6cc | ||
|
|
1ecc1908c7 | ||
|
|
6a2c7b467d | ||
|
|
0acef57865 | ||
|
|
43046ee649 | ||
|
|
a15fda0c08 | ||
|
|
e5988764ce | ||
|
|
9c9d9b5a8d | ||
|
|
44dc564d85 | ||
|
|
83e367afab | ||
|
|
8b7e7c2669 | ||
|
|
53474021b7 | ||
|
|
da1ed1b5b2 | ||
|
|
e08d661600 | ||
|
|
1aa1bc7a26 | ||
|
|
47634e942e | ||
|
|
15466cbf1a | ||
|
|
2a749db427 | ||
|
|
ecccce86e4 | ||
|
|
bf3f64bea4 | ||
|
|
2f2d6b8535 | ||
|
|
d68c884649 | ||
|
|
8b556de03b | ||
|
|
7229af53c3 | ||
|
|
81b3034c2f | ||
|
|
f0419396b5 | ||
|
|
6b9c2754e8 | ||
|
|
8edb131f8b | ||
|
|
d6f6520a79 | ||
|
|
cc2bb4d719 | ||
|
|
3859f1c9ae | ||
|
|
5f8d774e19 | ||
|
|
538a3e855c | ||
|
|
03f2ef1e2b | ||
|
|
237d0746cf | ||
|
|
33b6c58087 | ||
|
|
e96b023d04 | ||
|
|
7ac1d4621b | ||
|
|
a2d7cbe8fe | ||
|
|
c74ed29739 | ||
|
|
6c8501f122 | ||
|
|
941e945f74 | ||
|
|
f2844d59e4 | ||
|
|
047ff187f6 | ||
|
|
1136c40811 | ||
|
|
5a78dc864f | ||
|
|
15c98c3048 | ||
|
|
0a5b005ce5 | ||
|
|
4d64e64127 | ||
|
|
5470c70cd0 | ||
|
|
47959ee395 | ||
|
|
7c34c178cd | ||
|
|
ac7cb41483 | ||
|
|
0ab388b88e | ||
|
|
54448902f1 | ||
|
|
12107a02fd | ||
|
|
eace06efdc | ||
|
|
ee0afa1eec | ||
|
|
83cdd0dafe | ||
|
|
5be025f1d1 | ||
|
|
c651842ea1 | ||
|
|
423abe6788 | ||
|
|
4003c38fd1 | ||
|
|
3e0c322fd4 | ||
|
|
7fcdd4abdd | ||
|
|
3f3280b2d4 | ||
|
|
aae2399631 | ||
|
|
03bd2b6803 | ||
|
|
48754fd999 | ||
|
|
c496ebdef9 | ||
|
|
c009c40606 | ||
|
|
b29456c8e5 | ||
|
|
38266bf2ff | ||
|
|
c2e51f8948 | ||
|
|
c54a57838e | ||
|
|
64f040bddd | ||
|
|
1a099ea2f2 | ||
|
|
13c45807ef | ||
|
|
dfbb9d5fff | ||
|
|
a7fe369ea0 | ||
|
|
b62e6c5a69 | ||
|
|
92e29a6ad7 | ||
|
|
eeb9c69aa3 | ||
|
|
b7662ed5a1 | ||
|
|
9d6296f610 | ||
|
|
fd2a1320e0 | ||
|
|
8a8a6a4a82 | ||
|
|
8cdc14eec1 | ||
|
|
a1200b2fb5 | ||
|
|
c88c29eddc | ||
|
|
2845c4de98 | ||
|
|
bfa9cd15b7 | ||
|
|
659e2b414d | ||
|
|
7bcb58e3db | ||
|
|
2d7d7776a6 | ||
|
|
c5f429521c | ||
|
|
426d8636bc | ||
|
|
a265c7096e | ||
|
|
1c9953b1ba | ||
|
|
601cc21a44 | ||
|
|
102c42dfe4 | ||
|
|
4953727aa7 | ||
|
|
e6af874b47 | ||
|
|
801b4eef4c | ||
|
|
fe5c20a04e | ||
|
|
246fd05fae | ||
|
|
a09b298127 | ||
|
|
f89f40778f | ||
|
|
3d0c8d8d45 | ||
|
|
0e5e8bf14e | ||
|
|
ce34d329d3 | ||
|
|
eaf4a5805c | ||
|
|
8420e565d4 | ||
|
|
00df10c29a | ||
|
|
1b68deb0f6 | ||
|
|
d1497c9ac8 | ||
|
|
03d4cbf6d5 | ||
|
|
718be831af | ||
|
|
9d5ec523be | ||
|
|
81c43b45fb | ||
|
|
146a491769 | ||
|
|
4c53388579 | ||
|
|
3403ddcc6e | ||
|
|
684b81d835 | ||
|
|
4f32da57fd | ||
|
|
97265e48b3 | ||
|
|
64797158e2 | ||
|
|
8359293dcd | ||
|
|
b2dc53d18b | ||
|
|
edf8dd2a12 | ||
|
|
5a777bd598 | ||
|
|
bd39e01ee1 | ||
|
|
e3ed29aab6 | ||
|
|
896ce9c0e2 | ||
|
|
82934132e9 | ||
|
|
a2012b70de | ||
|
|
bcfeba8a57 | ||
|
|
d3dfd9ce57 | ||
|
|
aa06d5d356 | ||
|
|
448c8a29e1 | ||
|
|
928b7120f4 | ||
|
|
a3deacd718 | ||
|
|
78959fffbd | ||
|
|
1788616e52 | ||
|
|
c61e6d0777 | ||
|
|
41d91d628a | ||
|
|
a3bc7620b1 | ||
|
|
8064c588dc | ||
|
|
564e983c68 | ||
|
|
e1da181740 | ||
|
|
c63209200e | ||
|
|
737808cf53 | ||
|
|
a197bb7736 | ||
|
|
f9dd967bc5 | ||
|
|
44e4d55a66 | ||
|
|
095c84ac16 | ||
|
|
e063eae727 | ||
|
|
f02c5b5c69 | ||
|
|
838f1d645c | ||
|
|
ce2c30c437 | ||
|
|
d56fae0a7b | ||
|
|
e45ef00bef | ||
|
|
e9f31f7394 | ||
|
|
7c10a98eb2 | ||
|
|
f260483101 | ||
|
|
389e6e5c9e | ||
|
|
1cfd5866be | ||
|
|
c7ceac7f41 | ||
|
|
cd6eca0424 | ||
|
|
8c6136fea0 | ||
|
|
9644444028 | ||
|
|
9c4154291d | ||
|
|
533f5f6da6 | ||
|
|
1b8de756cd | ||
|
|
650b415537 | ||
|
|
04b50329fc | ||
|
|
25aab8c55c | ||
|
|
ceda2e70c1 | ||
|
|
2908303d4b | ||
|
|
a9f69711c6 | ||
|
|
a8ab16a720 | ||
|
|
8091b6b508 | ||
|
|
a00ef0fc7e | ||
|
|
5ce6d615a4 | ||
|
|
e06b69cdac | ||
|
|
d261ae7883 | ||
|
|
6fa77a63d7 | ||
|
|
f76c1b32d6 | ||
|
|
0aede2ef63 | ||
|
|
1e3a2e0a27 | ||
|
|
1bdabf43db | ||
|
|
05e568feb0 | ||
|
|
81e2519436 | ||
|
|
ef623c9bb5 | ||
|
|
da581525a6 | ||
|
|
6ff7b6570c | ||
|
|
8b2081837e | ||
|
|
ce978b602a | ||
|
|
9b00f5d550 | ||
|
|
d98ec59c79 | ||
|
|
d79b55be5a | ||
|
|
1f9a402dcd | ||
|
|
f9bcc9418b | ||
|
|
08256a3502 | ||
|
|
9b255e643a | ||
|
|
ca1f918e9e | ||
|
|
bb3fe1cd48 | ||
|
|
5d7772ecb0 | ||
|
|
56ce618eca | ||
|
|
605c3f9be1 | ||
|
|
b0381c7542 | ||
|
|
2f0894c220 | ||
|
|
b328ed5fa9 | ||
|
|
7d72f1711f | ||
|
|
d139b4557f | ||
|
|
cd05e03d63 | ||
|
|
e25029939d | ||
|
|
53de27417d | ||
|
|
74d3374d5c | ||
|
|
3ae00bebe4 | ||
|
|
f9df72c4d7 | ||
|
|
d0fb4576a8 | ||
|
|
0e4b0b3540 | ||
|
|
df1105d0c6 | ||
|
|
44478c36a3 | ||
|
|
fa267274b0 | ||
|
|
0db272946a | ||
|
|
91015b6499 | ||
|
|
2979a36a7c | ||
|
|
72f6d6b7b9 | ||
|
|
d81a7bcedf | ||
|
|
8fbbe8b82b | ||
|
|
271f5f9c64 | ||
|
|
7c992ffd21 | ||
|
|
fc2af8ba87 | ||
|
|
c8a539a6cb | ||
|
|
b7cdaa662a | ||
|
|
0a25930020 | ||
|
|
8643f4015f | ||
|
|
1854711aff | ||
|
|
c905119d82 | ||
|
|
c581ca8339 | ||
|
|
ccf9d9214a | ||
|
|
d37c8b732f | ||
|
|
f707fc1cad | ||
|
|
b1c713de60 | ||
|
|
0f13965391 | ||
|
|
8642e2b721 | ||
|
|
441534853b | ||
|
|
82f42c8664 | ||
|
|
5cd318fa9a | ||
|
|
5506071e9a | ||
|
|
ced98f2da7 | ||
|
|
282ec65e8b | ||
|
|
8e06dc5ace | ||
|
|
bfd3e2c01b | ||
|
|
a1957f0923 | ||
|
|
11a02ba361 | ||
|
|
4643c19abc | ||
|
|
a3369df62f | ||
|
|
4297c42597 | ||
|
|
e06e7157ac | ||
|
|
22f9e6f4c0 | ||
|
|
4b7a9233e7 | ||
|
|
204839f702 | ||
|
|
d15e3109ee | ||
|
|
8b513ee8f8 | ||
|
|
2c1488e65a | ||
|
|
8ebe1cc2d8 | ||
|
|
b0d6c15e63 | ||
|
|
3a3c7a7968 | ||
|
|
783d7ae605 | ||
|
|
bbf7a6b2f8 | ||
|
|
0fe6e24554 | ||
|
|
4bbaf55586 | ||
|
|
cda765a02d | ||
|
|
36856b18db | ||
|
|
66f0a8f994 | ||
|
|
455231170f | ||
|
|
5faeb58ab0 | ||
|
|
056e4a88ff | ||
|
|
8fd944ccf7 | ||
|
|
86105a547c | ||
|
|
9806648c07 | ||
|
|
6186babdb3 | ||
|
|
f2ecefb54a | ||
|
|
43bd529b78 | ||
|
|
9c82b3d4ca | ||
|
|
b19e6a8e87 | ||
|
|
e3a2bd75f3 | ||
|
|
da39e1485f | ||
|
|
88cc53a4b0 |
@@ -1,76 +0,0 @@
|
||||
---
|
||||
description: Deploy the latest OmniRoute code to the Akamai VPS (69.164.221.35) via npm
|
||||
---
|
||||
|
||||
# Deploy to VPS Workflow
|
||||
|
||||
Deploy OmniRoute to the production VPS using `npm install -g` + PM2.
|
||||
|
||||
**VPS:** `69.164.221.35` (Akamai, Ubuntu 24.04, 1GB RAM + 2.5GB swap)
|
||||
**Local VPS:** `192.168.0.15` (same setup)
|
||||
**Process manager:** PM2 (`omniroute`)
|
||||
**Port:** `20128`
|
||||
|
||||
> [!IMPORTANT]
|
||||
> PM2 runs from the global npm package at `/usr/lib/node_modules/omniroute`.
|
||||
> **DO NOT** use git clone or local copies. The `npm install -g` command handles
|
||||
> building, publishing, and installing the standalone app in one step.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Publish to npm
|
||||
|
||||
Ensure the version in `package.json` is bumped and the package is published:
|
||||
|
||||
```bash
|
||||
npm publish
|
||||
```
|
||||
|
||||
### 2. Install on VPS and restart PM2
|
||||
|
||||
// turbo-all
|
||||
|
||||
```bash
|
||||
ssh root@69.164.221.35 "npm install -g omniroute@latest && pm2 restart omniroute && pm2 save && echo '✅ Deploy complete!'"
|
||||
```
|
||||
|
||||
For the local VPS:
|
||||
|
||||
```bash
|
||||
ssh root@192.168.0.15 "npm install -g omniroute@latest && pm2 restart omniroute && pm2 save && echo '✅ Deploy complete!'"
|
||||
```
|
||||
|
||||
### 3. Verify the deployment
|
||||
|
||||
```bash
|
||||
ssh root@69.164.221.35 "pm2 list && cat \$(npm root -g)/omniroute/package.json | grep version | head -1 && curl -s -o /dev/null -w 'HTTP %{http_code}' http://localhost:20128/"
|
||||
```
|
||||
|
||||
Expected: PM2 shows `online`, version matches published, HTTP returns `307` (redirect to login).
|
||||
|
||||
## How it works
|
||||
|
||||
1. `npm publish` builds Next.js standalone + bundles everything into the npm package
|
||||
2. `npm install -g omniroute@latest` downloads and installs to `/usr/lib/node_modules/omniroute/`
|
||||
3. PM2 is registered to run `npm start` from that directory (cwd: `/usr/lib/node_modules/omniroute`)
|
||||
4. `pm2 restart omniroute` picks up the new code immediately
|
||||
|
||||
## PM2 Setup (one-time)
|
||||
|
||||
If PM2 needs to be reconfigured from scratch:
|
||||
|
||||
```bash
|
||||
ssh root@<VPS> "
|
||||
cd /usr/lib/node_modules/omniroute &&
|
||||
PORT=20128 pm2 start app/server.js --name omniroute --env PORT=20128 &&
|
||||
pm2 save &&
|
||||
pm2 startup
|
||||
"
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- The `.env` file is at `/usr/lib/node_modules/omniroute/.env`. Back it up before major npm updates.
|
||||
- PM2 is configured with `pm2 startup` to auto-restart on reboot.
|
||||
- Nginx proxies `omniroute.online` → `localhost:20128`.
|
||||
- The VPS has only 1GB RAM — builds happen locally via `npm publish`, not on the VPS.
|
||||
@@ -1,110 +0,0 @@
|
||||
---
|
||||
description: Create a new release, bump version up to 1.x.10 threshold, update changelog, and manage Pull Requests
|
||||
---
|
||||
|
||||
# Generate Release Workflow
|
||||
|
||||
Bump version, finalize CHANGELOG, commit, tag, push, publish to npm, and create GitHub release.
|
||||
|
||||
> **VERSION RULE: Always use PATCH bumps (2.x.y → 2.x.y+1)**
|
||||
> NEVER use `npm version minor` or `npm version major`.
|
||||
> Always use: `npm version patch --no-git-tag-version`
|
||||
> The threshold rule: when `y` reaches 10, bump to `2.(x+1).0` — e.g. `2.1.10` → `2.2.0`.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Determine new version
|
||||
|
||||
Check current version in `package.json` and increment the **patch** number only:
|
||||
|
||||
```bash
|
||||
grep '"version"' package.json
|
||||
```
|
||||
|
||||
Version format: `2.x.y` — examples:
|
||||
|
||||
- `2.1.2` → `2.1.3` (patch)
|
||||
- `2.1.9` → `2.1.10` (patch)
|
||||
- `2.1.10` → `2.2.0` (minor threshold — do manually with `sed`)
|
||||
|
||||
```bash
|
||||
# ALWAYS use patch:
|
||||
npm version patch --no-git-tag-version
|
||||
```
|
||||
|
||||
### 2. Regenerate lock file (REQUIRED after version bump)
|
||||
|
||||
**Mandatory** — skipping causes `@swc/helpers` lock mismatch and CI failures:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### 3. Finalize CHANGELOG.md
|
||||
|
||||
Replace `[Unreleased]` header with the new version and date.
|
||||
Keep an empty `## [Unreleased]` section above it.
|
||||
|
||||
```markdown
|
||||
## [Unreleased]
|
||||
|
||||
---
|
||||
|
||||
## [2.x.y] — YYYY-MM-DD
|
||||
```
|
||||
|
||||
### 4. Update openapi.yaml version ⚠️ MANDATORY
|
||||
|
||||
> **CI will fail** if `docs/openapi.yaml` version ≠ `package.json` version (`check:docs-sync` enforces this).
|
||||
|
||||
// turbo
|
||||
|
||||
```bash
|
||||
VERSION=$(node -p "require('./package.json').version") && sed -i "s/ version: .*/ version: $VERSION/" docs/openapi.yaml && echo "✓ openapi.yaml → $VERSION"
|
||||
```
|
||||
|
||||
### 5. Stage, commit, and tag
|
||||
|
||||
// turbo-all
|
||||
|
||||
```bash
|
||||
git add package.json package-lock.json CHANGELOG.md docs/openapi.yaml
|
||||
git commit -m "chore(release): v2.x.y — summary of changes"
|
||||
git tag -a v2.x.y -m "Release v2.x.y"
|
||||
```
|
||||
|
||||
### 6. Push to GitHub
|
||||
|
||||
```bash
|
||||
git push origin main --tags
|
||||
```
|
||||
|
||||
### 7. Create GitHub release
|
||||
|
||||
```bash
|
||||
gh release create v2.x.y --title "v2.x.y — summary" --notes "..."
|
||||
```
|
||||
|
||||
### 8. Deploy to VPS (if requested)
|
||||
|
||||
See `/deploy-vps` workflow for Akamai VPS or use npm for local VPS:
|
||||
|
||||
```bash
|
||||
ssh root@<VPS_IP> "npm install -g omniroute@2.x.y && pm2 restart omniroute"
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Always run `/update-docs` BEFORE this workflow (ensures CHANGELOG and README are current)
|
||||
- The `prepublishOnly` script runs `npm run build:cli` automatically during `npm publish`
|
||||
- After npm publish, verify with `npm info omniroute version`
|
||||
- Lock file sync errors are caused by skipping `npm install` after version bump
|
||||
|
||||
## Known CI Pitfalls
|
||||
|
||||
| CI failure | Cause | Fix |
|
||||
| ------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `[docs-sync] FAIL - OpenAPI version differs from package.json` | Skipped step 4 — `docs/openapi.yaml` version not updated | Run step 4 (`sed -i ...`) and commit |
|
||||
| `[docs-sync] FAIL - CHANGELOG.md first section must be "## [Unreleased]"` | `## [Unreleased]` missing or not at top of CHANGELOG | Add `## [Unreleased]\n\n---\n` before the first versioned `## [x.y.z]` |
|
||||
| Electron Linux `.deb` build fails (`FpmTarget` error) | `fpm` Ruby gem not installed on `ubuntu-latest` runner | Already fixed in `electron-release.yml` (`gem install fpm` step) |
|
||||
| Docker Hub `502 error writing layer blob` | Transient Docker Hub network error during ARM64 push | Re-run the Docker publish workflow; no code change needed |
|
||||
@@ -1,131 +0,0 @@
|
||||
---
|
||||
description: Analyze open feature request issues, implement viable ones on dedicated branches, and respond to authors
|
||||
---
|
||||
|
||||
# /implement-features — Feature Request Implementation Workflow
|
||||
|
||||
## Overview
|
||||
|
||||
Fetches open feature request issues, analyzes each against the current codebase, implements viable ones on dedicated branches, and responds to authors with results. Does NOT merge to main — leaves branches for author validation.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Identify the Repository
|
||||
|
||||
// turbo
|
||||
|
||||
- Run: `git -C <project_root> remote get-url origin` to extract owner/repo
|
||||
|
||||
### 2. Fetch Open Feature Request Issues
|
||||
|
||||
// turbo
|
||||
|
||||
- Run: `gh issue list --repo <owner>/<repo> --state open --limit 50 --json number,title,labels,body,comments,createdAt,author`
|
||||
- Filter for issues that are feature requests (label `enhancement`/`feature`, or body describes new functionality, or previously classified as feature request)
|
||||
- Sort by oldest first
|
||||
|
||||
### 3. Analyze Each Feature Request
|
||||
|
||||
For each feature request issue, perform a **two-level analysis**:
|
||||
|
||||
#### Level 1 — Viability Assessment
|
||||
|
||||
Ask yourself:
|
||||
|
||||
- Does this feature align with the project's goals and architecture?
|
||||
- Is the request technically feasible with the current codebase?
|
||||
- Does it duplicate existing functionality?
|
||||
- Would it introduce breaking changes or security risks?
|
||||
- Is there enough detail to implement it?
|
||||
|
||||
**Verdict options:**
|
||||
|
||||
1. ✅ **VIABLE** — Makes sense, enough detail to implement → Go to Level 2
|
||||
2. ❓ **NEEDS MORE INFO** — Good idea but insufficient detail → Post comment asking for specifics
|
||||
3. ❌ **NOT VIABLE** — Doesn't fit the project or is fundamentally flawed → Post comment explaining why, close issue
|
||||
|
||||
#### Level 2 — Implementation (only for VIABLE features)
|
||||
|
||||
1. **Research** — Read all related source files to understand the current architecture
|
||||
2. **Design** — Plan the implementation, filling gaps in the original request
|
||||
3. **Create branch** — Name format: `feat/issue-<NUMBER>-<short-slug>`
|
||||
```bash
|
||||
git checkout main
|
||||
git pull origin main
|
||||
git checkout -b feat/issue-<NUMBER>-<short-slug>
|
||||
```
|
||||
4. **Implement** — Build the complete solution following project patterns
|
||||
5. **Build** — Run `npm run build` to verify compilation
|
||||
6. **Commit** — Commit with: `feat: <description> (#<NUMBER>)`
|
||||
7. **Push** — Push the branch: `git push -u origin feat/issue-<NUMBER>-<short-slug>`
|
||||
8. **Return to main** — `git checkout main`
|
||||
|
||||
### 4. Respond to Authors
|
||||
|
||||
#### For VIABLE (implemented) features:
|
||||
|
||||
// turbo
|
||||
Post a comment on the issue:
|
||||
|
||||
````markdown
|
||||
## ✅ Feature Implemented!
|
||||
|
||||
Hi @<author>! We've analyzed your request and implemented it on a dedicated branch.
|
||||
|
||||
**Branch:** `feat/issue-<NUMBER>-<short-slug>`
|
||||
|
||||
### What was implemented:
|
||||
|
||||
- <bullet list of what was done>
|
||||
|
||||
### How to try it:
|
||||
|
||||
```bash
|
||||
git fetch origin
|
||||
git checkout feat/issue-<NUMBER>-<short-slug>
|
||||
npm install && npm run dev
|
||||
```
|
||||
````
|
||||
|
||||
### Next steps:
|
||||
|
||||
1. **Test it** — Please verify it works as you expected
|
||||
2. **Want to improve it?** — You're welcome to contribute! Just:
|
||||
```bash
|
||||
git checkout feat/issue-<NUMBER>-<short-slug>
|
||||
# Make your improvements
|
||||
git add -A && git commit -m "improve: <your changes>"
|
||||
git push origin feat/issue-<NUMBER>-<short-slug>
|
||||
```
|
||||
Then open a Pull Request from your branch to `main` 🎉
|
||||
3. **Not quite right?** — Let us know in this issue what needs to change
|
||||
|
||||
Looking forward to your feedback! 🚀
|
||||
|
||||
```
|
||||
|
||||
#### For NEEDS MORE INFO:
|
||||
// turbo
|
||||
Post a comment asking for specific missing details needed to implement, e.g.:
|
||||
- "Could you describe the exact behavior when X happens?"
|
||||
- "Which API endpoints should be affected?"
|
||||
- "Should this apply to all providers or only specific ones?"
|
||||
|
||||
Add the context of WHY you need each piece of information.
|
||||
|
||||
#### For NOT VIABLE:
|
||||
// turbo
|
||||
Post a polite comment explaining why the feature doesn't fit at this time:
|
||||
- If the idea is decent but timing is wrong: "This is an interesting idea, but it doesn't align with our current priorities. Feel free to open a new issue with more details if you'd like us to reconsider."
|
||||
- If fundamentally flawed: Explain the technical or architectural reasons why it won't work, suggest alternatives if possible.
|
||||
- Close the issue after posting the comment.
|
||||
|
||||
### 5. Summary Report
|
||||
Present a summary report to the user via `notify_user`:
|
||||
|
||||
| Issue | Title | Verdict | Branch / Action |
|
||||
|---|---|---|---|
|
||||
| #N | Title | ✅ Implemented | `feat/issue-N-slug` |
|
||||
| #N | Title | ❓ Needs Info | Comment posted |
|
||||
| #N | Title | ❌ Not Viable | Closed with explanation |
|
||||
```
|
||||
@@ -1,50 +0,0 @@
|
||||
---
|
||||
description: How to respond to GitHub issues with insufficient information
|
||||
---
|
||||
|
||||
# Issue Triage Workflow
|
||||
|
||||
Respond to GitHub issues that need more information before they can be investigated.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Identify issues needing triage
|
||||
|
||||
```bash
|
||||
gh issue list --state open --limit 20
|
||||
```
|
||||
|
||||
### 2. Evaluate each issue
|
||||
|
||||
Check if the issue has:
|
||||
|
||||
- Clear reproduction steps
|
||||
- Environment details (OS, Node.js version, OmniRoute version)
|
||||
- Error logs/screenshots
|
||||
- Expected vs actual behavior
|
||||
|
||||
### 3. Respond with triage template
|
||||
|
||||
For issues missing information:
|
||||
|
||||
```markdown
|
||||
Thank you for reporting this issue! To help us investigate, please provide:
|
||||
|
||||
1. **OmniRoute version**: (`omniroute --version`)
|
||||
2. **Node.js version**: (`node --version`)
|
||||
3. **Operating system**: (e.g., Ubuntu 24.04, macOS 15, Windows 11)
|
||||
4. **Installation method**: (npm, Docker, source)
|
||||
5. **Steps to reproduce**: (exact commands/actions that trigger the issue)
|
||||
6. **Error logs**: (paste relevant logs from the console)
|
||||
7. **Expected behavior**: (what should happen)
|
||||
|
||||
This will help us debug and resolve your issue faster. 🙏
|
||||
```
|
||||
|
||||
### 4. Label the issue
|
||||
|
||||
Add appropriate labels: `needs-info`, `bug`, `enhancement`, `question`, etc.
|
||||
|
||||
```bash
|
||||
gh issue edit <NUMBER> --add-label "needs-info"
|
||||
```
|
||||
@@ -1,120 +0,0 @@
|
||||
---
|
||||
description: Fetch all open GitHub issues, analyze bugs, resolve what's possible, triage the rest, wait for user validation, then commit and release
|
||||
---
|
||||
|
||||
# /resolve-issues — Automated Issue Resolution Workflow
|
||||
|
||||
## Overview
|
||||
|
||||
This workflow fetches all open issues from the project's GitHub repository, classifies them, analyzes bugs, resolves what can be fixed, and triages issues with insufficient information. **It does NOT merge or release automatically** — it creates a PR and waits for user validation before merging.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Identify the GitHub Repository
|
||||
|
||||
// turbo
|
||||
|
||||
- Run: `git -C <project_root> remote get-url origin` to extract the owner/repo
|
||||
- Parse the owner and repo name from the URL
|
||||
|
||||
### 2. Fetch All Open Issues
|
||||
|
||||
// turbo
|
||||
|
||||
- Run: `gh issue list --repo <owner>/<repo> --state open --limit 100 --json number,title,labels,body,comments,createdAt,author`
|
||||
- Parse the JSON output to get a list of all open issues
|
||||
- Sort by oldest first (FIFO)
|
||||
|
||||
### 3. Classify Each Issue
|
||||
|
||||
For each issue, determine its type:
|
||||
|
||||
- **Bug** — Has `bug` label, or body contains error messages, stack traces, "doesn't work", "broken", "crash", "error"
|
||||
- **Feature Request** — Has `enhancement`/`feature` label, or body describes new functionality
|
||||
- **Question** — Has `question` label, or is asking "how to" something
|
||||
- **Other** — Anything else
|
||||
|
||||
Focus ONLY on **Bugs** for resolution. Feature requests and questions should be skipped with a note in the final report.
|
||||
|
||||
### 4. Analyze Each Bug — For each bug issue:
|
||||
|
||||
#### 4a. Check Information Sufficiency
|
||||
|
||||
Verify the issue contains enough information to reproduce and fix:
|
||||
|
||||
- [ ] Clear description of the problem
|
||||
- [ ] Steps to reproduce
|
||||
- [ ] Error messages or logs
|
||||
- [ ] Expected vs actual behavior
|
||||
|
||||
#### 4b. If Information Is INSUFFICIENT
|
||||
|
||||
Call the `/issue-triage` workflow (located at `~/.gemini/antigravity/global_workflows/issue-triage.md`):
|
||||
// turbo
|
||||
|
||||
- Post a comment asking for more details using `gh issue comment`
|
||||
- Add `needs-info` label using `gh issue edit`
|
||||
- Mark this issue as **DEFERRED** and move to the next one
|
||||
|
||||
#### 4c. If Information Is SUFFICIENT
|
||||
|
||||
Proceed with resolution:
|
||||
|
||||
1. **Create a fix branch** — `git checkout -b fix/issue-<NUMBER>-<short-description>`
|
||||
2. **Research** — Search the codebase for files related to the issue
|
||||
3. **Root Cause** — Identify the root cause by reading the relevant source files
|
||||
4. **Implement Fix** — Apply the fix following existing code patterns and conventions
|
||||
5. **Test** — Build the project and run tests to verify the fix
|
||||
6. **Commit** — Commit with message format: `fix: <description> (#<issue_number>)`
|
||||
|
||||
### 5. Generate Report & Wait for Validation
|
||||
|
||||
Present a summary report to the user via `notify_user` with `BlockedOnUser: true`:
|
||||
|
||||
| Issue | Title | Status | Action |
|
||||
| ----- | ----- | ------------- | ----------------------------- |
|
||||
| #N | Title | ✅ Ready | Files changed (not committed) |
|
||||
| #N | Title | ❓ Needs Info | Triage comment posted |
|
||||
| #N | Title | ⏭️ Skipped | Feature request / not a bug |
|
||||
|
||||
> **⚠️ IMPORTANT**: Do NOT commit, close issues, or generate releases at this step.
|
||||
> Wait for the user to review the changes and respond with **OK** before proceeding.
|
||||
|
||||
- If the user says **OK** or approves → Proceed to step 6
|
||||
- If the user requests changes → Apply the requested adjustments first, then present the report again
|
||||
- If the user rejects → Revert the changes and stop
|
||||
|
||||
### 6. Commit & Push Fix Branch (only after user approval)
|
||||
|
||||
After the user validates:
|
||||
|
||||
- Commit each fix individually with message format: `fix: <description> (#<issue_number>)`
|
||||
- Push the fix branch: `git push origin fix/issue-<NUMBER>-<short-description>`
|
||||
- Create a PR: `gh pr create --title "fix: <description> (#<issue_number>)" --body "<details>" --base main`
|
||||
|
||||
### 7. 🛑 WAIT — Notify User & Await PR Verification
|
||||
|
||||
**This is a mandatory stop point.** Use `notify_user` with `BlockedOnUser: true`:
|
||||
|
||||
- Inform the user that the PR was created and is **awaiting their verification**
|
||||
- Include the PR number, URL, and a summary of what was changed
|
||||
- **DO NOT merge, close issues, generate releases, or deploy until the user confirms**
|
||||
|
||||
Wait for the user to respond:
|
||||
|
||||
- **User confirms** → Proceed to step 8
|
||||
- **User requests changes** → Apply changes, push to the same branch, notify again
|
||||
- **User rejects** → Close the PR and stop
|
||||
|
||||
### 8. Merge, Close Issues & Release (only after user confirms PR)
|
||||
|
||||
After the user confirms the PR:
|
||||
|
||||
1. **Merge** the PR: `gh pr merge <NUMBER> --merge --repo <owner>/<repo>` or via local merge
|
||||
2. **Close** resolved issues with a comment: `gh issue close <NUMBER> --repo <owner>/<repo> --comment "Fixed in <commit_hash>. The fix will be included in the next release."`
|
||||
3. **Switch to main**: `git checkout main && git pull`
|
||||
4. Run the `/update-docs` workflow (at `~/.gemini/antigravity/global_workflows/update-docs.md`) to update CHANGELOG and README
|
||||
5. Run the `/generate-release` workflow (at `.agents/workflows/generate-release.md`) to bump version, tag, and publish
|
||||
6. Deploy to local VPS: `ssh root@192.168.0.15 "npm install -g omniroute@<VERSION> && pm2 restart omniroute"`
|
||||
|
||||
If NO fixes were committed, skip this step and just present the report.
|
||||
@@ -1,145 +0,0 @@
|
||||
---
|
||||
description: Analyze open Pull Requests from the project's GitHub repository, generate a critical report, and optionally implement approved changes
|
||||
---
|
||||
|
||||
# /review-prs — PR Review & Analysis Workflow
|
||||
|
||||
## Overview
|
||||
|
||||
This workflow fetches all open PRs from the project's GitHub repository, performs a critical analysis of each one, generates a detailed report, and waits for user approval before proceeding with implementation. **All improvements are committed on top of the PR branch** and the user must verify before merge.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Identify the GitHub Repository
|
||||
|
||||
- Read `package.json` to get the repository URL, or use the git remote origin URL
|
||||
// turbo
|
||||
- Run: `git -C <project_root> remote get-url origin` to extract the owner/repo
|
||||
|
||||
### 2. Fetch Open Pull Requests
|
||||
|
||||
- Navigate to `https://github.com/<owner>/<repo>/pulls` and scrape all open PRs
|
||||
- For each open PR, collect:
|
||||
- PR number, title, author, branch, number of commits, date
|
||||
- PR description/body
|
||||
- Files changed (diff)
|
||||
- Existing review comments (from bots or humans)
|
||||
|
||||
### 3. Analyze Each PR — For each open PR, perform the following analysis:
|
||||
|
||||
#### 3a. Feature Assessment
|
||||
|
||||
- **Does it make sense?** Evaluate if the feature fills a real gap or solves a valid problem
|
||||
- **Alignment** — Check if it aligns with the project's architecture and roadmap
|
||||
- **Complexity** — Assess if the scope is reasonable or if it should be split
|
||||
|
||||
#### 3b. Code Quality Review
|
||||
|
||||
- Check for code duplication
|
||||
- Evaluate error handling patterns (consistent with existing codebase?)
|
||||
- Check naming conventions and code style
|
||||
- Verify TypeScript types (any `any` usage, missing types?)
|
||||
|
||||
#### 3c. Security Review
|
||||
|
||||
- Check for missing authentication/authorization on new endpoints
|
||||
- Check for injection vulnerabilities (URL params, SQL, XSS)
|
||||
- Verify input validation on all user-controlled data
|
||||
- Check for hardcoded secrets or credentials
|
||||
|
||||
#### 3d. Architecture Review
|
||||
|
||||
- Does the change follow existing patterns?
|
||||
- Are there any breaking changes to public APIs?
|
||||
- Is the database schema affected? Migration needed?
|
||||
- Impact on performance (N+1 queries, missing indexes?)
|
||||
|
||||
#### 3e. Test Coverage
|
||||
|
||||
- Does the PR include tests?
|
||||
- Are edge cases covered?
|
||||
- Would existing tests break?
|
||||
|
||||
#### 3f. Cross-Layer (Global) Analysis
|
||||
|
||||
Perform a **global impact assessment** to verify whether the PR changes are complete across all layers of the application:
|
||||
|
||||
- **Backend → Frontend check**: If the PR adds or modifies backend-only resources (new endpoints, services, data models), evaluate whether corresponding frontend changes are missing:
|
||||
- Does a new endpoint require a new screen/page in the dashboard?
|
||||
- Should there be a new action button, menu item, or navigation link?
|
||||
- Are there new data fields that should be displayed or editable in the UI?
|
||||
- Does a new feature need a toggle, configuration panel, or status indicator?
|
||||
- **Frontend → Backend check**: If the PR adds frontend elements, verify the backend support exists:
|
||||
- Are the required API endpoints implemented?
|
||||
- Is the data model sufficient for the new UI components?
|
||||
- **Cross-cutting concerns**: Check shared layers (types, DTOs, validation schemas, routes, middleware) for completeness
|
||||
- **Document gaps** — If missing layers are detected, list them as **IMPORTANT** issues in the report with concrete suggestions for what should be added
|
||||
|
||||
### 4. Generate Report — Create a markdown report for each PR including:
|
||||
|
||||
- **PR Summary** — What it does, files affected, commit count
|
||||
- **Improvements/Benefits** — Numbered list with impact level (HIGH/MEDIUM/LOW)
|
||||
- **Risks & Issues** — Categorized as CRITICAL / IMPORTANT / MINOR
|
||||
- **Scoring Table** — Rate across: Feature Relevance, Code Quality, Security, Robustness, Tests
|
||||
- **Verdict** — Ready to merge? With mandatory vs optional fixes
|
||||
- **Next Steps** — What will happen if approved
|
||||
|
||||
### 5. Present to User
|
||||
|
||||
- Show the report via `notify_user` with `BlockedOnUser: true`
|
||||
- Wait for user decision:
|
||||
- **Approved** → Proceed to step 6
|
||||
- **Approved with changes** → Implement the fixes and corrections before merging
|
||||
- **Rejected** → Close the PR or leave a review comment
|
||||
|
||||
### 6. Implementation (if approved)
|
||||
|
||||
- Checkout the PR branch: `gh pr checkout <NUMBER>`
|
||||
- Implement any required fixes identified in the analysis
|
||||
- If the Cross-Layer Analysis (3f) identified missing frontend/backend counterparts, implement them
|
||||
- **Commit improvements on top of the PR branch** with descriptive commit messages
|
||||
- Run the project's test suite to verify nothing breaks
|
||||
// turbo
|
||||
- Run: `npm test` or equivalent test command
|
||||
- Build the project to verify compilation
|
||||
// turbo
|
||||
- Run: `npm run build` or equivalent build command
|
||||
- Push the updated branch: `git push origin <branch-name>`
|
||||
|
||||
### 7. 🛑 WAIT — Notify User & Await PR Verification
|
||||
|
||||
**This is a mandatory stop point.** Use `notify_user` with `BlockedOnUser: true`:
|
||||
|
||||
- Inform the user that the PR has been **improved and pushed**, and is **awaiting their verification**
|
||||
- Include:
|
||||
- PR number and URL
|
||||
- Summary of improvements/fixes applied
|
||||
- Build/test status
|
||||
- List of files changed
|
||||
- **DO NOT merge, generate releases, or deploy until the user confirms**
|
||||
|
||||
Wait for the user to respond:
|
||||
|
||||
- **User confirms** → Proceed to step 8
|
||||
- **User requests more changes** → Apply changes, push to the same branch, notify again
|
||||
- **User rejects** → Leave a review comment and stop
|
||||
|
||||
### 8. Thank the Contributor
|
||||
|
||||
- Post a **thank-you comment** on the PR via the GitHub API
|
||||
- The message should:
|
||||
- Thank the author by name/username for their contribution
|
||||
- Briefly mention what the PR accomplishes and any improvements applied
|
||||
- Be friendly, professional, and encouraging
|
||||
- Example: _"Thanks @author for this great contribution! 🎉 The [feature/fix] is now merged and will be part of the next release. We appreciate your effort!"_
|
||||
|
||||
### 9. Merge & Release (only after user confirms PR)
|
||||
|
||||
After the user confirms the PR:
|
||||
|
||||
1. **Merge** the PR into main (local merge with `--no-ff` or via `gh pr merge`)
|
||||
2. **Push** to main: `git push origin main`
|
||||
3. **Clean up** the feature branch: `git branch -d <branch-name>`
|
||||
4. **Update CHANGELOG.md** with the new feature/fix
|
||||
5. Run the `/generate-release` workflow (at `.agents/workflows/generate-release.md`) to bump version, tag, and publish
|
||||
6. Deploy to local VPS: `ssh root@192.168.0.15 "npm install -g omniroute@<VERSION> && pm2 restart omniroute"`
|
||||
@@ -1,105 +0,0 @@
|
||||
---
|
||||
description: How to automatically summarize recent changes and update README and CHANGELOG
|
||||
---
|
||||
|
||||
# Update Documentation Workflow
|
||||
|
||||
Update CHANGELOG.md, README.md, docs/ files, and all multi-language translations whenever features are added or changed.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Summarize recent changes
|
||||
|
||||
Review git log and identify new features, fixes, or changes since the last release tag:
|
||||
|
||||
```bash
|
||||
git log $(git describe --tags --abbrev=0)..HEAD --oneline
|
||||
```
|
||||
|
||||
### 2. Update English CHANGELOG.md
|
||||
|
||||
Add an `[Unreleased]` section (or version header if releasing) with:
|
||||
|
||||
- `### ✨ New Features` — each feature as a bullet point
|
||||
- `### 🐛 Bug Fixes` — if applicable
|
||||
- `### 🧪 Tests` — test count changes
|
||||
- `### 📁 New Files` — table of new files with purpose
|
||||
|
||||
### 3. Update English README.md
|
||||
|
||||
Update the feature tables in these sections:
|
||||
|
||||
- **🧠 Routing & Intelligence** — for routing/model features
|
||||
- **🛡️ Resilience & Security** — for security/resilience features
|
||||
- **📊 Observability & Analytics** — for monitoring features
|
||||
- **☁️ Deploy & Sync** — for deployment features
|
||||
|
||||
### 4. Update docs/ files
|
||||
|
||||
- `docs/FEATURES.md` — update the Settings section description
|
||||
- `docs/API_REFERENCE.md` — add new API routes if any
|
||||
- `docs/ARCHITECTURE.md` — update architecture if structural changes
|
||||
|
||||
### 5. 🌐 Sync Multi-Language Documentation (CRITICAL)
|
||||
|
||||
// turbo-all
|
||||
|
||||
**This step MUST be run after every README or docs update.**
|
||||
|
||||
The project has **30 language versions** of documentation:
|
||||
|
||||
**README files (root directory):**
|
||||
|
||||
```
|
||||
README.md (English - source of truth)
|
||||
README.pt-BR.md README.pt.md README.es.md README.fr.md README.it.md
|
||||
README.de.md README.nl.md README.sv.md README.no.md README.da.md README.fi.md
|
||||
README.ru.md README.uk-UA.md README.bg.md README.sk.md README.pl.md README.ro.md README.hu.md
|
||||
README.ar.md README.he.md README.th.md README.in.md README.id.md README.ms.md README.vi.md
|
||||
README.ja.md README.ko.md README.zh-CN.md README.phi.md
|
||||
```
|
||||
|
||||
**docs/i18n/ directories (29 languages):**
|
||||
|
||||
```
|
||||
docs/i18n/{ar,bg,da,de,es,fi,fr,he,hu,id,in,it,ja,ko,ms,nl,no,phi,pl,pt,pt-BR,ro,ru,sk,sv,th,uk-UA,vi,zh-CN}/
|
||||
Each contains: API_REFERENCE.md, ARCHITECTURE.md, CODEBASE_DOCUMENTATION.md, FEATURES.md, TROUBLESHOOTING.md, USER_GUIDE.md
|
||||
```
|
||||
|
||||
**Sync approach for feature table updates:**
|
||||
|
||||
a. Identify which feature table rows were added to English README.md
|
||||
b. For each translated README, find the corresponding anchor lines:
|
||||
|
||||
- **Routing section:** Find the `💬` (System Prompt) table row — the line before it is always the last routing feature. Insert new routing features before System Prompt.
|
||||
- **Resilience section:** Find the `📊` Rate Limits table row (the one in lines 590-600, NOT the quota tracking one in lines 560-570). Insert new resilience features after it.
|
||||
c. The new feature entries can stay in English for technical features, matching the pattern used in the existing translations.
|
||||
d. Use `sed` or similar tool to batch-insert across all 29 translated READMEs.
|
||||
|
||||
**Verification:**
|
||||
|
||||
```bash
|
||||
# Verify all READMEs have the new features
|
||||
grep -l "NEW_FEATURE_NAME" README.*.md | wc -l
|
||||
# Should return 30 (all language versions)
|
||||
```
|
||||
|
||||
**FEATURES.md sync:**
|
||||
|
||||
```bash
|
||||
# Update Settings description in all docs/i18n/*/FEATURES.md
|
||||
for dir in docs/i18n/*/; do
|
||||
# Update the Settings section description to mention new features
|
||||
# Check FEATURES.md in each directory
|
||||
done
|
||||
```
|
||||
|
||||
### 6. Verify documentation changes
|
||||
|
||||
```bash
|
||||
# Check all modified files
|
||||
git status --short
|
||||
|
||||
# Verify no broken markdown
|
||||
# Optional: run markdownlint if available
|
||||
```
|
||||
@@ -9,6 +9,7 @@
|
||||
# Dependencies and build output
|
||||
node_modules
|
||||
.next
|
||||
.build
|
||||
out
|
||||
build
|
||||
dist
|
||||
@@ -30,3 +31,95 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Test suites
|
||||
tests
|
||||
test-results
|
||||
playwright-report
|
||||
blob-report
|
||||
|
||||
# Documentation
|
||||
# Issue #2348: The Dashboard Docs viewer reads markdown from `/app/docs` at
|
||||
# runtime. The previous `docs/*` block hid every file except openapi.yaml,
|
||||
# so the in-product help screen failed with ENOENT for every page.
|
||||
# We now keep the English markdown tree plus the docs assets imported by MDX
|
||||
# during `next build`, while still dropping the bulky translated docs and
|
||||
# extra raster diagram sources that account for most of the docs footprint
|
||||
# of the ~50 MB docs directory. The Docs viewer reads the default-locale
|
||||
# (English) sources at runtime, so translations are not required in the
|
||||
# container image.
|
||||
docs/i18n/**
|
||||
docs/diagrams/**/*.png
|
||||
docs/diagrams/**/*.jpg
|
||||
docs/diagrams/**/*.jpeg
|
||||
docs/diagrams/**/*.gif
|
||||
docs/diagrams/**/*.webp
|
||||
# Note: `*.md` matches the root only (Go filepath.Match does not cross /),
|
||||
# so nested docs/**/*.md is implicitly kept without a re-include rule.
|
||||
*.md
|
||||
!README.md
|
||||
|
||||
# Electron (separate build)
|
||||
electron
|
||||
|
||||
# VS Code extension (separate project)
|
||||
vscode-extension
|
||||
|
||||
# Build artifacts
|
||||
*.tgz
|
||||
*.AppImage
|
||||
*.deb
|
||||
*.rpm
|
||||
|
||||
# Package manager lock (bun)
|
||||
bun.lock
|
||||
|
||||
# Agent config
|
||||
.agents
|
||||
.gemini
|
||||
|
||||
# Misc
|
||||
llm.txt
|
||||
images
|
||||
clipr
|
||||
omnirouteCloud
|
||||
omnirouteSite
|
||||
|
||||
# Temporary/Scratch Folders
|
||||
_*
|
||||
|
||||
# CI/CD and Version Control (that are not actual code)
|
||||
.github
|
||||
.husky
|
||||
.omc
|
||||
|
||||
# Test Configs and Reports
|
||||
playwright.config.ts
|
||||
vitest*.ts
|
||||
audit-report.json
|
||||
sonar-project.properties
|
||||
|
||||
# Deployment Configs
|
||||
docker-compose*.yml
|
||||
fly.toml
|
||||
|
||||
# Consistent with .gitignore
|
||||
.DS_Store
|
||||
.idea/
|
||||
.config/
|
||||
.data/
|
||||
.omnivscodeagent/
|
||||
*.sqlite-*
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
security-analysis/
|
||||
.analysis/
|
||||
antigravity-manager-analysis/
|
||||
.sisyphus/
|
||||
.plans/
|
||||
app.__qa_backup/
|
||||
.app-build-backup-*/
|
||||
.gitnexus
|
||||
.worktrees
|
||||
.next-playwright/
|
||||
cloud/
|
||||
|
||||
1604
.env.example
1604
.env.example
File diff suppressed because it is too large
Load Diff
2
.github/CODEOWNERS
vendored
Normal file
2
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
* @diegosouzapw
|
||||
|
||||
5
.github/FUNDING.yml
vendored
Normal file
5
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# Funding links for OmniRoute — rendered as the "Sponsor" button on GitHub.
|
||||
# Docs: https://docs.github.com/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
|
||||
github: diegosouzapw
|
||||
# Additional platforms (uncomment and fill in before enabling):
|
||||
# custom: ["https://omniroute.online/donate"]
|
||||
171
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
171
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@@ -0,0 +1,171 @@
|
||||
name: Bug Report
|
||||
description: Report a bug or unexpected behavior in OmniRoute
|
||||
title: "[BUG] "
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to report a bug. Please fill out the sections below so we can reproduce and fix the issue.
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: OmniRoute Version
|
||||
description: "Run `omniroute --version` or check the left sidebar in the dashboard."
|
||||
placeholder: "e.g. 3.7.9"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: install-method
|
||||
attributes:
|
||||
label: Installation Method
|
||||
options:
|
||||
- npm (global)
|
||||
- Docker / Docker Compose
|
||||
- Electron desktop app
|
||||
- Built from source
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: os
|
||||
attributes:
|
||||
label: Operating System
|
||||
options:
|
||||
- Windows
|
||||
- macOS
|
||||
- Linux
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: os-version
|
||||
attributes:
|
||||
label: OS Version
|
||||
placeholder: "e.g. Windows 11 25H2, macOS 26.5, Ubuntu 26.04"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
id: node-version
|
||||
attributes:
|
||||
label: Node.js Version
|
||||
description: "Run `node --version`. Skip if using Docker."
|
||||
placeholder: "e.g. 24.15.0"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
id: provider
|
||||
attributes:
|
||||
label: Provider(s) Involved
|
||||
description: "Which AI provider(s) does this affect?"
|
||||
placeholder: "e.g. Antigravity, OpenRouter, Ollama, Qwen"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
id: model
|
||||
attributes:
|
||||
label: Model(s) Involved
|
||||
placeholder: "e.g. claude-opus-4-7, gpt-5.5, gemini-3.1-pro"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
id: client-tool
|
||||
attributes:
|
||||
label: Client Tool
|
||||
description: "Which tool are you using OmniRoute with?"
|
||||
placeholder: "e.g. Claude Code, Cursor, Roo Code, OpenClaw, Gemini CLI, cURL"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: "A clear description of what the bug is."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to Reproduce
|
||||
description: "Step-by-step instructions to reproduce the behavior."
|
||||
placeholder: |
|
||||
1. Go to '...'
|
||||
2. Click on '...'
|
||||
3. See error
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected Behavior
|
||||
description: "What did you expect to happen?"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual Behavior
|
||||
description: "What actually happened?"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: test-impact
|
||||
attributes:
|
||||
label: Test Impact
|
||||
description: "What automated test coverage should exist for this bug?"
|
||||
options:
|
||||
- Needs a new unit test
|
||||
- Needs a new integration test
|
||||
- Needs a new e2e test
|
||||
- Existing automated test already fails
|
||||
- Unsure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Error Logs / Output
|
||||
description: "Paste any relevant error messages, logs, or terminal output. This will be automatically formatted as code."
|
||||
render: shell
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: screenshots
|
||||
attributes:
|
||||
label: Screenshots
|
||||
description: "If applicable, add screenshots to help explain the problem. Please also include the text of any error messages above — screenshots alone are not searchable."
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
attributes:
|
||||
label: Additional Context
|
||||
description: "Any other context about the problem (e.g. proxy config, number of accounts, network setup)."
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: validation-plan
|
||||
attributes:
|
||||
label: Validation Plan
|
||||
description: "Which commands or tests should prove this bug is fixed?"
|
||||
placeholder: |
|
||||
Example:
|
||||
- node --import tsx --test tests/unit/my-file.test.ts
|
||||
- npm run test:coverage
|
||||
validations:
|
||||
required: false
|
||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Question / Help
|
||||
url: https://github.com/diegosouzapw/OmniRoute/discussions
|
||||
about: For questions or help with setup, please use GitHub Discussions instead of opening an issue.
|
||||
96
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
96
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@@ -0,0 +1,96 @@
|
||||
name: Feature Request
|
||||
description: Suggest a new feature or improvement for OmniRoute
|
||||
title: "[Feature] "
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for suggesting a feature! Please describe the problem you're trying to solve and how you'd like it to work.
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem / Use Case
|
||||
description: "What problem does this feature solve? Why do you need it?"
|
||||
placeholder: "I'm trying to ... but currently ..."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: solution
|
||||
attributes:
|
||||
label: Proposed Solution
|
||||
description: "How would you like this to work?"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives Considered
|
||||
description: "Have you considered any workarounds or alternative approaches?"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: acceptance
|
||||
attributes:
|
||||
label: Acceptance Criteria
|
||||
description: "Describe the concrete behaviors or outcomes that should be validated before this is considered done."
|
||||
placeholder: |
|
||||
Example:
|
||||
- API route returns 200 with valid payload
|
||||
- Unit coverage added for the new branch
|
||||
- Existing integrations remain green
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: "Which part of OmniRoute does this relate to?"
|
||||
multiple: true
|
||||
options:
|
||||
- Dashboard / UI
|
||||
- Proxy / Routing
|
||||
- Provider Support
|
||||
- CLI Tools Integration
|
||||
- OAuth / Authentication
|
||||
- Analytics / Usage Tracking
|
||||
- Docker / Deployment
|
||||
- Documentation
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: provider
|
||||
attributes:
|
||||
label: Related Provider(s)
|
||||
description: "If this relates to specific providers, list them."
|
||||
placeholder: "e.g. Antigravity, OpenRouter, Ollama"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
attributes:
|
||||
label: Additional Context
|
||||
description: "Any other context, mockups, or references."
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: test-plan
|
||||
attributes:
|
||||
label: Expected Test Plan
|
||||
description: "Which automated tests or coverage changes should accompany this work?"
|
||||
placeholder: |
|
||||
Example:
|
||||
- Add unit tests for open-sse/services/combo.ts
|
||||
- Extend integration coverage for /api/v1/models
|
||||
- Keep npm run test:coverage at 60%+
|
||||
validations:
|
||||
required: false
|
||||
73
.github/ISSUE_TEMPLATE/test_coverage_task.yml
vendored
Normal file
73
.github/ISSUE_TEMPLATE/test_coverage_task.yml
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
name: Test Coverage Task
|
||||
description: Create a focused coverage-improvement issue tied to concrete files and targets
|
||||
title: "[Coverage] "
|
||||
labels: ["test", "coverage"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this template for scoped coverage work. Keep it tied to specific files, measurable targets, and the gate that must stay green.
|
||||
|
||||
- type: input
|
||||
id: baseline
|
||||
attributes:
|
||||
label: Current Coverage Baseline
|
||||
description: "Paste the current overall or file-level coverage number that justifies this task."
|
||||
placeholder: "e.g. Lines 79.00%, Branches 72.85%, open-sse/handlers/chatCore.ts = 67.22%"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Target Files Or Modules
|
||||
description: "List the concrete source files or directories that this task will cover."
|
||||
placeholder: |
|
||||
Example:
|
||||
- open-sse/handlers/chatCore.ts
|
||||
- open-sse/services/combo.ts
|
||||
- tests/integration/chat-pipeline.test.ts
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: scenarios
|
||||
attributes:
|
||||
label: Missing Scenarios
|
||||
description: "Describe the specific behaviors, branches, or failure paths that are currently uncovered."
|
||||
placeholder: |
|
||||
Example:
|
||||
- Upstream timeout path
|
||||
- Empty tool_calls normalization
|
||||
- Fallback route after first provider failure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: target
|
||||
attributes:
|
||||
label: Coverage Target
|
||||
description: "Set the expected target for this task."
|
||||
placeholder: "e.g. Raise open-sse/handlers to 80%+ lines and keep global gate >= 60%"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: validation
|
||||
attributes:
|
||||
label: Validation Commands
|
||||
description: "List the commands that must pass before this issue can be closed."
|
||||
placeholder: |
|
||||
Example:
|
||||
- node --import tsx --test tests/unit/my-suite.test.ts
|
||||
- npm run test:coverage
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: notes
|
||||
attributes:
|
||||
label: Notes
|
||||
description: "Optional context, blockers, or dependencies."
|
||||
validations:
|
||||
required: false
|
||||
15
.github/copilot-instructions.md
vendored
Normal file
15
.github/copilot-instructions.md
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# OmniRoute PR and Coverage Instructions
|
||||
|
||||
- Treat `npm run test:coverage` as a required gate for PR work.
|
||||
- The repository minimum is `60%` for statements, lines, functions, and branches.
|
||||
- If a PR changes production code in `src/`, `open-sse/`, `electron/`, or `bin/`, it must include automated tests in the same PR.
|
||||
- When reviewing or updating a PR, if the report shows missing tests or coverage below `60%`, do not stop after reporting the problem. Add or update tests in the PR first, rerun the coverage gate, and only then ask for confirmation.
|
||||
- Prefer the smallest test layer that proves the behavior:
|
||||
- unit tests first
|
||||
- integration tests when multiple modules or DB state are involved
|
||||
- e2e only when the behavior is truly UI or workflow-dependent
|
||||
- For bug issues, try to encode the reproduction as an automated test before or alongside the fix.
|
||||
- In the final PR report, include:
|
||||
- the commands you ran
|
||||
- the changed test files
|
||||
- the final coverage result
|
||||
16
.github/dependabot.yml
vendored
16
.github/dependabot.yml
vendored
@@ -29,3 +29,19 @@ updates:
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/electron"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
commit-message:
|
||||
prefix: "deps"
|
||||
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
commit-message:
|
||||
prefix: "deps"
|
||||
|
||||
30
.github/pull_request_template.md
vendored
Normal file
30
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
## Summary
|
||||
|
||||
- Describe the user-facing or operational change.
|
||||
|
||||
## Related Issues
|
||||
|
||||
- Closes #
|
||||
- Related to #
|
||||
|
||||
## Validation
|
||||
|
||||
- [ ] `npm run lint`
|
||||
- [ ] `npm run test:unit`
|
||||
- [ ] `npm run test:coverage`
|
||||
- [ ] Coverage is still `>= 60%` for statements, lines, functions, and branches
|
||||
- [ ] SonarQube PR analysis is green or any remaining issues are explicitly documented below
|
||||
|
||||
## Tests Added Or Updated
|
||||
|
||||
- List every changed or added automated test file.
|
||||
- If no production code changed, state that here.
|
||||
|
||||
## Coverage Notes
|
||||
|
||||
- If this PR changes `src/`, `open-sse/`, `electron/`, or `bin/`, explain which tests cover the change.
|
||||
- If coverage moved down in any touched file, explain why and what follow-up task will recover it.
|
||||
|
||||
## Reviewer Notes
|
||||
|
||||
- Call out any risky areas, migrations, feature flags, or manual validation that reviewers should know about.
|
||||
65
.github/workflows/build-fork.yml
vendored
Normal file
65
.github/workflows/build-fork.yml
vendored
Normal file
@@ -0,0 +1,65 @@
|
||||
name: Publish Fork Image to GHCR
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
env:
|
||||
IMAGE_NAME: ghcr.io/kang-heewon/omniroute
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build and Push Fork Image
|
||||
if: github.repository == 'kang-heewon/OmniRoute'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
type=sha,prefix=sha-
|
||||
type=ref,event=tag
|
||||
labels: |
|
||||
org.opencontainers.image.title=omniroute
|
||||
org.opencontainers.image.description=Unified AI proxy/router — fork image
|
||||
org.opencontainers.image.url=https://github.com/kang-heewon/OmniRoute
|
||||
org.opencontainers.image.source=https://github.com/kang-heewon/OmniRoute
|
||||
org.opencontainers.image.licenses=MIT
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
target: runner-base
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
720
.github/workflows/ci.yml
vendored
720
.github/workflows/ci.yml
vendored
@@ -5,6 +5,8 @@ on:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -13,79 +15,421 @@ concurrency:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
CI_NODE_VERSION: "24"
|
||||
CI_NODE_24_VERSION: "24"
|
||||
CI_NODE_26_VERSION: "26"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# tsx gates below (known-symbols, route-guard-membership) import modules that
|
||||
# open SQLite on load; provide DB env so a fresh CI DB initializes cleanly.
|
||||
JWT_SECRET: ci-lint-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-lint-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- run: npm run audit:deps
|
||||
- run: npm run lint
|
||||
- run: npm run check:cycles
|
||||
- run: npm run check:route-validation:t06
|
||||
- run: npm run check:any-budget:t11
|
||||
- run: npm run check:provider-consistency
|
||||
- run: npm run check:fetch-targets
|
||||
- run: npm run check:deps
|
||||
- run: npm run check:file-size
|
||||
- run: npm run check:error-helper
|
||||
- run: npm run check:migration-numbering
|
||||
- run: npm run check:public-creds
|
||||
- run: npm run check:db-rules
|
||||
- run: npm run check:known-symbols
|
||||
- run: npm run check:route-guard-membership
|
||||
- run: npm run check:test-discovery
|
||||
- run: npm run check:docs-sync
|
||||
- run: npm run typecheck:core
|
||||
# typecheck:noimplicit:core is a forward-looking gate (noImplicitAny).
|
||||
# Run informationally for now — many pre-existing call sites still need
|
||||
# explicit annotations; track in a dedicated follow-up.
|
||||
- run: npm run typecheck:noimplicit:core
|
||||
continue-on-error: true
|
||||
|
||||
security:
|
||||
name: Security Audit
|
||||
quality-gate:
|
||||
name: Quality Ratchet
|
||||
runs-on: ubuntu-latest
|
||||
needs: test-coverage
|
||||
if: ${{ always() && needs.test-coverage.result == 'success' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
# Coverage mergeada (coverage-summary.json) p/ o ratchet de cobertura.
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: coverage-report
|
||||
path: coverage/
|
||||
- run: npm run quality:collect
|
||||
# Catraca: falha se qualquer métrica regredir vs quality-baseline.json (commitado).
|
||||
# Hoje: contagem de warnings do ESLint. Fase 4 estende com cobertura (lida do
|
||||
# coverage mergeado). Tamanho de arquivo e duplicação têm gates dedicados.
|
||||
- name: Ratchet check
|
||||
run: node scripts/quality/check-quality-ratchet.mjs --summary .artifacts/quality-ratchet.md
|
||||
# Catraca de duplicação (jscpd@4 sobre src+open-sse). Roda neste job (paralelo)
|
||||
# para não pesar no caminho crítico do lint.
|
||||
- name: Duplication ratchet
|
||||
run: npm run check:duplication
|
||||
- name: Complexity ratchet
|
||||
run: npm run check:complexity
|
||||
- name: Append summary
|
||||
if: always()
|
||||
run: cat .artifacts/quality-ratchet.md >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Upload ratchet report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: quality-ratchet
|
||||
path: .artifacts/quality-ratchet.md
|
||||
if-no-files-found: warn
|
||||
|
||||
docs-sync-strict:
|
||||
name: Docs Sync (Strict)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Dependency audit
|
||||
run: npm audit --audit-level=high --omit=dev
|
||||
- name: Check for known vulnerabilities
|
||||
run: npx is-my-node-vulnerable
|
||||
continue-on-error: true
|
||||
- run: npm run check:docs-all
|
||||
# Previously-orphaned contract gates (existed as files, never wired anywhere).
|
||||
# All exit 0 today: cli-i18n is a hard gate, openapi-coverage is a ratchet
|
||||
# (floor ~36), openapi-security-tiers is advisory (Hard Rules #15/#17).
|
||||
- name: CLI i18n consistency
|
||||
run: npm run check:cli-i18n
|
||||
- name: OpenAPI route coverage (ratchet)
|
||||
run: npm run check:openapi-coverage
|
||||
- name: OpenAPI security-tier consistency (advisory)
|
||||
run: npm run check:openapi-security-tiers
|
||||
- name: OpenAPI spec paths resolve to real routes (anti-hallucination)
|
||||
run: npm run check:openapi-routes
|
||||
- name: Doc /api refs resolve to real routes (anti-hallucination)
|
||||
run: npm run check:docs-symbols
|
||||
- name: i18n translation drift (warn)
|
||||
run: node scripts/i18n/check-translation-drift.mjs --warn
|
||||
|
||||
i18n-ui-coverage:
|
||||
name: i18n UI Coverage
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: node scripts/i18n/check-ui-keys-coverage.mjs --threshold=65
|
||||
|
||||
i18n-matrix:
|
||||
name: Build language matrix
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
langs: ${{ steps.langs.outputs.langs }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- id: langs
|
||||
run: |
|
||||
LANG_DIR="src/i18n/messages"
|
||||
LANGS=$(ls "$LANG_DIR"/*.json | xargs -n1 basename | sed 's/.json$//' | grep -v '^en$' | jq -R . | jq -s . | jq -c .)
|
||||
echo "langs=${LANGS}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
i18n:
|
||||
name: i18n Validation
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
lang: ${{ fromJson(needs.i18n-matrix.outputs.langs) }}
|
||||
needs: i18n-matrix
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Validate ${{ matrix.lang }}
|
||||
run: |
|
||||
python3 scripts/i18n/validate_translation.py quick -l '${{ matrix.lang }}' > result.txt
|
||||
|
||||
- name: Upload result
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: i18n-${{ matrix.lang }}
|
||||
path: result.txt
|
||||
|
||||
pr-test-policy:
|
||||
name: PR Test Policy
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
- name: Fetch base branch
|
||||
run: git fetch --no-tags origin "${GITHUB_BASE_REF}" --depth=1
|
||||
- name: Validate source changes include tests
|
||||
run: node scripts/check/check-pr-test-policy.mjs --summary-file .artifacts/pr-test-policy.md
|
||||
# Anti test-masking: flag net assert removal / new assert.ok(true) in changed tests.
|
||||
- name: Detect test-masking (weakened assertions)
|
||||
run: npm run check:test-masking
|
||||
- name: Publish PR test policy summary
|
||||
if: always()
|
||||
run: |
|
||||
if [ -f .artifacts/pr-test-policy.md ]; then
|
||||
cat .artifacts/pr-test-policy.md >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20, 22]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- run: npm run build
|
||||
- name: Archive Next.js build for E2E shards
|
||||
# Use tar so the archive preserves paths relative to CWD (.build/next/...).
|
||||
# upload-artifact path-stripping is ambiguous when exclude patterns are used;
|
||||
# an explicit tar avoids the double-nesting issue (.build/next/next/...).
|
||||
run: |
|
||||
tar -czf /tmp/e2e-build.tar.gz \
|
||||
--exclude='.build/next/standalone/node_modules' \
|
||||
--exclude='.build/next/cache' \
|
||||
.build/next
|
||||
- name: Upload Next.js build for E2E shards
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: e2e-next-build
|
||||
path: /tmp/e2e-build.tar.gz
|
||||
retention-days: 1
|
||||
|
||||
test-unit:
|
||||
name: Unit Tests
|
||||
package-artifact:
|
||||
name: Package Artifact
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
env:
|
||||
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
# build:cli runs a clean build into .build/next and assembles dist/
|
||||
# For release builds prefer: npm run build:release (clean rebuild + HEAD sentinel)
|
||||
- run: npm run build:cli
|
||||
- name: Assert dist/server.js exists
|
||||
run: test -f dist/server.js || (echo "dist/server.js missing — build:cli did not assemble correctly" && exit 1)
|
||||
- run: npm run check:pack-artifact
|
||||
|
||||
electron-package-smoke:
|
||||
name: Electron Package Smoke
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
needs: build
|
||||
env:
|
||||
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
|
||||
CSC_IDENTITY_AUTO_DISCOVERY: "false"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- run: npm run build
|
||||
- name: Install Electron dependencies
|
||||
working-directory: electron
|
||||
run: npm install --no-audit --no-fund
|
||||
- name: Pack Electron app
|
||||
working-directory: electron
|
||||
run: npm run pack
|
||||
- name: Smoke packaged Electron app
|
||||
env:
|
||||
ELECTRON_SMOKE_TIMEOUT_MS: 60000
|
||||
run: xvfb-run -a npm run electron:smoke:packaged
|
||||
|
||||
test-unit:
|
||||
name: Unit Tests (${{ matrix.shard }}/8)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node-version: [20, 22]
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run test:unit
|
||||
- run: npm run check:node-runtime
|
||||
- run: node --max-old-space-size=4096 --import tsx --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/8 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,compression,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts"
|
||||
|
||||
test-vitest:
|
||||
name: Vitest (MCP / autoCombo / UI components)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: build
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
# The second test runner (CLAUDE.md: "Both test runners must pass") — was never
|
||||
# wired into CI until the 2026-06-09 quality audit (Fase 6A.2).
|
||||
- run: npm run test:vitest
|
||||
# vitest:ui is RED today (14 fails — UI component drift accumulated while the
|
||||
# suite never ran in CI). Informational until the Fase 6A triage (2026-06-16+)
|
||||
# fixes the components/tests; then drop continue-on-error to make it blocking.
|
||||
- run: npm run test:vitest:ui
|
||||
continue-on-error: true
|
||||
|
||||
node-24-compat:
|
||||
name: Node 24 Compatibility (${{ matrix.shard }}/2)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_24_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- run: npm run build
|
||||
- run: node --import tsx --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,compression,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts"
|
||||
|
||||
node-26-compat:
|
||||
name: Node 26 Compatibility (${{ matrix.shard }}/2)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_26_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- run: npm run build
|
||||
- run: node --import tsx --test --test-force-exit --test-concurrency=4 --test-shard=${{ matrix.shard }}/2 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,compression,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts"
|
||||
|
||||
test-coverage-shard:
|
||||
name: Coverage Shard (${{ matrix.shard }}/8)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- name: Run c8 over shard ${{ matrix.shard }}/8
|
||||
run: |
|
||||
rm -rf coverage-shard coverage-shard-report
|
||||
# `--temp-directory` (writable via NODE_V8_COVERAGE) is what the merge
|
||||
# job reads with `c8 report --temp-directory ...`. Using `--output-dir`
|
||||
# only produces the final json *report* and leaves the raw v8 files in
|
||||
# `coverage/tmp`, so uploading `coverage-shard/` was empty. Pin the temp
|
||||
# dir so the raw coverage files live there and the artifact upload picks
|
||||
# them up regardless of `--test-force-exit` timing.
|
||||
npx c8 \
|
||||
--temp-directory=coverage-shard \
|
||||
--reports-dir=coverage-shard-report \
|
||||
--reporter=json \
|
||||
--exclude=tests/** \
|
||||
--exclude=**/*.test.* \
|
||||
node --max-old-space-size=4096 --import tsx --test --test-force-exit --test-concurrency=4 \
|
||||
--test-shard=${{ matrix.shard }}/8 tests/unit/*.test.ts "tests/unit/{api,auth,authz,build,cli,cli-helper,compression,cors,dashboard,db,db-adapters,docs,gamification,guardrails,lib,mcp,runtime,security,services,settings,shared,ui}/**/*.test.ts"
|
||||
- name: Upload raw shard coverage
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: coverage-shard-${{ matrix.shard }}
|
||||
path: coverage-shard/*.json
|
||||
if-no-files-found: error
|
||||
|
||||
test-coverage:
|
||||
name: Coverage
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
timeout-minutes: 10
|
||||
needs: test-coverage-shard
|
||||
if: ${{ always() && needs.test-coverage-shard.result == 'success' }}
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
@@ -93,49 +437,249 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run test:coverage
|
||||
- name: Check coverage threshold
|
||||
- name: Download all shard coverage
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: coverage-shard-*
|
||||
path: coverage-shards/
|
||||
merge-multiple: true
|
||||
- name: Merge + report + gate
|
||||
# Merging 8 shards of raw v8 coverage is memory-heavy; the default Node
|
||||
# heap OOMs (exit 134). Raise it for the c8 merge/report step.
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=6144
|
||||
run: |
|
||||
echo "Coverage report generated. Check output for threshold compliance."
|
||||
mkdir -p coverage
|
||||
if [ ! -d coverage-shards ] || ! find coverage-shards -maxdepth 1 -type f -name '*.json' | grep -q .; then
|
||||
echo "::error::No raw coverage shard data was downloaded."
|
||||
find . -maxdepth 3 -type f | sort
|
||||
exit 1
|
||||
fi
|
||||
# Gate aligned to the project's local coverage bar: `npm run test:coverage`
|
||||
# gates at 60/60/60/60, so CI must match it (the previous CI floor of 40
|
||||
# silently undershot the local bar — a real drift). Real merged coverage is
|
||||
# ~79/79/82/75, so 60 is a conservative floor with headroom; the Fase-4
|
||||
# coverage ratchet (quality-baseline.json) layers "must not drop vs baseline"
|
||||
# on top of this floor.
|
||||
npx c8 report \
|
||||
--temp-directory coverage-shards \
|
||||
--reports-dir coverage \
|
||||
--reporter=text-summary \
|
||||
--reporter=html \
|
||||
--reporter=json-summary \
|
||||
--reporter=lcov \
|
||||
--exclude=tests/** \
|
||||
--exclude=**/*.test.* \
|
||||
--check-coverage \
|
||||
--statements 60 --lines 60 --functions 60 --branches 60
|
||||
- name: Build coverage summary
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p coverage
|
||||
if [ -f coverage/coverage-summary.json ]; then
|
||||
node scripts/check/test-report-summary.mjs \
|
||||
--input coverage/coverage-summary.json \
|
||||
--output coverage/coverage-report.md \
|
||||
--threshold 60
|
||||
else
|
||||
printf '%s\n' \
|
||||
'# Coverage Report' \
|
||||
'' \
|
||||
'Coverage summary JSON was not generated. Inspect the Coverage job logs.' \
|
||||
> coverage/coverage-report.md
|
||||
fi
|
||||
cat coverage/coverage-report.md >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Upload coverage artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: coverage-report
|
||||
path: |
|
||||
coverage/coverage-summary.json
|
||||
coverage/lcov.info
|
||||
coverage/coverage-report.md
|
||||
if-no-files-found: warn
|
||||
|
||||
sonarqube:
|
||||
name: SonarQube
|
||||
runs-on: ubuntu-latest
|
||||
needs: test-coverage
|
||||
if: ${{ always() && needs.test-coverage.result == 'success' }}
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: coverage-report
|
||||
path: .
|
||||
- name: Explain SonarQube skip
|
||||
if: ${{ github.event_name != 'pull_request' || env.SONAR_TOKEN == '' || env.SONAR_HOST_URL == '' }}
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" != "pull_request" ]; then
|
||||
echo "SonarQube scan skipped on non-PR events to keep main pushes governed by repository CI gates." >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "SonarQube scan skipped because SONAR_TOKEN or SONAR_HOST_URL is not configured." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
- name: SonarQube Scan
|
||||
if: ${{ github.event_name == 'pull_request' && env.SONAR_TOKEN != '' && env.SONAR_HOST_URL != '' }}
|
||||
uses: SonarSource/sonarqube-scan-action@v8
|
||||
env:
|
||||
SONAR_TOKEN: ${{ env.SONAR_TOKEN }}
|
||||
SONAR_HOST_URL: ${{ env.SONAR_HOST_URL }}
|
||||
|
||||
coverage-pr-comment:
|
||||
name: PR Coverage Comment
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ always() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false }}
|
||||
needs:
|
||||
- pr-test-policy
|
||||
- test-coverage
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Download coverage artifact
|
||||
if: ${{ needs.test-coverage.result != 'cancelled' }}
|
||||
continue-on-error: true
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: coverage-report
|
||||
path: .
|
||||
- name: Prepare PR coverage comment
|
||||
env:
|
||||
COVERAGE_RESULT: ${{ needs.test-coverage.result }}
|
||||
POLICY_RESULT: ${{ needs.pr-test-policy.result }}
|
||||
run: |
|
||||
mkdir -p .artifacts
|
||||
{
|
||||
echo "<!-- omniroute-coverage-report -->"
|
||||
echo "## CI Coverage Report"
|
||||
echo ""
|
||||
echo "- Coverage job: \`${COVERAGE_RESULT}\`"
|
||||
echo "- PR test policy: \`${POLICY_RESULT}\`"
|
||||
echo ""
|
||||
if [ -f coverage/coverage-report.md ]; then
|
||||
cat coverage/coverage-report.md
|
||||
else
|
||||
echo "Coverage artifact was not available for this run."
|
||||
fi
|
||||
if [ "${POLICY_RESULT}" = "failure" ]; then
|
||||
echo ""
|
||||
echo "## PR Test Policy"
|
||||
echo ""
|
||||
echo "This PR changes production code in \`src/\`, \`open-sse/\`, \`electron/\`, or \`bin/\` without accompanying automated tests."
|
||||
fi
|
||||
} > .artifacts/pr-coverage-comment.md
|
||||
- uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
const fs = require("fs");
|
||||
const marker = "<!-- omniroute-coverage-report -->";
|
||||
const body = fs.readFileSync(".artifacts/pr-coverage-comment.md", "utf8");
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = context.issue.number;
|
||||
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner,
|
||||
repo,
|
||||
issue_number,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const existing = comments.find((comment) => comment.body?.includes(marker));
|
||||
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner,
|
||||
repo,
|
||||
comment_id: existing.id,
|
||||
body,
|
||||
});
|
||||
} else {
|
||||
await github.rest.issues.createComment({
|
||||
owner,
|
||||
repo,
|
||||
issue_number,
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
test-e2e:
|
||||
name: E2E Tests
|
||||
name: E2E Tests (${{ matrix.shard }}/9)
|
||||
runs-on: ubuntu-latest
|
||||
# Build artifact from the `build` job is downloaded instead of rebuilding
|
||||
# (~5min saved per shard). 9 shards (up from 6) reduces tests per shard by
|
||||
# ~33%. Playwright browser is cached across runs (~1.5min saved per shard).
|
||||
# Heavy shard target: ≤20min (was ~40min). Timeout 45min to cover slow runners.
|
||||
timeout-minutes: 45
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
OMNIROUTE_PLAYWRIGHT_SKIP_BUILD: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
|
||||
restore-keys: playwright-chromium-${{ runner.os }}-
|
||||
- run: npx playwright install --with-deps chromium
|
||||
- run: npm run build
|
||||
- run: npm run test:e2e
|
||||
- name: Download Next.js build artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: e2e-next-build
|
||||
path: /tmp/
|
||||
- name: Extract Next.js build and restore standalone node_modules
|
||||
run: |
|
||||
tar -xzf /tmp/e2e-build.tar.gz
|
||||
cp -r node_modules .build/next/standalone/node_modules
|
||||
- run: npx playwright test tests/e2e/*.spec.ts --shard=${{ matrix.shard }}/9
|
||||
|
||||
test-integration:
|
||||
name: Integration Tests
|
||||
name: Integration Tests (${{ matrix.shard }}/2)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
INITIAL_PASSWORD: ci-test-password-for-integration
|
||||
DATA_DIR: /tmp/omniroute-ci
|
||||
DATA_DIR: /tmp/omniroute-ci-${{ matrix.shard }}
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run test:integration
|
||||
- run: npm run check:node-runtime
|
||||
- run: node --import tsx --test --test-force-exit --test-concurrency=1 --test-shard=${{ matrix.shard }}/2 tests/integration/*.test.ts
|
||||
|
||||
test-security:
|
||||
name: Security Tests
|
||||
@@ -144,11 +688,123 @@ jobs:
|
||||
env:
|
||||
JWT_SECRET: ci-test-secret-with-sufficient-length-for-validation
|
||||
API_KEY_SECRET: ci-test-api-key-secret-long
|
||||
DISABLE_SQLITE_AUTO_BACKUP: "true"
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.CI_NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run check:node-runtime
|
||||
- run: npm run test:security
|
||||
|
||||
ci-summary:
|
||||
name: CI Dashboard
|
||||
runs-on: ubuntu-latest
|
||||
if: always()
|
||||
needs:
|
||||
- lint
|
||||
- docs-sync-strict
|
||||
- i18n-ui-coverage
|
||||
- i18n
|
||||
- pr-test-policy
|
||||
|
||||
- build
|
||||
- package-artifact
|
||||
- electron-package-smoke
|
||||
- test-unit
|
||||
- node-24-compat
|
||||
- node-26-compat
|
||||
- test-coverage
|
||||
- sonarqube
|
||||
- coverage-pr-comment
|
||||
- test-e2e
|
||||
- test-integration
|
||||
- test-security
|
||||
steps:
|
||||
- name: Download i18n results
|
||||
continue-on-error: true
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: i18n-*
|
||||
path: results
|
||||
merge-multiple: true
|
||||
|
||||
- name: Generate dashboard
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
run: |
|
||||
status() {
|
||||
case "$1" in
|
||||
success) echo "🟢 PASS" ;;
|
||||
failure) echo "🔴 FAIL" ;;
|
||||
cancelled) echo "⚫ CANCELLED" ;;
|
||||
skipped) echo "⚪ SKIPPED" ;;
|
||||
*) echo "🟡 UNKNOWN" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
echo "# 🚀 CI Dashboard" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
echo "## 🧱 Core Checks" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Job | Status |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "|-----|--------|" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Lint | $(status '${{ needs.lint.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Docs Sync (Strict) | $(status '${{ needs.docs-sync-strict.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| i18n UI Coverage | $(status '${{ needs.i18n-ui-coverage.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| PR Test Policy | $(status '${{ needs.pr-test-policy.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
echo "| SonarQube | $(status '${{ needs.sonarqube.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "## 🏗️ Build" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Job | Status |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "|-----|--------|" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Build Matrix | $(status '${{ needs.build.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Package Artifact | $(status '${{ needs.package-artifact.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Electron Package Smoke | $(status '${{ needs.electron-package-smoke.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "## 🧪 Tests" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Suite | Status |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "|-------|--------|" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Unit | $(status '${{ needs.test-unit.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Node 24 Compatibility | $(status '${{ needs.node-24-compat.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Node 26 Compatibility | $(status '${{ needs.node-26-compat.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Coverage | $(status '${{ needs.test-coverage.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| PR Coverage Comment | $(status '${{ needs.coverage-pr-comment.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| E2E | $(status '${{ needs.test-e2e.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Integration | $(status '${{ needs.test-integration.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Security Tests | $(status '${{ needs.test-security.result }}') |" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "## 🌍 Translations" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
total=0
|
||||
langs=0
|
||||
|
||||
if [ -d results ]; then
|
||||
for file in results/*.txt; do
|
||||
[ -f "$file" ] || continue
|
||||
val=$(sed -r 's/\x1B\[[0-9;]*[mK]//g' "$file" | grep "Untranslated:" | awk '{print $2}')
|
||||
val=${val:-0}
|
||||
total=$((total + val))
|
||||
langs=$((langs + 1))
|
||||
done
|
||||
fi
|
||||
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Metric | Value |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "|--------|------|" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Languages checked | $langs |" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "| Total untranslated | $total |" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
if [ "$total" -gt 0 ]; then
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "⚠️ **Translations need attention**" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "✅ **All translations complete**" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
49
.github/workflows/claude.yml
vendored
Normal file
49
.github/workflows/claude.yml
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
name: Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
||||
# This is an optional setting that allows Claude to read CI results on PRs
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
|
||||
# Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it.
|
||||
# prompt: 'Update the pull request description to include a summary of changes.'
|
||||
|
||||
# Optional: Add claude_args to customize behavior and configuration
|
||||
# See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md
|
||||
# or https://code.claude.com/docs/en/cli-reference for available options
|
||||
# claude_args: '--allowed-tools Bash(gh pr *)'
|
||||
82
.github/workflows/deploy-vps.yml
vendored
82
.github/workflows/deploy-vps.yml
vendored
@@ -6,6 +6,9 @@ on:
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: >-
|
||||
@@ -14,27 +17,82 @@ jobs:
|
||||
name: Deploy OmniRoute to VPS
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check VPS SSH reachability from runner
|
||||
id: reach
|
||||
env:
|
||||
# Pass the host via env (never interpolate a secret straight into the
|
||||
# script body) so /dev/tcp gets a shell variable, not inlined text.
|
||||
VPS_HOST: ${{ secrets.VPS_HOST }}
|
||||
run: |
|
||||
set -uo pipefail
|
||||
# A GitHub-hosted runner can only deploy when it can actually open a TCP
|
||||
# connection to the VPS SSH port. The Local VPS lives on a private LAN and
|
||||
# the Akamai host firewalls :22 to known IPs, so the runner is routinely
|
||||
# unable to reach it (`dial tcp ***:22: i/o timeout`). Treat "unreachable
|
||||
# from the runner" as a SKIP — the real deploys are run manually from an
|
||||
# allowed network via the deploy-vps-local / deploy-vps-akamai skills — so
|
||||
# an unreachable host no longer red-fails every release/push pipeline.
|
||||
# When the host IS reachable, the deploy step below still runs in full and
|
||||
# its health gate surfaces any genuine deploy failure.
|
||||
if timeout 15 bash -c 'exec 3<>"/dev/tcp/${VPS_HOST}/22"' 2>/dev/null; then
|
||||
echo "reachable=true" >> "$GITHUB_OUTPUT"
|
||||
echo "✅ VPS_HOST:22 reachable from the runner — proceeding with deploy."
|
||||
else
|
||||
echo "reachable=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::warning title=Auto-deploy skipped::VPS_HOST:22 is not reachable from this GitHub runner (private LAN / firewalled). Deploy manually with the deploy-vps-local or deploy-vps-akamai skill."
|
||||
fi
|
||||
|
||||
- name: Deploy via SSH
|
||||
if: steps.reach.outputs.reachable == 'true'
|
||||
uses: appleboy/ssh-action@v1
|
||||
continue-on-error: true
|
||||
with:
|
||||
host: ${{ secrets.VPS_HOST }}
|
||||
username: ${{ secrets.VPS_USER }}
|
||||
key: ${{ secrets.VPS_SSH_KEY }}
|
||||
port: 22
|
||||
timeout: 30s
|
||||
command_timeout: 5m
|
||||
timeout: 60s
|
||||
command_timeout: 15m
|
||||
script: |
|
||||
echo "=== Updating OmniRoute ==="
|
||||
npm install -g omniroute@latest 2>&1
|
||||
INSTALLED_VERSION=$(omniroute --version 2>/dev/null || echo "unknown")
|
||||
echo "Installed version: $INSTALLED_VERSION"
|
||||
set -euo pipefail
|
||||
|
||||
echo "=== Restarting PM2 ==="
|
||||
pm2 restart omniroute || pm2 start omniroute --name omniroute -- --port 20128
|
||||
echo "=== Updating OmniRoute ==="
|
||||
npm install -g omniroute@latest
|
||||
INSTALLED_VERSION=$(omniroute --version 2>/dev/null | tr -d '[:space:]' || echo "unknown")
|
||||
echo "Installed CLI version: $INSTALLED_VERSION"
|
||||
|
||||
# Recreate the PM2 process instead of `pm2 restart`. A bare restart
|
||||
# re-runs whatever script path was saved earlier; after the build-output
|
||||
# reorg (app/ -> dist/, .next -> .build/next) a process pinned to the old
|
||||
# app/server-ws.mjs path can no longer start, and the node process dies
|
||||
# while PM2 still reports "online" — so the box never binds :20128.
|
||||
# Always launch via the `omniroute` bin so .env is loaded and the dist/
|
||||
# layout is resolved correctly.
|
||||
echo "=== (Re)creating PM2 process via bin ==="
|
||||
pm2 delete omniroute 2>/dev/null || true
|
||||
pm2 start omniroute --name omniroute -- --port 20128
|
||||
pm2 save
|
||||
|
||||
echo "=== Health Check ==="
|
||||
sleep 3
|
||||
curl -sf http://localhost:20128/api/settings > /dev/null && echo "✅ OmniRoute is healthy" || echo "❌ Health check failed"
|
||||
# Health gate: fail the deploy unless the box actually reports healthy.
|
||||
# Poll /api/monitoring/health for "status":"healthy" (a deeper signal than
|
||||
# a static page 200 — it confirms the app booted, not just that a port is
|
||||
# bound). Boot can take a while after a native-module/build-layout change,
|
||||
# so poll up to ~3min before giving up.
|
||||
echo "=== Health Check (gates the deploy) ==="
|
||||
ok=0
|
||||
for i in $(seq 1 36); do
|
||||
BODY=$(curl -sf -m 5 http://localhost:20128/api/monitoring/health 2>/dev/null || true)
|
||||
if printf '%s' "$BODY" | grep -q '"status":"healthy"'; then
|
||||
ok=1
|
||||
echo "✅ /api/monitoring/health -> healthy (attempt $i) — version $INSTALLED_VERSION"
|
||||
break
|
||||
fi
|
||||
echo "… not healthy yet (attempt $i/36), retrying in 5s"
|
||||
sleep 5
|
||||
done
|
||||
if [ "$ok" != "1" ]; then
|
||||
echo "❌ Health check failed — /api/monitoring/health never reported healthy after ~3min"
|
||||
echo "--- recent PM2 logs ---"
|
||||
pm2 logs omniroute --lines 40 --nostream || true
|
||||
exit 1
|
||||
fi
|
||||
echo "=== Deploy complete ==="
|
||||
|
||||
309
.github/workflows/docker-publish.yml
vendored
309
.github/workflows/docker-publish.yml
vendored
@@ -1,24 +1,147 @@
|
||||
name: Publish to Docker Hub
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
paths-ignore:
|
||||
- ".github/workflows/**"
|
||||
# Use 'released' instead of 'published' so editing/re-publishing old releases
|
||||
# does NOT re-trigger this workflow. 'released' fires only on the initial
|
||||
# release publication (and pre-release → release transition).
|
||||
release:
|
||||
types: [published]
|
||||
types: [released]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version tag to build (e.g. 3.8.4)"
|
||||
required: true
|
||||
type: string
|
||||
promote_latest:
|
||||
description: "Also tag :latest (only if this is the highest semver)"
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
name: Build and Push Docker (multi-arch)
|
||||
prepare:
|
||||
name: Resolve Docker release metadata
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
promote_latest: ${{ steps.version.outputs.promote_latest }}
|
||||
skip: ${{ steps.version.outputs.skip }}
|
||||
env:
|
||||
IMAGE_NAME: diegosouzapw/omniroute
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || '' }}
|
||||
# Need full tag history for semver comparison when deciding :latest.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up QEMU (for multi-arch builds)
|
||||
uses: docker/setup-qemu-action@v4
|
||||
- name: Resolve version, latest-promotion, and skip flag
|
||||
id: version
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
REF_TYPE: ${{ github.ref_type }}
|
||||
INPUT_VERSION: ${{ inputs.version }}
|
||||
PROMOTE_INPUT: ${{ inputs.promote_latest }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# 1) Resolve version string from the trigger (all inputs come via env).
|
||||
case "$EVENT_NAME" in
|
||||
workflow_dispatch)
|
||||
VERSION="${INPUT_VERSION#v}"
|
||||
;;
|
||||
push)
|
||||
if [ "$REF_TYPE" = "tag" ]; then
|
||||
VERSION="${REF_NAME#v}"
|
||||
else
|
||||
# Push to main → build & tag as `main` only. Never touch :latest.
|
||||
VERSION="main"
|
||||
fi
|
||||
;;
|
||||
release)
|
||||
VERSION="${REF_NAME#v}"
|
||||
;;
|
||||
*)
|
||||
VERSION="${REF_NAME#v}"
|
||||
;;
|
||||
esac
|
||||
# Sanity-check: only allow [A-Za-z0-9._-] in VERSION (defense in depth).
|
||||
if ! printf '%s' "$VERSION" | grep -qE '^[A-Za-z0-9._-]+$'; then
|
||||
echo "Refusing to use unsafe VERSION value: $VERSION" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# 2) Decide whether to promote :latest.
|
||||
PROMOTE="false"
|
||||
if [ "$VERSION" = "main" ]; then
|
||||
PROMOTE="false"
|
||||
elif printf '%s' "$VERSION" | grep -qE -- '-(rc|alpha|beta|pre|next)'; then
|
||||
echo "Pre-release identifier detected — skipping :latest."
|
||||
PROMOTE="false"
|
||||
elif [ "$EVENT_NAME" = "workflow_dispatch" ]; then
|
||||
PROMOTE="${PROMOTE_INPUT:-false}"
|
||||
else
|
||||
git fetch --tags --quiet || true
|
||||
HIGHEST=$(git tag -l 'v[0-9]*' | sed 's/^v//' | grep -vE -- '-(rc|alpha|beta|pre|next)' | sort -V | tail -1 || echo "")
|
||||
if [ -n "$HIGHEST" ] && [ "$VERSION" = "$HIGHEST" ]; then
|
||||
PROMOTE="true"
|
||||
else
|
||||
echo "Version $VERSION is not the highest semver tag (highest=${HIGHEST:-<none>}). Not promoting :latest."
|
||||
fi
|
||||
fi
|
||||
echo "promote_latest=$PROMOTE" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# 3) Skip if this exact version is already published in Docker Hub.
|
||||
# `main` is always rebuilt (mutable floating tag).
|
||||
SKIP="false"
|
||||
if [ "$VERSION" != "main" ]; then
|
||||
if docker manifest inspect "diegosouzapw/omniroute:${VERSION}" >/dev/null 2>&1; then
|
||||
echo "Image diegosouzapw/omniroute:${VERSION} already exists on Docker Hub — skipping rebuild."
|
||||
SKIP="true"
|
||||
fi
|
||||
fi
|
||||
echo "skip=$SKIP" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "Publishing diegosouzapw/omniroute:$VERSION (promote_latest=$PROMOTE, skip=$SKIP)"
|
||||
|
||||
build:
|
||||
name: Build Docker (${{ matrix.platform }})
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.skip != 'true'
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-24.04
|
||||
arch: amd64
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
arch: arm64
|
||||
env:
|
||||
IMAGE_NAME: diegosouzapw/omniroute
|
||||
GHCR_IMAGE_NAME: ghcr.io/diegosouzapw/omniroute
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || '' }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
@@ -29,35 +152,179 @@ jobs:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Extract version from release tag
|
||||
id: version
|
||||
run: |
|
||||
VERSION="${GITHUB_REF_NAME}"
|
||||
VERSION="${VERSION#v}"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "Publishing Docker image: $IMAGE_NAME:$VERSION"
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push multi-arch image
|
||||
- name: Build and push platform image by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
target: runner-base
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
|
||||
tags: |
|
||||
${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}
|
||||
${{ env.IMAGE_NAME }}:latest
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
${{ env.IMAGE_NAME }}
|
||||
${{ env.GHCR_IMAGE_NAME }}
|
||||
cache-from: type=gha,scope=docker-${{ matrix.arch }}
|
||||
cache-to: type=gha,scope=docker-${{ matrix.arch }},mode=max
|
||||
no-cache: false
|
||||
env:
|
||||
DOCKER_BUILDKIT_INLINE_CACHE: 1
|
||||
|
||||
- name: Inspect image
|
||||
- name: Build and push WEB platform image by digest
|
||||
id: build-web
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
target: runner-web
|
||||
platforms: ${{ matrix.platform }}
|
||||
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
|
||||
tags: |
|
||||
${{ env.IMAGE_NAME }}
|
||||
${{ env.GHCR_IMAGE_NAME }}
|
||||
cache-from: type=gha,scope=docker-web-${{ matrix.arch }}
|
||||
cache-to: type=gha,scope=docker-web-${{ matrix.arch }},mode=max
|
||||
no-cache: false
|
||||
env:
|
||||
DOCKER_BUILDKIT_INLINE_CACHE: 1
|
||||
|
||||
- name: Export digests
|
||||
env:
|
||||
DIGEST_BASE: ${{ steps.build.outputs.digest }}
|
||||
DIGEST_WEB: ${{ steps.build-web.outputs.digest }}
|
||||
run: |
|
||||
docker buildx imagetools inspect "${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}"
|
||||
set -euo pipefail
|
||||
mkdir -p /tmp/digests/base /tmp/digests/web
|
||||
touch "/tmp/digests/base/${DIGEST_BASE#sha256:}"
|
||||
touch "/tmp/digests/web/${DIGEST_WEB#sha256:}"
|
||||
|
||||
- name: Upload base digests
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: digests-base-${{ matrix.arch }}
|
||||
path: /tmp/digests/base/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
- name: Upload web digests
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: digests-web-${{ matrix.arch }}
|
||||
path: /tmp/digests/web/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
merge:
|
||||
name: Publish multi-arch manifests
|
||||
needs:
|
||||
- prepare
|
||||
- build
|
||||
if: needs.prepare.outputs.skip != 'true'
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
IMAGE_NAME: diegosouzapw/omniroute
|
||||
GHCR_IMAGE_NAME: ghcr.io/diegosouzapw/omniroute
|
||||
VERSION: ${{ needs.prepare.outputs.version }}
|
||||
PROMOTE_LATEST: ${{ needs.prepare.outputs.promote_latest }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || '' }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Download base digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: digests-base-*
|
||||
path: /tmp/digests/base
|
||||
merge-multiple: true
|
||||
|
||||
- name: Download web digests
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: digests-web-*
|
||||
path: /tmp/digests/web
|
||||
merge-multiple: true
|
||||
|
||||
- name: Create Docker Hub manifest
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
create_manifest() {
|
||||
local image="$1" suffix="$2" dir="$3"
|
||||
local tags=(-t "${image}:${VERSION}${suffix}")
|
||||
if [ "$PROMOTE_LATEST" = "true" ]; then
|
||||
tags+=(-t "${image}:latest${suffix}")
|
||||
fi
|
||||
local refs=()
|
||||
while IFS= read -r digest_file; do
|
||||
refs+=("${image}@sha256:$(basename "$digest_file")")
|
||||
done < <(find "$dir" -type f | sort)
|
||||
if [ "${#refs[@]}" -eq 0 ]; then
|
||||
echo "No image digests in $dir" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker buildx imagetools create "${tags[@]}" "${refs[@]}"
|
||||
}
|
||||
|
||||
create_manifest "${IMAGE_NAME}" "" /tmp/digests/base
|
||||
create_manifest "${IMAGE_NAME}" "-web" /tmp/digests/web
|
||||
|
||||
- name: Create GHCR manifest
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
create_manifest() {
|
||||
local image="$1" suffix="$2" dir="$3"
|
||||
local tags=(-t "${image}:${VERSION}${suffix}")
|
||||
if [ "$PROMOTE_LATEST" = "true" ]; then
|
||||
tags+=(-t "${image}:latest${suffix}")
|
||||
fi
|
||||
local refs=()
|
||||
while IFS= read -r digest_file; do
|
||||
refs+=("${image}@sha256:$(basename "$digest_file")")
|
||||
done < <(find "$dir" -type f | sort)
|
||||
if [ "${#refs[@]}" -eq 0 ]; then
|
||||
echo "No image digests in $dir" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker buildx imagetools create "${tags[@]}" "${refs[@]}"
|
||||
}
|
||||
|
||||
create_manifest "${GHCR_IMAGE_NAME}" "" /tmp/digests/base
|
||||
create_manifest "${GHCR_IMAGE_NAME}" "-web" /tmp/digests/web
|
||||
|
||||
- name: Inspect image
|
||||
if: needs.prepare.outputs.version != 'main'
|
||||
run: |
|
||||
docker buildx imagetools inspect "${IMAGE_NAME}:${VERSION}"
|
||||
|
||||
- name: Update Docker Hub description
|
||||
# Only refresh README/description when we actually promote :latest
|
||||
# (avoids overwriting from main pushes or back-fill builds).
|
||||
if: needs.prepare.outputs.promote_latest == 'true'
|
||||
uses: peter-evans/dockerhub-description@v5
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
|
||||
59
.github/workflows/electron-release.yml
vendored
59
.github/workflows/electron-release.yml
vendored
@@ -13,6 +13,8 @@ on:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
@@ -69,13 +71,11 @@ jobs:
|
||||
deb_ext: .deb
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Cache node_modules
|
||||
@@ -88,10 +88,23 @@ jobs:
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
env:
|
||||
NPM_CONFIG_LEGACY_PEER_DEPS: true
|
||||
|
||||
- name: Sanitize Windows home directory
|
||||
if: runner.os == 'Windows'
|
||||
shell: bash
|
||||
run: |
|
||||
# The default USERPROFILE contains junction points (Application Data)
|
||||
# that cause EPERM errors during Next.js standalone build glob scans.
|
||||
# Create a clean temp profile directory to avoid this.
|
||||
mkdir -p "$RUNNER_TEMP/home"
|
||||
echo "USERPROFILE=$RUNNER_TEMP/home" >> $GITHUB_ENV
|
||||
|
||||
- name: Build Next.js standalone
|
||||
env:
|
||||
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
|
||||
NODE_OPTIONS: "--max_old_space_size=6144"
|
||||
run: npm run build
|
||||
|
||||
- name: Sync version in electron/package.json
|
||||
@@ -121,6 +134,30 @@ jobs:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: npm run build:${{ matrix.target }}
|
||||
|
||||
- name: Smoke packaged Electron app
|
||||
if: matrix.platform != 'linux'
|
||||
# Best-effort smoke on Windows + macos-arm64:
|
||||
# - Windows: requestSingleInstanceLock() fails due to USERPROFILE
|
||||
# sanitization needed for the build step.
|
||||
# - macos-arm64: the headless GitHub arm64 runner crashes Electron's GPU
|
||||
# process (gpu_process_host exit_code=15 → network service crash →
|
||||
# "No rendezvous client, terminating process"), so the app can't bind
|
||||
# 127.0.0.1:20128 in time. The identical bundle is smoke-gated on
|
||||
# macos-intel + linux, so packaging is still verified per-OS; we don't
|
||||
# let the arm64 runner's GPU flakiness block the desktop release.
|
||||
continue-on-error: ${{ matrix.platform == 'windows' || matrix.platform == 'macos-arm64' }}
|
||||
env:
|
||||
ELECTRON_SMOKE_TIMEOUT_MS: 60000
|
||||
ELECTRON_SMOKE_STREAM_LOGS: "1"
|
||||
run: npm run electron:smoke:packaged
|
||||
|
||||
- name: Smoke packaged Electron app (Linux)
|
||||
if: matrix.platform == 'linux'
|
||||
env:
|
||||
ELECTRON_SMOKE_TIMEOUT_MS: 60000
|
||||
ELECTRON_SMOKE_STREAM_LOGS: "1"
|
||||
run: xvfb-run -a npm run electron:smoke:packaged
|
||||
|
||||
- name: Collect installers
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -184,7 +221,7 @@ jobs:
|
||||
run: ls -la release-assets/
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ needs.validate.outputs.version }}
|
||||
draft: false
|
||||
@@ -201,3 +238,13 @@ jobs:
|
||||
release-assets/*.source.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
publish-npm:
|
||||
name: Publish to npm
|
||||
needs: [validate, release]
|
||||
uses: ./.github/workflows/npm-publish.yml
|
||||
with:
|
||||
version: ${{ needs.validate.outputs.version }}
|
||||
tag: latest
|
||||
secrets:
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
125
.github/workflows/lock-released-branch.yml
vendored
Normal file
125
.github/workflows/lock-released-branch.yml
vendored
Normal file
@@ -0,0 +1,125 @@
|
||||
name: Lock released branch
|
||||
|
||||
# Two responsibilities (defense in depth — Hard Rule #18 enforcement):
|
||||
#
|
||||
# 1. `on: release: published` — when a GitHub Release publishes tag v3.X.Y,
|
||||
# apply branch protection (lock_branch + enforce_admins) to release/v3.X.Y
|
||||
# so no further commits can land on a shipped version. To reopen later:
|
||||
# gh api -X DELETE repos/<owner>/<repo>/branches/release/<tag>/protection
|
||||
#
|
||||
# 2. `on: push: branches: ['release/v*']` — verify that no push lands on a
|
||||
# release/* branch whose matching tag already exists. This is the preventive
|
||||
# guard: if the lock didn't apply (workflow bug, missing PAT, race), this
|
||||
# job FAILS the push run so the operator gets paged immediately.
|
||||
#
|
||||
# `permissions:` cannot grant the `Administration` scope to GITHUB_TOKEN — that
|
||||
# scope only exists on PATs. Set BRANCH_LOCK_TOKEN as a repo secret pointing to
|
||||
# a PAT/fine-grained token with `Administration: read & write`. Without it, the
|
||||
# lock step will fail loudly (which is what we want — silent failure caused the
|
||||
# v3.8.3 incident on 2026-05-26 where 6 commits landed post-release).
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
push:
|
||||
branches:
|
||||
- "release/v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Tag of the released version (e.g. v3.8.2)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# Job 1 — Lock the release branch when a Release is published.
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
lock-branch:
|
||||
if: github.event_name == 'release' || github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Lock release/<tag> branch
|
||||
env:
|
||||
# Administration scope is required to PUT branch protection. Default
|
||||
# GITHUB_TOKEN cannot do this — operator must provision BRANCH_LOCK_TOKEN.
|
||||
GH_TOKEN: ${{ secrets.BRANCH_LOCK_TOKEN }}
|
||||
TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [ -z "${GH_TOKEN}" ]; then
|
||||
echo "::error::BRANCH_LOCK_TOKEN secret is not set. Create a PAT with Administration:write and add it as repo secret."
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "${TAG}" ]; then
|
||||
echo "::error::No tag provided; cannot determine release branch."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BRANCH="release/${TAG}"
|
||||
echo "Target branch: ${BRANCH} (repo: ${REPO})"
|
||||
|
||||
if ! gh api "repos/${REPO}/branches/${BRANCH}" >/dev/null 2>&1; then
|
||||
echo "::warning::Branch ${BRANCH} not found — nothing to lock."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Applying lock_branch protection to ${BRANCH}..."
|
||||
gh api -X PUT "repos/${REPO}/branches/${BRANCH}/protection" --input - <<'JSON'
|
||||
{
|
||||
"required_status_checks": null,
|
||||
"enforce_admins": true,
|
||||
"required_pull_request_reviews": null,
|
||||
"restrictions": null,
|
||||
"lock_branch": true,
|
||||
"allow_force_pushes": false,
|
||||
"allow_deletions": false
|
||||
}
|
||||
JSON
|
||||
|
||||
LOCKED=$(gh api "repos/${REPO}/branches/${BRANCH}/protection" \
|
||||
--jq '.lock_branch.enabled')
|
||||
if [ "${LOCKED}" != "true" ]; then
|
||||
echo "::error::Failed to confirm lock on ${BRANCH} (lock_branch=${LOCKED})."
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ ${BRANCH} is now locked (read-only)."
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
# Job 2 — Preventive guard: fail if a push lands on release/vX.Y.Z whose
|
||||
# tag already exists. This catches the case where the lock didn't apply
|
||||
# (PAT missing, race window, workflow bug) and pages the operator.
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
guard-no-push-after-release:
|
||||
if: github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Reject push if matching release tag exists
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPO: ${{ github.repository }}
|
||||
REF: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# Extract version from ref: release/v3.8.3 -> v3.8.3
|
||||
if [[ ! "${REF}" =~ ^release/(v[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
echo "Ref ${REF} does not match release/vX.Y.Z — nothing to guard."
|
||||
exit 0
|
||||
fi
|
||||
TAG="${BASH_REMATCH[1]}"
|
||||
echo "Checking if tag ${TAG} already exists on ${REPO}..."
|
||||
|
||||
if gh api "repos/${REPO}/git/refs/tags/${TAG}" >/dev/null 2>&1; then
|
||||
echo "::error::Hard Rule #18 violation — push to ${REF} but tag ${TAG} is already released."
|
||||
echo "::error::Hotfixes for a released version must go on a NEW branch: release/v$(echo "${TAG#v}" | awk -F. '{$3=$3+1; print $1"."$2"."$3}' OFS=.)"
|
||||
echo "::error::To undo this push: revert the offending commits, or contact an admin to lock the branch if it wasn't already."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ No release tag for ${TAG} yet — push is OK."
|
||||
211
.github/workflows/npm-publish.yml
vendored
211
.github/workflows/npm-publish.yml
vendored
@@ -1,17 +1,177 @@
|
||||
name: Publish to npm
|
||||
|
||||
on:
|
||||
# 'released' (not 'published') so editing/re-publishing old releases does NOT
|
||||
# re-trigger this workflow. Pairs with the semver guard below as defense in
|
||||
# depth against accidental dist-tag clobbering by old releases.
|
||||
release:
|
||||
types: [published]
|
||||
types: [released]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version to publish (e.g. 2.9.5 or 3.0.0-rc.15)"
|
||||
required: true
|
||||
type: string
|
||||
tag:
|
||||
description: "npm dist-tag (auto / latest / next / historic)"
|
||||
required: false
|
||||
default: "auto"
|
||||
type: choice
|
||||
options:
|
||||
- auto
|
||||
- latest
|
||||
- next
|
||||
- historic
|
||||
workflow_call:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version to publish (without v prefix)"
|
||||
required: true
|
||||
type: string
|
||||
tag:
|
||||
description: "npm dist-tag (auto / latest / next / historic)"
|
||||
required: false
|
||||
default: "auto"
|
||||
type: string
|
||||
secrets:
|
||||
NPM_TOKEN:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
packages: write
|
||||
|
||||
env:
|
||||
NPM_PUBLISH_NODE_VERSION: "24"
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
environment: NPM_TOKEN
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
# Need full tag history to compare against highest semver when
|
||||
# deciding whether this release should claim dist-tag `latest`.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies (skip scripts to avoid heavy build)
|
||||
run: npm install --ignore-scripts --no-audit --no-fund
|
||||
|
||||
- name: Resolve version, dist-tag and skip flag
|
||||
id: resolve
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
REF_NAME: ${{ github.ref_name }}
|
||||
INPUT_VERSION: ${{ inputs.version }}
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# 1) Resolve VERSION from the trigger (all inputs come via env).
|
||||
VERSION="${INPUT_VERSION:-}"
|
||||
if [ -z "$VERSION" ] && [ "$EVENT_NAME" = "release" ]; then
|
||||
VERSION="$REF_NAME"
|
||||
fi
|
||||
VERSION="${VERSION#v}"
|
||||
if ! printf '%s' "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9.-]+)?$'; then
|
||||
echo "Refusing to publish unsafe VERSION value: $VERSION" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2) Resolve dist-tag.
|
||||
# - explicit 'latest'/'next'/'historic' is honored
|
||||
# - 'auto' (or empty): pre-release identifiers → 'next';
|
||||
# stable versions → 'latest' only if VERSION is the highest
|
||||
# stable semver among `v*` tags (otherwise → 'historic').
|
||||
REQUESTED_TAG="${INPUT_TAG:-auto}"
|
||||
TAG="$REQUESTED_TAG"
|
||||
if [ "$TAG" = "auto" ] || [ -z "$TAG" ]; then
|
||||
if printf '%s' "$VERSION" | grep -qE -- '-(rc|alpha|beta|pre|next)'; then
|
||||
TAG="next"
|
||||
else
|
||||
git fetch --tags --quiet || true
|
||||
HIGHEST=$(git tag -l 'v[0-9]*' | sed 's/^v//' | grep -vE -- '-(rc|alpha|beta|pre|next)' | sort -V | tail -1 || echo "")
|
||||
if [ -n "$HIGHEST" ] && [ "$VERSION" = "$HIGHEST" ]; then
|
||||
TAG="latest"
|
||||
else
|
||||
echo "Version $VERSION is not the highest semver tag (highest=${HIGHEST:-<none>}). Using dist-tag 'historic' to avoid clobbering @latest."
|
||||
TAG="historic"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# 3) Skip-if-already-published. NOTE: do NOT pass `--silent` to
|
||||
# `npm view` — it suppresses stdout and breaks the grep, which
|
||||
# caused old releases (3.2.8) to be re-published and steal
|
||||
# dist-tag `latest`. See incident notes in CHANGELOG.
|
||||
PUBLISHED="$(npm view "omniroute@${VERSION}" version 2>/dev/null || true)"
|
||||
SKIP="false"
|
||||
if [ "$PUBLISHED" = "$VERSION" ]; then
|
||||
echo "⚠️ omniroute@${VERSION} is already on npm — skipping publish."
|
||||
SKIP="true"
|
||||
fi
|
||||
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "skip=$SKIP" >> "$GITHUB_OUTPUT"
|
||||
echo "📦 Resolved omniroute@$VERSION dist-tag=$TAG skip=$SKIP"
|
||||
|
||||
- name: Sync package.json version
|
||||
if: steps.resolve.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.resolve.outputs.version }}
|
||||
run: |
|
||||
npm version "$VERSION" --no-git-tag-version --allow-same-version
|
||||
|
||||
- name: Build CLI bundle (standalone app)
|
||||
if: steps.resolve.outputs.skip != 'true'
|
||||
env:
|
||||
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
|
||||
run: npm run build:cli
|
||||
|
||||
- name: Validate npm package artifact
|
||||
if: steps.resolve.outputs.skip != 'true'
|
||||
run: npm run check:pack-artifact
|
||||
|
||||
- name: Publish to npm
|
||||
if: steps.resolve.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.resolve.outputs.version }}
|
||||
TAG: ${{ steps.resolve.outputs.tag }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Always pass --tag explicitly. Defense in depth: even if VERSION is
|
||||
# accidentally an older release, `npm publish --tag historic` will
|
||||
# NOT promote it to `@latest`.
|
||||
npm publish --access public --tag "$TAG"
|
||||
echo "✅ Published omniroute@$VERSION (dist-tag=$TAG)"
|
||||
|
||||
- name: Publish to GitHub Packages
|
||||
if: steps.resolve.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.resolve.outputs.version }}
|
||||
TAG: ${{ steps.resolve.outputs.tag }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "Configuring for GitHub Packages..."
|
||||
echo "//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}" > .npmrc
|
||||
npm pkg set name="@diegosouzapw/omniroute"
|
||||
npm publish --registry=https://npm.pkg.github.com --tag "$TAG" \
|
||||
|| echo "⚠️ omniroute@${VERSION} might already be published on GitHub Packages."
|
||||
echo "✅ Action finished for GitHub Packages"
|
||||
|
||||
publish-opencode-plugin:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -19,33 +179,34 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
node-version: ${{ env.NPM_PUBLISH_NODE_VERSION }}
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies (skip scripts to avoid heavy build)
|
||||
run: npm install --ignore-scripts --no-audit --no-fund
|
||||
- name: Install plugin dependencies
|
||||
working-directory: "@omniroute/opencode-plugin"
|
||||
run: npm install --no-audit --no-fund
|
||||
|
||||
- name: Sync version from release tag
|
||||
run: |
|
||||
VERSION="${GITHUB_REF_NAME}"
|
||||
# Remove 'v' prefix if present (v2.1.0 -> 2.1.0)
|
||||
VERSION="${VERSION#v}"
|
||||
npm version "$VERSION" --no-git-tag-version --allow-same-version
|
||||
echo "Publishing version: $VERSION"
|
||||
- name: Build plugin
|
||||
working-directory: "@omniroute/opencode-plugin"
|
||||
run: npm run clean && npm run build
|
||||
|
||||
- name: Build CLI bundle (standalone app)
|
||||
env:
|
||||
JWT_SECRET: ci-build-secret-with-sufficient-length-for-validation
|
||||
run: node scripts/prepublish.mjs
|
||||
- name: Test plugin
|
||||
working-directory: "@omniroute/opencode-plugin"
|
||||
run: npm test
|
||||
|
||||
- name: Publish to npm
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
# Check if this version is already published — skip instead of failing with E403
|
||||
if npm view "omniroute@${VERSION}" version --silent 2>/dev/null | grep -q "^${VERSION}$"; then
|
||||
echo "️⚠️ Version ${VERSION} is already published on npm — skipping."
|
||||
exit 0
|
||||
fi
|
||||
npm publish --access public
|
||||
- name: Publish @omniroute/opencode-plugin to npm
|
||||
working-directory: "@omniroute/opencode-plugin"
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
PKG_VERSION=$(node -p "require('./package.json').version")
|
||||
PKG_NAME=$(node -p "require('./package.json').name")
|
||||
# Same hardened skip-check as the main job (no --silent flag).
|
||||
PUBLISHED="$(npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null || true)"
|
||||
if [ "$PUBLISHED" = "$PKG_VERSION" ]; then
|
||||
echo "⚠️ ${PKG_NAME}@${PKG_VERSION} is already published on npm — skipping."
|
||||
exit 0
|
||||
fi
|
||||
npm publish --access public --ignore-scripts
|
||||
echo "✅ Published ${PKG_NAME}@${PKG_VERSION}"
|
||||
|
||||
62
.github/workflows/opencode-plugin-ci.yml
vendored
Normal file
62
.github/workflows/opencode-plugin-ci.yml
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
name: opencode-plugin CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, release/v3.8.2]
|
||||
paths:
|
||||
- "@omniroute/opencode-plugin/**"
|
||||
pull_request:
|
||||
branches: [main, release/v3.8.2]
|
||||
paths:
|
||||
- "@omniroute/opencode-plugin/**"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: "@omniroute/opencode-plugin"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test (Node ${{ matrix.node }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node: ["22", "24"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
cache: npm
|
||||
cache-dependency-path: "@omniroute/opencode-plugin/package-lock.json"
|
||||
- run: npm install --no-audit --no-fund
|
||||
- run: npm run build
|
||||
- run: npm test
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
cache-dependency-path: "@omniroute/opencode-plugin/package-lock.json"
|
||||
- run: npm install --no-audit --no-fund
|
||||
- run: npm run build
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opencode-plugin-dist
|
||||
path: "@omniroute/opencode-plugin/dist"
|
||||
retention-days: 7
|
||||
61
.github/workflows/opencode-provider-ci.yml
vendored
Normal file
61
.github/workflows/opencode-provider-ci.yml
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
name: opencode-provider CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, release/v3.8.0]
|
||||
paths:
|
||||
- "@omniroute/opencode-provider/**"
|
||||
pull_request:
|
||||
branches: [main, release/v3.8.0]
|
||||
paths:
|
||||
- "@omniroute/opencode-provider/**"
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
defaults:
|
||||
run:
|
||||
working-directory: "@omniroute/opencode-provider"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test (Node ${{ matrix.node }})
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node: ["20", "22", "24"]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
cache: npm
|
||||
cache-dependency-path: "@omniroute/opencode-provider/package-lock.json"
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: npm
|
||||
cache-dependency-path: "@omniroute/opencode-provider/package-lock.json"
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opencode-provider-dist
|
||||
path: "@omniroute/opencode-provider/dist"
|
||||
retention-days: 7
|
||||
202
.gitignore
vendored
202
.gitignore
vendored
@@ -4,32 +4,55 @@
|
||||
.omnivscodeagent/
|
||||
omnirouteCloud/
|
||||
omnirouteSite/
|
||||
_cache/
|
||||
_ideia/
|
||||
_mono_repo/
|
||||
_references/
|
||||
_tasks/
|
||||
.agents/**
|
||||
.claude/**
|
||||
.gemini/**
|
||||
.config/**
|
||||
.data/**
|
||||
.logs/**
|
||||
.tests/**
|
||||
.coverage/**
|
||||
coverage/
|
||||
.dist/**
|
||||
.next/**
|
||||
.build/**
|
||||
.out/**
|
||||
|
||||
|
||||
# Memory Bank and Cursor rules (local-only AI agent context)
|
||||
memory-bank/
|
||||
.cursor/rules/core.mdc
|
||||
.cursor/rules/memory-bank.mdc
|
||||
|
||||
# Claude Code local state — runtime files only; shared commands at .claude/commands/ are tracked
|
||||
.claude/scheduled_tasks.lock
|
||||
.claude/scheduled_tasks/
|
||||
.claude/sessions/
|
||||
.claude/state.json
|
||||
.claude/settings.local.json
|
||||
|
||||
# Root-level underscore-prefixed directories (private/draft — never commit)
|
||||
/_*/
|
||||
|
||||
# Draft features documentation (internal only)
|
||||
docs/new-features/
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
coverage/
|
||||
|
||||
# next.js
|
||||
.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
/app
|
||||
cloud/*
|
||||
|
||||
# misc
|
||||
*.map
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# Obsidian sync plugin — committed for community distribution
|
||||
!obsidian-plugin/
|
||||
obsidian-plugin/node_modules/
|
||||
|
||||
# Serena AI assistant config (local-only tool, not project code)
|
||||
.serena/
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
@@ -40,6 +63,9 @@ yarn-error.log*
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
!.env.example
|
||||
# Provider API keys (never commit)
|
||||
*.api-key
|
||||
.nvidia-api-key
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
@@ -50,42 +76,15 @@ next-env.d.ts
|
||||
|
||||
# data and logs
|
||||
data/
|
||||
.data/
|
||||
logs/*
|
||||
test_output.log
|
||||
|
||||
# analysis directories (generated, not tracked)
|
||||
.analysis/
|
||||
antigravity-manager-analysis/
|
||||
|
||||
# docs (allow specific tracked files)
|
||||
docs/*
|
||||
!docs/ARCHITECTURE.md
|
||||
!docs/CODEBASE_DOCUMENTATION.md
|
||||
!docs/CONTRIBUTING.md
|
||||
!docs/USER_GUIDE.md
|
||||
!docs/API_REFERENCE.md
|
||||
!docs/TROUBLESHOOTING.md
|
||||
!docs/EXECUTION_CONTEXT_PROVIDER_SYNC.md
|
||||
!docs/TASK_NEBIUS_BACKEND_ENABLEMENT.md
|
||||
!docs/frontend-backend-provider-gap-report.md
|
||||
!docs/openapi.yaml
|
||||
!docs/RELEASE_CHECKLIST.md
|
||||
!docs/PLANO-IMPLANTACAO.md
|
||||
!docs/TASKS.md
|
||||
!docs/FASE-*.md
|
||||
!docs/adr/
|
||||
!docs/cli-tools/
|
||||
!docs/planning/
|
||||
!docs/improvement-plans/
|
||||
!docs/api/
|
||||
!docs/VM_DEPLOYMENT_GUIDE.md
|
||||
!docs/FEATURES.md
|
||||
!docs/screenshots/
|
||||
!docs/i18n/
|
||||
!docs/i18n/**
|
||||
!docs/A2A-SERVER.md
|
||||
!docs/AUTO-COMBO.md
|
||||
!docs/MCP-SERVER.md
|
||||
!docs/CLI-TOOLS.md
|
||||
.sisyphus/
|
||||
.plans/
|
||||
|
||||
# open-sse tests
|
||||
open-sse/test/*
|
||||
@@ -94,10 +93,12 @@ open-sse/test/*
|
||||
.github/instructions/codacy.instructions.md
|
||||
|
||||
# Playwright
|
||||
.playwright-mcp/
|
||||
test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
cloud/
|
||||
.tmp/
|
||||
|
||||
# Security Analysis (standalone project with own git)
|
||||
security-analysis/
|
||||
@@ -106,17 +107,25 @@ security-analysis/
|
||||
clipr/
|
||||
app.log
|
||||
*.tgz
|
||||
.gh-discussions.json
|
||||
deploy.sh
|
||||
docker-compose.minimal.yml
|
||||
|
||||
|
||||
# Backup directories
|
||||
app.__qa_backup/
|
||||
.app-build-backup-*/
|
||||
backup/
|
||||
|
||||
# Production standalone build (created by scripts/prepublish.mjs)
|
||||
# Conflicts with Next.js App Router detection in dev (root app/ shadows src/app/)
|
||||
# npm publish still includes it via package.json "files" field
|
||||
/app/
|
||||
# Build intermediates (.build/) and shippable standalone (dist/).
|
||||
# These are fully reproducible from source; never committed.
|
||||
# Layer 1: Next.js now writes to .build/next (was .next); assembled bundle → dist/
|
||||
# (Previously /app/ was the standalone output; renamed to /dist/ in Layer 1.)
|
||||
/.build/
|
||||
/dist/
|
||||
/.next/
|
||||
|
||||
# Electron (subproject dependency lock and build artifacts)
|
||||
electron/package-lock.json
|
||||
# Electron
|
||||
electron/dist-electron/
|
||||
electron/node_modules/
|
||||
icon.iconset/
|
||||
@@ -128,3 +137,78 @@ vscode-extension/
|
||||
*.sqlite-shm
|
||||
*.sqlite-wal
|
||||
*.sqlite-journal
|
||||
|
||||
# IDEA
|
||||
.idea/
|
||||
|
||||
# Local OpenCode agent config
|
||||
.config/
|
||||
|
||||
# Empty/dangling files
|
||||
typescript
|
||||
|
||||
# Gemini Antigravity agent data
|
||||
.gemini/
|
||||
|
||||
# Superpowers plans/specs (internal tooling, not project code)
|
||||
docs/superpowers/
|
||||
|
||||
# GitNexus local index
|
||||
.gitnexus
|
||||
.worktrees
|
||||
bin/omniroute.mjs
|
||||
|
||||
# Consistent with .dockerignore / .npmignore
|
||||
.omc/
|
||||
audit-report.json
|
||||
bun.lock
|
||||
|
||||
# Private environment variables for .http-client
|
||||
http-client.private.env.json
|
||||
|
||||
# Note: _ideia/ (feature-triage drafts) is fully covered by the /_*/ rule above
|
||||
# and kept as a separate local-only git repo. Never committed to OmniRoute.
|
||||
|
||||
# i18n audit artifact (generated by scripts/i18n/audit-dashboard-pages.mjs)
|
||||
scripts/i18n/_audit.json
|
||||
scripts/i18n/_pending-keys.json
|
||||
|
||||
# Private workflow / skill / command implementations
|
||||
# These contain proprietary multi-phase logic and should not be committed
|
||||
.agents/workflows/implement-features-ag.md
|
||||
.agents/workflows/port-upstream-features-ag.md
|
||||
.agents/workflows/port-upstream-issues-ag.md
|
||||
.agents/skills/implement-features/
|
||||
.claude/commands/implement-features-cc.md
|
||||
.claude/commands/port-upstream-features-cc.md
|
||||
.claude/commands/port-upstream-issues-cc.md
|
||||
.claude/worktrees/
|
||||
.codegraph/
|
||||
|
||||
# Fumadocs generated source
|
||||
.source/
|
||||
|
||||
# AI agent local settings and configs
|
||||
.agents/
|
||||
.antigravitycli/
|
||||
.claude/
|
||||
|
||||
# PR Reviews and local feedback files
|
||||
pr_reviews*.json
|
||||
|
||||
#hidden local data directories (never commit)
|
||||
.local-data/
|
||||
.data-dev/
|
||||
/.junie/
|
||||
|
||||
# internal setup prompts with personal credentials — never commit
|
||||
CODEX-SETUP-PROMPT.md
|
||||
# Quality ratchet — métricas efêmeras (baseline é commitado, métricas não)
|
||||
quality-metrics.json
|
||||
-home-diegosouzapw-dev-automações-bots-yt-downloader-20260504 .txt
|
||||
-home-diegosouzapw-dev-automações-bots-yt-downloader-20260410 .txt
|
||||
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute.md
|
||||
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.md
|
||||
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute-mim.md
|
||||
docs/prompts/AGENT-OWNERSHIP-PROTOCOL.omniroute-mid.md
|
||||
omniroute.md
|
||||
|
||||
12
.husky/pre-commit
Normal file → Executable file
12
.husky/pre-commit
Normal file → Executable file
@@ -1,2 +1,12 @@
|
||||
#!/usr/bin/env sh
|
||||
if ! command -v npx >/dev/null 2>&1; then
|
||||
echo "⚠️ npx not found in PATH — skipping pre-commit hooks"
|
||||
echo " Run 'npm run lint && npm run check:any-budget:t11' manually before pushing."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Cheap, deterministic local gates (re-enabled). Slower checks (i18n drift,
|
||||
# openapi coverage/security-tiers, env-doc sync) run in CI to keep commits fast.
|
||||
npx lint-staged
|
||||
node scripts/check-docs-sync.mjs
|
||||
node scripts/check/check-docs-sync.mjs
|
||||
npm run check:any-budget:t11
|
||||
|
||||
8
.husky/pre-push
Executable file
8
.husky/pre-push
Executable file
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env sh
|
||||
#if ! command -v npm >/dev/null 2>&1; then
|
||||
# echo "⚠️ npm not found in PATH — skipping pre-push hooks"
|
||||
# echo " Run 'npm test' manually before pushing."
|
||||
# exit 0
|
||||
#fi
|
||||
|
||||
#npm run test:unit
|
||||
1
.node-version
Normal file
1
.node-version
Normal file
@@ -0,0 +1 @@
|
||||
24
|
||||
86
.npmignore
86
.npmignore
@@ -3,7 +3,22 @@ data/
|
||||
**/data/
|
||||
**/db.json
|
||||
|
||||
# VS Code extension test runtime (large binary, not needed in npm package)
|
||||
app/vscode-extension/
|
||||
**/data/
|
||||
**/db.json
|
||||
|
||||
# Source code (pre-built app/ is published instead)
|
||||
#
|
||||
# NOTE (#3578 / #3821-review): package.json "files" is the source of truth for what
|
||||
# ships. It now allowlists the backend source closure the MCP server needs at runtime
|
||||
# (open-sse/, src/lib, src/server, ...) and OVERRIDES the broad src/ + open-sse/ excludes
|
||||
# below — npm honors files[] over .npmignore for inclusion. These lines are kept only as
|
||||
# intent/back-stop: if files[] is ever trimmed back to specific paths, they must NOT be
|
||||
# allowed to re-hide the MCP closure (that would silently reintroduce the --mcp
|
||||
# ERR_MODULE_NOT_FOUND #3578 fixed). The closure gate in
|
||||
# tests/unit/mcp-published-files-closure-3578.test.ts asserts the real `npm pack` output
|
||||
# in both directions (closure present + zero test files), catching such a regression.
|
||||
src/
|
||||
open-sse/
|
||||
docs/
|
||||
@@ -13,6 +28,17 @@ images/
|
||||
logs/
|
||||
scripts/
|
||||
|
||||
# Co-located tests must never ship even when their parent dir is allowlisted by files[].
|
||||
# (Primary guard is the "!**/*.test.*" negations in package.json files[]; this is defense
|
||||
# in depth for any nested dir the allowlist pulls in.)
|
||||
**/__tests__/
|
||||
**/*.test.ts
|
||||
**/*.test.tsx
|
||||
**/*.test.js
|
||||
**/*.test.mjs
|
||||
**/*.spec.ts
|
||||
**/*.spec.tsx
|
||||
|
||||
# Config/dev files
|
||||
*.md
|
||||
!README.md
|
||||
@@ -21,14 +47,21 @@ scripts/
|
||||
.github/
|
||||
.husky/
|
||||
.vscode/
|
||||
.agents/
|
||||
.env*
|
||||
app/.env
|
||||
app/.env*
|
||||
eslint.config.mjs
|
||||
prettier.config.mjs
|
||||
postcss.config.mjs
|
||||
next.config.mjs
|
||||
tsconfig.json
|
||||
tsconfig.typecheck-core.json
|
||||
tsconfig.typecheck-noimplicit-core.json
|
||||
playwright.config.ts
|
||||
vitest.config.ts
|
||||
next-env.d.ts
|
||||
llm.txt
|
||||
|
||||
# Docker
|
||||
docker-compose*.yml
|
||||
@@ -36,9 +69,56 @@ Dockerfile
|
||||
.dockerignore
|
||||
|
||||
# Misc
|
||||
restart.sh
|
||||
AGENTS.md
|
||||
bun.lock
|
||||
|
||||
# Build artifacts (pre-built goes inside app/)
|
||||
.next/
|
||||
node_modules/
|
||||
/.next/
|
||||
/node_modules/
|
||||
|
||||
# Ignore large binary files and other build directories
|
||||
*.tgz
|
||||
*.AppImage
|
||||
*.deb
|
||||
*.rpm
|
||||
electron/
|
||||
app/electron/
|
||||
app/vscode-extension/
|
||||
|
||||
# Subprojects
|
||||
clipr/
|
||||
omnirouteCloud/
|
||||
omnirouteSite/
|
||||
vscode-extension/
|
||||
|
||||
# Root-level underscore-prefixed directories (private/draft — never publish)
|
||||
/_*/
|
||||
app/_*/
|
||||
app/coverage/
|
||||
app/logs/
|
||||
app/tests/
|
||||
|
||||
# Consistent with .gitignore and .dockerignore
|
||||
.DS_Store
|
||||
.idea/
|
||||
.config/
|
||||
.data/
|
||||
.omnivscodeagent/
|
||||
.omc/
|
||||
*.sqlite-*
|
||||
*.tsbuildinfo
|
||||
security-analysis/
|
||||
.analysis/
|
||||
antigravity-manager-analysis/
|
||||
.sisyphus/
|
||||
.plans/
|
||||
app.__qa_backup/
|
||||
.app-build-backup-*/
|
||||
.gitnexus
|
||||
.worktrees
|
||||
.next-playwright/
|
||||
test-results/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
coverage/
|
||||
@omniroute/
|
||||
|
||||
4
.npmrc
Normal file
4
.npmrc
Normal file
@@ -0,0 +1,4 @@
|
||||
# @lobehub/icons declares UI peers that are not needed by our deep icon imports.
|
||||
# Keeping peer auto-install disabled prevents npm from pulling @lobehub/ui/mermaid
|
||||
# back into the tree and reopening npm audit findings for unused packages.
|
||||
legacy-peer-deps=true
|
||||
8
.source/dynamic.ts
Normal file
8
.source/dynamic.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// @ts-nocheck
|
||||
import { dynamic } from 'fumadocs-mdx/runtime/dynamic';
|
||||
import * as Config from '../source.config';
|
||||
|
||||
const create = await dynamic<typeof Config, import("fumadocs-mdx/runtime/types").InternalTypeConfig & {
|
||||
DocData: {
|
||||
}
|
||||
}>(Config, {"configPath":"source.config.ts","environment":"next","outDir":".source"}, {"doc":{"passthroughs":["extractedReferences"]}});
|
||||
23
.source/source.config.mjs
Normal file
23
.source/source.config.mjs
Normal file
@@ -0,0 +1,23 @@
|
||||
// source.config.ts
|
||||
import { defineDocs, defineConfig } from "fumadocs-mdx/config";
|
||||
var docs = defineDocs({
|
||||
dir: "docs",
|
||||
docs: {
|
||||
files: [
|
||||
"./getting-started/**/*.md",
|
||||
"./architecture/**/*.md",
|
||||
"./guides/**/*.md",
|
||||
"./reference/**/*.md",
|
||||
"./frameworks/**/*.md",
|
||||
"./routing/**/*.md",
|
||||
"./security/**/*.md",
|
||||
"./compression/**/*.md",
|
||||
"./ops/**/*.md"
|
||||
]
|
||||
}
|
||||
});
|
||||
var source_config_default = defineConfig();
|
||||
export {
|
||||
source_config_default as default,
|
||||
docs
|
||||
};
|
||||
49
.vscode/settings.json
vendored
49
.vscode/settings.json
vendored
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"workbench.sideBar.location": "left",
|
||||
"css.lint.unknownAtRules": "ignore",
|
||||
"sonarlint.rules": {
|
||||
"css:S4662": {
|
||||
@@ -16,5 +17,53 @@
|
||||
"javascript:S3776": {
|
||||
"level": "off"
|
||||
}
|
||||
},
|
||||
"git.ignoreLimitWarning": true,
|
||||
// "files.exclude": {
|
||||
// "**/_references": true,
|
||||
// "**/_mono_repo": true,
|
||||
// "**/electron": true,
|
||||
// "**/node_modules": true,
|
||||
// "**/.next": true,
|
||||
// "**/coverage": true,
|
||||
// "**/omniroute-*.tgz": true,
|
||||
// "**/_tasks": true
|
||||
// },
|
||||
"files.watcherExclude": {
|
||||
"**/_references/**": true,
|
||||
"**/_mono_repo/**": true,
|
||||
"**/electron/**": true,
|
||||
"**/node_modules/**": true,
|
||||
"**/.next/**": true,
|
||||
"**/coverage/**": true,
|
||||
"**/_tasks/**": true,
|
||||
"**/.git/objects/**": true,
|
||||
"**/dist/**": true,
|
||||
"**/build/**": true,
|
||||
"**/out/**": true,
|
||||
"**/.cache/**": true,
|
||||
"**/.turbo/**": true,
|
||||
"**/OmniRoute-*/**": true,
|
||||
"**/*-merge-*/**": true,
|
||||
"**/*-worktree-*/**": true,
|
||||
"**/*-issues-*/**": true,
|
||||
"**/*-reorg*/**": true
|
||||
},
|
||||
"search.exclude": {
|
||||
"**/_references": true,
|
||||
"**/_mono_repo": true,
|
||||
"**/electron": true,
|
||||
"**/node_modules": true,
|
||||
"**/.next": true,
|
||||
"**/coverage": true,
|
||||
"**/_tasks": true,
|
||||
"**/dist": true,
|
||||
"**/build": true,
|
||||
"**/out": true,
|
||||
"**/OmniRoute-*": true,
|
||||
"**/*-merge-*": true,
|
||||
"**/*-worktree-*": true,
|
||||
"**/*-issues-*": true,
|
||||
"**/*-reorg*": true
|
||||
}
|
||||
}
|
||||
|
||||
4
@omniroute/opencode-plugin/.gitignore
vendored
Normal file
4
@omniroute/opencode-plugin/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
*.log
|
||||
.DS_Store
|
||||
21
@omniroute/opencode-plugin/LICENSE
Normal file
21
@omniroute/opencode-plugin/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 OmniRoute contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
296
@omniroute/opencode-plugin/README.md
Normal file
296
@omniroute/opencode-plugin/README.md
Normal file
@@ -0,0 +1,296 @@
|
||||
# @omniroute/opencode-plugin
|
||||
|
||||
> **Recommended way to use OmniRoute with OpenCode.** Pulls a live model catalog from `/v1/models` (including `-low`/`-medium`/`-high`/`-thinking` variants as first-class IDs), aggregates combos via `/api/combos` using a least-common-denominator capability/limit join, sanitizes Gemini tool schemas in flight, and supports multiple side-by-side OmniRoute instances out of the box.
|
||||
|
||||
## Why this and not `@omniroute/opencode-provider`?
|
||||
|
||||
`@omniroute/opencode-provider` is the legacy config-generator package — it writes a frozen `provider.omniroute` block into `opencode.json` with a **hardcoded list of 8 models** ([`OMNIROUTE_DEFAULT_OPENCODE_MODELS`](https://github.com/diegosouzapw/OmniRoute/blob/main/%40omniroute/opencode-provider/src/index.ts#L48-L56)). It works on the CLI but in the **OpenCode Desktop / Web** builds (Tauri / Electron) the runtime re-runs the model picker and the static block surfaces only a few of those — and they drift behind the live OmniRoute catalog.
|
||||
|
||||
This plugin solves that by:
|
||||
|
||||
- Fetching `/v1/models` and `/api/combos` **at OpenCode startup, in Node.js** — no CORS, no WebView restrictions
|
||||
- Emitting the provider block **dynamically** in the plugin's `config`/`provider` hook — so `opencode.json` only needs the plugin entry, not a static `provider.omniroute`
|
||||
- Re-fetching on a configurable TTL (default 5 min), so new models / combo changes in the OmniRoute UI appear without restarting OpenCode
|
||||
- Computing `limit.context` for combos as `min(member.context_length)` from the live catalog (no more `null` values that cause 4K-token truncation)
|
||||
- **Auto-pickup of `interleaved` capability** for thinking models (merged via PR #3138)
|
||||
|
||||
**If you only have the legacy `opencode-provider` block in your `opencode.json`, replace it with a single plugin entry.** No other config changes required — the same `auth.json` API key works.
|
||||
|
||||
## Install
|
||||
|
||||
The plugin ships **pre-built inside the `omniroute` npm package** since v3.8.23.
|
||||
If you have OmniRoute installed, the plugin is already on disk:
|
||||
|
||||
```sh
|
||||
# 1. One command — copy the plugin into OpenCode and update opencode.json
|
||||
omniroute setup opencode --auth
|
||||
|
||||
# 2. Follow the interactive prompt to enter your OmniRoute API key
|
||||
# 3. Restart OpenCode — /models lists the full live catalog
|
||||
```
|
||||
|
||||
The `--auth` flag runs `opencode auth login --provider omniroute` automatically.
|
||||
Use `--base-url` to point at a non-default OmniRoute address:
|
||||
|
||||
```sh
|
||||
omniroute setup opencode --base-url https://or.example.com --auth
|
||||
```
|
||||
|
||||
### What it does
|
||||
|
||||
1. Locates the bundled plugin inside the omniroute installation
|
||||
2. Copies `dist/` + `package.json` to `~/.config/opencode/plugins/omniroute/`
|
||||
3. Writes/updates `opencode.json` with the plugin entry (idempotent, replaces legacy entries)
|
||||
4. (With `--auth`) runs `opencode auth login` so the API key is stored
|
||||
|
||||
Re-run any time to update the plugin or change the base URL. Older entries for
|
||||
`@omniroute/opencode-provider` or the legacy `opencode-omniroute-auth` package are
|
||||
automatically cleaned up.
|
||||
|
||||
### Manual install (without omniroute CLI)
|
||||
|
||||
If you cannot run `omniroute setup opencode` (local dev, CI, air-gapped), reference
|
||||
the built artifact directly:
|
||||
|
||||
```sh
|
||||
cd @omniroute/opencode-plugin && npm run build && npm pack
|
||||
# then extract into ~/.config/opencode/plugins/omniroute-opencode-plugin/
|
||||
```
|
||||
|
||||
And add the entry to `opencode.json` manually (see Quick Start below).
|
||||
|
||||
Peer dep: `@opencode-ai/plugin` (managed by your OpenCode install).
|
||||
|
||||
## Quick start (single instance, manual)
|
||||
|
||||
```jsonc
|
||||
// opencode.json
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"plugin": [
|
||||
[
|
||||
"./plugins/omniroute-opencode-plugin/dist/index.js",
|
||||
{
|
||||
"providerId": "omniroute",
|
||||
"baseURL": "https://or.example.com",
|
||||
},
|
||||
],
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
opencode auth login --provider omniroute
|
||||
# prompts for the OmniRoute API key, writes to ~/.local/share/opencode/auth.json
|
||||
```
|
||||
|
||||
> ⚠ Use the `--provider` flag explicitly. `opencode auth login omniroute` is parsed as a positional `url` argument by current OC releases (≤1.15.5) and fails with `fetch() URL is invalid`. Tracked upstream.
|
||||
|
||||
Restart OpenCode. `/models` lists the full live catalog. Variants (`-low`, `-medium`, `-high`, `-thinking`) and combos appear as first-class IDs — OmniRoute is the source of truth, no client-side synthesis.
|
||||
|
||||
## Multi-instance (prod + preprod side-by-side)
|
||||
|
||||
> ⚠ OC ≤1.15.5 dedupes plugin loads by absolute module path. Two `plugin:` entries pointing at the same `dist/index.js` collapse into one (last-listed options win). Workaround: install the plugin twice into separate directories so each entry resolves to a distinct module file. v0.2.x will introduce an `instances: [...]` shape that registers N providers from a single load.
|
||||
|
||||
### Dual-install workaround (works today on OC ≤1.15.5)
|
||||
|
||||
Pack the plugin once, extract it twice into named directories, then point each `plugin:` entry at its own copy:
|
||||
|
||||
```sh
|
||||
# 1. Build + pack the plugin (run from the plugin worktree)
|
||||
cd /path/to/OmniRoute/@omniroute/opencode-plugin
|
||||
npm run build
|
||||
npm pack
|
||||
# produces omniroute-opencode-plugin-0.1.0.tgz
|
||||
|
||||
# 2. Extract one copy per OmniRoute endpoint
|
||||
mkdir -p ~/.config/opencode/plugins/omniroute-opencode-plugin-prod
|
||||
mkdir -p ~/.config/opencode/plugins/omniroute-opencode-plugin-preprod
|
||||
tar -xzf omniroute-opencode-plugin-0.1.0.tgz -C ~/.config/opencode/plugins/omniroute-opencode-plugin-prod --strip-components=1
|
||||
tar -xzf omniroute-opencode-plugin-0.1.0.tgz -C ~/.config/opencode/plugins/omniroute-opencode-plugin-preprod --strip-components=1
|
||||
```
|
||||
|
||||
Then in `~/.config/opencode/opencode.json` reference each directory by absolute path:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"plugin": [
|
||||
[
|
||||
"./plugins/omniroute-opencode-plugin-prod/dist/index.js",
|
||||
{
|
||||
"providerId": "omniroute",
|
||||
"displayName": "OmniRoute",
|
||||
"baseURL": "https://or.example.com",
|
||||
},
|
||||
],
|
||||
[
|
||||
"./plugins/omniroute-opencode-plugin-preprod/dist/index.js",
|
||||
{
|
||||
"providerId": "omniroute-preprod",
|
||||
"displayName": "OmniRoute Preprod",
|
||||
"baseURL": "https://or-preprod.example.com",
|
||||
},
|
||||
],
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
Paths are relative to `~/.config/opencode/`. Each entry now resolves to a distinct module file, so OC loads them as two separate plugin instances. Authenticate each:
|
||||
|
||||
```sh
|
||||
opencode auth login --provider omniroute
|
||||
opencode auth login --provider omniroute-preprod
|
||||
```
|
||||
|
||||
Each entry gets its own provider id, its own model picker entry, its own slot in `auth.json`, and its own TTL cache. Closures are isolated per plugin instance — no cross-talk.
|
||||
|
||||
### After publish (`@omniroute/opencode-plugin` npm)
|
||||
|
||||
Once the package is published, the dual-install becomes two `npm install --prefix` commands instead of `tar -xzf`:
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.config/opencode/plugins/omniroute-opencode-plugin-prod
|
||||
mkdir -p ~/.config/opencode/plugins/omniroute-opencode-plugin-preprod
|
||||
npm install --prefix ~/.config/opencode/plugins/omniroute-opencode-plugin-prod @omniroute/opencode-plugin
|
||||
npm install --prefix ~/.config/opencode/plugins/omniroute-opencode-plugin-preprod @omniroute/opencode-plugin
|
||||
```
|
||||
|
||||
`opencode.json` paths become `./plugins/omniroute-opencode-plugin-prod/node_modules/@omniroute/opencode-plugin/dist/index.js` (and the preprod equivalent).
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | What it does | Hook |
|
||||
| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
||||
| Dynamic `/v1/models` | Pulls live catalog (455+ entries on prod) on each refresh, TTL-cached | `provider.models` |
|
||||
| Variants pass-through | `-low`/`-medium`/`-high`/`-thinking` ship as first-class IDs from OmniRoute (no client synthesis) | `provider.models` |
|
||||
| Combo LCD aggregation | Combos appear with intersected capabilities + min context/output across members | `provider.models` + `config` |
|
||||
| `combo/<slug>` namespace + `Combo: ` prefix | Combos surface under `combo/claude-primary` (not the upstream UUID) and the picker shows `Combo: claude-primary` so they stand apart from raw provider/model pairs | both hooks |
|
||||
| Nice names + cost | `/api/pricing/models` display names AND `/api/pricing` per-million-token cost overlaid onto the live catalog | both hooks |
|
||||
| Canonical-twin dedup + alias-fallback | `/v1/models` exposes the same upstream model under both short alias (`cc/claude-opus-4-7`) and canonical name (`claude/claude-opus-4-7`); the plugin drops the canonical twin when an alias twin exists (no duplicate rows in the picker) and reverse-maps canonical → alias to pick up enrichment for short aliases (`dg/nova-3 → Deepgram - Nova 3`) that `/api/pricing/models` only indexes by canonical | both hooks |
|
||||
| Compression pipeline tags | Combo names get tagged with their compression pipeline (e.g. `Combo: claude-primary [rtk🟡 → caveman🟠]`) when `features.compressionMetadata: true`. Intensity tokens render as a traffic-light emoji: 🟢 lite/minimal · 🟡 standard · 🟠 aggressive/full · 🔴 ultra | both hooks |
|
||||
| Provider-tag prefix | Prepend short upstream-provider label to enriched names (e.g. `Claude - Claude Opus 4.7` vs `Kiro - Claude Opus 4.7`, `GHM - GPT 5`) so same-id models routed via different upstream connections group visibly in the picker (default-on, opt-out via `features.providerTag: false`) | both hooks |
|
||||
| Usable-only filter | Filter to providers with at least one healthy connection in `/api/providers` (opt-in via `features.usableOnly`) | both hooks |
|
||||
| Disk-cache fallback | Last-known-good catalog persisted to disk; hydrates on a cold start when `/v1/models` is unreachable (default-on, opt-out via `features.diskCache: false`) | `config` |
|
||||
| Bearer injection + suffix-spoof guard | Adds `Authorization` on baseURL-matched requests only | `auth.loader.fetch` |
|
||||
| Gemini schema sanitization | Strips `$schema`/`$ref`/`additionalProperties` for `gemini-*`/`google-vertex-gemini/*` | `auth.loader.fetch` wrap |
|
||||
| Multi-instance | Each plugin entry binds to its own `providerId`; closures isolated | factory |
|
||||
| Config-hook shim | OC ≤1.15.5 fallback: writes static catalog into `config.provider[id]` (config hook is the only one that fires in `serve` mode on these versions) | `config` |
|
||||
|
||||
## Plugin options
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| --------------- | -------- | ------------------------------------------ | ---------------------------------------------------------- |
|
||||
| `providerId` | `string` | `"omniroute"` | OpenCode provider id; must be unique across plugin entries |
|
||||
| `displayName` | `string` | `"OmniRoute"` or `OmniRoute (<id>)` | Label in the OC UI |
|
||||
| `modelCacheTtl` | `number` | `300000` (5 min) | `/v1/models` TTL in ms |
|
||||
| `baseURL` | `string` | resolved from `auth.json` after `/connect` | Override OmniRoute base URL |
|
||||
| `features` | `object` | see below | Feature toggles (all opt-in/out, defaults preserve v0.1.0) |
|
||||
|
||||
### `features` block
|
||||
|
||||
Every field is optional. Defaults mirror v0.1.0 behaviour so existing `opencode.json` files do not need to change.
|
||||
|
||||
| Feature | Type | Default | What it does |
|
||||
| --------------------- | --------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `combos` | `boolean` | `true` | Discover `/api/combos` and surface them as pseudo-models with LCD capabilities. Combos are keyed under the `combo/<slug>` namespace and labelled `Combo: <name>` in the model picker so they're distinguishable from raw provider/model pairs. |
|
||||
| `enrichment` | `boolean` | `true` | Pull display names from `/api/pricing/models` AND per-million-token pricing (`input`, `output`, `cached` → `cacheRead`, `cache_creation` → `cacheWrite`) from `/api/pricing`, then overlay both onto the live catalog (so the UI shows `Claude 4.7 Opus` with `cost.input: 5`, `cost.output: 25` instead of raw IDs and zeroed cost). |
|
||||
| `compressionMetadata` | `boolean` | `false` | Pull `/api/context/combos` so combo names get tagged with their compression pipeline, e.g. `Combo: claude-primary [rtk🟡 → caveman🟠]`. Intensity tokens render as traffic-light emoji (🟢 lite/minimal · 🟡 standard · 🟠 aggressive/full · 🔴 ultra) so the picker advertises "how compressed" each combo is at a glance. |
|
||||
| `providerTag` | `boolean` | `true` | Prepend a short upstream-provider label to the enriched display name with `" - "` separator, so `cc/claude-opus-4-7 → Claude - Claude Opus 4.7` differs visibly from `kr/claude-opus-4-7 → Kiro - Claude Opus 4.7` in the OC TUI model picker. Label resolution: use `/api/pricing/models[<alias>].name` verbatim when ≤8 chars (e.g. `Claude`, `Kiro`, `Codex`, `Qwen`), otherwise fall back to `UPPER(alias)` (e.g. `GitHub Models` → `GHM`, `Gemini-cli` → `GEMINI-CLI`). Idempotent. Combos intentionally skipped (the `Combo: ` prefix already conveys multi-upstream). |
|
||||
| `usableOnly` | `boolean` | `false` | Read `/api/providers` and filter the catalog to providers that have at least one connection with `isActive: true` AND `testStatus: 'active'`. Subtract-filter semantics: providers unknown to BOTH the pricing-models catalog AND the connection table pass through (so synthetic prefixes like `agentrouter/*` survive). On fetch failure the filter is disabled for the refresh — never hides the whole catalog. |
|
||||
| `diskCache` | `boolean` | `true` | Persist the last successful `/v1/models` + `/api/combos` + enrichment + connections + compression snapshot to `${OPENCODE_DATA_DIR ?? ~/.local/share/opencode}/plugins/omniroute-<providerId>.json`. On a subsequent cold start where `/v1/models` throws (network down / IP whitelist drop / 5xx) the static block hydrates from the snapshot so OC's model picker survives offline. Soft-fail on read/write — never blocks publishing. |
|
||||
| `geminiSanitization` | `boolean` | `true` | Strip `$schema`/`$ref`/`additionalProperties` from tool params when the model id matches `gemini` |
|
||||
| `mcpAutoEmit` | `boolean` | `false` | Auto-write an `mcp.<providerId>` remote entry into the OC config pointing at `<baseURL>/api/mcp/stream` with the resolved Bearer token |
|
||||
| `mcpToken` | `string` | _unset_ | Optional separate Bearer for the auto-emitted MCP entry. Falls back to the provider's `apiKey` (from `auth.json`) when unset |
|
||||
| `fetchInterceptor` | `boolean` | `true` | Inject `Authorization: Bearer` + default `Content-Type` on every outbound request targeting `baseURL` (suffix-spoof guarded) |
|
||||
|
||||
#### Example — enrichment + compression tags + MCP auto-emit
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"plugin": [
|
||||
[
|
||||
"@omniroute/opencode-plugin",
|
||||
{
|
||||
"providerId": "omniroute",
|
||||
"baseURL": "https://or.example.com",
|
||||
"features": {
|
||||
"combos": true,
|
||||
"enrichment": true,
|
||||
"compressionMetadata": true,
|
||||
"mcpAutoEmit": true,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
With `mcpAutoEmit: true`, the plugin synthesises an `mcp.omniroute` entry equivalent to a manual:
|
||||
|
||||
```jsonc
|
||||
"mcp": {
|
||||
"omniroute": {
|
||||
"type": "remote",
|
||||
"url": "https://or.example.com/api/mcp/stream",
|
||||
"enabled": true,
|
||||
"headers": { "Authorization": "Bearer <apiKey-from-auth.json>" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you want a narrower-scoped Bearer for MCP (different from the chat/inference key), set `features.mcpToken`. Operator overrides win: if you already set `mcp.omniroute` in `opencode.json`, the plugin will not overwrite it.
|
||||
|
||||
#### Example — production-leaning defaults (clean picker, offline resilience)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"plugin": [
|
||||
[
|
||||
"@omniroute/opencode-plugin",
|
||||
{
|
||||
"providerId": "omniroute",
|
||||
"baseURL": "https://or.example.com",
|
||||
"features": {
|
||||
"combos": true,
|
||||
"enrichment": true,
|
||||
"compressionMetadata": true,
|
||||
"usableOnly": true,
|
||||
"diskCache": true,
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
- `usableOnly: true` drops models whose canonical provider has no healthy connection in your OmniRoute instance — your `/models` picker stays focused on what you can actually call.
|
||||
- `diskCache: true` (default) writes a snapshot to `${OPENCODE_DATA_DIR}/plugins/omniroute-<providerId>.json` on every healthy refresh. On a cold start where `/v1/models` is unreachable (laptop offline, IP whitelist drop), the snapshot hydrates the static block so OC still shows the catalog instead of a stub.
|
||||
- `compressionMetadata: true` annotates combo display names with their pipeline using traffic-light emoji for intensity (e.g. `Combo: claude-primary [rtk🟡 → caveman🟠]`) so the picker advertises which compression each combo applies and how heavy it is at a glance. Palette: 🟢 lite/minimal · 🟡 standard · 🟠 aggressive/full · 🔴 ultra. Unknown intensities fall through to raw text (`[rtk:custom-thing]`) so the plugin never hides a value OmniRoute knows but the plugin doesn't.
|
||||
- `providerTag: true` (default) prepends a short upstream-provider label so the picker shows `Claude - Claude Opus 4.7` for `cc/claude-opus-4-7`, `Kiro - Claude Opus 4.7` for `kr/claude-opus-4-7`, and `GHM - GPT 5` for `ghm/gpt-5` (slot.name `GitHub Models` > 8 chars → abbreviated). Critical when the same model id is sold through multiple upstream connections with different cost/auth/rate-limit profiles. Set to `false` to keep the pre-v3.8.3 unsuffixed format.
|
||||
|
||||
## Comparison vs `@omniroute/opencode-provider`
|
||||
|
||||
[`@omniroute/opencode-provider`](https://github.com/diegosouzapw/OmniRoute/tree/main/%40omniroute/opencode-provider) is the existing config-generator package — it writes a frozen `provider.<id>` block into `opencode.json` at build time. This plugin is the runtime integration.
|
||||
|
||||
| | `@omniroute/opencode-plugin` (this) | `@omniroute/opencode-provider` |
|
||||
| ----------------- | ----------------------------------- | --------------------------------- |
|
||||
| Type | OC plugin | Config generator (CLI/build-time) |
|
||||
| Models | Live from `/v1/models` | Frozen at scaffold |
|
||||
| Combos | LCD-aggregated live | None |
|
||||
| Gemini sanitize | Yes | N/A |
|
||||
| OC UI integration | `/connect`, `/models` | None |
|
||||
| Multi-instance | Native | Manual |
|
||||
|
||||
Both can coexist; pick the one that fits your environment.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Node `>=22.22.3` (per `engines.node`); tested on Node 22 and 24.
|
||||
- OpenCode: verified end-to-end against `opencode@1.15.5` with `@opencode-ai/plugin@1.15.6`.
|
||||
- OC plugin peer (`@opencode-ai/plugin`) `>=1.14.49` for the full feature set (provider hook surfaces models in `/models`). On `<=1.14.48`, the plugin falls back to its `config` hook, writing a static catalog snapshot into `config.provider[id]` so models still appear.
|
||||
- The plugin uses the OC v1 plugin shape (`default: { id, server }`) — older OC releases that only walk named exports will reject it. Stay on OC ≥1.15.
|
||||
|
||||
## License
|
||||
|
||||
MIT. See [LICENSE](./LICENSE).
|
||||
2414
@omniroute/opencode-plugin/package-lock.json
generated
Normal file
2414
@omniroute/opencode-plugin/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
73
@omniroute/opencode-plugin/package.json
Normal file
73
@omniroute/opencode-plugin/package.json
Normal file
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"name": "@omniroute/opencode-plugin",
|
||||
"version": "0.1.0",
|
||||
"description": "OpenCode plugin for the OmniRoute AI Gateway. Drives dynamic model discovery, /connect auth flow, and multi-instance OmniRoute providers via the official @opencode-ai/plugin contract.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/index.d.cts",
|
||||
"default": "./dist/index.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"clean": "rm -rf dist",
|
||||
"test": "node --import tsx/esm --test tests/scaffold.test.ts tests/auth.test.ts tests/options-schema.test.ts tests/multi-instance.test.ts tests/fetch-interceptor.test.ts tests/provider.test.ts tests/gemini-sanitize.test.ts tests/combos.test.ts tests/config-shim.test.ts tests/features.test.ts tests/usable-combo.test.ts tests/disk-snapshot-perms.test.ts tests/fork-features.test.ts tests/auto-combo-context.test.ts",
|
||||
"prepublishOnly": "npm run clean && npm run build && npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"omniroute",
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"ai-sdk",
|
||||
"openai-compatible",
|
||||
"provider",
|
||||
"gemini",
|
||||
"combos",
|
||||
"mcp"
|
||||
],
|
||||
"author": "OmniRoute contributors",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/diegosouzapw/OmniRoute.git",
|
||||
"directory": "@omniroute/opencode-plugin"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/diegosouzapw/OmniRoute/issues"
|
||||
},
|
||||
"homepage": "https://github.com/diegosouzapw/OmniRoute/tree/main/%40omniroute/opencode-plugin#readme",
|
||||
"engines": {
|
||||
"node": ">=22.22.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opencode-ai/plugin": "*"
|
||||
},
|
||||
"dependencies": {
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@opencode-ai/plugin": "^1.15.6",
|
||||
"@types/node": "^22.19.19",
|
||||
"tsup": "^8.5.1",
|
||||
"tsx": "^4.22.3",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
4657
@omniroute/opencode-plugin/src/index.ts
Normal file
4657
@omniroute/opencode-plugin/src/index.ts
Normal file
File diff suppressed because it is too large
Load Diff
74
@omniroute/opencode-plugin/src/logger.ts
Normal file
74
@omniroute/opencode-plugin/src/logger.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Structured logger for the OmniRoute plugin.
|
||||
*
|
||||
* Levels: error < warn < info < debug
|
||||
* Default: warn (matches current console.warn behavior)
|
||||
* Set via features.logLevel in plugin options.
|
||||
*/
|
||||
|
||||
export type LogLevel = "error" | "warn" | "info" | "debug";
|
||||
|
||||
const LEVEL_ORDER: Record<LogLevel, number> = {
|
||||
error: 0,
|
||||
warn: 1,
|
||||
info: 2,
|
||||
debug: 3,
|
||||
};
|
||||
|
||||
const TAG = "[omniroute-plugin]";
|
||||
|
||||
function shouldLog(current: LogLevel, target: LogLevel): boolean {
|
||||
return LEVEL_ORDER[current] >= LEVEL_ORDER[target];
|
||||
}
|
||||
|
||||
let _level: LogLevel = "warn";
|
||||
|
||||
export function setLogLevel(level: LogLevel): void {
|
||||
_level = level;
|
||||
}
|
||||
|
||||
export function getLogLevel(): LogLevel {
|
||||
return _level;
|
||||
}
|
||||
|
||||
function fmt(level: LogLevel, msg: string, tag?: string): string {
|
||||
const prefix = tag ? `${TAG}${tag}` : TAG;
|
||||
return `${prefix} [${level.toUpperCase()}] ${msg}`;
|
||||
}
|
||||
|
||||
export const logger = {
|
||||
error(msg: string, ...args: unknown[]): void {
|
||||
if (shouldLog(_level, "error")) console.error(fmt("error", msg), ...args);
|
||||
},
|
||||
warn(msg: string, ...args: unknown[]): void {
|
||||
if (shouldLog(_level, "warn")) console.warn(fmt("warn", msg), ...args);
|
||||
},
|
||||
info(msg: string, ...args: unknown[]): void {
|
||||
if (shouldLog(_level, "info")) console.warn(fmt("info", msg), ...args);
|
||||
},
|
||||
debug(msg: string, ...args: unknown[]): void {
|
||||
if (shouldLog(_level, "debug")) console.warn(fmt("debug", msg), ...args);
|
||||
},
|
||||
/** Always emit regardless of level (for critical init breadcrumbs). */
|
||||
always(msg: string, ...args: unknown[]): void {
|
||||
console.warn(TAG, msg, ...args);
|
||||
},
|
||||
|
||||
// ── Tagged child loggers ──────────────────────────────────────────────
|
||||
child(tag: string) {
|
||||
return {
|
||||
error: (msg: string, ...args: unknown[]) =>
|
||||
shouldLog(_level, "error") &&
|
||||
console.error(fmt("error", msg, tag), ...args),
|
||||
warn: (msg: string, ...args: unknown[]) =>
|
||||
shouldLog(_level, "warn") &&
|
||||
console.warn(fmt("warn", msg, tag), ...args),
|
||||
info: (msg: string, ...args: unknown[]) =>
|
||||
shouldLog(_level, "info") &&
|
||||
console.warn(fmt("info", msg, tag), ...args),
|
||||
debug: (msg: string, ...args: unknown[]) =>
|
||||
shouldLog(_level, "debug") &&
|
||||
console.warn(fmt("debug", msg, tag), ...args),
|
||||
};
|
||||
},
|
||||
};
|
||||
301
@omniroute/opencode-plugin/src/naming.ts
Normal file
301
@omniroute/opencode-plugin/src/naming.ts
Normal file
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Universal model naming template for the OmniRoute plugin.
|
||||
*
|
||||
* Naming pipeline:
|
||||
* [tag] <provider-label><separator><display-name><suffix>
|
||||
*
|
||||
* [Free] <provider> - <name> · <budget> ← free model
|
||||
* Auto: <variant> (<N>p) ← auto combo
|
||||
* Combo: <name> ← DB combo
|
||||
* <provider> - <name> ← regular model
|
||||
*/
|
||||
|
||||
// ── Constants ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Separator between provider label and model display name. */
|
||||
export const PROVIDER_TAG_SEPARATOR = " - ";
|
||||
|
||||
/** Threshold beyond which providerDisplayName is abbreviated. */
|
||||
const PROVIDER_LABEL_MAX_CHARS = 12;
|
||||
|
||||
/** Aliases longer than this get title-case instead of UPPER. */
|
||||
const ALIAS_UPPER_MAX_CHARS = 5;
|
||||
|
||||
// ── Auto Combo Types ─────────────────────────────────────────────────────
|
||||
|
||||
export type AutoVariant =
|
||||
| "coding"
|
||||
| "fast"
|
||||
| "cheap"
|
||||
| "offline"
|
||||
| "smart"
|
||||
| "lkgp";
|
||||
|
||||
export const AUTO_VARIANTS: AutoVariant[] = [
|
||||
"coding",
|
||||
"fast",
|
||||
"cheap",
|
||||
"offline",
|
||||
"smart",
|
||||
"lkgp",
|
||||
];
|
||||
|
||||
export const AUTO_VARIANT_DESCRIPTIONS: Record<
|
||||
AutoVariant | "default",
|
||||
string
|
||||
> = {
|
||||
default: "Best provider via scoring",
|
||||
coding: "Quality-first for code tasks",
|
||||
fast: "Latency-optimized routing",
|
||||
cheap: "Cost-optimized routing",
|
||||
offline: "Offline-friendly providers",
|
||||
smart: "Quality-first with exploration",
|
||||
lkgp: "Last-Known-Good-Provider routing",
|
||||
};
|
||||
|
||||
// ── Free Model Types ─────────────────────────────────────────────────────
|
||||
|
||||
export type FreeModelFreeType =
|
||||
| "recurring-daily"
|
||||
| "recurring-monthly"
|
||||
| "recurring-credit"
|
||||
| "one-time-initial"
|
||||
| "keyless"
|
||||
| "discontinued";
|
||||
|
||||
// ── Provider Label ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Title-case a long, lowercase-looking alias.
|
||||
* `antigravity` → `Antigravity`
|
||||
*/
|
||||
function titleCaseAlias(alias: string): string {
|
||||
if (alias.length === 0) return alias;
|
||||
return alias.charAt(0).toUpperCase() + alias.slice(1).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the short label for an upstream provider.
|
||||
*
|
||||
* Rules:
|
||||
* 1. Trim `providerDisplayName`. If ≤12 chars → use verbatim.
|
||||
* 2. Alias ≤5 chars → UPPER(alias). Alias >5 → titleCase.
|
||||
* 3. Neither → undefined.
|
||||
*/
|
||||
export function shortProviderLabel(
|
||||
enrichment:
|
||||
| { providerDisplayName?: string; providerAlias?: string }
|
||||
| undefined,
|
||||
): string | undefined {
|
||||
if (!enrichment) return undefined;
|
||||
const raw =
|
||||
typeof enrichment.providerDisplayName === "string"
|
||||
? enrichment.providerDisplayName.trim()
|
||||
: "";
|
||||
if (raw.length > 0 && raw.length <= PROVIDER_LABEL_MAX_CHARS) return raw;
|
||||
const alias =
|
||||
typeof enrichment.providerAlias === "string"
|
||||
? enrichment.providerAlias.trim()
|
||||
: "";
|
||||
if (alias.length > 0) {
|
||||
return alias.length <= ALIAS_UPPER_MAX_CHARS
|
||||
? alias.toUpperCase()
|
||||
: titleCaseAlias(alias);
|
||||
}
|
||||
// Long displayName with no alias to fall back on: keep the long label
|
||||
// rather than dropping the provider prefix entirely.
|
||||
return raw.length > 0 ? raw : undefined;
|
||||
}
|
||||
|
||||
// ── Free Label ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Normalise display name so free-tier models get a consistent `[Free] ` prefix.
|
||||
*
|
||||
* "GPT-4.1 (Free)" → "[Free] GPT-4.1"
|
||||
* "DeepSeek V4 Flash Free" → "[Free] DeepSeek V4 Flash"
|
||||
* "Claude Opus 4.7" → "Claude Opus 4.7" (unchanged)
|
||||
*/
|
||||
export function normaliseFreeLabel(name: string): string {
|
||||
// Bounded whitespace quantifiers ({0,8}/{1,8}) avoid the polynomial-ReDoS
|
||||
// backtracking that unbounded \s* before an anchored \s*$ would allow on
|
||||
// attacker-influenced display names. 8 covers any realistic label spacing.
|
||||
const cleaned = name
|
||||
.replace(/\s{0,8}\(free\)\s{0,8}$/i, "")
|
||||
.replace(/[\s-]{1,8}free\s{0,8}$/i, "")
|
||||
.trim();
|
||||
const wasFree = cleaned.length < name.trim().length;
|
||||
if (!wasFree) return name;
|
||||
return `[Free] ${cleaned}`;
|
||||
}
|
||||
|
||||
// ── Free Budget Formatting ────────────────────────────────────────────────
|
||||
|
||||
function fmtTokens(n: number): string {
|
||||
if (n >= 1e9) return (n / 1e9).toFixed(1).replace(/\.0$/, "") + "B";
|
||||
if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, "") + "M";
|
||||
if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, "") + "K";
|
||||
return String(n);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a free model budget into a short human-readable suffix.
|
||||
*
|
||||
* recurring-daily → "25M tokens/day"
|
||||
* recurring-monthly → "25M tokens/month"
|
||||
* recurring-credit → "10M credits"
|
||||
* one-time-initial → "1M credits (one-time)"
|
||||
* keyless → "(keyless)"
|
||||
* discontinued → "(discontinued)"
|
||||
*/
|
||||
export function formatFreeBudget(params: {
|
||||
freeType: FreeModelFreeType;
|
||||
monthlyTokens?: number;
|
||||
creditTokens?: number;
|
||||
}): string {
|
||||
const { freeType, monthlyTokens = 0, creditTokens = 0 } = params;
|
||||
|
||||
switch (freeType) {
|
||||
case "recurring-daily":
|
||||
return `${fmtTokens(monthlyTokens)} tokens/day`;
|
||||
case "recurring-monthly":
|
||||
return `${fmtTokens(monthlyTokens)} tokens/month`;
|
||||
case "recurring-credit":
|
||||
return `${fmtTokens(creditTokens)} credits`;
|
||||
case "one-time-initial":
|
||||
return `${fmtTokens(creditTokens)} credits (one-time)`;
|
||||
case "keyless":
|
||||
return "(keyless)";
|
||||
case "discontinued":
|
||||
return "(discontinued)";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ── Auto Combo Naming ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Format auto combo display name.
|
||||
*
|
||||
* "Auto: Coding (4p)"
|
||||
* "Auto: Default (6p)"
|
||||
* "Auto" (no candidate count when unknown)
|
||||
*/
|
||||
export function formatAutoComboName(
|
||||
variant: AutoVariant | undefined,
|
||||
candidateCount?: number,
|
||||
): string {
|
||||
const label = variant
|
||||
? variant.charAt(0).toUpperCase() + variant.slice(1)
|
||||
: "Default";
|
||||
const count =
|
||||
typeof candidateCount === "number" && candidateCount > 0
|
||||
? ` (${candidateCount}p)`
|
||||
: "";
|
||||
return `Auto: ${label}${count}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the model ID for an auto combo entry.
|
||||
* "auto/coding", "auto/fast", "auto" (default).
|
||||
*/
|
||||
export function autoComboModelId(variant: AutoVariant | undefined): string {
|
||||
return variant ? `auto/${variant}` : "auto";
|
||||
}
|
||||
|
||||
// ── Universal Display Name Builder ────────────────────────────────────────
|
||||
|
||||
export interface ModelDisplayNameParams {
|
||||
/** Raw model ID (e.g. "cc/claude-sonnet-4-6"). */
|
||||
rawId: string;
|
||||
/** Enrichment display name (e.g. "Claude Sonnet 4.6"). */
|
||||
enrichmentName?: string;
|
||||
/** Provider tag enrichment. */
|
||||
providerAlias?: string;
|
||||
/** Human-readable upstream provider label. */
|
||||
providerDisplayName?: string;
|
||||
/** Whether model is free tier. */
|
||||
isFree?: boolean;
|
||||
/** Free model budget info. */
|
||||
freeType?: FreeModelFreeType;
|
||||
/** Monthly token budget (for recurring free models). */
|
||||
monthlyTokens?: number;
|
||||
/** Credit token budget (for credit-based free models). */
|
||||
creditTokens?: number;
|
||||
/** Whether this is a combo entry (skip provider tag). */
|
||||
isCombo?: boolean;
|
||||
/** Whether this is an auto combo entry. */
|
||||
isAutoCombo?: boolean;
|
||||
/** Auto combo variant. */
|
||||
autoVariant?: AutoVariant;
|
||||
/** Auto combo candidate count. */
|
||||
autoCandidateCount?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the final display name following the universal template.
|
||||
*
|
||||
* Priority:
|
||||
* 1. Auto combo → "Auto: <variant> (<N>p)"
|
||||
* 2. DB combo → "Combo: <name>"
|
||||
* 3. Free + enrichment + provider tag → "[Free] <label> - <name> · <budget>"
|
||||
* 4. Free + enrichment → "[Free] <name> · <budget>"
|
||||
* 5. Free + raw → "[Free] <rawId> · <budget>"
|
||||
* 6. Enrichment + provider tag → "<label> - <name>"
|
||||
* 7. Enrichment only → "<name>"
|
||||
* 8. Raw fallback → normaliseFreeLabel(rawId)
|
||||
*/
|
||||
export function buildModelDisplayName(params: ModelDisplayNameParams): string {
|
||||
// Auto combos
|
||||
if (params.isAutoCombo) {
|
||||
return formatAutoComboName(params.autoVariant, params.autoCandidateCount);
|
||||
}
|
||||
|
||||
// Determine base name — strip any existing free suffix first
|
||||
const rawBase =
|
||||
params.enrichmentName && params.enrichmentName.trim().length > 0
|
||||
? params.enrichmentName
|
||||
: params.rawId;
|
||||
const cleanedBase = rawBase
|
||||
.replace(/\s*\(free\)\s*$/i, "")
|
||||
.replace(/[\s-]+free\s*$/i, "")
|
||||
.trim();
|
||||
const wasFree = cleanedBase.length < rawBase.trim().length;
|
||||
const isFree = !!params.isFree || wasFree;
|
||||
|
||||
let baseName = cleanedBase;
|
||||
|
||||
// Provider tag (skip for combos)
|
||||
if (!params.isCombo) {
|
||||
const label = shortProviderLabel({
|
||||
providerDisplayName: params.providerDisplayName,
|
||||
providerAlias: params.providerAlias,
|
||||
});
|
||||
if (label) {
|
||||
const prefix = `${label}${PROVIDER_TAG_SEPARATOR}`;
|
||||
if (!baseName.startsWith(prefix)) {
|
||||
baseName = `${prefix}${baseName}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepend [Free] if applicable (AFTER provider tag for correct ordering)
|
||||
if (isFree) {
|
||||
baseName = `[Free] ${baseName}`;
|
||||
}
|
||||
|
||||
// Free budget suffix
|
||||
if (isFree && params.freeType) {
|
||||
const budget = formatFreeBudget({
|
||||
freeType: params.freeType,
|
||||
monthlyTokens: params.monthlyTokens,
|
||||
creditTokens: params.creditTokens,
|
||||
});
|
||||
if (budget) {
|
||||
baseName = `${baseName} · ${budget}`;
|
||||
}
|
||||
}
|
||||
|
||||
return baseName;
|
||||
}
|
||||
147
@omniroute/opencode-plugin/tests/auth.test.ts
Normal file
147
@omniroute/opencode-plugin/tests/auth.test.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* T-02 auth-hook contract tests.
|
||||
*
|
||||
* Covers the `createOmniRouteAuthHook(opts)` factory and its loader behaviour
|
||||
* against every Auth flavor (`api`, `oauth`, null, empty key). Validates the
|
||||
* multi-instance fix: provider id flows from plugin options, not a module
|
||||
* constant.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createOmniRouteAuthHook } from "../src/index.js";
|
||||
|
||||
test("createOmniRouteAuthHook: default providerId is 'omniroute'", () => {
|
||||
const hook = createOmniRouteAuthHook();
|
||||
assert.equal(hook.provider, "omniroute");
|
||||
});
|
||||
|
||||
test("createOmniRouteAuthHook: custom providerId binds to hook.provider (multi-instance)", () => {
|
||||
const hook = createOmniRouteAuthHook({ providerId: "omniroute-preprod" });
|
||||
assert.equal(hook.provider, "omniroute-preprod");
|
||||
});
|
||||
|
||||
test("createOmniRouteAuthHook: methods[0] is type 'api' with label including displayName", () => {
|
||||
const hook = createOmniRouteAuthHook();
|
||||
assert.equal(Array.isArray(hook.methods), true);
|
||||
assert.equal(hook.methods.length, 1);
|
||||
const m = hook.methods[0];
|
||||
assert.equal(m.type, "api");
|
||||
assert.equal(m.label, "OmniRoute API Key");
|
||||
|
||||
const custom = createOmniRouteAuthHook({ providerId: "omniroute-preprod" });
|
||||
assert.equal(custom.methods[0].label, "OmniRoute (omniroute-preprod) API Key");
|
||||
});
|
||||
|
||||
test("createOmniRouteAuthHook: prompts[0] uses key='apiKey' per @opencode-ai/plugin contract", () => {
|
||||
// NOTE: spec referenced `name: "apiKey"`; the official
|
||||
// @opencode-ai/plugin@1.15.6 prompt shape uses `key` + `message` (no
|
||||
// `name`/`label`/`mask` fields). Asserting against the real type contract.
|
||||
const hook = createOmniRouteAuthHook();
|
||||
const m = hook.methods[0];
|
||||
assert.equal(m.type, "api");
|
||||
// narrow: api method may carry prompts
|
||||
const prompts = "prompts" in m ? m.prompts : undefined;
|
||||
assert.ok(Array.isArray(prompts) && prompts.length === 1, "expected one prompt");
|
||||
const p = prompts![0];
|
||||
assert.equal(p.type, "text");
|
||||
assert.equal((p as { key: string }).key, "apiKey");
|
||||
assert.ok(
|
||||
typeof (p as { message: string }).message === "string" &&
|
||||
(p as { message: string }).message.includes("omniroute"),
|
||||
"prompt message should mention provider id"
|
||||
);
|
||||
});
|
||||
|
||||
test("loader: valid api auth → {apiKey} when no baseURL option (T-04: fetch omitted)", async () => {
|
||||
// T-04 changed the loader return shape: without a resolvable baseURL the
|
||||
// interceptor cannot gate-keep requests, so the loader falls back to
|
||||
// apiKey-only and the AI-SDK uses its default fetch. See fetch-interceptor
|
||||
// tests for the wired-fetch branches.
|
||||
const hook = createOmniRouteAuthHook();
|
||||
assert.ok(hook.loader, "loader must be defined");
|
||||
const result = await hook.loader!(
|
||||
async () => ({ type: "api", key: "sk-test" }) as never,
|
||||
{} as never
|
||||
);
|
||||
assert.deepEqual(result, { apiKey: "sk-test" });
|
||||
});
|
||||
|
||||
test("loader: valid api auth → {apiKey, baseURL, fetch} when baseURL option set (T-04)", async () => {
|
||||
const hook = createOmniRouteAuthHook({ baseURL: "https://or.example.com/v1" });
|
||||
const result = await hook.loader!(
|
||||
async () => ({ type: "api", key: "sk-x" }) as never,
|
||||
{} as never
|
||||
);
|
||||
assert.equal((result as { apiKey: string }).apiKey, "sk-x");
|
||||
assert.equal((result as { baseURL: string }).baseURL, "https://or.example.com/v1");
|
||||
assert.equal(
|
||||
typeof (result as { fetch?: unknown }).fetch,
|
||||
"function",
|
||||
"T-04: loader must wire fetch interceptor when baseURL resolves"
|
||||
);
|
||||
});
|
||||
|
||||
test("loader: features.fetchInterceptor=false AND geminiSanitization=false → no custom fetch (flags honored)", async () => {
|
||||
// Regression: both fetch-layer flags were documented + schema-validated but
|
||||
// silently ignored. Disabling both must fall back to the SDK default fetch.
|
||||
const hook = createOmniRouteAuthHook({
|
||||
baseURL: "https://or.example.com/v1",
|
||||
features: { fetchInterceptor: false, geminiSanitization: false },
|
||||
});
|
||||
const result = await hook.loader!(
|
||||
async () => ({ type: "api", key: "sk-x" }) as never,
|
||||
{} as never
|
||||
);
|
||||
assert.deepEqual(result, { apiKey: "sk-x", baseURL: "https://or.example.com/v1" });
|
||||
assert.equal(
|
||||
(result as { fetch?: unknown }).fetch,
|
||||
undefined,
|
||||
"both flags off must omit the custom fetch"
|
||||
);
|
||||
});
|
||||
|
||||
test("loader: features.fetchInterceptor=false but geminiSanitization=true → fetch still wired (sanitizer only)", async () => {
|
||||
const hook = createOmniRouteAuthHook({
|
||||
baseURL: "https://or.example.com/v1",
|
||||
features: { fetchInterceptor: false, geminiSanitization: true },
|
||||
});
|
||||
const result = await hook.loader!(
|
||||
async () => ({ type: "api", key: "sk-x" }) as never,
|
||||
{} as never
|
||||
);
|
||||
assert.equal(
|
||||
typeof (result as { fetch?: unknown }).fetch,
|
||||
"function",
|
||||
"geminiSanitization alone must still provide a fetch wrapper"
|
||||
);
|
||||
});
|
||||
|
||||
test("loader: null/undefined auth → {} (no creds yet, OC surfaces /connect)", async () => {
|
||||
const hook = createOmniRouteAuthHook();
|
||||
const r1 = await hook.loader!(async () => null as never, {} as never);
|
||||
assert.deepEqual(r1, {});
|
||||
const r2 = await hook.loader!(async () => undefined as never, {} as never);
|
||||
assert.deepEqual(r2, {});
|
||||
});
|
||||
|
||||
test("loader: oauth-flavored auth → {} (wrong method type, ignored)", async () => {
|
||||
const hook = createOmniRouteAuthHook();
|
||||
const result = await hook.loader!(
|
||||
async () =>
|
||||
({
|
||||
type: "oauth",
|
||||
refresh: "r",
|
||||
access: "a",
|
||||
expires: 0,
|
||||
}) as never,
|
||||
{} as never
|
||||
);
|
||||
assert.deepEqual(result, {});
|
||||
});
|
||||
|
||||
test("loader: api auth with empty key → {} (empty creds rejected)", async () => {
|
||||
const hook = createOmniRouteAuthHook();
|
||||
const result = await hook.loader!(async () => ({ type: "api", key: "" }) as never, {} as never);
|
||||
assert.deepEqual(result, {});
|
||||
});
|
||||
74
@omniroute/opencode-plugin/tests/auto-combo-context.test.ts
Normal file
74
@omniroute/opencode-plugin/tests/auto-combo-context.test.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* TDD regression — auto combos must never advertise `limit.context: 0`.
|
||||
*
|
||||
* opencode's overflow guard (packages/opencode/src/session/overflow.ts)
|
||||
* short-circuits when `model.limit.context === 0`:
|
||||
*
|
||||
* if (input.model.limit.context === 0) return false // never overflow
|
||||
*
|
||||
* so a zero context silently DISABLES opencode's smart auto-compaction for
|
||||
* auto combos. The session then grows unbounded until OmniRoute's
|
||||
* server-side purifyHistory() destructively drops old messages — the
|
||||
* "coding agent keeps forgetting things" bug.
|
||||
*
|
||||
* Fix under test: mapAutoComboToStaticEntry consumes the context_length /
|
||||
* max_output_tokens now served by GET /api/combos/auto, and falls back to a
|
||||
* safe positive default (128000 / 8192) for older servers that do not send
|
||||
* the fields yet.
|
||||
*/
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { mapAutoComboToStaticEntry } from "../src/index.ts";
|
||||
import type { OmniRouteRawAutoCombo } from "../src/index.ts";
|
||||
|
||||
test("uses server-provided context_length and max_output_tokens", () => {
|
||||
const raw = {
|
||||
id: "auto/coding",
|
||||
name: "Auto Coding",
|
||||
variant: "coding",
|
||||
candidateCount: 5,
|
||||
context_length: 1048576,
|
||||
max_output_tokens: 65536,
|
||||
} as OmniRouteRawAutoCombo;
|
||||
|
||||
const entry = mapAutoComboToStaticEntry(raw);
|
||||
assert.equal(entry.limit?.context, 1048576);
|
||||
assert.equal(entry.limit?.output, 65536);
|
||||
});
|
||||
|
||||
test("falls back to a safe positive default when the server omits limits (old servers)", () => {
|
||||
const raw = {
|
||||
id: "auto",
|
||||
name: "Auto",
|
||||
candidateCount: 3,
|
||||
} as OmniRouteRawAutoCombo;
|
||||
|
||||
const entry = mapAutoComboToStaticEntry(raw);
|
||||
assert.ok(
|
||||
typeof entry.limit?.context === "number" && entry.limit.context > 0,
|
||||
`context must be a positive number (never 0 — zero disables opencode auto-compaction), got ${entry.limit?.context}`
|
||||
);
|
||||
assert.ok(
|
||||
typeof entry.limit?.output === "number" && entry.limit.output > 0,
|
||||
`output must be a positive number, got ${entry.limit?.output}`
|
||||
);
|
||||
});
|
||||
|
||||
test("ignores non-positive server values and keeps the safe fallback", () => {
|
||||
const raw = {
|
||||
id: "auto/fast",
|
||||
name: "Auto Fast",
|
||||
variant: "fast",
|
||||
candidateCount: 2,
|
||||
context_length: 0,
|
||||
max_output_tokens: -1,
|
||||
} as OmniRouteRawAutoCombo;
|
||||
|
||||
const entry = mapAutoComboToStaticEntry(raw);
|
||||
assert.ok(
|
||||
typeof entry.limit?.context === "number" && entry.limit.context > 0,
|
||||
"zero/negative server values must not propagate"
|
||||
);
|
||||
assert.ok(typeof entry.limit?.output === "number" && entry.limit.output > 0);
|
||||
});
|
||||
641
@omniroute/opencode-plugin/tests/combos.test.ts
Normal file
641
@omniroute/opencode-plugin/tests/combos.test.ts
Normal file
@@ -0,0 +1,641 @@
|
||||
/**
|
||||
* T-05 combo-discovery contract tests.
|
||||
*
|
||||
* Covers:
|
||||
* - `defaultOmniRouteCombosFetcher(baseURL, apiKey, timeoutMs?)`
|
||||
* — envelope tolerance (`{combos: [...]}` and bare array), non-2xx errors.
|
||||
* - `mapComboToModelV2(combo, members, providerId, baseURL)`
|
||||
* — LCD policy across capabilities, limits, modalities; defensive
|
||||
* posture on empty members; nice-name preference.
|
||||
* - `createOmniRouteProviderHook(opts, deps)` extension
|
||||
* — combos merged into the models map; collision resolution (combo
|
||||
* wins, warn-once); soft-fail when the combos fetcher throws;
|
||||
* combos cached + reused under the same TTL key as models.
|
||||
*
|
||||
* Mocking strategy mirrors `provider.test.ts`: both fetchers are
|
||||
* dependency-injected at hook construction, no `fetch` monkey-patch.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
createOmniRouteProviderHook,
|
||||
defaultOmniRouteCombosFetcher,
|
||||
mapComboToModelV2,
|
||||
type OmniRouteCombosFetcher,
|
||||
type OmniRouteModelsFetcher,
|
||||
type OmniRouteRawCombo,
|
||||
type OmniRouteRawModelEntry,
|
||||
} from "../src/index.js";
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// Fixtures
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const MODEL_PRIMARY: OmniRouteRawModelEntry = {
|
||||
id: "claude-primary",
|
||||
capabilities: {
|
||||
tool_calling: true,
|
||||
reasoning: true,
|
||||
vision: true,
|
||||
thinking: true,
|
||||
temperature: true,
|
||||
},
|
||||
context_length: 200_000,
|
||||
max_output_tokens: 64_000,
|
||||
max_input_tokens: 180_000,
|
||||
input_modalities: ["text", "image"],
|
||||
output_modalities: ["text"],
|
||||
};
|
||||
|
||||
const MODEL_SECONDARY: OmniRouteRawModelEntry = {
|
||||
id: "claude-secondary",
|
||||
capabilities: {
|
||||
tool_calling: true,
|
||||
reasoning: false,
|
||||
vision: true,
|
||||
thinking: false,
|
||||
temperature: true,
|
||||
},
|
||||
context_length: 100_000,
|
||||
max_output_tokens: 32_000,
|
||||
max_input_tokens: 96_000,
|
||||
input_modalities: ["text", "image"],
|
||||
output_modalities: ["text"],
|
||||
};
|
||||
|
||||
const MODEL_NO_TOOLS: OmniRouteRawModelEntry = {
|
||||
id: "gemini-3-flash",
|
||||
capabilities: { tool_calling: false, reasoning: false, vision: false, thinking: false },
|
||||
context_length: 1_000_000,
|
||||
max_output_tokens: 8_192,
|
||||
input_modalities: ["text"],
|
||||
output_modalities: ["text"],
|
||||
};
|
||||
|
||||
const COMBO_CLAUDE_TIER: OmniRouteRawCombo = {
|
||||
id: "combo-claude-tier",
|
||||
name: "Claude Tier",
|
||||
strategy: "priority",
|
||||
models: [
|
||||
{ id: "s1", kind: "model", model: "claude-primary", weight: 100 },
|
||||
{ id: "s2", kind: "model", model: "claude-secondary", weight: 80 },
|
||||
],
|
||||
};
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
function stubModelsFetcher(
|
||||
payload: OmniRouteRawModelEntry[]
|
||||
): OmniRouteModelsFetcher & { callCount: () => number } {
|
||||
let n = 0;
|
||||
const f: OmniRouteModelsFetcher = async () => {
|
||||
n++;
|
||||
return payload;
|
||||
};
|
||||
return Object.assign(f, { callCount: () => n });
|
||||
}
|
||||
|
||||
function stubCombosFetcher(
|
||||
payload: OmniRouteRawCombo[]
|
||||
): OmniRouteCombosFetcher & { callCount: () => number; callsBy: () => Array<[string, string]> } {
|
||||
let n = 0;
|
||||
const calls: Array<[string, string]> = [];
|
||||
const f: OmniRouteCombosFetcher = async (baseURL, apiKey) => {
|
||||
n++;
|
||||
calls.push([baseURL, apiKey]);
|
||||
return payload;
|
||||
};
|
||||
return Object.assign(f, {
|
||||
callCount: () => n,
|
||||
callsBy: () => calls,
|
||||
});
|
||||
}
|
||||
|
||||
function failingCombosFetcher(
|
||||
err = new Error("boom")
|
||||
): OmniRouteCombosFetcher & { callCount: () => number } {
|
||||
let n = 0;
|
||||
const f: OmniRouteCombosFetcher = async () => {
|
||||
n++;
|
||||
throw err;
|
||||
};
|
||||
return Object.assign(f, { callCount: () => n });
|
||||
}
|
||||
|
||||
const apiAuth = (key: string): unknown => ({ type: "api", key });
|
||||
|
||||
// Capture console.warn invocations for the duration of a callback, then
|
||||
// restore the original. Needed because the collision + soft-fail paths
|
||||
// emit warnings we want to assert on.
|
||||
async function withWarnCapture<T>(
|
||||
fn: (warnings: Array<{ args: unknown[] }>) => Promise<T>
|
||||
): Promise<{ result: T; warnings: Array<{ args: unknown[] }> }> {
|
||||
const original = console.warn;
|
||||
const warnings: Array<{ args: unknown[] }> = [];
|
||||
console.warn = (...args: unknown[]) => {
|
||||
warnings.push({ args });
|
||||
};
|
||||
try {
|
||||
const result = await fn(warnings);
|
||||
return { result, warnings };
|
||||
} finally {
|
||||
console.warn = original;
|
||||
}
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// defaultOmniRouteCombosFetcher — envelope tolerance + error surfacing
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
test("defaultOmniRouteCombosFetcher: parses {combos:[…]} envelope", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: unknown) => {
|
||||
const url = typeof input === "string" ? input : (input as { url: string }).url;
|
||||
assert.equal(url, "https://or.example.com/api/combos");
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
combos: [
|
||||
{ id: "c1", name: "Combo One", strategy: "priority", models: [] },
|
||||
{ id: "c2", name: "Combo Two", strategy: "weighted", models: [] },
|
||||
],
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } }
|
||||
);
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
const combos = await defaultOmniRouteCombosFetcher("https://or.example.com", "sk-test");
|
||||
assert.equal(combos.length, 2);
|
||||
assert.equal(combos[0].id, "c1");
|
||||
assert.equal(combos[1].id, "c2");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("defaultOmniRouteCombosFetcher: parses bare array envelope", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () => {
|
||||
return new Response(JSON.stringify([{ id: "c1" }, { id: "c2" }, { not_an_id: 42 }]), {
|
||||
status: 200,
|
||||
});
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
const combos = await defaultOmniRouteCombosFetcher("https://or.example.com/v1", "sk-test");
|
||||
// Strip /v1 before /api/combos, AND filter out entries with no string id.
|
||||
assert.equal(combos.length, 2);
|
||||
assert.equal(combos[0].id, "c1");
|
||||
assert.equal(combos[1].id, "c2");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("defaultOmniRouteCombosFetcher: strips trailing /v1 before /api/combos", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
let observedUrl = "";
|
||||
globalThis.fetch = (async (input: unknown) => {
|
||||
observedUrl = typeof input === "string" ? input : (input as { url: string }).url;
|
||||
return new Response(JSON.stringify({ combos: [] }), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
await defaultOmniRouteCombosFetcher("https://or.example.com/v1/", "sk-test");
|
||||
assert.equal(observedUrl, "https://or.example.com/api/combos");
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("defaultOmniRouteCombosFetcher: throws on non-2xx with status code in message", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async () => {
|
||||
return new Response(JSON.stringify({ error: "Invalid token" }), {
|
||||
status: 403,
|
||||
statusText: "Forbidden",
|
||||
});
|
||||
}) as typeof fetch;
|
||||
try {
|
||||
await assert.rejects(
|
||||
async () => {
|
||||
await defaultOmniRouteCombosFetcher("https://or.example.com", "sk-bad");
|
||||
},
|
||||
(err: unknown) => {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
assert.match(msg, /403/, "status code must appear in message");
|
||||
assert.match(msg, /\/api\/combos/, "url must appear in message");
|
||||
return true;
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
|
||||
test("defaultOmniRouteCombosFetcher: throws when apiKey missing", async () => {
|
||||
await assert.rejects(
|
||||
async () => defaultOmniRouteCombosFetcher("https://or.example.com", ""),
|
||||
/apiKey required/
|
||||
);
|
||||
});
|
||||
|
||||
test("defaultOmniRouteCombosFetcher: throws when baseURL missing", async () => {
|
||||
await assert.rejects(
|
||||
async () => defaultOmniRouteCombosFetcher("", "sk-test"),
|
||||
/baseURL required/
|
||||
);
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// mapComboToModelV2 — LCD semantics
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
test("mapComboToModelV2: empty members → capabilities all false (defensive)", () => {
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "combo-empty", name: "Empty Combo" },
|
||||
[],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m.id, "combo-empty");
|
||||
assert.equal(m.name, "Empty Combo");
|
||||
assert.equal(m.capabilities.temperature, false);
|
||||
assert.equal(m.capabilities.reasoning, false);
|
||||
assert.equal(m.capabilities.attachment, false);
|
||||
assert.equal(m.capabilities.toolcall, false);
|
||||
assert.equal(m.capabilities.input.text, false);
|
||||
assert.equal(m.capabilities.output.text, false);
|
||||
assert.equal(m.limit.context, 0);
|
||||
assert.equal(m.limit.output, 0);
|
||||
assert.equal(m.limit.input, undefined);
|
||||
assert.deepEqual(m.cost, { input: 0, output: 0, cache: { read: 0, write: 0 } });
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: all members reasoning=true → combo reasoning=true", () => {
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[
|
||||
MODEL_PRIMARY,
|
||||
{
|
||||
...MODEL_PRIMARY,
|
||||
id: "p2",
|
||||
capabilities: { ...MODEL_PRIMARY.capabilities, thinking: false, reasoning: true },
|
||||
},
|
||||
],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m.capabilities.reasoning, true);
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: any member reasoning=false → combo reasoning=false", () => {
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_NO_TOOLS], // gemini-3-flash has reasoning:false, thinking:false
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m.capabilities.reasoning, false);
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: limit.context is min of members'", () => {
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_SECONDARY, MODEL_NO_TOOLS],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
// min(200_000, 100_000, 1_000_000) = 100_000
|
||||
assert.equal(m.limit.context, 100_000);
|
||||
// min(64_000, 32_000, 8_192) = 8_192
|
||||
assert.equal(m.limit.output, 8_192);
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: limit.input only emitted when EVERY member declares one", () => {
|
||||
const m1 = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_SECONDARY],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
// Both declare max_input_tokens → limit.input = min(180000, 96000)
|
||||
assert.equal(m1.limit.input, 96_000);
|
||||
|
||||
const m2 = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_NO_TOOLS], // gemini-3-flash doesn't declare max_input_tokens
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m2.limit.input, undefined);
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: nice name preferred from combo.name", () => {
|
||||
const m1 = mapComboToModelV2(
|
||||
{ id: "combo-x", name: "Pretty Name" },
|
||||
[MODEL_PRIMARY],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m1.name, "Pretty Name");
|
||||
|
||||
// Falls back to id when name is absent or empty.
|
||||
const m2 = mapComboToModelV2(
|
||||
{ id: "combo-y" },
|
||||
[MODEL_PRIMARY],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m2.name, "combo-y");
|
||||
|
||||
const m3 = mapComboToModelV2(
|
||||
{ id: "combo-z", name: " " },
|
||||
[MODEL_PRIMARY],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m3.name, "combo-z");
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: attachment AND vision flag both honored across members", () => {
|
||||
// MODEL_PRIMARY: vision=true; MODEL_SECONDARY: vision=true → combo attachment=true
|
||||
const yes = mapComboToModelV2(
|
||||
{ id: "c1", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_SECONDARY],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(yes.capabilities.attachment, true);
|
||||
|
||||
// Add a member with no vision/attachment → AND collapses to false
|
||||
const no = mapComboToModelV2(
|
||||
{ id: "c2", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_NO_TOOLS],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(no.capabilities.attachment, false);
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: modalities AND'd across members", () => {
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_SECONDARY], // both have text+image
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m.capabilities.input.text, true);
|
||||
assert.equal(m.capabilities.input.image, true);
|
||||
assert.equal(m.capabilities.input.audio, false);
|
||||
|
||||
// Add a text-only member → image collapses to false.
|
||||
const m2 = mapComboToModelV2(
|
||||
{ id: "c", models: [] },
|
||||
[MODEL_PRIMARY, MODEL_NO_TOOLS],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m2.capabilities.input.text, true);
|
||||
assert.equal(m2.capabilities.input.image, false);
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: api block matches providerId + baseURL", () => {
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "c" },
|
||||
[MODEL_PRIMARY],
|
||||
"omniroute-preprod",
|
||||
"https://or-preprod.example.com/v1"
|
||||
);
|
||||
assert.equal(m.providerID, "omniroute-preprod");
|
||||
assert.equal(m.api.id, "openai-compatible");
|
||||
assert.equal(m.api.url, "https://or-preprod.example.com/v1");
|
||||
assert.equal(m.api.npm, "@ai-sdk/openai-compatible");
|
||||
assert.equal(m.status, "active");
|
||||
});
|
||||
|
||||
test("mapComboToModelV2: explicit member temperature=false drops combo temperature=false", () => {
|
||||
const tempFalse: OmniRouteRawModelEntry = {
|
||||
id: "no-temp",
|
||||
capabilities: { tool_calling: true, temperature: false },
|
||||
context_length: 100_000,
|
||||
max_output_tokens: 8_000,
|
||||
input_modalities: ["text"],
|
||||
output_modalities: ["text"],
|
||||
};
|
||||
const m = mapComboToModelV2(
|
||||
{ id: "c" },
|
||||
[MODEL_PRIMARY, tempFalse],
|
||||
"omniroute",
|
||||
"https://or.example.com/v1"
|
||||
);
|
||||
assert.equal(m.capabilities.temperature, false);
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// createOmniRouteProviderHook — combos merge + collision + soft-fail + cache
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
test("models() returns combo entries merged into the map", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY, MODEL_SECONDARY, MODEL_NO_TOOLS]);
|
||||
const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher: modelsFetcher, combosFetcher }
|
||||
);
|
||||
const out = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
|
||||
// 3 raw models + 1 combo = 4 entries
|
||||
assert.equal(Object.keys(out).length, 4);
|
||||
assert.ok(out["claude-primary"]);
|
||||
assert.ok(out["claude-secondary"]);
|
||||
assert.ok(out["gemini-3-flash"]);
|
||||
assert.ok(out["combo/claude-tier"]);
|
||||
|
||||
const combo = out["combo/claude-tier"];
|
||||
assert.equal(combo.name, "Combo: Claude Tier");
|
||||
assert.equal(combo.providerID, "omniroute");
|
||||
// LCD over claude-primary (200k, reasoning) + claude-secondary (100k, no reasoning)
|
||||
assert.equal(combo.limit.context, 100_000);
|
||||
assert.equal(combo.capabilities.reasoning, false);
|
||||
assert.equal(combo.capabilities.toolcall, true);
|
||||
});
|
||||
|
||||
test("models(): combo with unknown member ids degrades to all-false LCD posture", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY]); // catalog only has claude-primary
|
||||
const combosFetcher = stubCombosFetcher([
|
||||
{
|
||||
id: "phantom",
|
||||
name: "Phantom Combo",
|
||||
models: [
|
||||
{ id: "s1", kind: "model", model: "does-not-exist-1", weight: 50 },
|
||||
{ id: "s2", kind: "model", model: "does-not-exist-2", weight: 50 },
|
||||
],
|
||||
},
|
||||
]);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher: modelsFetcher, combosFetcher }
|
||||
);
|
||||
const out = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
assert.ok(out["combo/phantom-combo"]);
|
||||
// With zero resolvable members, LCD = all-false (defensive posture).
|
||||
assert.equal(out["combo/phantom-combo"].capabilities.toolcall, false);
|
||||
assert.equal(out["combo/phantom-combo"].capabilities.reasoning, false);
|
||||
assert.equal(out["combo/phantom-combo"].limit.context, 0);
|
||||
});
|
||||
|
||||
test("models(): hidden combos are excluded from the map", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY]);
|
||||
const combosFetcher = stubCombosFetcher([
|
||||
{
|
||||
id: "visible",
|
||||
name: "Visible",
|
||||
models: [{ id: "s1", kind: "model", model: "claude-primary", weight: 100 }],
|
||||
},
|
||||
{
|
||||
id: "hidden",
|
||||
name: "Hidden",
|
||||
isHidden: true,
|
||||
models: [{ id: "s1", kind: "model", model: "claude-primary", weight: 100 }],
|
||||
},
|
||||
]);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher: modelsFetcher, combosFetcher }
|
||||
);
|
||||
const out = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
assert.ok(out["combo/visible"]);
|
||||
assert.ok(!out["combo/hidden"], "hidden combo must be omitted");
|
||||
});
|
||||
|
||||
test("models(): combo name exactly matches raw model id → raw deleted, combo lives at combo/ key, no warn", async () => {
|
||||
// Combo.name === raw model id triggers the dedup deletion. This mirrors
|
||||
// the real OmniRoute payload where /v1/models pre-mirrors combos as
|
||||
// no-slash raw entries whose ids match /api/combos friendly names.
|
||||
const colliderCombo: OmniRouteRawCombo = {
|
||||
id: "uuid-collider",
|
||||
name: "claude-primary", // EXACT match to MODEL_PRIMARY.id
|
||||
models: [{ id: "s1", kind: "model", model: "claude-secondary", weight: 100 }],
|
||||
};
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY, MODEL_SECONDARY]);
|
||||
const combosFetcher = stubCombosFetcher([colliderCombo]);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher: modelsFetcher, combosFetcher }
|
||||
);
|
||||
|
||||
const { result: out, warnings } = await withWarnCapture(async (_w) => {
|
||||
return hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
});
|
||||
|
||||
// Raw model deleted by combo-name dedup; combo surfaces under combo/<slug>.
|
||||
assert.equal(out["claude-primary"], undefined, "raw deleted by combo-name dedup");
|
||||
assert.ok(out["combo/claude-primary"], "combo surfaces under combo/ namespace");
|
||||
assert.equal(out["combo/claude-primary"].name, "Combo: claude-primary");
|
||||
|
||||
// No collision warning fires — dedup makes keys disjoint.
|
||||
const collisionWarns = warnings.filter((w) => {
|
||||
const msg = w.args[0];
|
||||
return typeof msg === "string" && msg.includes("collides");
|
||||
});
|
||||
assert.equal(collisionWarns.length, 0, "no collision warn after dedup");
|
||||
});
|
||||
|
||||
test("models(): two combos with same slug → second gets disambiguator suffix", async () => {
|
||||
// Both combos slug to `claude` — second must get `combo/claude-<id-prefix>`.
|
||||
const combos: OmniRouteRawCombo[] = [
|
||||
{
|
||||
id: "uuid-a",
|
||||
name: "Claude",
|
||||
models: [{ id: "s", kind: "model", model: "claude-primary", weight: 1 }],
|
||||
},
|
||||
{
|
||||
id: "uuid-b",
|
||||
name: "Claude",
|
||||
models: [{ id: "s", kind: "model", model: "claude-secondary", weight: 1 }],
|
||||
},
|
||||
];
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{
|
||||
fetcher: stubModelsFetcher([MODEL_PRIMARY, MODEL_SECONDARY]),
|
||||
combosFetcher: stubCombosFetcher(combos),
|
||||
}
|
||||
);
|
||||
|
||||
const out = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
// First combo gets the bare slug; second gets disambiguated.
|
||||
assert.ok(out["combo/claude"], "first combo at bare slug");
|
||||
assert.ok(out["combo/claude-uuid"], "second combo disambiguated by id prefix");
|
||||
});
|
||||
|
||||
test("models(): combos fetch fails → falls back to models-only, warn emitted, no throw", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY, MODEL_SECONDARY]);
|
||||
const combosFetcher = failingCombosFetcher(new Error("ECONNRESET"));
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher: modelsFetcher, combosFetcher }
|
||||
);
|
||||
|
||||
const { result: out, warnings } = await withWarnCapture(async () => {
|
||||
return hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
});
|
||||
|
||||
// Catalog includes the models but NOT any combo entries.
|
||||
assert.equal(Object.keys(out).length, 2);
|
||||
assert.ok(out["claude-primary"]);
|
||||
assert.ok(out["claude-secondary"]);
|
||||
|
||||
// Soft-fail warning surfaced.
|
||||
const softFail = warnings.find((w) => {
|
||||
const msg = w.args[0];
|
||||
return typeof msg === "string" && msg.includes("combos fetch failed");
|
||||
});
|
||||
assert.ok(softFail, "soft-fail warning must be emitted on combos fetch error");
|
||||
assert.equal(combosFetcher.callCount(), 1);
|
||||
});
|
||||
|
||||
test("models(): combos cached + reused within TTL (one combo fetch per TTL window)", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY, MODEL_SECONDARY]);
|
||||
const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
|
||||
let nowMs = 1_000_000;
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1", modelCacheTtl: 60_000 },
|
||||
{ fetcher: modelsFetcher, combosFetcher, now: () => nowMs }
|
||||
);
|
||||
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
nowMs += 30_000; // half the TTL
|
||||
const second = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
assert.equal(combosFetcher.callCount(), 1, "combos fetched only once within TTL");
|
||||
assert.equal(modelsFetcher.callCount(), 1, "models fetched only once within TTL");
|
||||
assert.ok(second["combo/claude-tier"]);
|
||||
});
|
||||
|
||||
test("models(): combos refetched after TTL expiry (same key as models)", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY]);
|
||||
const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
|
||||
let nowMs = 1_000_000;
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1", modelCacheTtl: 60_000 },
|
||||
{ fetcher: modelsFetcher, combosFetcher, now: () => nowMs }
|
||||
);
|
||||
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
nowMs += 60_001;
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
assert.equal(combosFetcher.callCount(), 2, "combos must refetch past TTL");
|
||||
assert.equal(modelsFetcher.callCount(), 2, "models must refetch past TTL");
|
||||
});
|
||||
|
||||
test("models(): combos fetcher receives the resolved baseURL + apiKey", async () => {
|
||||
const modelsFetcher = stubModelsFetcher([MODEL_PRIMARY]);
|
||||
const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher: modelsFetcher, combosFetcher }
|
||||
);
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-spy") as never });
|
||||
assert.deepEqual(combosFetcher.callsBy()[0], ["https://or.example.com/v1", "sk-spy"]);
|
||||
});
|
||||
1364
@omniroute/opencode-plugin/tests/config-shim.test.ts
Normal file
1364
@omniroute/opencode-plugin/tests/config-shim.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
66
@omniroute/opencode-plugin/tests/disk-snapshot-perms.test.ts
Normal file
66
@omniroute/opencode-plugin/tests/disk-snapshot-perms.test.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Regression test for the disk-snapshot file permissions (release/v3.8.2
|
||||
* review finding C2). The snapshot embeds provider topology + connection
|
||||
* records and lives alongside auth.json (0o600), so it must NOT be readable by
|
||||
* group/other. Before the fix it was written with the default (typically
|
||||
* world-readable 0o644) mode.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
defaultDiskSnapshotWriter,
|
||||
diskSnapshotPath,
|
||||
type OmniRouteFetchCacheEntry,
|
||||
} from "../src/index.js";
|
||||
|
||||
function makeEntry(): Omit<OmniRouteFetchCacheEntry, "expiresAt"> {
|
||||
return {
|
||||
rawModels: [],
|
||||
rawCombos: [],
|
||||
rawEnrichment: new Map(),
|
||||
rawCompressionCombos: [],
|
||||
rawConnections: [],
|
||||
};
|
||||
}
|
||||
|
||||
test("defaultDiskSnapshotWriter writes an owner-only (no group/other) snapshot", async (t) => {
|
||||
// POSIX-only assertion; Windows does not honor numeric file modes.
|
||||
if (process.platform === "win32") {
|
||||
t.skip("file mode semantics are POSIX-only");
|
||||
return;
|
||||
}
|
||||
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-disk-perms-"));
|
||||
const prevDataDir = process.env.OPENCODE_DATA_DIR;
|
||||
process.env.OPENCODE_DATA_DIR = tmp;
|
||||
|
||||
try {
|
||||
await defaultDiskSnapshotWriter("perm-test", makeEntry());
|
||||
|
||||
const file = diskSnapshotPath("perm-test");
|
||||
assert.ok(fs.existsSync(file), "snapshot file should be written");
|
||||
|
||||
const fileMode = fs.statSync(file).mode & 0o777;
|
||||
assert.equal(
|
||||
fileMode & 0o077,
|
||||
0,
|
||||
`snapshot must not be group/other accessible (got ${fileMode.toString(8)})`
|
||||
);
|
||||
|
||||
const dirMode = fs.statSync(path.dirname(file)).mode & 0o777;
|
||||
assert.equal(
|
||||
dirMode & 0o077,
|
||||
0,
|
||||
`plugins dir must not be group/other accessible (got ${dirMode.toString(8)})`
|
||||
);
|
||||
} finally {
|
||||
if (prevDataDir === undefined) delete process.env.OPENCODE_DATA_DIR;
|
||||
else process.env.OPENCODE_DATA_DIR = prevDataDir;
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
1064
@omniroute/opencode-plugin/tests/features.test.ts
Normal file
1064
@omniroute/opencode-plugin/tests/features.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
269
@omniroute/opencode-plugin/tests/fetch-interceptor.test.ts
Normal file
269
@omniroute/opencode-plugin/tests/fetch-interceptor.test.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* T-04 fetch-interceptor contract tests.
|
||||
*
|
||||
* Covers `createOmniRouteFetchInterceptor` (URL-prefix gating, header merge,
|
||||
* Content-Type defaulting, input-shape polymorphism) plus the loader
|
||||
* integration that wires it into the AuthHook return shape.
|
||||
*
|
||||
* Strategy: replace `globalThis.fetch` with a closure-based recorder for the
|
||||
* duration of each test (saved-and-restored in try/finally — node:test has
|
||||
* no built-in spy/restore lifecycle). The recorder captures `(input, init)`
|
||||
* as observed by the wrapped global call so we can assert on what was
|
||||
* forwarded after header injection.
|
||||
*/
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createOmniRouteAuthHook, createOmniRouteFetchInterceptor } from "../src/index.js";
|
||||
|
||||
type FetchCall = { input: Parameters<typeof fetch>[0]; init?: RequestInit };
|
||||
|
||||
function installFetchRecorder(response: Response = new Response("ok")) {
|
||||
const calls: FetchCall[] = [];
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: any, init?: any) => {
|
||||
calls.push({ input, init });
|
||||
return response;
|
||||
}) as typeof fetch;
|
||||
const restore = () => {
|
||||
globalThis.fetch = original;
|
||||
};
|
||||
return { calls, restore };
|
||||
}
|
||||
|
||||
const BASE = "https://or.example.com/v1";
|
||||
const KEY = "sk-test-fetch";
|
||||
|
||||
test("createOmniRouteFetchInterceptor: targets baseURL → Authorization header injected", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f(`${BASE}/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ x: 1 }),
|
||||
});
|
||||
assert.equal(calls.length, 1);
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: targets baseURL → Authorization OVERRIDES caller-supplied Bearer", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f(`${BASE}/chat/completions`, {
|
||||
method: "POST",
|
||||
body: "{}",
|
||||
headers: { Authorization: "Bearer attacker-key" },
|
||||
});
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
// We own the apiKey for this provider — caller-supplied Bearer must lose.
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: targets baseURL + body → Content-Type defaults to application/json", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f(`${BASE}/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ m: "x" }),
|
||||
});
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Content-Type"), "application/json");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: caller-set Content-Type is NOT overwritten", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f(`${BASE}/v2/whatever`, {
|
||||
method: "POST",
|
||||
body: "raw",
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Content-Type"), "text/plain; charset=utf-8");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: non-baseURL host → passthrough, no Authorization injected", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f("https://third-party.example.org/v1/chat", {
|
||||
method: "POST",
|
||||
body: "{}",
|
||||
headers: { "X-Caller": "yes" },
|
||||
});
|
||||
const sent = calls[0]!;
|
||||
// Init forwarded verbatim — no header injection.
|
||||
const sentHeaders = new Headers((sent.init as RequestInit | undefined)?.headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), null, "MUST NOT leak apiKey");
|
||||
assert.equal(sentHeaders.get("X-Caller"), "yes");
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: refuses suffix-spoof — `${base}-attacker.evil` does NOT match baseURL", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
// baseURL is `https://or.example.com/v1`. A spoofed
|
||||
// `https://or.example.com/v1-attacker.evil/chat` shares the literal prefix
|
||||
// but is NOT under our origin path — must be treated as passthrough.
|
||||
await f("https://or.example.com/v1-attacker.evil/chat", {
|
||||
method: "POST",
|
||||
body: "{}",
|
||||
});
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit | undefined)?.headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), null);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: URL object input is handled", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f(new URL(`${BASE}/models`), {});
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: Request input is handled (reads .url)", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
const req = new Request(`${BASE}/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ a: 1 }),
|
||||
headers: { "X-Caller": "preserved" },
|
||||
});
|
||||
await f(req);
|
||||
const sent = calls[0]!;
|
||||
// The interceptor forwards the original Request as `input` but layers our
|
||||
// headers into the `init`. We assert against the init view since fetch()
|
||||
// resolves headers from init first when both are present.
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
assert.equal(
|
||||
sentHeaders.get("X-Caller"),
|
||||
"preserved",
|
||||
"Request-attached headers must survive the merge"
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: trailing slash in baseURL is normalized", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({
|
||||
apiKey: KEY,
|
||||
baseURL: `${BASE}////`,
|
||||
});
|
||||
await f(`${BASE}/models`, {});
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteFetchInterceptor: GET without body does NOT set Content-Type", async () => {
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const f = createOmniRouteFetchInterceptor({ apiKey: KEY, baseURL: BASE });
|
||||
await f(`${BASE}/models`); // no init at all
|
||||
const sent = calls[0]!;
|
||||
const sentHeaders = new Headers((sent.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
assert.equal(
|
||||
sentHeaders.get("Content-Type"),
|
||||
null,
|
||||
"Content-Type should only default when a body exists"
|
||||
);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// loader integration
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
test("loader: returns fetch fn when apiKey + baseURL both present (via opts)", async () => {
|
||||
const hook = createOmniRouteAuthHook({ baseURL: BASE });
|
||||
const result = await hook.loader!(async () => ({ type: "api", key: KEY }) as never, {} as never);
|
||||
assert.equal((result as { apiKey: string }).apiKey, KEY);
|
||||
assert.equal((result as { baseURL: string }).baseURL, BASE);
|
||||
assert.equal(
|
||||
typeof (result as { fetch?: unknown }).fetch,
|
||||
"function",
|
||||
"loader must wire fetch interceptor when baseURL resolves"
|
||||
);
|
||||
});
|
||||
|
||||
test("loader: returns fetch fn when baseURL is stashed on the auth credential", async () => {
|
||||
// Some auth backends attach baseURL alongside the key (post-/connect flow).
|
||||
// The loader should pick it up even when plugin opts.baseURL is unset.
|
||||
const hook = createOmniRouteAuthHook();
|
||||
const result = await hook.loader!(
|
||||
async () => ({ type: "api", key: KEY, baseURL: BASE }) as never,
|
||||
{} as never
|
||||
);
|
||||
assert.equal((result as { baseURL?: string }).baseURL, BASE);
|
||||
assert.equal(typeof (result as { fetch?: unknown }).fetch, "function");
|
||||
});
|
||||
|
||||
test("loader: omits fetch fn when baseURL missing (apiKey-only return)", async () => {
|
||||
const hook = createOmniRouteAuthHook(); // no baseURL opt
|
||||
const result = await hook.loader!(async () => ({ type: "api", key: KEY }) as never, {} as never);
|
||||
// Interceptor needs a baseURL to gate-keep; without one, fall back to
|
||||
// apiKey-only and let the SDK use its default fetch.
|
||||
assert.deepEqual(result, { apiKey: KEY });
|
||||
});
|
||||
|
||||
test("loader integration: wired interceptor actually injects Bearer when invoked", async () => {
|
||||
// End-to-end: pull the fetch fn out of the loader return and exercise it,
|
||||
// proving the wiring matches the standalone interceptor's contract.
|
||||
const { calls, restore } = installFetchRecorder();
|
||||
try {
|
||||
const hook = createOmniRouteAuthHook({ baseURL: BASE });
|
||||
const result = await hook.loader!(
|
||||
async () => ({ type: "api", key: KEY }) as never,
|
||||
{} as never
|
||||
);
|
||||
const wiredFetch = (result as { fetch: typeof fetch }).fetch;
|
||||
await wiredFetch(`${BASE}/v1/models`, {});
|
||||
assert.equal(calls.length, 1);
|
||||
const sentHeaders = new Headers((calls[0]!.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), `Bearer ${KEY}`);
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
291
@omniroute/opencode-plugin/tests/fork-features.test.ts
Normal file
291
@omniroute/opencode-plugin/tests/fork-features.test.ts
Normal file
@@ -0,0 +1,291 @@
|
||||
/**
|
||||
* Tests for the 3 mrmm-fork features backported to @omniroute/opencode-plugin:
|
||||
*
|
||||
* 1. `normaliseFreeLabel` — free-tier model display names get a consistent
|
||||
* `[Free] ` prefix instead of trailing "(Free)" or ad-hoc "free" words.
|
||||
*
|
||||
* 2. `resolveApiBlock` — per-provider-prefix API format routing. Anthropic
|
||||
* prefixes (`cc/`, `claude/`, `anthropic/`, `kiro/`, `kr/`) get the
|
||||
* Anthropic SDK block; everything else gets OpenAI-compat.
|
||||
*
|
||||
* 3. `debugLog` — JSONL request/response capture, gated by
|
||||
* `features.debugLog` and togglable at runtime via
|
||||
* `debugLogEnabled/SetEnabled`.
|
||||
*/
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
normaliseFreeLabel,
|
||||
resolveApiBlock,
|
||||
DEFAULT_ANTHROPIC_PREFIXES,
|
||||
ensureV1Suffix,
|
||||
debugLogEnabled,
|
||||
debugLogSetEnabled,
|
||||
debugLogClear,
|
||||
debugLogRead,
|
||||
debugLogAppend,
|
||||
createDebugLoggingFetch,
|
||||
DebugLogEntry,
|
||||
} from "../src/index.js";
|
||||
|
||||
// ── 1. normaliseFreeLabel ────────────────────────────────────────────────────
|
||||
|
||||
test("normaliseFreeLabel: '(Free)' suffix becomes [Free] prefix", () => {
|
||||
assert.equal(normaliseFreeLabel("GPT-4.1 (Free)"), "[Free] GPT-4.1");
|
||||
});
|
||||
|
||||
test("normaliseFreeLabel: trailing ' Free' word becomes [Free] prefix", () => {
|
||||
assert.equal(
|
||||
normaliseFreeLabel("DeepSeek V4 Flash Free"),
|
||||
"[Free] DeepSeek V4 Flash"
|
||||
);
|
||||
});
|
||||
|
||||
test("normaliseFreeLabel: trailing '-free' (hyphen) becomes [Free] prefix", () => {
|
||||
assert.equal(normaliseFreeLabel("Llama 4 Scout-free"), "[Free] Llama 4 Scout");
|
||||
});
|
||||
|
||||
test("normaliseFreeLabel: case-insensitive (FREE, Free, free all match)", () => {
|
||||
assert.equal(normaliseFreeLabel("Model A FREE"), "[Free] Model A");
|
||||
assert.equal(normaliseFreeLabel("Model A free"), "[Free] Model A");
|
||||
assert.equal(normaliseFreeLabel("Model A Free"), "[Free] Model A");
|
||||
});
|
||||
|
||||
test("normaliseFreeLabel: names without 'free' pass through unchanged", () => {
|
||||
assert.equal(normaliseFreeLabel("Claude 4.7 Opus"), "Claude 4.7 Opus");
|
||||
assert.equal(normaliseFreeLabel("GPT-5"), "GPT-5");
|
||||
});
|
||||
|
||||
test("normaliseFreeLabel: 'free' in the middle of a name is NOT rewritten", () => {
|
||||
// Only trailing/standalone "free" markers count; embedded "freedom" stays
|
||||
assert.equal(
|
||||
normaliseFreeLabel("Freedom Model"),
|
||||
"Freedom Model"
|
||||
);
|
||||
});
|
||||
|
||||
test("normaliseFreeLabel: empty / whitespace-only inputs are handled", () => {
|
||||
// Empty input returns empty; pure whitespace input passes through (no Free marker)
|
||||
assert.equal(normaliseFreeLabel(""), "");
|
||||
assert.equal(normaliseFreeLabel(" "), " ");
|
||||
});
|
||||
|
||||
// ── 2. resolveApiBlock ───────────────────────────────────────────────────────
|
||||
|
||||
test("resolveApiBlock: cc/* models get the Anthropic SDK block (no /v1)", () => {
|
||||
const block = resolveApiBlock("cc/claude-opus-4-7", "https://api.example.com");
|
||||
assert.equal(block.id, "anthropic");
|
||||
assert.equal(block.npm, "@ai-sdk/anthropic");
|
||||
assert.equal(block.url, "https://api.example.com"); // NO /v1 suffix
|
||||
});
|
||||
|
||||
test("resolveApiBlock: claude/*, anthropic/*, kiro/*, kr/* all route to Anthropic", () => {
|
||||
for (const id of [
|
||||
"claude/claude-opus-4-7",
|
||||
"anthropic/claude-sonnet-4",
|
||||
"kiro/claude-sonnet-4-5",
|
||||
"kr/claude-opus-4-6",
|
||||
]) {
|
||||
const block = resolveApiBlock(id, "https://api.example.com");
|
||||
assert.equal(block.id, "anthropic", `${id} should route to Anthropic`);
|
||||
assert.equal(block.npm, "@ai-sdk/anthropic");
|
||||
}
|
||||
});
|
||||
|
||||
test("resolveApiBlock: non-Anthropic models get OpenAI-compat with /v1", () => {
|
||||
const block = resolveApiBlock("gpt-4o", "https://api.example.com");
|
||||
assert.equal(block.id, "openai-compatible");
|
||||
assert.equal(block.npm, "@ai-sdk/openai-compatible");
|
||||
assert.equal(block.url, "https://api.example.com/v1");
|
||||
});
|
||||
|
||||
test("resolveApiBlock: user can override anthropicPrefixes to add custom prefixes", () => {
|
||||
const block = resolveApiBlock("myproxy/claude-opus", "https://api.example.com", {
|
||||
anthropicPrefixes: ["myproxy"],
|
||||
});
|
||||
assert.equal(block.id, "anthropic");
|
||||
assert.equal(block.npm, "@ai-sdk/anthropic");
|
||||
});
|
||||
|
||||
test("resolveApiBlock: empty anthropicPrefixes forces OpenAI-compat for everything", () => {
|
||||
const block = resolveApiBlock("cc/claude-opus", "https://api.example.com", {
|
||||
anthropicPrefixes: [],
|
||||
});
|
||||
assert.equal(block.id, "openai-compatible");
|
||||
});
|
||||
|
||||
test("resolveApiBlock: baseURL that already ends in /v1 is not double-suffixed (OpenAI path)", () => {
|
||||
const block = resolveApiBlock("gpt-4o", "https://api.example.com/v1");
|
||||
assert.equal(block.url, "https://api.example.com/v1"); // idempotent
|
||||
});
|
||||
|
||||
test("resolveApiBlock: model id without '/' uses the id as prefix", () => {
|
||||
const block = resolveApiBlock("claude-opus-4-7", "https://api.example.com");
|
||||
// The whole id is the prefix, which doesn't match "cc"/"claude" etc.
|
||||
// So it falls through to OpenAI-compat.
|
||||
assert.equal(block.id, "openai-compatible");
|
||||
});
|
||||
|
||||
test("DEFAULT_ANTHROPIC_PREFIXES: contains the canonical Anthropic aliases", () => {
|
||||
assert.deepEqual(DEFAULT_ANTHROPIC_PREFIXES, [
|
||||
"cc",
|
||||
"claude",
|
||||
"anthropic",
|
||||
"kiro",
|
||||
"kr",
|
||||
]);
|
||||
});
|
||||
|
||||
test("ensureV1Suffix: idempotent for URLs that already end in /v1", () => {
|
||||
assert.equal(ensureV1Suffix("https://api.example.com/v1"), "https://api.example.com/v1");
|
||||
assert.equal(
|
||||
ensureV1Suffix("https://api.example.com/v1/"),
|
||||
"https://api.example.com/v1" // trailing slash is stripped
|
||||
);
|
||||
});
|
||||
|
||||
test("ensureV1Suffix: appends /v1 when missing", () => {
|
||||
assert.equal(ensureV1Suffix("https://api.example.com"), "https://api.example.com/v1");
|
||||
assert.equal(ensureV1Suffix("https://api.example.com/"), "https://api.example.com/v1");
|
||||
});
|
||||
|
||||
// ── 3. debugLog ──────────────────────────────────────────────────────────────
|
||||
|
||||
test("debugLog: default state is disabled", () => {
|
||||
debugLogClear("test-provider-disabled-default");
|
||||
assert.equal(debugLogEnabled("test-provider-disabled-default"), false);
|
||||
});
|
||||
|
||||
test("debugLogSetEnabled + debugLogEnabled: roundtrip", () => {
|
||||
debugLogSetEnabled("test-provider-toggle", true);
|
||||
assert.equal(debugLogEnabled("test-provider-toggle"), true);
|
||||
debugLogSetEnabled("test-provider-toggle", false);
|
||||
assert.equal(debugLogEnabled("test-provider-toggle"), false);
|
||||
});
|
||||
|
||||
test("debugLogAppend + debugLogRead: roundtrip preserves entry shape", () => {
|
||||
const providerId = "test-provider-readroundtrip";
|
||||
debugLogClear(providerId);
|
||||
const entry: DebugLogEntry = {
|
||||
reqId: "req-1",
|
||||
providerId,
|
||||
ts: 1700000000000,
|
||||
url: "https://api.example.com/v1/chat",
|
||||
method: "POST",
|
||||
reqHeaders: { "content-type": "application/json" },
|
||||
reqBody: { model: "gpt-4o", messages: [] },
|
||||
resStatus: 200,
|
||||
resHeaders: { "content-type": "application/json" },
|
||||
resBody: { choices: [] },
|
||||
durationMs: 42,
|
||||
};
|
||||
debugLogAppend(entry);
|
||||
const read = debugLogRead(providerId, 10);
|
||||
assert.equal(read.length, 1);
|
||||
assert.deepEqual(read[0], entry);
|
||||
});
|
||||
|
||||
test("createDebugLoggingFetch: passes through when disabled", async () => {
|
||||
const providerId = "test-provider-passthrough";
|
||||
debugLogClear(providerId);
|
||||
debugLogSetEnabled(providerId, false);
|
||||
const calls: unknown[] = [];
|
||||
const inner: typeof fetch = async (input) => {
|
||||
calls.push(input);
|
||||
return new Response("ok", { status: 200 });
|
||||
};
|
||||
const wrapped = createDebugLoggingFetch(inner, providerId, false);
|
||||
const res = await wrapped("https://api.example.com/v1/chat");
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(calls.length, 1);
|
||||
// No log entry should be written when disabled
|
||||
assert.equal(debugLogRead(providerId).length, 0);
|
||||
});
|
||||
|
||||
test("createDebugLoggingFetch: captures request/response when enabled", async () => {
|
||||
const providerId = "test-provider-captures";
|
||||
debugLogClear(providerId);
|
||||
const inner: typeof fetch = async () =>
|
||||
new Response(JSON.stringify({ ok: true }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
const wrapped = createDebugLoggingFetch(inner, providerId, true);
|
||||
const res = await wrapped("https://api.example.com/v1/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: "gpt-4o" }),
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
const entries = debugLogRead(providerId);
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(entries[0].method, "POST");
|
||||
assert.equal(entries[0].resStatus, 200);
|
||||
assert.equal(entries[0].url, "https://api.example.com/v1/chat");
|
||||
assert.deepEqual(entries[0].reqBody, { model: "gpt-4o" });
|
||||
});
|
||||
|
||||
test("createDebugLoggingFetch: records error without crashing the wrapped fetch", async () => {
|
||||
const providerId = "test-provider-error";
|
||||
debugLogClear(providerId);
|
||||
const inner: typeof fetch = async () => {
|
||||
throw new Error("network down");
|
||||
};
|
||||
const wrapped = createDebugLoggingFetch(inner, providerId, true);
|
||||
await assert.rejects(wrapped("https://api.example.com/v1/chat"), /network down/);
|
||||
const entries = debugLogRead(providerId);
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(entries[0].resStatus, null);
|
||||
assert.equal(entries[0].error, "network down");
|
||||
});
|
||||
|
||||
// ── Regression tests for the 3 HIGH-priority bot review fixes ───────────────
|
||||
|
||||
test("createDebugLoggingFetch: URL instance input is captured (not 'undefined')", async () => {
|
||||
const providerId = "test-provider-url-input";
|
||||
debugLogClear(providerId);
|
||||
const inner: typeof fetch = async () =>
|
||||
new Response("ok", { status: 200 });
|
||||
const wrapped = createDebugLoggingFetch(inner, providerId, true);
|
||||
await wrapped(new URL("https://api.example.com/v1/chat"));
|
||||
const entries = debugLogRead(providerId);
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(entries[0].url, "https://api.example.com/v1/chat");
|
||||
assert.notEqual(entries[0].url, undefined);
|
||||
});
|
||||
|
||||
test("createDebugLoggingFetch: Request object input captures URL and headers", async () => {
|
||||
const providerId = "test-provider-request-input";
|
||||
debugLogClear(providerId);
|
||||
const inner: typeof fetch = async () =>
|
||||
new Response("ok", { status: 200 });
|
||||
const wrapped = createDebugLoggingFetch(inner, providerId, true);
|
||||
const req = new Request("https://api.example.com/v1/chat", {
|
||||
method: "POST",
|
||||
headers: { "x-test": "yes" },
|
||||
});
|
||||
await wrapped(req);
|
||||
const entries = debugLogRead(providerId);
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(entries[0].url, "https://api.example.com/v1/chat");
|
||||
assert.equal(entries[0].reqHeaders["x-test"], "yes");
|
||||
});
|
||||
|
||||
test("createDebugLoggingFetch: SSE response is NOT buffered (resBody is the stream marker)", async () => {
|
||||
const providerId = "test-provider-sse";
|
||||
debugLogClear(providerId);
|
||||
const inner: typeof fetch = async () =>
|
||||
new Response("data: hello\n\n", {
|
||||
status: 200,
|
||||
headers: { "content-type": "text/event-stream" },
|
||||
});
|
||||
const wrapped = createDebugLoggingFetch(inner, providerId, true);
|
||||
const res = await wrapped("https://api.example.com/v1/stream");
|
||||
// The response body must remain readable downstream
|
||||
const txt = await res.text();
|
||||
assert.equal(txt, "data: hello\n\n");
|
||||
const entries = debugLogRead(providerId);
|
||||
assert.equal(entries.length, 1);
|
||||
assert.equal(entries[0].resBody, "[stream]", "SSE responses must not be buffered");
|
||||
});
|
||||
410
@omniroute/opencode-plugin/tests/gemini-sanitize.test.ts
Normal file
410
@omniroute/opencode-plugin/tests/gemini-sanitize.test.ts
Normal file
@@ -0,0 +1,410 @@
|
||||
/**
|
||||
* T-06 Gemini tool-schema sanitisation contract tests.
|
||||
*
|
||||
* Three layers under test:
|
||||
* 1. `sanitizeGeminiToolSchemas` — pure function; key stripping + clone
|
||||
* semantics on chat-completion + Responses-API shapes.
|
||||
* 2. `shouldSanitizeForGemini` — model-string detection (liberal).
|
||||
* 3. `createGeminiSanitizingFetch` — wrapper composition; URL gating,
|
||||
* body-shape polymorphism, streaming-body bypass, fail-open behaviour,
|
||||
* composition with the T-04 Bearer interceptor.
|
||||
*
|
||||
* Strategy: same posture as fetch-interceptor.test.ts — install a
|
||||
* closure-based fetch recorder; assert on the `(input, init)` observed by
|
||||
* the inner fetch after the sanitising wrapper has had its say.
|
||||
*/
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
__resetGeminiStreamingWarning,
|
||||
createGeminiSanitizingFetch,
|
||||
createOmniRouteFetchInterceptor,
|
||||
sanitizeGeminiToolSchemas,
|
||||
shouldSanitizeForGemini,
|
||||
} from "../src/index.js";
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
type FetchCall = { input: Parameters<typeof fetch>[0]; init?: RequestInit };
|
||||
|
||||
function recorder(response: Response = new Response("ok")): {
|
||||
fn: typeof fetch;
|
||||
calls: FetchCall[];
|
||||
} {
|
||||
const calls: FetchCall[] = [];
|
||||
const fn = (async (input: any, init?: any) => {
|
||||
calls.push({ input, init });
|
||||
return response;
|
||||
}) as typeof fetch;
|
||||
return { fn, calls };
|
||||
}
|
||||
|
||||
function bodyAsRecord(init: RequestInit | undefined): Record<string, unknown> {
|
||||
const b = init?.body;
|
||||
if (typeof b !== "string") {
|
||||
throw new Error(`expected string body, got ${typeof b}`);
|
||||
}
|
||||
return JSON.parse(b) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
// Sample tool payloads — small enough to inline, big enough to cover
|
||||
// chat-completion + Responses-API + nested properties.
|
||||
|
||||
function chatCompletionsWithDollarSchema(): Record<string, unknown> {
|
||||
return {
|
||||
model: "gemini-2.5-pro",
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "search",
|
||||
parameters: {
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
type: "object",
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
q: { type: "string" },
|
||||
},
|
||||
required: ["q"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function responsesApiWithRef(): Record<string, unknown> {
|
||||
return {
|
||||
model: "gemini-2.5-flash",
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
name: "lookup",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
$ref: "#/definitions/Lookup",
|
||||
properties: {
|
||||
id: { type: "string", ref: "Id" },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function nestedPropertiesPayload(): Record<string, unknown> {
|
||||
return {
|
||||
model: "gemini-pro",
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "deep",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
outer: {
|
||||
type: "object",
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
properties: {
|
||||
inner: {
|
||||
type: "object",
|
||||
additionalProperties: true,
|
||||
$ref: "#/inner",
|
||||
properties: {
|
||||
leaf: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// sanitizeGeminiToolSchemas — pure function
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
test("sanitizeGeminiToolSchemas: strips $schema from top-level", () => {
|
||||
const input = {
|
||||
model: "gemini-2.5-pro",
|
||||
$schema: "http://json-schema.org/draft-07/schema#",
|
||||
tools: [],
|
||||
};
|
||||
const out = sanitizeGeminiToolSchemas(input) as Record<string, unknown>;
|
||||
assert.equal(out.$schema, undefined);
|
||||
assert.equal(out.model, "gemini-2.5-pro");
|
||||
});
|
||||
|
||||
test("sanitizeGeminiToolSchemas: strips $ref + additionalProperties from tools[].function.parameters", () => {
|
||||
const input = chatCompletionsWithDollarSchema();
|
||||
const out = sanitizeGeminiToolSchemas(input) as Record<string, unknown>;
|
||||
const params = (out.tools as Array<{ function: { parameters: Record<string, unknown> } }>)[0]!
|
||||
.function.parameters;
|
||||
assert.equal(params.$schema, undefined);
|
||||
assert.equal(params.additionalProperties, undefined);
|
||||
// Untouched keys survive.
|
||||
assert.equal(params.type, "object");
|
||||
assert.deepEqual(params.required, ["q"]);
|
||||
});
|
||||
|
||||
test("sanitizeGeminiToolSchemas: strips nested $schema from properties.x.properties.y", () => {
|
||||
const input = nestedPropertiesPayload();
|
||||
const out = sanitizeGeminiToolSchemas(input) as Record<string, unknown>;
|
||||
const params = (out.tools as Array<{ function: { parameters: Record<string, unknown> } }>)[0]!
|
||||
.function.parameters;
|
||||
const outer = (params.properties as Record<string, Record<string, unknown>>).outer!;
|
||||
const inner = (outer.properties as Record<string, Record<string, unknown>>).inner!;
|
||||
assert.equal(outer.$schema, undefined);
|
||||
assert.equal(inner.$ref, undefined);
|
||||
assert.equal(inner.additionalProperties, undefined);
|
||||
// Leaf still intact.
|
||||
assert.deepEqual(inner.properties, { leaf: { type: "string" } });
|
||||
});
|
||||
|
||||
test("sanitizeGeminiToolSchemas: handles Responses-API tools[].input_schema shape", () => {
|
||||
const input = responsesApiWithRef();
|
||||
const out = sanitizeGeminiToolSchemas(input) as Record<string, unknown>;
|
||||
const inputSchema = (out.tools as Array<{ input_schema: Record<string, unknown> }>)[0]!
|
||||
.input_schema;
|
||||
assert.equal(inputSchema.$ref, undefined);
|
||||
// Nested `ref` (lowercase) also stripped.
|
||||
const props = inputSchema.properties as Record<string, Record<string, unknown>>;
|
||||
assert.equal(props.id!.ref, undefined);
|
||||
assert.equal(props.id!.type, "string");
|
||||
});
|
||||
|
||||
test("sanitizeGeminiToolSchemas: leaves payload without tools untouched", () => {
|
||||
const input = { model: "gemini-2.5-pro", messages: [{ role: "user", content: "hi" }] };
|
||||
const out = sanitizeGeminiToolSchemas(input) as Record<string, unknown>;
|
||||
assert.deepEqual(out, input);
|
||||
});
|
||||
|
||||
test("sanitizeGeminiToolSchemas: does not mutate input (returned object is distinct)", () => {
|
||||
const input = chatCompletionsWithDollarSchema();
|
||||
const beforeJson = JSON.stringify(input);
|
||||
const out = sanitizeGeminiToolSchemas(input);
|
||||
// Input bit-identical to its pre-sanitise serialisation.
|
||||
assert.equal(JSON.stringify(input), beforeJson);
|
||||
// Output is a different reference.
|
||||
assert.notEqual(out, input);
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// shouldSanitizeForGemini — detection
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
test("shouldSanitizeForGemini: gemini-2.5-pro → true", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ model: "gemini-2.5-pro" }), true);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: models/gemini-pro → true", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ model: "models/gemini-pro" }), true);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: google-vertex/gemini-1.5-flash → true", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ model: "google-vertex/gemini-1.5-flash" }), true);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: gemini-cli/gemini-2.5-pro → true (real OmniRoute alias)", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ model: "gemini-cli/gemini-2.5-pro" }), true);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: claude-sonnet-4 → false", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ model: "claude-sonnet-4" }), false);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: payload.model missing → false", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ messages: [] }), false);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: payload is null → false", () => {
|
||||
assert.equal(shouldSanitizeForGemini(null), false);
|
||||
});
|
||||
|
||||
test("shouldSanitizeForGemini: payload.model is non-string → false", () => {
|
||||
assert.equal(shouldSanitizeForGemini({ model: 42 }), false);
|
||||
});
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
// createGeminiSanitizingFetch — wrapper
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const URL_CHAT = "https://or.example.com/v1/chat/completions";
|
||||
const URL_RESPONSES = "https://or.example.com/v1/responses";
|
||||
const URL_MODELS = "https://or.example.com/v1/models";
|
||||
|
||||
test("createGeminiSanitizingFetch: gemini model + chat/completions → tool schemas stripped before forward", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
await wrapped(URL_CHAT, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(chatCompletionsWithDollarSchema()),
|
||||
});
|
||||
assert.equal(rec.calls.length, 1);
|
||||
const forwarded = bodyAsRecord(rec.calls[0]!.init);
|
||||
const params = (
|
||||
forwarded.tools as Array<{ function: { parameters: Record<string, unknown> } }>
|
||||
)[0]!.function.parameters;
|
||||
assert.equal(params.$schema, undefined);
|
||||
assert.equal(params.additionalProperties, undefined);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: non-gemini model + chat/completions → body passed through unchanged", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
const originalBody = JSON.stringify({
|
||||
model: "claude-sonnet-4",
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "x",
|
||||
parameters: { $schema: "keep-me", type: "object" },
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
await wrapped(URL_CHAT, { method: "POST", body: originalBody });
|
||||
// Identity check on body — wrapper must NOT mutate non-Gemini payloads.
|
||||
assert.equal(rec.calls[0]!.init!.body, originalBody);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: gemini model + /v1/models (non-completion endpoint) → body passed through unchanged", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
// GET /v1/models has no body in production; assert that even if a caller
|
||||
// attached a Gemini-shaped body to a non-completion URL, the wrapper
|
||||
// doesn't touch it.
|
||||
const body = JSON.stringify(chatCompletionsWithDollarSchema());
|
||||
await wrapped(URL_MODELS, { method: "POST", body });
|
||||
assert.equal(rec.calls[0]!.init!.body, body);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: gemini model + /responses endpoint → input_schema stripped", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
await wrapped(URL_RESPONSES, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(responsesApiWithRef()),
|
||||
});
|
||||
const forwarded = bodyAsRecord(rec.calls[0]!.init);
|
||||
const schema = (forwarded.tools as Array<{ input_schema: Record<string, unknown> }>)[0]!
|
||||
.input_schema;
|
||||
assert.equal(schema.$ref, undefined);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: gemini model + Request input with body → tool schemas stripped", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
const req = new Request(URL_CHAT, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(chatCompletionsWithDollarSchema()),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
await wrapped(req);
|
||||
const forwarded = bodyAsRecord(rec.calls[0]!.init);
|
||||
const params = (
|
||||
forwarded.tools as Array<{ function: { parameters: Record<string, unknown> } }>
|
||||
)[0]!.function.parameters;
|
||||
assert.equal(params.$schema, undefined);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: gemini model + ReadableStream body → skipped + warn emitted once", async () => {
|
||||
__resetGeminiStreamingWarning();
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
|
||||
// Capture console.warn for the duration of this test.
|
||||
const warnings: string[] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => {
|
||||
warnings.push(args.map(String).join(" "));
|
||||
};
|
||||
|
||||
try {
|
||||
const stream1 = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("{}"));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
const stream2 = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("{}"));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
// Two streaming calls — only one warn expected.
|
||||
await wrapped(URL_CHAT, { method: "POST", body: stream1 });
|
||||
await wrapped(URL_CHAT, { method: "POST", body: stream2 });
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
|
||||
// Both calls forwarded to inner fetch with their streams intact.
|
||||
assert.equal(rec.calls.length, 2);
|
||||
// ONE warning total — one-shot latch held.
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.match(warnings[0]!, /streaming Request body, skipping schema strip/);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: invalid JSON body → pass through, no throw", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
// Garbage body must not crash the wrapper.
|
||||
await wrapped(URL_CHAT, { method: "POST", body: "this is not json{{" });
|
||||
assert.equal(rec.calls.length, 1);
|
||||
assert.equal(rec.calls[0]!.init!.body, "this is not json{{");
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: empty body → pass through unchanged", async () => {
|
||||
const rec = recorder();
|
||||
const wrapped = createGeminiSanitizingFetch(rec.fn);
|
||||
await wrapped(URL_CHAT, { method: "POST" });
|
||||
assert.equal(rec.calls.length, 1);
|
||||
});
|
||||
|
||||
test("createGeminiSanitizingFetch: composes correctly with createOmniRouteFetchInterceptor (Bearer + sanitization)", async () => {
|
||||
// Save and replace globalThis.fetch — the Bearer interceptor calls global
|
||||
// fetch when the URL targets its baseURL.
|
||||
const originalFetch = globalThis.fetch;
|
||||
const observed: FetchCall[] = [];
|
||||
globalThis.fetch = (async (input: any, init?: any) => {
|
||||
observed.push({ input, init });
|
||||
return new Response("ok");
|
||||
}) as typeof fetch;
|
||||
|
||||
try {
|
||||
const composed = createGeminiSanitizingFetch(
|
||||
createOmniRouteFetchInterceptor({
|
||||
apiKey: "sk-test",
|
||||
baseURL: "https://or.example.com/v1",
|
||||
})
|
||||
);
|
||||
await composed(URL_CHAT, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(chatCompletionsWithDollarSchema()),
|
||||
});
|
||||
|
||||
assert.equal(observed.length, 1);
|
||||
// Bearer injected (header concern).
|
||||
const sentHeaders = new Headers((observed[0]!.init as RequestInit).headers);
|
||||
assert.equal(sentHeaders.get("Authorization"), "Bearer sk-test");
|
||||
// Schema sanitised (body concern).
|
||||
const forwarded = bodyAsRecord(observed[0]!.init);
|
||||
const params = (
|
||||
forwarded.tools as Array<{ function: { parameters: Record<string, unknown> } }>
|
||||
)[0]!.function.parameters;
|
||||
assert.equal(params.$schema, undefined);
|
||||
assert.equal(params.additionalProperties, undefined);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
});
|
||||
136
@omniroute/opencode-plugin/tests/multi-instance.test.ts
Normal file
136
@omniroute/opencode-plugin/tests/multi-instance.test.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* T-08 multi-instance smoke.
|
||||
*
|
||||
* Validates that two `OmniRoutePlugin(input, opts)` invocations with
|
||||
* different `providerId` values coexist without sharing mutable state.
|
||||
* This is the contract that lets opencode.json declare prod + preprod
|
||||
* side by side:
|
||||
*
|
||||
* "plugin": [
|
||||
* ["@omniroute/opencode-plugin", {"providerId": "omniroute-prod", "baseURL": "https://or.example/v1"}],
|
||||
* ["@omniroute/opencode-plugin", {"providerId": "omniroute-preprod", "baseURL": "https://or-preprod.example/v1"}]
|
||||
* ]
|
||||
*
|
||||
* Assertions:
|
||||
* - Each invocation returns its own hooks object (no identity reuse).
|
||||
* - Each `auth` hook carries its own `provider` matching opts.providerId.
|
||||
* - Each `auth.methods` array is its own array (not the same reference).
|
||||
* - Calling the factory twice with IDENTICAL opts still yields two
|
||||
* independent objects (no instance reuse / no shared closure cache).
|
||||
* - Mutating one instance's auth hook does NOT bleed into the other.
|
||||
* - Each instance's loader closure captures its OWN baseURL — no
|
||||
* last-write-wins module-scope state.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { OmniRoutePlugin } from "../src/index.js";
|
||||
|
||||
const fakeInput = {} as Parameters<typeof OmniRoutePlugin>[0];
|
||||
|
||||
test("multi-instance: two plugin invocations bind to their own providerId", async () => {
|
||||
const a = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "omniroute-prod",
|
||||
baseURL: "https://a.example/v1",
|
||||
});
|
||||
const b = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "omniroute-preprod",
|
||||
baseURL: "https://b.example/v1",
|
||||
});
|
||||
|
||||
assert.equal(a.auth?.provider, "omniroute-prod");
|
||||
assert.equal(b.auth?.provider, "omniroute-preprod");
|
||||
});
|
||||
|
||||
test("multi-instance: hook objects + nested arrays are independent references", async () => {
|
||||
const a = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "alpha",
|
||||
baseURL: "https://a.example/v1",
|
||||
});
|
||||
const b = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "bravo",
|
||||
baseURL: "https://b.example/v1",
|
||||
});
|
||||
|
||||
assert.notEqual(a, b, "top-level hooks objects must not be the same reference");
|
||||
assert.notEqual(a.auth, b.auth, "auth hooks must not be the same reference");
|
||||
assert.notEqual(
|
||||
a.auth?.methods,
|
||||
b.auth?.methods,
|
||||
"methods arrays must not be the same reference"
|
||||
);
|
||||
});
|
||||
|
||||
test("multi-instance: identical opts twice still yield independent objects", async () => {
|
||||
const opts = { providerId: "twin", baseURL: "https://twin.example/v1" };
|
||||
const first = await OmniRoutePlugin(fakeInput, { ...opts });
|
||||
const second = await OmniRoutePlugin(fakeInput, { ...opts });
|
||||
|
||||
assert.notEqual(first, second);
|
||||
assert.notEqual(first.auth, second.auth);
|
||||
assert.notEqual(first.auth?.methods, second.auth?.methods);
|
||||
// Same provider id is fine — what matters is no shared mutable state.
|
||||
assert.equal(first.auth?.provider, "twin");
|
||||
assert.equal(second.auth?.provider, "twin");
|
||||
});
|
||||
|
||||
test("multi-instance: mutating instance A's auth.methods does not affect instance B", async () => {
|
||||
const a = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "iso-a",
|
||||
baseURL: "https://a.example/v1",
|
||||
});
|
||||
const b = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "iso-b",
|
||||
baseURL: "https://b.example/v1",
|
||||
});
|
||||
|
||||
const beforeLen = b.auth?.methods?.length ?? 0;
|
||||
// Mutate a's methods array — extend it; b's must be untouched.
|
||||
// We don't know the concrete method shape so push a sentinel cast.
|
||||
a.auth?.methods?.push({ type: "api", label: "sentinel" } as never);
|
||||
assert.equal(b.auth?.methods?.length, beforeLen, "instance B leaked from instance A mutation");
|
||||
});
|
||||
|
||||
test("multi-instance: loader closures see their own opts (not last-write-wins)", async () => {
|
||||
// Each plugin's loader builds its loader payload from the providerId/baseURL
|
||||
// captured at invocation time. If the factory accidentally shared a closure
|
||||
// (e.g. a module-scope let that the last invocation overwrites), both
|
||||
// loaders would emit the same baseURL. Verify they don't.
|
||||
const a = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "omniroute-prod",
|
||||
baseURL: "https://prod.example/v1",
|
||||
});
|
||||
const b = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "omniroute-preprod",
|
||||
baseURL: "https://preprod.example/v1",
|
||||
});
|
||||
|
||||
assert.ok(a.auth?.loader, "instance A must have a loader");
|
||||
assert.ok(b.auth?.loader, "instance B must have a loader");
|
||||
|
||||
const getAuthA = async () => ({ type: "api", key: "sk-prod" }) as never;
|
||||
const getAuthB = async () => ({ type: "api", key: "sk-preprod" }) as never;
|
||||
|
||||
const rA = (await a.auth!.loader!(getAuthA, {} as never)) as Record<string, unknown>;
|
||||
const rB = (await b.auth!.loader!(getAuthB, {} as never)) as Record<string, unknown>;
|
||||
|
||||
assert.equal(rA.apiKey, "sk-prod");
|
||||
assert.equal(rA.baseURL, "https://prod.example/v1");
|
||||
assert.equal(rB.apiKey, "sk-preprod");
|
||||
assert.equal(rB.baseURL, "https://preprod.example/v1");
|
||||
});
|
||||
|
||||
test("multi-instance: invalid opts on one instance does not poison the other", async () => {
|
||||
// Sequencing: bad opts → good opts. The bad call must throw cleanly; the
|
||||
// good call must still produce a working hooks object. Confirms no
|
||||
// half-built module-level state survives a failed parse.
|
||||
await assert.rejects(
|
||||
() => OmniRoutePlugin(fakeInput, { providerId: "bad id!" } as never),
|
||||
/providerId/
|
||||
);
|
||||
const ok = await OmniRoutePlugin(fakeInput, {
|
||||
providerId: "recovered",
|
||||
baseURL: "https://ok.example/v1",
|
||||
});
|
||||
assert.equal(ok.auth?.provider, "recovered");
|
||||
});
|
||||
104
@omniroute/opencode-plugin/tests/options-schema.test.ts
Normal file
104
@omniroute/opencode-plugin/tests/options-schema.test.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* T-08 options-schema tests.
|
||||
*
|
||||
* Covers `parseOmniRoutePluginOptions(opts)` — the strict Zod gate that
|
||||
* validates the second-arg `PluginOptions` bag from opencode.json before
|
||||
* any hook is wired. Anti-pattern checklist mirrored here:
|
||||
*
|
||||
* - `null` / `undefined` must collapse to `{}` (defaults apply downstream).
|
||||
* - Unknown keys must THROW (`.strict()` catches opencode.json typos).
|
||||
* - Validation runs at parse time, not import time (module loads cleanly).
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { parseOmniRoutePluginOptions } from "../src/index.js";
|
||||
|
||||
test("parseOmniRoutePluginOptions: undefined → {}", () => {
|
||||
assert.deepEqual(parseOmniRoutePluginOptions(undefined), {});
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: null → {}", () => {
|
||||
assert.deepEqual(parseOmniRoutePluginOptions(null), {});
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: empty object → {}", () => {
|
||||
assert.deepEqual(parseOmniRoutePluginOptions({}), {});
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: valid providerId → returns it", () => {
|
||||
const r = parseOmniRoutePluginOptions({ providerId: "omniroute-preprod" });
|
||||
assert.equal(r.providerId, "omniroute-preprod");
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: invalid providerId (special chars) → throws", () => {
|
||||
assert.throws(
|
||||
() => parseOmniRoutePluginOptions({ providerId: "omniroute prod!" }),
|
||||
/providerId.*slug/i
|
||||
);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: empty providerId → throws", () => {
|
||||
assert.throws(() => parseOmniRoutePluginOptions({ providerId: "" }), /providerId/i);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: valid modelCacheTtl → returns it", () => {
|
||||
const r = parseOmniRoutePluginOptions({ modelCacheTtl: 60_000 });
|
||||
assert.equal(r.modelCacheTtl, 60_000);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: negative modelCacheTtl → throws", () => {
|
||||
assert.throws(() => parseOmniRoutePluginOptions({ modelCacheTtl: -1 }), /modelCacheTtl/i);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: zero modelCacheTtl → throws (positive required)", () => {
|
||||
assert.throws(() => parseOmniRoutePluginOptions({ modelCacheTtl: 0 }), /modelCacheTtl/i);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: invalid baseURL (not a URL) → throws", () => {
|
||||
assert.throws(() => parseOmniRoutePluginOptions({ baseURL: "not-a-url" }), /baseURL/i);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: unknown key → throws (strict mode catches typos)", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
parseOmniRoutePluginOptions({
|
||||
providerId: "omniroute",
|
||||
provider_id: "typo-here",
|
||||
}),
|
||||
/provider_id|unrecognized/i
|
||||
);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: all four fields populated correctly → returns them", () => {
|
||||
const opts = {
|
||||
providerId: "omniroute-prod",
|
||||
displayName: "OmniRoute Production",
|
||||
modelCacheTtl: 120_000,
|
||||
baseURL: "https://or.example.com/v1",
|
||||
};
|
||||
const r = parseOmniRoutePluginOptions(opts);
|
||||
assert.deepEqual(r, opts);
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: error message lists every issue path", () => {
|
||||
// Two bad fields at once → error string should mention BOTH.
|
||||
try {
|
||||
parseOmniRoutePluginOptions({
|
||||
providerId: "",
|
||||
baseURL: "garbage",
|
||||
});
|
||||
assert.fail("expected throw");
|
||||
} catch (err) {
|
||||
const msg = (err as Error).message;
|
||||
assert.match(msg, /providerId/);
|
||||
assert.match(msg, /baseURL/);
|
||||
}
|
||||
});
|
||||
|
||||
test("parseOmniRoutePluginOptions: module import alone does NOT throw", async () => {
|
||||
// Re-importing the entry must not trigger validation; validation only fires
|
||||
// on explicit parseOmniRoutePluginOptions / OmniRoutePlugin invocation.
|
||||
const mod = await import("../src/index.js");
|
||||
assert.equal(typeof mod.parseOmniRoutePluginOptions, "function");
|
||||
});
|
||||
269
@omniroute/opencode-plugin/tests/provider.test.ts
Normal file
269
@omniroute/opencode-plugin/tests/provider.test.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* T-03 provider-hook contract tests.
|
||||
*
|
||||
* Covers `createOmniRouteProviderHook(opts, deps)`:
|
||||
* - hook.id binds to resolved providerId (single + multi-instance)
|
||||
* - models() narrows ctx.auth, fetches via injected fetcher, caches per
|
||||
* (baseURL, apiKey) tuple, refetches after TTL
|
||||
* - mapRawModelToModelV2 emits a v2 Model shape matching the
|
||||
* @opencode-ai/sdk/v2 type
|
||||
*
|
||||
* Mocking strategy: the fetcher is dependency-injected at hook construction
|
||||
* (`deps.fetcher`). No global fetch monkey-patch needed. `deps.now` lets us
|
||||
* fast-forward time deterministically for TTL assertions.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
createOmniRouteProviderHook,
|
||||
mapRawModelToModelV2,
|
||||
type OmniRouteRawModelEntry,
|
||||
type OmniRouteModelsFetcher,
|
||||
} from "../src/index.js";
|
||||
|
||||
const FIXTURE: OmniRouteRawModelEntry[] = [
|
||||
{
|
||||
id: "claude-primary",
|
||||
object: "model",
|
||||
owned_by: "combo",
|
||||
capabilities: { tool_calling: true, reasoning: true, vision: true, thinking: true },
|
||||
context_length: 200000,
|
||||
max_output_tokens: 64000,
|
||||
input_modalities: ["text", "image"],
|
||||
output_modalities: ["text"],
|
||||
},
|
||||
{
|
||||
id: "claude-low",
|
||||
object: "model",
|
||||
owned_by: "combo",
|
||||
capabilities: { tool_calling: true, reasoning: true, vision: true, thinking: false },
|
||||
context_length: 200000,
|
||||
max_output_tokens: 64000,
|
||||
input_modalities: ["text", "image"],
|
||||
output_modalities: ["text"],
|
||||
},
|
||||
{
|
||||
id: "gemini-3-flash",
|
||||
object: "model",
|
||||
owned_by: "google",
|
||||
capabilities: { tool_calling: true, reasoning: false, vision: true, thinking: false },
|
||||
context_length: 1000000,
|
||||
max_output_tokens: 8192,
|
||||
input_modalities: ["text", "image"],
|
||||
output_modalities: ["text"],
|
||||
},
|
||||
];
|
||||
|
||||
function stubFetcher(payload: OmniRouteRawModelEntry[]): OmniRouteModelsFetcher & {
|
||||
callCount: () => number;
|
||||
callsBy: () => Array<[string, string]>;
|
||||
} {
|
||||
let calls: Array<[string, string]> = [];
|
||||
const f: OmniRouteModelsFetcher = async (baseURL, apiKey) => {
|
||||
calls.push([baseURL, apiKey]);
|
||||
return payload;
|
||||
};
|
||||
return Object.assign(f, {
|
||||
callCount: () => calls.length,
|
||||
callsBy: () => calls,
|
||||
});
|
||||
}
|
||||
|
||||
const apiAuth = (key: string, baseURL?: string): unknown =>
|
||||
baseURL ? { type: "api", key, baseURL } : { type: "api", key };
|
||||
|
||||
test("createOmniRouteProviderHook: default providerId is 'omniroute'", () => {
|
||||
const hook = createOmniRouteProviderHook(undefined, { combosFetcher: async () => [] });
|
||||
assert.equal(hook.id, "omniroute");
|
||||
});
|
||||
|
||||
test("createOmniRouteProviderHook: custom providerId binds to hook.id (multi-instance)", () => {
|
||||
const a = createOmniRouteProviderHook(
|
||||
{ providerId: "omniroute-preprod" },
|
||||
{ combosFetcher: async () => [] }
|
||||
);
|
||||
const b = createOmniRouteProviderHook(
|
||||
{ providerId: "omniroute-local" },
|
||||
{ combosFetcher: async () => [] }
|
||||
);
|
||||
assert.equal(a.id, "omniroute-preprod");
|
||||
assert.equal(b.id, "omniroute-local");
|
||||
});
|
||||
|
||||
test("models: extracts apiKey from ctx.auth (type=api) and calls fetcher with it", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher, combosFetcher: async () => [] }
|
||||
);
|
||||
const out = await hook.models!({} as never, { auth: apiAuth("sk-abc") as never });
|
||||
assert.equal(fetcher.callCount(), 1);
|
||||
assert.deepEqual(fetcher.callsBy()[0], ["https://or.example.com/v1", "sk-abc"]);
|
||||
assert.equal(Object.keys(out).length, 3);
|
||||
assert.ok(out["claude-primary"]);
|
||||
});
|
||||
|
||||
test("models: returns {} when ctx.auth is null/undefined/wrong-type/empty-key", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher, combosFetcher: async () => [] }
|
||||
);
|
||||
|
||||
assert.deepEqual(await hook.models!({} as never, {} as never), {});
|
||||
assert.deepEqual(await hook.models!({} as never, { auth: undefined } as never), {});
|
||||
assert.deepEqual(
|
||||
await hook.models!({} as never, {
|
||||
auth: { type: "oauth", refresh: "r", access: "a", expires: 0 } as never,
|
||||
}),
|
||||
{}
|
||||
);
|
||||
assert.deepEqual(
|
||||
await hook.models!({} as never, { auth: { type: "api", key: "" } as never }),
|
||||
{}
|
||||
);
|
||||
assert.equal(fetcher.callCount(), 0, "fetcher must not be called on auth rejection");
|
||||
});
|
||||
|
||||
test("models: returns {} when no baseURL resolvable (no opts.baseURL and no auth.baseURL)", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook({}, { fetcher, combosFetcher: async () => [] });
|
||||
// valid api auth but neither opts nor auth carries a baseURL
|
||||
assert.deepEqual(await hook.models!({} as never, { auth: apiAuth("sk-x") as never }), {});
|
||||
assert.equal(fetcher.callCount(), 0);
|
||||
});
|
||||
|
||||
test("models: baseURL falls back to auth.baseURL when opts.baseURL absent", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook({}, { fetcher, combosFetcher: async () => [] });
|
||||
const out = await hook.models!({} as never, {
|
||||
auth: apiAuth("sk-y", "https://or.creds-attached.example/v1") as never,
|
||||
});
|
||||
assert.equal(fetcher.callCount(), 1);
|
||||
assert.equal(fetcher.callsBy()[0][0], "https://or.creds-attached.example/v1");
|
||||
assert.equal(Object.keys(out).length, 3);
|
||||
});
|
||||
|
||||
test("models: maps a sample /v1/models entry to ModelV2 (sanity)", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ providerId: "omniroute", baseURL: "https://or.example.com/v1" },
|
||||
{ fetcher, combosFetcher: async () => [] }
|
||||
);
|
||||
const out = await hook.models!({} as never, { auth: apiAuth("sk-abc") as never });
|
||||
const claude = out["claude-primary"];
|
||||
assert.ok(claude, "claude-primary present");
|
||||
assert.equal(claude.id, "claude-primary");
|
||||
assert.equal(claude.name, "claude-primary");
|
||||
assert.equal(claude.providerID, "omniroute");
|
||||
assert.equal(claude.api.id, "openai-compatible");
|
||||
assert.equal(claude.api.url, "https://or.example.com/v1");
|
||||
assert.equal(claude.api.npm, "@ai-sdk/openai-compatible");
|
||||
// capabilities: toolcall (one word), reasoning OR thinking, attachment = vision
|
||||
assert.equal(claude.capabilities.toolcall, true);
|
||||
assert.equal(claude.capabilities.reasoning, true);
|
||||
assert.equal(claude.capabilities.attachment, true);
|
||||
assert.equal(claude.capabilities.temperature, true);
|
||||
// modalities mapped from arrays
|
||||
assert.equal(claude.capabilities.input.text, true);
|
||||
assert.equal(claude.capabilities.input.image, true);
|
||||
assert.equal(claude.capabilities.input.audio, false);
|
||||
assert.equal(claude.capabilities.output.text, true);
|
||||
assert.equal(claude.capabilities.output.image, false);
|
||||
// cost is zeroed (OmniRoute /v1/models has no pricing)
|
||||
assert.deepEqual(claude.cost, { input: 0, output: 0, cache: { read: 0, write: 0 } });
|
||||
// limits
|
||||
assert.equal(claude.limit.context, 200000);
|
||||
assert.equal(claude.limit.output, 64000);
|
||||
assert.equal(claude.status, "active");
|
||||
});
|
||||
|
||||
test("mapRawModelToModelV2: thinking-only model still surfaces reasoning=true", () => {
|
||||
const m = mapRawModelToModelV2(
|
||||
{
|
||||
id: "thinking-only",
|
||||
capabilities: { thinking: true, reasoning: false },
|
||||
context_length: 100000,
|
||||
max_output_tokens: 8192,
|
||||
},
|
||||
{ providerId: "omniroute", baseURL: "https://or.example.com/v1" }
|
||||
);
|
||||
assert.equal(m.capabilities.reasoning, true);
|
||||
});
|
||||
|
||||
test("mapRawModelToModelV2: missing capabilities defaults to all-false (except temperature)", () => {
|
||||
const m = mapRawModelToModelV2(
|
||||
{ id: "minimal" },
|
||||
{ providerId: "omniroute", baseURL: "https://or.example.com/v1" }
|
||||
);
|
||||
assert.equal(m.capabilities.temperature, true);
|
||||
assert.equal(m.capabilities.reasoning, false);
|
||||
assert.equal(m.capabilities.attachment, false);
|
||||
assert.equal(m.capabilities.toolcall, false);
|
||||
// default modalities = text only
|
||||
assert.equal(m.capabilities.input.text, true);
|
||||
assert.equal(m.capabilities.output.text, true);
|
||||
// missing context / output tokens → 0 fallback (ModelV2.limit.{context,output} required)
|
||||
assert.equal(m.limit.context, 0);
|
||||
assert.equal(m.limit.output, 0);
|
||||
});
|
||||
|
||||
test("models: caches result for second call within TTL (fetcher called once)", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
let nowMs = 1_000_000;
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1", modelCacheTtl: 60_000 },
|
||||
{ fetcher, now: () => nowMs, combosFetcher: async () => [] }
|
||||
);
|
||||
|
||||
const a = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
nowMs += 30_000; // half the TTL
|
||||
const b = await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
assert.equal(fetcher.callCount(), 1, "second call within TTL must hit the cache");
|
||||
assert.equal(Object.keys(a).length, 3);
|
||||
assert.equal(Object.keys(b).length, 3);
|
||||
});
|
||||
|
||||
test("models: refetches after TTL expires", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
let nowMs = 1_000_000;
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1", modelCacheTtl: 60_000 },
|
||||
{ fetcher, now: () => nowMs, combosFetcher: async () => [] }
|
||||
);
|
||||
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
nowMs += 60_001; // just past the TTL
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-z") as never });
|
||||
assert.equal(fetcher.callCount(), 2, "call past TTL must refetch");
|
||||
});
|
||||
|
||||
test("models: caches per (baseURL, apiKey) tuple (different keys → independent fetches)", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ baseURL: "https://or.example.com/v1", modelCacheTtl: 300_000 },
|
||||
{ fetcher, combosFetcher: async () => [] }
|
||||
);
|
||||
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-A") as never });
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-B") as never });
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-A") as never }); // cached
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-B") as never }); // cached
|
||||
assert.equal(fetcher.callCount(), 2, "one fetch per distinct apiKey, then cache hits");
|
||||
});
|
||||
|
||||
test("models: caches per (baseURL, apiKey) tuple (different baseURL → independent fetches)", async () => {
|
||||
const fetcher = stubFetcher(FIXTURE);
|
||||
const hook = createOmniRouteProviderHook(
|
||||
{ modelCacheTtl: 300_000 }, // no opts.baseURL → falls back to auth.baseURL
|
||||
{ fetcher, combosFetcher: async () => [] }
|
||||
);
|
||||
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-same", "https://prod.example/v1") as never });
|
||||
await hook.models!({} as never, {
|
||||
auth: apiAuth("sk-same", "https://preprod.example/v1") as never,
|
||||
});
|
||||
await hook.models!({} as never, { auth: apiAuth("sk-same", "https://prod.example/v1") as never }); // cached
|
||||
assert.equal(fetcher.callCount(), 2, "distinct baseURLs share apiKey but not cache");
|
||||
});
|
||||
73
@omniroute/opencode-plugin/tests/scaffold.test.ts
Normal file
73
@omniroute/opencode-plugin/tests/scaffold.test.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createRequire } from "node:module";
|
||||
import {
|
||||
OmniRoutePlugin,
|
||||
OMNIROUTE_PROVIDER_KEY,
|
||||
DEFAULT_MODEL_CACHE_TTL_MS,
|
||||
resolveOmniRoutePluginOptions,
|
||||
} from "../src/index.js";
|
||||
|
||||
test("scaffold: exports public surface", () => {
|
||||
assert.equal(
|
||||
typeof OmniRoutePlugin,
|
||||
"function",
|
||||
"OmniRoutePlugin must be a function (Plugin factory)"
|
||||
);
|
||||
assert.equal(OMNIROUTE_PROVIDER_KEY, "omniroute");
|
||||
assert.equal(DEFAULT_MODEL_CACHE_TTL_MS, 300_000);
|
||||
});
|
||||
|
||||
test("scaffold: default export is v1 plugin shape { id, server: OmniRoutePlugin }", async () => {
|
||||
const mod = await import("../src/index.js");
|
||||
assert.equal(typeof mod.default, "object");
|
||||
assert.equal(mod.default.id, "@omniroute/opencode-plugin");
|
||||
assert.equal(mod.default.server, mod.OmniRoutePlugin);
|
||||
});
|
||||
|
||||
test("resolveOmniRoutePluginOptions: defaults", () => {
|
||||
const r = resolveOmniRoutePluginOptions();
|
||||
assert.equal(r.providerId, "omniroute");
|
||||
assert.equal(r.displayName, "OmniRoute");
|
||||
assert.equal(r.modelCacheTtl, 300_000);
|
||||
assert.equal(r.baseURL, undefined);
|
||||
});
|
||||
|
||||
test("resolveOmniRoutePluginOptions: custom providerId derives displayName", () => {
|
||||
const r = resolveOmniRoutePluginOptions({ providerId: "omniroute-preprod" });
|
||||
assert.equal(r.providerId, "omniroute-preprod");
|
||||
assert.equal(r.displayName, "OmniRoute (omniroute-preprod)");
|
||||
});
|
||||
|
||||
test("resolveOmniRoutePluginOptions: explicit displayName wins", () => {
|
||||
const r = resolveOmniRoutePluginOptions({
|
||||
providerId: "omniroute-x",
|
||||
displayName: "Custom Label",
|
||||
});
|
||||
assert.equal(r.displayName, "Custom Label");
|
||||
});
|
||||
|
||||
test("resolveOmniRoutePluginOptions: invalid TTL falls back to default", () => {
|
||||
assert.equal(resolveOmniRoutePluginOptions({ modelCacheTtl: 0 }).modelCacheTtl, 300_000);
|
||||
assert.equal(resolveOmniRoutePluginOptions({ modelCacheTtl: -1 }).modelCacheTtl, 300_000);
|
||||
});
|
||||
|
||||
test("resolveOmniRoutePluginOptions: positive TTL respected", () => {
|
||||
assert.equal(resolveOmniRoutePluginOptions({ modelCacheTtl: 60_000 }).modelCacheTtl, 60_000);
|
||||
});
|
||||
|
||||
test("OmniRoutePlugin: returns an empty hooks object (scaffold)", async () => {
|
||||
const fakeCtx = {} as Parameters<typeof OmniRoutePlugin>[0];
|
||||
const hooks = await OmniRoutePlugin(fakeCtx);
|
||||
assert.equal(typeof hooks, "object");
|
||||
assert.notEqual(hooks, null);
|
||||
});
|
||||
|
||||
test("scaffold: CJS default export resolves via require() with v1 shape", () => {
|
||||
const require_ = createRequire(import.meta.url);
|
||||
const cjs = require_("../dist/index.cjs");
|
||||
// after cjsInterop:true, default export is on cjs.default
|
||||
assert.strictEqual(typeof cjs.default, "object");
|
||||
assert.strictEqual(cjs.default.id, "@omniroute/opencode-plugin");
|
||||
assert.strictEqual(typeof cjs.default.server, "function");
|
||||
});
|
||||
85
@omniroute/opencode-plugin/tests/usable-combo.test.ts
Normal file
85
@omniroute/opencode-plugin/tests/usable-combo.test.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Regression tests for `isUsableCombo` (release/v3.8.2 code review, finding C1).
|
||||
*
|
||||
* The combo member refs returned by `/api/combos` do NOT carry a separate
|
||||
* `providerId` field — OmniRoute's `normalizeComboRecord` folds the provider
|
||||
* id INTO the full model string (e.g. "cc/claude-opus-4-7"). The previous
|
||||
* implementation read `step.providerId` (always `undefined`), so the
|
||||
* `usableOnly` combo filter silently never dropped anything. These tests pin
|
||||
* the corrected behavior: the verdict is derived from the `step.model` prefix,
|
||||
* mirroring `isUsableRawModelId`'s subtract-filter semantics.
|
||||
*/
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { isUsableCombo, type OmniRouteRawCombo } from "../src/index.js";
|
||||
|
||||
/** Build a `usable` set bundle for the tests. */
|
||||
function buildUsable(opts: { aliases?: string[]; canonicals?: string[]; known?: string[] }): {
|
||||
aliases: Set<string>;
|
||||
canonicals: Set<string>;
|
||||
knownAliases: Set<string>;
|
||||
} {
|
||||
return {
|
||||
aliases: new Set(opts.aliases ?? []),
|
||||
canonicals: new Set(opts.canonicals ?? []),
|
||||
// knownAliases is the union of every prefix the universe is aware of —
|
||||
// usable or not. Default to including the usable aliases too.
|
||||
knownAliases: new Set([...(opts.known ?? []), ...(opts.aliases ?? [])]),
|
||||
};
|
||||
}
|
||||
|
||||
function combo(models: OmniRouteRawCombo["models"]): OmniRouteRawCombo {
|
||||
return { id: "c1", name: "Test Combo", models };
|
||||
}
|
||||
|
||||
test("isUsableCombo: member with a usable alias prefix → keep", () => {
|
||||
const usable = buildUsable({ aliases: ["cc"], known: ["cc", "dead"] });
|
||||
const c = combo([{ kind: "model", model: "cc/claude-opus-4-7" }]);
|
||||
assert.equal(isUsableCombo(c, usable), true);
|
||||
});
|
||||
|
||||
test("isUsableCombo: all members known-but-NOT-usable → drop (the C1 regression)", () => {
|
||||
// Before the fix this returned true unconditionally because step.providerId
|
||||
// was always undefined. Now the known-but-unusable "dead" prefix is dropped.
|
||||
const usable = buildUsable({ aliases: ["cc"], known: ["cc", "dead"] });
|
||||
const c = combo([
|
||||
{ kind: "model", model: "dead/legacy-model" },
|
||||
{ kind: "model", model: "dead/another" },
|
||||
]);
|
||||
assert.equal(isUsableCombo(c, usable), false);
|
||||
});
|
||||
|
||||
test("isUsableCombo: unknown prefix → keep (cannot prove unroutable)", () => {
|
||||
const usable = buildUsable({ aliases: ["cc"], known: ["cc", "dead"] });
|
||||
const c = combo([{ kind: "model", model: "agentrouter/mystery" }]);
|
||||
assert.equal(isUsableCombo(c, usable), true);
|
||||
});
|
||||
|
||||
test("isUsableCombo: mixed non-usable + usable member → keep", () => {
|
||||
const usable = buildUsable({ aliases: ["cc"], known: ["cc", "dead"] });
|
||||
const c = combo([
|
||||
{ kind: "model", model: "dead/legacy" },
|
||||
{ kind: "model", model: "cc/claude-opus-4-7" },
|
||||
]);
|
||||
assert.equal(isUsableCombo(c, usable), true);
|
||||
});
|
||||
|
||||
test("isUsableCombo: zero members → keep", () => {
|
||||
const usable = buildUsable({ aliases: ["cc"], known: ["cc"] });
|
||||
assert.equal(isUsableCombo(combo([]), usable), true);
|
||||
assert.equal(isUsableCombo(combo(undefined), usable), true);
|
||||
});
|
||||
|
||||
test("isUsableCombo: only combo-ref steps (no resolvable model) → keep", () => {
|
||||
const usable = buildUsable({ aliases: ["cc"], known: ["cc", "dead"] });
|
||||
const c = combo([{ kind: "combo-ref", comboName: "nested" }]);
|
||||
assert.equal(isUsableCombo(c, usable), true);
|
||||
});
|
||||
|
||||
test("isUsableCombo: usable canonical prefix → keep", () => {
|
||||
const usable = buildUsable({ canonicals: ["anthropic"], known: ["anthropic", "dead"] });
|
||||
const c = combo([{ kind: "model", model: "anthropic/claude-opus-4-7" }]);
|
||||
assert.equal(isUsableCombo(c, usable), true);
|
||||
});
|
||||
20
@omniroute/opencode-plugin/tsconfig.json
Normal file
20
@omniroute/opencode-plugin/tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022"],
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"isolatedModules": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules", "tests"]
|
||||
}
|
||||
20
@omniroute/opencode-plugin/tsup.config.ts
Normal file
20
@omniroute/opencode-plugin/tsup.config.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
dts: true,
|
||||
clean: true,
|
||||
sourcemap: false,
|
||||
splitting: false,
|
||||
treeshake: false,
|
||||
target: "node22",
|
||||
outDir: "dist",
|
||||
minify: false,
|
||||
cjsInterop: true,
|
||||
// Bundle runtime deps so the .tgz / npm install is self-contained.
|
||||
// `zod` is required at runtime by the options schema and would otherwise
|
||||
// need a peer install when the plugin is loaded directly from a file path
|
||||
// in opencode.jsonc.
|
||||
noExternal: ["zod"],
|
||||
});
|
||||
4
@omniroute/opencode-provider/.gitignore
vendored
Normal file
4
@omniroute/opencode-provider/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
*.log
|
||||
.DS_Store
|
||||
7
@omniroute/opencode-provider/.npmignore
Normal file
7
@omniroute/opencode-provider/.npmignore
Normal file
@@ -0,0 +1,7 @@
|
||||
src
|
||||
tests
|
||||
tsconfig.json
|
||||
tsup.config.ts
|
||||
node_modules
|
||||
.DS_Store
|
||||
*.log
|
||||
21
@omniroute/opencode-provider/LICENSE
Normal file
21
@omniroute/opencode-provider/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 OmniRoute contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
156
@omniroute/opencode-provider/README.md
Normal file
156
@omniroute/opencode-provider/README.md
Normal file
@@ -0,0 +1,156 @@
|
||||
# @omniroute/opencode-provider
|
||||
|
||||
> ## ⚠️ Deprecated — use [`@omniroute/opencode-plugin`](https://www.npmjs.com/package/@omniroute/opencode-plugin) instead
|
||||
>
|
||||
> This package writes a **static** `provider.omniroute` block to `opencode.json` from a hardcoded default model list, so it **drifts behind your live OmniRoute catalog** — adding a model in OmniRoute won't show up in OpenCode until you re-run the generator, and OpenCode Desktop/Web only surfaces a subset of the static models.
|
||||
>
|
||||
> **`@omniroute/opencode-plugin`** solves this by fetching `GET /v1/models` from your OmniRoute instance at OpenCode startup, so the model list is always live (see [#3419](https://github.com/diegosouzapw/OmniRoute/issues/3419)). It is now the recommended path.
|
||||
>
|
||||
> **One-line migration** — replace the static `provider.omniroute` block in `opencode.json` with a single plugin entry:
|
||||
>
|
||||
> ```jsonc
|
||||
> // opencode.json
|
||||
> {
|
||||
> "$schema": "https://opencode.ai/config.json",
|
||||
> "plugin": ["@omniroute/opencode-plugin"]
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> This package is **not removed** and still works for static/offline config generation, but it is no longer actively recommended and won't track new models automatically.
|
||||
|
||||
Helper for connecting [OpenCode](https://opencode.ai) to a running [OmniRoute](https://github.com/diegosouzapw/OmniRoute) AI gateway.
|
||||
|
||||
The package emits a **schema-valid entry** for `opencode.json` (`https://opencode.ai/config.json`) that delegates the actual runtime to [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible). It does not ship any new HTTP client — OmniRoute already exposes an OpenAI-compatible surface, and OpenCode already speaks it through the AI SDK.
|
||||
|
||||
> Pre-1.0. The API may still change. See `CHANGELOG` in the OmniRoute repo for breaking notes.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install --save-dev @omniroute/opencode-provider
|
||||
# or
|
||||
pnpm add -D @omniroute/opencode-provider
|
||||
```
|
||||
|
||||
You also need OpenCode's own runtime dep, but that's a transitive concern — OpenCode itself ships with `@ai-sdk/openai-compatible`. This package only **generates configuration**.
|
||||
|
||||
## Quick start
|
||||
|
||||
### 1. Scaffold a fresh `opencode.json`
|
||||
|
||||
```ts
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
|
||||
|
||||
const config = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128", // or your OmniRoute deployment URL
|
||||
apiKey: process.env.OMNIROUTE_API_KEY ?? "sk_omniroute",
|
||||
});
|
||||
|
||||
writeFileSync("opencode.json", JSON.stringify(config, null, 2));
|
||||
```
|
||||
|
||||
The resulting `opencode.json`:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"provider": {
|
||||
"omniroute": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "OmniRoute",
|
||||
"options": {
|
||||
"baseURL": "http://localhost:20128/v1",
|
||||
"apiKey": "sk_omniroute",
|
||||
},
|
||||
"models": {
|
||||
"claude-opus-4-5-thinking": { "name": "claude-opus-4-5-thinking" },
|
||||
"claude-sonnet-4-5-thinking": { "name": "claude-sonnet-4-5-thinking" },
|
||||
"gemini-3.1-pro-high": { "name": "gemini-3.1-pro-high" },
|
||||
"gemini-3-flash": { "name": "gemini-3-flash" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Merge into an existing `opencode.json`
|
||||
|
||||
```ts
|
||||
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
|
||||
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: process.env.OMNIROUTE_API_KEY!,
|
||||
});
|
||||
|
||||
// Place `provider` under provider.omniroute in your opencode.json
|
||||
```
|
||||
|
||||
If you already have an `opencode.json` on disk and want a non-destructive merge from the OmniRoute side, use `omniroute config opencode` from the CLI (ships with the main OmniRoute install) — it preserves comments and unrelated keys.
|
||||
|
||||
## API
|
||||
|
||||
### `createOmniRouteProvider(options): OpenCodeProviderEntry`
|
||||
|
||||
Returns the value to place under `provider.omniroute` inside `opencode.json`.
|
||||
|
||||
| Option | Type | Required | Description |
|
||||
| ------------- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| `baseURL` | `string` | Yes | OmniRoute base URL. Accepts `http://host:port` **or** `http://host:port/v1`. Trailing slashes are tolerated. |
|
||||
| `apiKey` | `string` | Yes | OmniRoute API key. Use `sk_omniroute` for local installs that have `REQUIRE_API_KEY=false`. |
|
||||
| `displayName` | `string` | No | Custom name shown in the OpenCode UI. Default: `"OmniRoute"`. |
|
||||
| `models` | `string[]` | No | Override the surfaced model catalog. Default: 4 curated models — see `OMNIROUTE_DEFAULT_OPENCODE_MODELS`. |
|
||||
| `modelLabels` | `Record<string,string>` | No | Human-readable labels keyed by model id. |
|
||||
|
||||
Throws on empty/invalid input — `baseURL` must be a real URL, `apiKey` must be a non-empty string.
|
||||
|
||||
### `buildOmniRouteOpenCodeConfig(options): OpenCodeConfigDocument`
|
||||
|
||||
Same options as above, but returns a full document with `$schema` and the `provider.omniroute` wrapper, ready to write to `opencode.json`.
|
||||
|
||||
### `normalizeBaseURL(input): string`
|
||||
|
||||
Exported for completeness. Strips trailing `/`, deduplicates a trailing `/v1`, and re-appends exactly one `/v1`. Throws on empty / non-URL input.
|
||||
|
||||
### Constants
|
||||
|
||||
- `OMNIROUTE_PROVIDER_KEY` — `"omniroute"` (the key used under `provider.*`).
|
||||
- `OMNIROUTE_PROVIDER_NPM` — `"@ai-sdk/openai-compatible"` (the runtime delegate).
|
||||
- `OPENCODE_CONFIG_SCHEMA` — `"https://opencode.ai/config.json"`.
|
||||
- `OMNIROUTE_DEFAULT_OPENCODE_MODELS` — readonly list of default model ids.
|
||||
|
||||
## Custom model catalog
|
||||
|
||||
```ts
|
||||
import { createOmniRouteProvider } from "@omniroute/opencode-provider";
|
||||
|
||||
createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["auto", "claude-opus-4-8", "gpt-5.5"],
|
||||
modelLabels: {
|
||||
auto: "Auto-Combo (recommended)",
|
||||
"claude-opus-4-8": "Claude Opus 4.8",
|
||||
"gpt-5.5": "GPT-5.5",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Duplicates and empty strings are dropped automatically, and order is preserved.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Requests 404 with `/v1/v1/...`** — you're on an old version (≤1.0.0). Update to `≥0.1.0` of this re-released package. The new build normalises `baseURL` automatically.
|
||||
- **`401 Invalid API key`** — your OmniRoute instance has `REQUIRE_API_KEY=true` but the key you supplied doesn't exist there. Create one via the dashboard or set `REQUIRE_API_KEY=false` and use `sk_omniroute`.
|
||||
- **OpenCode complains the provider has no models** — supply an explicit `models` list; the default 4 may be hidden by your provider visibility settings.
|
||||
|
||||
## Related
|
||||
|
||||
- [OmniRoute](https://github.com/diegosouzapw/OmniRoute) — the AI gateway this plugin targets.
|
||||
- [OpenCode](https://opencode.ai) — the agentic CLI consumer.
|
||||
- [`@ai-sdk/openai-compatible`](https://www.npmjs.com/package/@ai-sdk/openai-compatible) — the runtime delegate that actually speaks HTTP.
|
||||
|
||||
## License
|
||||
|
||||
MIT — see [`LICENSE`](./LICENSE).
|
||||
1998
@omniroute/opencode-provider/package-lock.json
generated
Normal file
1998
@omniroute/opencode-provider/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
60
@omniroute/opencode-provider/package.json
Normal file
60
@omniroute/opencode-provider/package.json
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"name": "@omniroute/opencode-provider",
|
||||
"version": "0.1.0",
|
||||
"description": "DEPRECATED — use @omniroute/opencode-plugin instead (it fetches the live OmniRoute /v1/models catalog at startup, so models never drift). This static-config generator still works but is no longer the recommended path. OpenCode provider helper for the OmniRoute AI Gateway.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js",
|
||||
"require": "./dist/index.cjs"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"clean": "rm -rf dist",
|
||||
"test": "node --import tsx/esm --test tests/index.test.ts",
|
||||
"prepublishOnly": "npm run clean && npm run build && npm test"
|
||||
},
|
||||
"keywords": [
|
||||
"omniroute",
|
||||
"opencode",
|
||||
"opencode-ai",
|
||||
"ai-sdk",
|
||||
"openai-compatible",
|
||||
"provider",
|
||||
"ai-gateway",
|
||||
"llm-router"
|
||||
],
|
||||
"author": "OmniRoute contributors",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/diegosouzapw/OmniRoute.git",
|
||||
"directory": "@omniroute/opencode-provider"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/diegosouzapw/OmniRoute/issues"
|
||||
},
|
||||
"homepage": "https://github.com/diegosouzapw/OmniRoute/tree/main/%40omniroute/opencode-provider#readme",
|
||||
"engines": {
|
||||
"node": ">=22.22.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.19.19",
|
||||
"tsup": "^8.5.1",
|
||||
"tsx": "^4.22.3",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
908
@omniroute/opencode-provider/src/index.ts
Normal file
908
@omniroute/opencode-provider/src/index.ts
Normal file
@@ -0,0 +1,908 @@
|
||||
/**
|
||||
* OpenCode provider plugin for OmniRoute AI Gateway.
|
||||
*
|
||||
* Generates an OpenCode-compatible provider object that points to a running
|
||||
* OmniRoute instance. The output follows the OpenCode config schema
|
||||
* (https://opencode.ai/config.json) and delegates the runtime to
|
||||
* `@ai-sdk/openai-compatible` so OpenCode can drive any OmniRoute-exposed
|
||||
* model through its standard OpenAI-compatible client.
|
||||
*
|
||||
* Two ways to consume the helper:
|
||||
*
|
||||
* 1. As code, when you build your own opencode.json programmatically:
|
||||
*
|
||||
* ```ts
|
||||
* import { buildOmniRouteOpenCodeConfig } from "@omniroute/opencode-provider";
|
||||
* const config = buildOmniRouteOpenCodeConfig({
|
||||
* baseURL: "http://localhost:20128",
|
||||
* apiKey: "sk_omniroute",
|
||||
* });
|
||||
* // config -> { $schema, provider: { omniroute: { npm, name, options, models } } }
|
||||
* ```
|
||||
*
|
||||
* 2. As a single-provider entry to merge into an existing opencode.json:
|
||||
*
|
||||
* ```ts
|
||||
* import { createOmniRouteProvider } from "@omniroute/opencode-provider";
|
||||
* const provider = createOmniRouteProvider({ baseURL, apiKey });
|
||||
* // provider -> the value to place under provider.omniroute in opencode.json
|
||||
* ```
|
||||
*
|
||||
* Note: `baseURL` accepts both `http://host:port` and `http://host:port/v1`.
|
||||
* The helper normalises trailing slashes / `/v1` so you never get `/v1/v1`.
|
||||
*/
|
||||
|
||||
export const OMNIROUTE_PROVIDER_KEY = "omniroute" as const;
|
||||
export const OMNIROUTE_PROVIDER_NPM = "@ai-sdk/openai-compatible" as const;
|
||||
export const OPENCODE_CONFIG_SCHEMA = "https://opencode.ai/config.json" as const;
|
||||
|
||||
/**
|
||||
* Default catalog of models surfaced to OpenCode when the caller does not
|
||||
* supply an explicit `models` list.
|
||||
*
|
||||
* Curated set covering the most commonly deployed OmniRoute models. Synced
|
||||
* with the Alph4d0g/opencode-omniroute-auth OMNIROUTE_DEFAULT_MODELS constant
|
||||
* (https://github.com/Alph4d0g/opencode-omniroute-auth, MIT) and extended
|
||||
* with Claude Code passthrough models (`cc/` prefix).
|
||||
*/
|
||||
export const OMNIROUTE_DEFAULT_OPENCODE_MODELS = [
|
||||
"cc/claude-opus-4-8",
|
||||
"cc/claude-opus-4-7",
|
||||
"cc/claude-sonnet-4-6",
|
||||
"cc/claude-haiku-4-5-20251001",
|
||||
"claude-opus-4-5-thinking",
|
||||
"claude-sonnet-4-5-thinking",
|
||||
"gemini-3.1-pro-high",
|
||||
"gemini-3-flash",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Optional capability flags surfaced to OpenCode's model picker.
|
||||
*
|
||||
* OpenCode reads these per-model keys (snake_case in JSON) to render badges
|
||||
* and to gate features such as image attachments, reasoning mode, temperature
|
||||
* controls and tool-calling. Omitted flags default to OpenCode's heuristics.
|
||||
*
|
||||
* Mirrors the capability shape used by Alph4d0g/opencode-omniroute-auth
|
||||
* (https://github.com/Alph4d0g/opencode-omniroute-auth, MIT).
|
||||
*/
|
||||
export interface ModelCapabilities {
|
||||
/** Display label shown in the model picker. Falls back to the model id. */
|
||||
label?: string;
|
||||
/** Model accepts image / file attachments. */
|
||||
attachment?: boolean;
|
||||
/** Model exposes a "reasoning" / extended-thinking surface. */
|
||||
reasoning?: boolean;
|
||||
/** Model honours the `temperature` parameter. */
|
||||
temperature?: boolean;
|
||||
/** Model supports tool / function calling. */
|
||||
tool_call?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default per-model context window sizes (tokens) for the curated default catalog.
|
||||
* Matches the context lengths used by OmniRoute's provider registry.
|
||||
*/
|
||||
export const OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS: Record<string, number> = {
|
||||
"cc/claude-opus-4-8": 1_000_000,
|
||||
"cc/claude-opus-4-7": 1_000_000,
|
||||
"cc/claude-sonnet-4-6": 200_000,
|
||||
"cc/claude-haiku-4-5-20251001": 200_000,
|
||||
"claude-opus-4-5-thinking": 200_000,
|
||||
"claude-sonnet-4-5-thinking": 200_000,
|
||||
"gemini-3.1-pro-high": 1_000_000,
|
||||
"gemini-3-flash": 1_000_000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Default per-model capability hints for the curated default catalog.
|
||||
*
|
||||
* Conservative defaults: every default model accepts attachments, tool calls
|
||||
* and temperature; `reasoning` is opt-in per model id. Callers override per
|
||||
* model via `OmniRouteProviderOptions.modelCapabilities`.
|
||||
*/
|
||||
export const OMNIROUTE_DEFAULT_MODEL_CAPABILITIES: Record<string, ModelCapabilities> = {
|
||||
"cc/claude-opus-4-8": { attachment: true, reasoning: true, temperature: true, tool_call: true },
|
||||
"cc/claude-opus-4-7": { attachment: true, reasoning: true, temperature: true, tool_call: true },
|
||||
"cc/claude-sonnet-4-6": { attachment: true, reasoning: true, temperature: true, tool_call: true },
|
||||
"cc/claude-haiku-4-5-20251001": { attachment: true, temperature: true, tool_call: true },
|
||||
"claude-opus-4-5-thinking": {
|
||||
attachment: true,
|
||||
reasoning: true,
|
||||
temperature: true,
|
||||
tool_call: true,
|
||||
},
|
||||
"claude-sonnet-4-5-thinking": {
|
||||
attachment: true,
|
||||
reasoning: true,
|
||||
temperature: true,
|
||||
tool_call: true,
|
||||
},
|
||||
"gemini-3.1-pro-high": { attachment: true, reasoning: true, temperature: true, tool_call: true },
|
||||
"gemini-3-flash": { attachment: true, temperature: true, tool_call: true },
|
||||
};
|
||||
|
||||
export interface OmniRouteProviderOptions {
|
||||
/** OmniRoute base URL, with or without trailing `/v1`. Required. */
|
||||
baseURL: string;
|
||||
/** OmniRoute API key. Required. Use `sk_omniroute` for local instances without REQUIRE_API_KEY. */
|
||||
apiKey: string;
|
||||
/** Override the display name shown in OpenCode. Default: `"OmniRoute"`. */
|
||||
displayName?: string;
|
||||
/** Override the model catalog. Accepts model ids (strings) or live model entries from `fetchLiveModels`. When entries carry a `contextLength`, it is used directly — no hardcoded map needed. */
|
||||
models?: readonly (string | { id: string; contextLength?: number })[];
|
||||
/** Optional human-readable labels keyed by model id. Overridden by `modelCapabilities[id].label`. */
|
||||
modelLabels?: Record<string, string>;
|
||||
/**
|
||||
* Optional capability overrides keyed by model id. Merged on top of
|
||||
* `OMNIROUTE_DEFAULT_MODEL_CAPABILITIES` for ids in the default catalog;
|
||||
* for custom ids the override is used verbatim.
|
||||
*/
|
||||
modelCapabilities?: Record<string, ModelCapabilities>;
|
||||
/**
|
||||
* Optional per-model context-length overrides (tokens). Takes precedence
|
||||
* over the static `OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS` map but is
|
||||
* superseded by `contextLength` on live model entries passed via `models`.
|
||||
*/
|
||||
modelContextLengths?: Record<string, string | number>;
|
||||
/**
|
||||
* Primary model for OpenCode (top-level `model` key).
|
||||
* Emitted as `"omniroute/<id>"`. When omitted the key is not written.
|
||||
*/
|
||||
model?: string;
|
||||
/**
|
||||
* Secondary / cheap model for OpenCode (top-level `small_model` key).
|
||||
* Emitted as `"omniroute/<id>"`. When omitted the key is not written.
|
||||
*/
|
||||
smallModel?: string;
|
||||
}
|
||||
|
||||
/** Per-model entry written under `provider.omniroute.models[id]`. */
|
||||
export interface OpenCodeModelEntry {
|
||||
name: string;
|
||||
attachment?: boolean;
|
||||
reasoning?: boolean;
|
||||
temperature?: boolean;
|
||||
tool_call?: boolean;
|
||||
/**
|
||||
* Context window limit. OpenCode reads this to determine usable context
|
||||
* length for compaction, overflow detection, and router decisions.
|
||||
* Maps to `limit.context` in OpenCode's provider config schema.
|
||||
*/
|
||||
limit?: {
|
||||
/** Maximum context length in tokens (e.g. 200000 for Claude, 1000000 for Gemini). */
|
||||
context: number;
|
||||
/** Optional per-request max input tokens. */
|
||||
input?: number;
|
||||
/** Optional max output tokens. */
|
||||
output?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OpenCodeProviderEntry {
|
||||
/** Identifier of the OpenCode runtime package that will speak to OmniRoute. */
|
||||
npm: typeof OMNIROUTE_PROVIDER_NPM;
|
||||
/** Display name in the OpenCode UI. */
|
||||
name: string;
|
||||
/** Options forwarded to `@ai-sdk/openai-compatible`. */
|
||||
options: {
|
||||
baseURL: string;
|
||||
apiKey: string;
|
||||
};
|
||||
/** Model catalog surfaced to OpenCode. */
|
||||
models: Record<string, OpenCodeModelEntry>;
|
||||
}
|
||||
|
||||
export interface OpenCodeConfigDocument {
|
||||
$schema: typeof OPENCODE_CONFIG_SCHEMA;
|
||||
/** Primary model for OpenCode, e.g. `"omniroute/claude-sonnet-4-5-thinking"`. */
|
||||
model?: string;
|
||||
/** Secondary / cheap model for OpenCode, e.g. `"omniroute/gemini-3-flash"`. */
|
||||
small_model?: string;
|
||||
provider: {
|
||||
[OMNIROUTE_PROVIDER_KEY]: OpenCodeProviderEntry;
|
||||
};
|
||||
}
|
||||
|
||||
function requireNonEmpty(value: unknown, field: string): string {
|
||||
if (typeof value !== "string") {
|
||||
throw new TypeError(`@omniroute/opencode-provider: ${field} must be a string`);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error(`@omniroute/opencode-provider: ${field} is required and cannot be empty`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise the user-supplied baseURL so the final `options.baseURL` always
|
||||
* ends in exactly one `/v1`. Accepts both `http://host` and `http://host/v1`.
|
||||
*/
|
||||
export function normalizeBaseURL(rawBaseURL: string): string {
|
||||
const trimmed = requireNonEmpty(rawBaseURL, "baseURL");
|
||||
try {
|
||||
new URL(trimmed);
|
||||
} catch {
|
||||
throw new Error(
|
||||
`@omniroute/opencode-provider: baseURL is not a valid URL: ${JSON.stringify(rawBaseURL)}`
|
||||
);
|
||||
}
|
||||
let base = trimmed;
|
||||
let end = base.length;
|
||||
while (end > 0 && base[end - 1] === "/") end--;
|
||||
base = end < base.length ? base.slice(0, end) : base;
|
||||
if (base.endsWith("/v1")) base = base.slice(0, -3);
|
||||
return base + "/v1";
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `provider.omniroute` entry for an OpenCode config document.
|
||||
* The returned object is JSON-serialisable and safe to embed verbatim.
|
||||
*/
|
||||
export function createOmniRouteProvider(options: OmniRouteProviderOptions): OpenCodeProviderEntry {
|
||||
const baseURL = normalizeBaseURL(options.baseURL);
|
||||
const apiKey = requireNonEmpty(options.apiKey, "apiKey");
|
||||
|
||||
const modelList =
|
||||
options.models && options.models.length > 0
|
||||
? [...options.models]
|
||||
: [...OMNIROUTE_DEFAULT_OPENCODE_MODELS];
|
||||
|
||||
const labels = options.modelLabels ?? {};
|
||||
const overrides = options.modelCapabilities ?? {};
|
||||
const models: Record<string, OpenCodeModelEntry> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const raw of modelList) {
|
||||
const id =
|
||||
typeof raw === "object" && raw !== null && "id" in raw && typeof (raw as any).id === "string"
|
||||
? (raw as { id: string }).id.trim()
|
||||
: typeof raw === "string"
|
||||
? raw.trim()
|
||||
: "";
|
||||
if (!id || seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const defaults = OMNIROUTE_DEFAULT_MODEL_CAPABILITIES[id] ?? {};
|
||||
const override = overrides[id] ?? {};
|
||||
const merged: ModelCapabilities = { ...defaults, ...override };
|
||||
const explicitLabel =
|
||||
typeof merged.label === "string" && merged.label.trim()
|
||||
? merged.label.trim()
|
||||
: typeof labels[id] === "string" && labels[id].trim()
|
||||
? labels[id].trim()
|
||||
: id;
|
||||
const entry: OpenCodeModelEntry = { name: explicitLabel };
|
||||
if (typeof merged.attachment === "boolean") entry.attachment = merged.attachment;
|
||||
if (typeof merged.reasoning === "boolean") entry.reasoning = merged.reasoning;
|
||||
if (typeof merged.temperature === "boolean") entry.temperature = merged.temperature;
|
||||
if (typeof merged.tool_call === "boolean") entry.tool_call = merged.tool_call;
|
||||
|
||||
// Context window: live model entry (from API catalog) > modelContextLengths > static defaults
|
||||
const liveContext =
|
||||
typeof raw === "object" && raw !== null
|
||||
? (raw as { contextLength?: number }).contextLength
|
||||
: undefined;
|
||||
const rawContextLength =
|
||||
liveContext ??
|
||||
options.modelContextLengths?.[id] ??
|
||||
OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];
|
||||
const contextLength =
|
||||
typeof rawContextLength === "string" ? parseInt(rawContextLength, 10) : rawContextLength;
|
||||
if (typeof contextLength === "number" && !isNaN(contextLength) && contextLength > 0) {
|
||||
entry.limit = { context: contextLength };
|
||||
}
|
||||
|
||||
models[id] = entry;
|
||||
}
|
||||
|
||||
return {
|
||||
npm: OMNIROUTE_PROVIDER_NPM,
|
||||
name: options.displayName?.trim() || "OmniRoute",
|
||||
options: { baseURL, apiKey },
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a full OpenCode config document (with `$schema` + `provider.omniroute`).
|
||||
* Useful when scaffolding a fresh `opencode.json`.
|
||||
*
|
||||
* When `options.model` / `options.smallModel` are supplied they are emitted as
|
||||
* top-level `model` / `small_model` keys prefixed with `"omniroute/"` so
|
||||
* OpenCode resolves them through the configured provider.
|
||||
*/
|
||||
export function buildOmniRouteOpenCodeConfig(
|
||||
options: OmniRouteProviderOptions
|
||||
): OpenCodeConfigDocument {
|
||||
const doc: OpenCodeConfigDocument = {
|
||||
$schema: OPENCODE_CONFIG_SCHEMA,
|
||||
provider: {
|
||||
[OMNIROUTE_PROVIDER_KEY]: createOmniRouteProvider(options),
|
||||
},
|
||||
};
|
||||
|
||||
if (options.model !== undefined) {
|
||||
const id = options.model.trim();
|
||||
if (id) doc.model = `${OMNIROUTE_PROVIDER_KEY}/${id}`;
|
||||
}
|
||||
|
||||
if (options.smallModel !== undefined) {
|
||||
const id = options.smallModel.trim();
|
||||
if (id) doc.small_model = `${OMNIROUTE_PROVIDER_KEY}/${id}`;
|
||||
}
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge the OmniRoute provider entry (and optional `model` / `small_model`
|
||||
* keys) into an already-existing OpenCode config object.
|
||||
*
|
||||
* Performs a non-destructive merge: all top-level keys in `existing` are
|
||||
* preserved. The `provider` map is shallow-merged so other providers already
|
||||
* present are not removed. If `existing.provider.omniroute` already exists it
|
||||
* is overwritten by the newly built entry.
|
||||
*
|
||||
* `model` and `small_model` are only written when supplied in `options`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const existing = JSON.parse(readFileSync("opencode.json", "utf8"));
|
||||
* const updated = mergeIntoExistingConfig(existing, {
|
||||
* baseURL: "http://localhost:20128",
|
||||
* apiKey: "sk_omniroute",
|
||||
* model: "claude-sonnet-4-5-thinking",
|
||||
* });
|
||||
* writeFileSync("opencode.json", JSON.stringify(updated, null, 2));
|
||||
* ```
|
||||
*/
|
||||
export function mergeIntoExistingConfig(
|
||||
existing: Record<string, unknown>,
|
||||
options: OmniRouteProviderOptions
|
||||
): Record<string, unknown> {
|
||||
const partial = buildOmniRouteOpenCodeConfig(options);
|
||||
|
||||
const merged: Record<string, unknown> = { ...existing };
|
||||
|
||||
if (partial.model !== undefined) merged.model = partial.model;
|
||||
if (partial.small_model !== undefined) merged.small_model = partial.small_model;
|
||||
|
||||
const existingProvider =
|
||||
typeof existing.provider === "object" && existing.provider !== null
|
||||
? (existing.provider as Record<string, unknown>)
|
||||
: {};
|
||||
|
||||
merged.provider = {
|
||||
...existingProvider,
|
||||
[OMNIROUTE_PROVIDER_KEY]: partial.provider[OMNIROUTE_PROVIDER_KEY],
|
||||
};
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 7 read-only MCP scopes that allow inspection without any write access.
|
||||
* Suitable for shared / public environments.
|
||||
*/
|
||||
export const OMNIROUTE_MCP_DEFAULT_SCOPES = [
|
||||
"read:health",
|
||||
"read:combos",
|
||||
"read:quota",
|
||||
"read:usage",
|
||||
"read:models",
|
||||
"read:cache",
|
||||
"read:compression",
|
||||
] as const;
|
||||
|
||||
export type OmniRouteMCPScope = (typeof OMNIROUTE_MCP_DEFAULT_SCOPES)[number] | string;
|
||||
|
||||
export interface OmniRouteMCPOptions {
|
||||
/** Absolute path to the MCP server entry point (TypeScript or compiled JS). */
|
||||
serverPath: string;
|
||||
/** OmniRoute API key forwarded to the MCP server as `OMNIROUTE_API_KEY`. */
|
||||
apiKey: string;
|
||||
/**
|
||||
* Management API key used for management-scoped operations.
|
||||
* When supplied it is forwarded as `OMNIROUTE_MANAGEMENT_API_KEY`.
|
||||
*/
|
||||
managementApiKey?: string;
|
||||
/**
|
||||
* Comma-separated scope list passed as `OMNIROUTE_MCP_SCOPES`.
|
||||
* When omitted `OMNIROUTE_MCP_ENFORCE_SCOPES` is not set and all scopes are
|
||||
* available (development default). Pass an explicit list to restrict access.
|
||||
*/
|
||||
scopes?: OmniRouteMCPScope[];
|
||||
/**
|
||||
* Runtime used to execute the MCP server.
|
||||
*
|
||||
* - `"tsx"` (default) — runs via `npx tsx` for TypeScript source files.
|
||||
* - `"node"` — runs via `node` for compiled JS outputs.
|
||||
*/
|
||||
runtime?: "tsx" | "node";
|
||||
}
|
||||
|
||||
export interface OpenCodeMCPServerEntry {
|
||||
command: string;
|
||||
args: string[];
|
||||
env: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `mcp.servers.omniroute` entry for an OpenCode config document.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const mcpEntry = createOmniRouteMCPEntry({
|
||||
* serverPath: "/home/user/.local/share/omniroute/open-sse/mcp-server/server.ts",
|
||||
* apiKey: "sk_omniroute",
|
||||
* managementApiKey: "sk_manage_...",
|
||||
* scopes: ["read:health", "read:combos", "execute:completions"],
|
||||
* });
|
||||
* // Place at config.mcp.servers.omniroute
|
||||
* ```
|
||||
*/
|
||||
export function createOmniRouteMCPEntry(options: OmniRouteMCPOptions): OpenCodeMCPServerEntry {
|
||||
const serverPath = requireNonEmpty(options.serverPath, "serverPath");
|
||||
const apiKey = requireNonEmpty(options.apiKey, "apiKey");
|
||||
|
||||
const runtime = options.runtime ?? "tsx";
|
||||
|
||||
const command = runtime === "tsx" ? "npx" : "node";
|
||||
const args = runtime === "tsx" ? ["tsx", serverPath] : [serverPath];
|
||||
|
||||
const env: Record<string, string> = {
|
||||
OMNIROUTE_API_KEY: apiKey,
|
||||
};
|
||||
|
||||
if (options.managementApiKey !== undefined) {
|
||||
const mgmtKey = options.managementApiKey.trim();
|
||||
if (mgmtKey) env.OMNIROUTE_MANAGEMENT_API_KEY = mgmtKey;
|
||||
}
|
||||
|
||||
if (options.scopes !== undefined && options.scopes.length > 0) {
|
||||
env.OMNIROUTE_MCP_ENFORCE_SCOPES = "true";
|
||||
env.OMNIROUTE_MCP_SCOPES = options.scopes.join(",");
|
||||
}
|
||||
|
||||
return { command, args, env };
|
||||
}
|
||||
|
||||
async function fetchJSON<T>(url: string, apiKey: string, timeoutMs: number): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${apiKey}` },
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`received HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`@omniroute/opencode-provider: request to ${url} failed: ${message}`);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight model descriptor returned by `fetchLiveModels`.
|
||||
* The shape mirrors the subset of fields that OmniRoute's `/v1/models`
|
||||
* endpoint reliably provides across versions, normalised from both
|
||||
* camelCase and snake_case variants used by different OmniRoute releases.
|
||||
*
|
||||
* Attribution: field-variant normalisation logic adapted from
|
||||
* https://github.com/Alph4d0g/opencode-omniroute-auth (MIT).
|
||||
*/
|
||||
export interface OmniRouteLiveModel {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Context window length in tokens (e.g. 200000 for Claude, 1000000 for Gemini). */
|
||||
contextLength?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the live model catalog from a running OmniRoute instance.
|
||||
*
|
||||
* Returns an array of `{ id, name }` objects from `GET /v1/models`. Handles
|
||||
* both the camelCase (`modelId`, `displayName`) and snake_case (`model_id`,
|
||||
* `display_name`) field variants across OmniRoute versions.
|
||||
*
|
||||
* Useful for dynamically populating the `models` option of
|
||||
* `createOmniRouteProvider` / `buildOmniRouteOpenCodeConfig` instead of
|
||||
* relying on `OMNIROUTE_DEFAULT_OPENCODE_MODELS`.
|
||||
*
|
||||
* @param baseURL - OmniRoute base URL (with or without `/v1`).
|
||||
* @param apiKey - OmniRoute API key.
|
||||
* @param timeoutMs - Request timeout in milliseconds (default 5000).
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const models = await fetchLiveModels("http://localhost:20128", "sk_omniroute");
|
||||
* const config = buildOmniRouteOpenCodeConfig({
|
||||
* baseURL: "http://localhost:20128",
|
||||
* apiKey: "sk_omniroute",
|
||||
* models, // OmniRouteLiveModel[] — contextLength auto-extracted
|
||||
* modelLabels: Object.fromEntries(models.map((m) => [m.id, m.name])),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export async function fetchLiveModels(
|
||||
baseURL: string,
|
||||
apiKey: string,
|
||||
timeoutMs = 5_000
|
||||
): Promise<OmniRouteLiveModel[]> {
|
||||
const key = requireNonEmpty(apiKey, "apiKey");
|
||||
const url = `${normalizeBaseURL(baseURL)}/models`;
|
||||
|
||||
const body = await fetchJSON<unknown>(url, key, timeoutMs);
|
||||
|
||||
const rawList: unknown[] = Array.isArray(body)
|
||||
? body
|
||||
: body && typeof body === "object" && Array.isArray((body as { data?: unknown[] }).data)
|
||||
? ((body as { data: unknown[] }).data as unknown[])
|
||||
: [];
|
||||
|
||||
const models: OmniRouteLiveModel[] = [];
|
||||
for (const raw of rawList) {
|
||||
if (typeof raw !== "object" || raw === null) continue;
|
||||
const r = raw as Record<string, unknown>;
|
||||
|
||||
const id =
|
||||
typeof r.id === "string"
|
||||
? r.id.trim()
|
||||
: typeof r.modelId === "string"
|
||||
? r.modelId.trim()
|
||||
: typeof r.model_id === "string"
|
||||
? r.model_id.trim()
|
||||
: "";
|
||||
|
||||
if (!id) continue;
|
||||
|
||||
const name =
|
||||
typeof r.name === "string"
|
||||
? r.name.trim()
|
||||
: typeof r.displayName === "string"
|
||||
? r.displayName.trim()
|
||||
: typeof r.display_name === "string"
|
||||
? r.display_name.trim()
|
||||
: id;
|
||||
|
||||
// Extract context_length from OmniRoute's /v1/models response.
|
||||
// OmniRoute returns context_length in snake_case for both synced
|
||||
// models (with inputTokenLimit) and custom models; the catalog's
|
||||
// getDefaultContextFallback also injects it from registry defaults.
|
||||
const contextLength =
|
||||
typeof r.context_length === "number" && r.context_length > 0
|
||||
? r.context_length
|
||||
: typeof r.max_context_window_tokens === "number" && r.max_context_window_tokens > 0
|
||||
? r.max_context_window_tokens
|
||||
: undefined;
|
||||
|
||||
models.push({ id, name: name || id, ...(contextLength ? { contextLength } : {}) });
|
||||
}
|
||||
|
||||
return models;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valid per-combo compression override values.
|
||||
* An empty string clears any existing override (inherits global setting).
|
||||
*/
|
||||
export type OmniRouteCompressionOverride =
|
||||
| ""
|
||||
| "off"
|
||||
| "lite"
|
||||
| "standard"
|
||||
| "aggressive"
|
||||
| "ultra"
|
||||
| "rtk"
|
||||
| "stacked";
|
||||
|
||||
const VALID_COMPRESSION_OVERRIDES = new Set<string>([
|
||||
"",
|
||||
"off",
|
||||
"lite",
|
||||
"standard",
|
||||
"aggressive",
|
||||
"ultra",
|
||||
"rtk",
|
||||
"stacked",
|
||||
]);
|
||||
|
||||
/** Slim combo descriptor returned by `listCombos`. */
|
||||
export interface OmniRouteCombo {
|
||||
id: string;
|
||||
name: string;
|
||||
strategy: string;
|
||||
active: boolean;
|
||||
compressionOverride: OmniRouteCompressionOverride;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the active routing combo list from a running OmniRoute instance.
|
||||
*
|
||||
* Returns an array of combo descriptors from `GET /api/combos`. The
|
||||
* `compressionOverride` field reflects the per-combo compression strategy
|
||||
* (one of the 8 recognised values; empty string means "inherit global").
|
||||
*
|
||||
* Requires a management-scoped API key (Bearer `manage` scope) when the
|
||||
* instance has `REQUIRE_API_KEY` enabled.
|
||||
*
|
||||
* @param baseURL - OmniRoute base URL (with or without `/v1`).
|
||||
* @param managementApiKey - API key with `manage` scope.
|
||||
* @param timeoutMs - Request timeout in milliseconds (default 5000).
|
||||
*/
|
||||
export async function listCombos(
|
||||
baseURL: string,
|
||||
managementApiKey: string,
|
||||
timeoutMs = 5_000
|
||||
): Promise<OmniRouteCombo[]> {
|
||||
const key = requireNonEmpty(managementApiKey, "managementApiKey");
|
||||
const base = normalizeBaseURL(baseURL).replace(/\/v1$/, "");
|
||||
const url = `${base}/api/combos`;
|
||||
|
||||
const body = await fetchJSON<unknown>(url, key, timeoutMs);
|
||||
const rawList: unknown[] = Array.isArray(body)
|
||||
? body
|
||||
: body && typeof body === "object" && Array.isArray((body as { combos?: unknown[] }).combos)
|
||||
? ((body as { combos: unknown[] }).combos as unknown[])
|
||||
: [];
|
||||
|
||||
const combos: OmniRouteCombo[] = [];
|
||||
for (const raw of rawList) {
|
||||
if (typeof raw !== "object" || raw === null) continue;
|
||||
const r = raw as Record<string, unknown>;
|
||||
|
||||
const id = typeof r.id === "string" ? r.id.trim() : "";
|
||||
if (!id) continue;
|
||||
|
||||
const name = typeof r.name === "string" ? r.name.trim() : id;
|
||||
const strategy = typeof r.strategy === "string" ? r.strategy : "";
|
||||
const active = typeof r.active === "boolean" ? r.active : false;
|
||||
|
||||
const rawOverride = typeof r.compressionOverride === "string" ? r.compressionOverride : "";
|
||||
const compressionOverride = VALID_COMPRESSION_OVERRIDES.has(rawOverride)
|
||||
? (rawOverride as OmniRouteCompressionOverride)
|
||||
: "";
|
||||
|
||||
combos.push({ id, name, strategy, active, compressionOverride });
|
||||
}
|
||||
|
||||
return combos;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for `createOmniRouteComboConfig`.
|
||||
* Mirrors the subset of combo fields exposed by the OmniRoute `/api/combos`
|
||||
* PATCH / POST payload that are safe to set programmatically.
|
||||
*/
|
||||
export interface OmniRouteComboConfigOptions {
|
||||
/** Human-readable combo name. */
|
||||
name: string;
|
||||
/** Routing strategy (e.g. `"priority"`, `"weighted"`, `"round-robin"`). */
|
||||
strategy: string;
|
||||
/**
|
||||
* Per-combo compression override.
|
||||
* Empty string removes any override (inherits global setting).
|
||||
*/
|
||||
compressionOverride?: OmniRouteCompressionOverride;
|
||||
/** Whether this combo is active for routing. Default: `true`. */
|
||||
active?: boolean;
|
||||
/**
|
||||
* Ordered list of provider IDs in this combo.
|
||||
* Required for create operations; optional for updates.
|
||||
*/
|
||||
providers?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a typed combo payload suitable for OmniRoute's management API.
|
||||
*
|
||||
* The returned object is JSON-serialisable and safe to pass as the body of a
|
||||
* `POST /api/combos` (create) or `PATCH /api/combos/:id` (update) request.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const payload = createOmniRouteComboConfig({
|
||||
* name: "claude-primary",
|
||||
* strategy: "priority",
|
||||
* compressionOverride: "standard",
|
||||
* providers: ["anthropic-claude-opus", "anthropic-claude-sonnet"],
|
||||
* });
|
||||
* await fetch(`${baseURL}/api/combos`, {
|
||||
* method: "POST",
|
||||
* headers: { Authorization: `Bearer ${mgmtKey}`, "Content-Type": "application/json" },
|
||||
* body: JSON.stringify(payload),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function createOmniRouteComboConfig(
|
||||
options: OmniRouteComboConfigOptions
|
||||
): Record<string, unknown> {
|
||||
const name = requireNonEmpty(options.name, "name");
|
||||
const strategy = requireNonEmpty(options.strategy, "strategy");
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
name,
|
||||
strategy,
|
||||
active: options.active ?? true,
|
||||
};
|
||||
|
||||
if (options.compressionOverride !== undefined) {
|
||||
payload.compressionOverride = options.compressionOverride;
|
||||
}
|
||||
|
||||
if (options.providers !== undefined) {
|
||||
const providers = options.providers.filter((p) => typeof p === "string" && p.trim());
|
||||
if (providers.length > 0) {
|
||||
payload.providers = providers;
|
||||
}
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override fields supported per agent / mode entry. Mirrors the subset of
|
||||
* OpenCode's `AgentConfig` schema that is safe to set declaratively from a
|
||||
* config generator. Only fields present in
|
||||
* https://opencode.ai/config.json#AgentConfig are exposed.
|
||||
*/
|
||||
export interface OmniRouteRoleOverrides {
|
||||
/** Forward to OpenCode's `temperature` field. */
|
||||
temperature?: number;
|
||||
/** Forward to OpenCode's `top_p` field. */
|
||||
top_p?: number;
|
||||
}
|
||||
|
||||
/** Per-role binding used by `createOmniRouteAgentBlock`. */
|
||||
export interface OmniRouteAgentRole extends OmniRouteRoleOverrides {
|
||||
/** OmniRoute model id, e.g. `"claude-sonnet-4-5-thinking"`. */
|
||||
modelId: string;
|
||||
/** Optional tools allow-list; per OpenCode schema, map of tool name → enabled. */
|
||||
tools?: Record<string, boolean>;
|
||||
/** Optional system prompt for this agent role. */
|
||||
prompt?: string;
|
||||
}
|
||||
|
||||
/** Options for `createOmniRouteAgentBlock`. */
|
||||
export interface OmniRouteAgentBlockOptions {
|
||||
/** Per-role bindings. Keys become entries under OpenCode's `agent` block. */
|
||||
roles: Record<string, OmniRouteAgentRole>;
|
||||
}
|
||||
|
||||
/** Single entry inside the emitted OpenCode `agent` block. */
|
||||
export interface OpenCodeAgentEntry extends OmniRouteRoleOverrides {
|
||||
/** Always emitted as `"omniroute/<modelId>"`. */
|
||||
model: string;
|
||||
/** Per OpenCode schema, `Record<string, boolean>`. */
|
||||
tools?: Record<string, boolean>;
|
||||
/** Optional system prompt. */
|
||||
prompt?: string;
|
||||
}
|
||||
|
||||
function buildAgentEntry(role: OmniRouteAgentRole): OpenCodeAgentEntry | undefined {
|
||||
if (!role || typeof role.modelId !== "string") return undefined;
|
||||
const modelId = role.modelId.trim();
|
||||
if (!modelId) return undefined;
|
||||
const entry: OpenCodeAgentEntry = { model: `${OMNIROUTE_PROVIDER_KEY}/${modelId}` };
|
||||
if (typeof role.temperature === "number") entry.temperature = role.temperature;
|
||||
if (typeof role.top_p === "number") entry.top_p = role.top_p;
|
||||
if (role.tools && typeof role.tools === "object" && !Array.isArray(role.tools)) {
|
||||
const tools: Record<string, boolean> = {};
|
||||
for (const [name, enabled] of Object.entries(role.tools)) {
|
||||
if (typeof name !== "string" || !name.trim()) continue;
|
||||
if (typeof enabled !== "boolean") continue;
|
||||
tools[name] = enabled;
|
||||
}
|
||||
if (Object.keys(tools).length > 0) entry.tools = tools;
|
||||
}
|
||||
if (typeof role.prompt === "string" && role.prompt.trim()) {
|
||||
entry.prompt = role.prompt;
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the OpenCode `agent` block, pre-wired so each agent role routes to a
|
||||
* specific OmniRoute model. Useful for `.opencode/agent/*.md` defaults and
|
||||
* scaffolded `opencode.json` files.
|
||||
*
|
||||
* Emitted fields are limited to those declared in OpenCode's `AgentConfig`
|
||||
* schema (`model`, `temperature`, `top_p`, `tools`, `prompt`). The `tools`
|
||||
* field is a `Record<string, boolean>` per the schema, not a string array.
|
||||
*
|
||||
* Roles with empty / missing `modelId` are skipped.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const agentBlock = createOmniRouteAgentBlock({
|
||||
* roles: {
|
||||
* build: { modelId: "claude-sonnet-4-5-thinking", temperature: 0.2 },
|
||||
* plan: { modelId: "claude-opus-4-5-thinking", top_p: 0.95 },
|
||||
* review: { modelId: "gemini-3-flash", tools: { edit: false, bash: false } },
|
||||
* },
|
||||
* });
|
||||
* // -> { build: { model: "omniroute/claude-sonnet-4-5-thinking", temperature: 0.2 }, ... }
|
||||
* ```
|
||||
*/
|
||||
export function createOmniRouteAgentBlock(
|
||||
options: OmniRouteAgentBlockOptions
|
||||
): Record<string, OpenCodeAgentEntry> {
|
||||
const out: Record<string, OpenCodeAgentEntry> = {};
|
||||
const roles = options.roles ?? {};
|
||||
for (const [roleName, role] of Object.entries(roles)) {
|
||||
const entry = buildAgentEntry(role);
|
||||
if (entry) out[roleName] = entry;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-mode binding used by `createOmniRouteModesBlock`.
|
||||
*
|
||||
* @deprecated OpenCode's top-level `mode` block is deprecated in favour of
|
||||
* `agent`. Prefer `OmniRouteAgentRole` + `createOmniRouteAgentBlock`. This
|
||||
* type and the corresponding helper are kept for back-compat with configs
|
||||
* still using `mode:`.
|
||||
*/
|
||||
export interface OmniRouteMode extends OmniRouteAgentRole {}
|
||||
|
||||
/**
|
||||
* Options for `createOmniRouteModesBlock`.
|
||||
*
|
||||
* @deprecated See `OmniRouteMode`.
|
||||
*/
|
||||
export interface OmniRouteModesBlockOptions {
|
||||
/** Per-mode bindings. Keys become entries under OpenCode's deprecated top-level `mode` block. */
|
||||
modes: Record<string, OmniRouteMode>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Single entry inside the emitted OpenCode `mode` block.
|
||||
*
|
||||
* @deprecated See `OmniRouteMode`.
|
||||
*/
|
||||
export interface OpenCodeModeEntry extends OpenCodeAgentEntry {}
|
||||
|
||||
/**
|
||||
* Build the OpenCode top-level `mode` block, pre-wired so each mode routes to
|
||||
* a specific OmniRoute model. Emits the same shape as the `agent` block since
|
||||
* OpenCode's schema treats them identically (both reference `AgentConfig`).
|
||||
*
|
||||
* Modes with empty / missing `modelId` are skipped.
|
||||
*
|
||||
* @deprecated OpenCode's top-level `mode` block is deprecated in favour of
|
||||
* `agent`. Prefer `createOmniRouteAgentBlock`. This helper is kept for
|
||||
* back-compat with configs still using `mode:`.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const modesBlock = createOmniRouteModesBlock({
|
||||
* modes: {
|
||||
* build: { modelId: "claude-sonnet-4-5-thinking", tools: { edit: true, bash: true } },
|
||||
* plan: { modelId: "claude-opus-4-5-thinking", prompt: "Plan first, code later." },
|
||||
* review: { modelId: "gemini-3-flash" },
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function createOmniRouteModesBlock(
|
||||
options: OmniRouteModesBlockOptions
|
||||
): Record<string, OpenCodeModeEntry> {
|
||||
const out: Record<string, OpenCodeModeEntry> = {};
|
||||
const modes = options.modes ?? {};
|
||||
for (const [modeName, mode] of Object.entries(modes)) {
|
||||
const entry = buildAgentEntry(mode);
|
||||
if (entry) out[modeName] = entry;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export default createOmniRouteProvider;
|
||||
686
@omniroute/opencode-provider/tests/index.test.ts
Normal file
686
@omniroute/opencode-provider/tests/index.test.ts
Normal file
@@ -0,0 +1,686 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import type { Server } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
import {
|
||||
buildOmniRouteOpenCodeConfig,
|
||||
createOmniRouteAgentBlock,
|
||||
createOmniRouteComboConfig,
|
||||
createOmniRouteMCPEntry,
|
||||
createOmniRouteModesBlock,
|
||||
createOmniRouteProvider,
|
||||
fetchLiveModels,
|
||||
listCombos,
|
||||
mergeIntoExistingConfig,
|
||||
normalizeBaseURL,
|
||||
OMNIROUTE_DEFAULT_MODEL_CAPABILITIES,
|
||||
OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS,
|
||||
OMNIROUTE_DEFAULT_OPENCODE_MODELS,
|
||||
OMNIROUTE_MCP_DEFAULT_SCOPES,
|
||||
OMNIROUTE_PROVIDER_NPM,
|
||||
OPENCODE_CONFIG_SCHEMA,
|
||||
} from "../src/index.ts";
|
||||
|
||||
test("normalizeBaseURL preserves a bare host:port", () => {
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128"), "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("normalizeBaseURL strips trailing slashes", () => {
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128////"), "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("normalizeBaseURL deduplicates an existing /v1 suffix", () => {
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128/v1"), "http://localhost:20128/v1");
|
||||
assert.equal(normalizeBaseURL("http://localhost:20128/v1/"), "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("normalizeBaseURL rejects empty input", () => {
|
||||
assert.throws(() => normalizeBaseURL(" "), /baseURL is required/);
|
||||
});
|
||||
|
||||
test("normalizeBaseURL rejects malformed URLs", () => {
|
||||
assert.throws(() => normalizeBaseURL("not a url"), /not a valid URL/);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider validates required fields", () => {
|
||||
assert.throws(
|
||||
() => createOmniRouteProvider({ baseURL: "", apiKey: "x" } as never),
|
||||
/baseURL is required/
|
||||
);
|
||||
assert.throws(
|
||||
() => createOmniRouteProvider({ baseURL: "http://x", apiKey: "" } as never),
|
||||
/apiKey is required/
|
||||
);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider produces the OpenCode-compatible shape", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
|
||||
assert.equal(provider.npm, OMNIROUTE_PROVIDER_NPM);
|
||||
assert.equal(provider.name, "OmniRoute");
|
||||
assert.equal(provider.options.baseURL, "http://localhost:20128/v1");
|
||||
assert.equal(provider.options.apiKey, "sk_omniroute");
|
||||
assert.equal(typeof provider.models, "object");
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider seeds the default model catalog", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
|
||||
const modelIds = Object.keys(provider.models).sort();
|
||||
const defaultIds = [...OMNIROUTE_DEFAULT_OPENCODE_MODELS].sort();
|
||||
assert.deepEqual(modelIds, defaultIds);
|
||||
for (const id of defaultIds) {
|
||||
assert.equal(provider.models[id]?.name, id);
|
||||
assert.equal(provider.models[id]?.attachment, true);
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider honours a custom models list and labels", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["auto", "claude-opus-4-7"],
|
||||
modelLabels: { auto: "Auto-Combo", "claude-opus-4-7": "Opus 4.7" },
|
||||
});
|
||||
|
||||
assert.deepEqual(Object.keys(provider.models), ["auto", "claude-opus-4-7"]);
|
||||
assert.equal(provider.models.auto.name, "Auto-Combo");
|
||||
assert.equal(provider.models["claude-opus-4-7"].name, "Opus 4.7");
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider deduplicates and trims model ids", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: [" auto ", "auto", "", "claude-opus-4-7"],
|
||||
});
|
||||
assert.deepEqual(Object.keys(provider.models), ["auto", "claude-opus-4-7"]);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider honours displayName override", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
displayName: "Local OmniRoute",
|
||||
});
|
||||
assert.equal(provider.name, "Local OmniRoute");
|
||||
});
|
||||
|
||||
test("buildOmniRouteOpenCodeConfig wraps the provider with the OpenCode schema", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128/v1",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
|
||||
assert.equal(doc.$schema, OPENCODE_CONFIG_SCHEMA);
|
||||
assert.equal(typeof doc.provider.omniroute, "object");
|
||||
assert.equal(doc.provider.omniroute.options.baseURL, "http://localhost:20128/v1");
|
||||
});
|
||||
|
||||
test("config document is JSON-serialisable", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
const round = JSON.parse(JSON.stringify(doc));
|
||||
assert.deepEqual(round, doc);
|
||||
});
|
||||
|
||||
test("buildOmniRouteOpenCodeConfig emits model and small_model prefixed with provider key", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
model: "claude-sonnet-4-5-thinking",
|
||||
smallModel: "gemini-3-flash",
|
||||
});
|
||||
assert.equal(doc.model, "omniroute/claude-sonnet-4-5-thinking");
|
||||
assert.equal(doc.small_model, "omniroute/gemini-3-flash");
|
||||
});
|
||||
|
||||
test("buildOmniRouteOpenCodeConfig omits model and small_model when not supplied", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
assert.equal(doc.model, undefined);
|
||||
assert.equal(doc.small_model, undefined);
|
||||
assert.ok(!("model" in doc));
|
||||
assert.ok(!("small_model" in doc));
|
||||
});
|
||||
|
||||
test("buildOmniRouteOpenCodeConfig ignores blank model strings", () => {
|
||||
const doc = buildOmniRouteOpenCodeConfig({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
model: " ",
|
||||
smallModel: "",
|
||||
});
|
||||
assert.ok(!("model" in doc));
|
||||
assert.ok(!("small_model" in doc));
|
||||
});
|
||||
|
||||
test("mergeIntoExistingConfig preserves existing provider entries", () => {
|
||||
const existing = {
|
||||
$schema: OPENCODE_CONFIG_SCHEMA,
|
||||
provider: {
|
||||
anthropic: { npm: "@ai-sdk/anthropic", name: "Anthropic", options: {}, models: {} },
|
||||
},
|
||||
keybinds: { submit: "enter" },
|
||||
};
|
||||
const result = mergeIntoExistingConfig(existing, {
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
assert.ok("anthropic" in (result.provider as Record<string, unknown>));
|
||||
assert.ok("omniroute" in (result.provider as Record<string, unknown>));
|
||||
assert.deepEqual((result as Record<string, unknown>).keybinds, { submit: "enter" });
|
||||
});
|
||||
|
||||
test("mergeIntoExistingConfig overwrites existing omniroute entry", () => {
|
||||
const existing = {
|
||||
provider: {
|
||||
omniroute: {
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
name: "OLD",
|
||||
options: { baseURL: "http://old/v1", apiKey: "old" },
|
||||
models: {},
|
||||
},
|
||||
},
|
||||
};
|
||||
const result = mergeIntoExistingConfig(existing, {
|
||||
baseURL: "http://new",
|
||||
apiKey: "new-key",
|
||||
displayName: "NEW",
|
||||
});
|
||||
const omniroute = (result.provider as Record<string, unknown>).omniroute as { name: string };
|
||||
assert.equal(omniroute.name, "NEW");
|
||||
});
|
||||
|
||||
test("mergeIntoExistingConfig writes model and small_model when supplied", () => {
|
||||
const result = mergeIntoExistingConfig(
|
||||
{},
|
||||
{
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
model: "claude-sonnet-4-5-thinking",
|
||||
smallModel: "gemini-3-flash",
|
||||
}
|
||||
);
|
||||
assert.equal(result.model, "omniroute/claude-sonnet-4-5-thinking");
|
||||
assert.equal(result.small_model, "omniroute/gemini-3-flash");
|
||||
});
|
||||
|
||||
test("mergeIntoExistingConfig does not add model keys when not supplied", () => {
|
||||
const result = mergeIntoExistingConfig(
|
||||
{},
|
||||
{ baseURL: "http://localhost:20128", apiKey: "sk_omniroute" }
|
||||
);
|
||||
assert.ok(!("model" in result));
|
||||
assert.ok(!("small_model" in result));
|
||||
});
|
||||
|
||||
test("OMNIROUTE_MCP_DEFAULT_SCOPES contains 7 read-only scopes", () => {
|
||||
assert.equal(OMNIROUTE_MCP_DEFAULT_SCOPES.length, 7);
|
||||
assert.ok(OMNIROUTE_MCP_DEFAULT_SCOPES.every((s) => s.startsWith("read:")));
|
||||
});
|
||||
|
||||
test("createOmniRouteMCPEntry defaults to tsx runtime", () => {
|
||||
const entry = createOmniRouteMCPEntry({
|
||||
serverPath: "/path/to/server.ts",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
assert.equal(entry.command, "npx");
|
||||
assert.deepEqual(entry.args, ["tsx", "/path/to/server.ts"]);
|
||||
assert.equal(entry.env.OMNIROUTE_API_KEY, "sk_omniroute");
|
||||
assert.ok(!("OMNIROUTE_MCP_ENFORCE_SCOPES" in entry.env));
|
||||
assert.ok(!("OMNIROUTE_MANAGEMENT_API_KEY" in entry.env));
|
||||
});
|
||||
|
||||
test("createOmniRouteMCPEntry uses node runtime when specified", () => {
|
||||
const entry = createOmniRouteMCPEntry({
|
||||
serverPath: "/path/to/server.js",
|
||||
apiKey: "sk_omniroute",
|
||||
runtime: "node",
|
||||
});
|
||||
assert.equal(entry.command, "node");
|
||||
assert.deepEqual(entry.args, ["/path/to/server.js"]);
|
||||
});
|
||||
|
||||
test("createOmniRouteMCPEntry sets management key and scopes when supplied", () => {
|
||||
const entry = createOmniRouteMCPEntry({
|
||||
serverPath: "/path/to/server.ts",
|
||||
apiKey: "sk_omniroute",
|
||||
managementApiKey: "sk_manage",
|
||||
scopes: ["read:health", "read:combos", "execute:completions"],
|
||||
});
|
||||
assert.equal(entry.env.OMNIROUTE_MANAGEMENT_API_KEY, "sk_manage");
|
||||
assert.equal(entry.env.OMNIROUTE_MCP_ENFORCE_SCOPES, "true");
|
||||
assert.equal(entry.env.OMNIROUTE_MCP_SCOPES, "read:health,read:combos,execute:completions");
|
||||
});
|
||||
|
||||
test("createOmniRouteMCPEntry rejects missing required fields", () => {
|
||||
assert.throws(
|
||||
() => createOmniRouteMCPEntry({ serverPath: "", apiKey: "x" }),
|
||||
/serverPath is required/
|
||||
);
|
||||
assert.throws(
|
||||
() => createOmniRouteMCPEntry({ serverPath: "/p", apiKey: "" }),
|
||||
/apiKey is required/
|
||||
);
|
||||
});
|
||||
|
||||
function startMockServer(
|
||||
handler: (path: string) => unknown
|
||||
): Promise<{ url: string; close: () => void }> {
|
||||
return new Promise((resolve) => {
|
||||
const server: Server = createServer((req, res) => {
|
||||
const body = JSON.stringify(handler(req.url ?? ""));
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
res.end(body);
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const addr = server.address() as { port: number };
|
||||
resolve({ url: `http://127.0.0.1:${addr.port}`, close: () => server.close() });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("fetchLiveModels handles array envelope", async () => {
|
||||
const { url, close } = await startMockServer(() => [
|
||||
{ id: "claude-sonnet", name: "Claude Sonnet" },
|
||||
{ id: "gemini-flash", displayName: "Gemini Flash" },
|
||||
]);
|
||||
try {
|
||||
const models = await fetchLiveModels(url, "sk_test");
|
||||
assert.equal(models.length, 2);
|
||||
assert.equal(models[0].id, "claude-sonnet");
|
||||
assert.equal(models[0].name, "Claude Sonnet");
|
||||
assert.equal(models[1].id, "gemini-flash");
|
||||
assert.equal(models[1].name, "Gemini Flash");
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchLiveModels handles data-envelope and snake_case fields", async () => {
|
||||
const { url, close } = await startMockServer(() => ({
|
||||
data: [{ model_id: "gpt-4o", display_name: "GPT-4o" }],
|
||||
}));
|
||||
try {
|
||||
const models = await fetchLiveModels(url, "sk_test");
|
||||
assert.equal(models.length, 1);
|
||||
assert.equal(models[0].id, "gpt-4o");
|
||||
assert.equal(models[0].name, "GPT-4o");
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchLiveModels falls back to id as name when no name field", async () => {
|
||||
const { url, close } = await startMockServer(() => [{ id: "auto" }]);
|
||||
try {
|
||||
const models = await fetchLiveModels(url, "sk_test");
|
||||
assert.equal(models[0].name, "auto");
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
test("listCombos normalises compressionOverride", async () => {
|
||||
const { url, close } = await startMockServer(() => ({
|
||||
combos: [
|
||||
{
|
||||
id: "c1",
|
||||
name: "Primary",
|
||||
strategy: "priority",
|
||||
active: true,
|
||||
compressionOverride: "standard",
|
||||
},
|
||||
{
|
||||
id: "c2",
|
||||
name: "Cheap",
|
||||
strategy: "weighted",
|
||||
active: false,
|
||||
compressionOverride: "unknown-value",
|
||||
},
|
||||
{ id: "c3", name: "Off", strategy: "round-robin", active: true, compressionOverride: "" },
|
||||
],
|
||||
}));
|
||||
try {
|
||||
const combos = await listCombos(url, "sk_manage");
|
||||
assert.equal(combos.length, 3);
|
||||
assert.equal(combos[0].compressionOverride, "standard");
|
||||
assert.equal(combos[1].compressionOverride, "");
|
||||
assert.equal(combos[2].compressionOverride, "");
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteComboConfig builds minimal payload", () => {
|
||||
const payload = createOmniRouteComboConfig({ name: "my-combo", strategy: "priority" });
|
||||
assert.equal(payload.name, "my-combo");
|
||||
assert.equal(payload.strategy, "priority");
|
||||
assert.equal(payload.active, true);
|
||||
assert.ok(!("compressionOverride" in payload));
|
||||
assert.ok(!("providers" in payload));
|
||||
});
|
||||
|
||||
test("createOmniRouteComboConfig includes optional fields when supplied", () => {
|
||||
const payload = createOmniRouteComboConfig({
|
||||
name: "full",
|
||||
strategy: "weighted",
|
||||
compressionOverride: "aggressive",
|
||||
active: false,
|
||||
providers: ["provider-a", "provider-b"],
|
||||
});
|
||||
assert.equal(payload.compressionOverride, "aggressive");
|
||||
assert.equal(payload.active, false);
|
||||
assert.deepEqual(payload.providers, ["provider-a", "provider-b"]);
|
||||
});
|
||||
|
||||
test("OMNIROUTE_DEFAULT_OPENCODE_MODELS includes cc/ prefixed models", () => {
|
||||
const defaults = [...OMNIROUTE_DEFAULT_OPENCODE_MODELS];
|
||||
assert.ok(defaults.includes("cc/claude-opus-4-8"));
|
||||
assert.ok(
|
||||
defaults.some((m) => m.startsWith("cc/")),
|
||||
"should have cc/ prefixed models"
|
||||
);
|
||||
assert.ok(defaults.length >= 7, "should have at least 7 models");
|
||||
});
|
||||
|
||||
test("OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS covers every default model id", () => {
|
||||
for (const id of OMNIROUTE_DEFAULT_OPENCODE_MODELS) {
|
||||
const ctx = OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];
|
||||
assert.ok(
|
||||
typeof ctx === "number" && ctx > 0,
|
||||
`default context_length for ${id} missing — should be a positive number`
|
||||
);
|
||||
// Sanity: context should be at least 8K, at most 2M tokens
|
||||
assert.ok(ctx >= 8_000, `${id} context_length ${ctx} seems too low`);
|
||||
assert.ok(ctx <= 2_000_000, `${id} context_length ${ctx} seems too high`);
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider emits limit.context on default model entries", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
const entry = provider.models["cc/claude-opus-4-8"];
|
||||
assert.ok(entry.limit, "model entry should have a limit field");
|
||||
assert.equal(entry.limit!.context, 1_000_000);
|
||||
assert.equal(provider.models["cc/claude-opus-4-7"].limit!.context, 1_000_000);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider omits limit.context for unknown model ids", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["completely-unknown-model"],
|
||||
});
|
||||
const entry = provider.models["completely-unknown-model"];
|
||||
assert.equal(entry.limit, undefined);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider reads contextLength from a live model entry for ids absent from the static map", () => {
|
||||
// #3298 regression guard: the static OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS
|
||||
// map only covers the legacy 8 Claude/Gemini ids. Before this change, any
|
||||
// other model got `undefined` context (see the test above, string form) and
|
||||
// OpenCode silently fell back to its 128K internal default. A live model
|
||||
// entry carrying `contextLength` must now surface as `limit.context`.
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: [{ id: "completely-unknown-model", contextLength: 262_144 }],
|
||||
});
|
||||
const entry = provider.models["completely-unknown-model"];
|
||||
assert.ok(entry.limit, "a live contextLength should produce a limit field even for ids absent from the static map");
|
||||
assert.equal(entry.limit!.context, 262_144);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider: a live model contextLength wins over the static default map", () => {
|
||||
// `cc/claude-opus-4-8` has a static default (1_000_000). A live entry carrying
|
||||
// a different contextLength must take precedence (live > modelContextLengths >
|
||||
// static defaults).
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: [{ id: "cc/claude-opus-4-8", contextLength: 524_288 }],
|
||||
});
|
||||
assert.equal(provider.models["cc/claude-opus-4-8"].limit!.context, 524_288);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider serialises limit.context to JSON", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
const round = JSON.parse(JSON.stringify(provider));
|
||||
for (const id of OMNIROUTE_DEFAULT_OPENCODE_MODELS) {
|
||||
const expectedContext = OMNIROUTE_DEFAULT_MODEL_CONTEXT_LENGTHS[id];
|
||||
assert.equal(
|
||||
round.models[id].limit?.context,
|
||||
expectedContext,
|
||||
`${id} should serialise limit.context=${expectedContext}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchLiveModels extracts context_length from snake_case field", async () => {
|
||||
const { url, close } = await startMockServer(() => ({
|
||||
data: [
|
||||
{ id: "cc/claude-opus-4-7", name: "Claude Opus 4.7", context_length: 200_000 },
|
||||
{ id: "gemini-3.1-pro-high", name: "Gemini 3.1 Pro", context_length: 1_000_000 },
|
||||
{ id: "no-context", name: "No Context" },
|
||||
],
|
||||
}));
|
||||
try {
|
||||
const models = await fetchLiveModels(url, "sk_test");
|
||||
const claude = models.find((m) => m.id === "cc/claude-opus-4-7");
|
||||
assert.ok(claude, "claude model should be present");
|
||||
assert.equal(claude!.contextLength, 200_000);
|
||||
const gemini = models.find((m) => m.id === "gemini-3.1-pro-high");
|
||||
assert.equal(gemini!.contextLength, 1_000_000);
|
||||
const noCtx = models.find((m) => m.id === "no-context");
|
||||
assert.equal(noCtx!.contextLength, undefined);
|
||||
} finally {
|
||||
close();
|
||||
}
|
||||
});
|
||||
|
||||
test("OMNIROUTE_DEFAULT_MODEL_CAPABILITIES covers every default model id", () => {
|
||||
for (const id of OMNIROUTE_DEFAULT_OPENCODE_MODELS) {
|
||||
const caps = OMNIROUTE_DEFAULT_MODEL_CAPABILITIES[id];
|
||||
assert.ok(caps, `default capabilities for ${id} missing`);
|
||||
assert.equal(caps.attachment, true, `${id} should default to attachment=true`);
|
||||
assert.equal(caps.tool_call, true, `${id} should default to tool_call=true`);
|
||||
}
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider emits default capability flags inline with the model entry", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
});
|
||||
const entry = provider.models["cc/claude-opus-4-8"];
|
||||
assert.equal(entry.name, "cc/claude-opus-4-8");
|
||||
assert.equal(entry.attachment, true);
|
||||
assert.equal(entry.reasoning, true);
|
||||
assert.equal(entry.temperature, true);
|
||||
assert.equal(entry.tool_call, true);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider modelCapabilities overrides defaults and merges per id", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
modelCapabilities: {
|
||||
"cc/claude-opus-4-7": { reasoning: false, label: "Opus (no thinking)" },
|
||||
},
|
||||
});
|
||||
const entry = provider.models["cc/claude-opus-4-7"];
|
||||
assert.equal(entry.name, "Opus (no thinking)");
|
||||
assert.equal(entry.reasoning, false);
|
||||
assert.equal(entry.attachment, true);
|
||||
assert.equal(entry.tool_call, true);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider applies capability overrides to non-default model ids", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["custom-model"],
|
||||
modelCapabilities: {
|
||||
"custom-model": { attachment: false, tool_call: true, label: "Custom" },
|
||||
},
|
||||
});
|
||||
const entry = provider.models["custom-model"];
|
||||
assert.equal(entry.name, "Custom");
|
||||
assert.equal(entry.attachment, false);
|
||||
assert.equal(entry.tool_call, true);
|
||||
assert.equal(entry.reasoning, undefined);
|
||||
assert.equal(entry.temperature, undefined);
|
||||
});
|
||||
|
||||
test("createOmniRouteProvider modelLabels still works when modelCapabilities omits label", () => {
|
||||
const provider = createOmniRouteProvider({
|
||||
baseURL: "http://localhost:20128",
|
||||
apiKey: "sk_omniroute",
|
||||
models: ["claude-opus-4-5-thinking"],
|
||||
modelLabels: { "claude-opus-4-5-thinking": "Opus 4.5 (legacy label)" },
|
||||
});
|
||||
assert.equal(provider.models["claude-opus-4-5-thinking"].name, "Opus 4.5 (legacy label)");
|
||||
});
|
||||
|
||||
test("createOmniRouteAgentBlock builds provider-prefixed entries per role", () => {
|
||||
const block = createOmniRouteAgentBlock({
|
||||
roles: {
|
||||
build: { modelId: "claude-sonnet-4-5-thinking", temperature: 0.2 },
|
||||
plan: { modelId: "claude-opus-4-5-thinking", top_p: 0.95 },
|
||||
review: { modelId: "gemini-3-flash", temperature: 0.0 },
|
||||
},
|
||||
});
|
||||
assert.equal(block.build.model, "omniroute/claude-sonnet-4-5-thinking");
|
||||
assert.equal(block.build.temperature, 0.2);
|
||||
assert.equal(block.plan.model, "omniroute/claude-opus-4-5-thinking");
|
||||
assert.equal(block.plan.top_p, 0.95);
|
||||
assert.equal(block.review.model, "omniroute/gemini-3-flash");
|
||||
assert.equal(block.review.temperature, 0.0);
|
||||
});
|
||||
|
||||
test("createOmniRouteAgentBlock omits optional fields when not supplied", () => {
|
||||
const block = createOmniRouteAgentBlock({
|
||||
roles: { build: { modelId: "claude-sonnet-4-5-thinking" } },
|
||||
});
|
||||
assert.equal(block.build.model, "omniroute/claude-sonnet-4-5-thinking");
|
||||
assert.ok(!("temperature" in block.build));
|
||||
assert.ok(!("top_p" in block.build));
|
||||
assert.ok(!("tools" in block.build));
|
||||
assert.ok(!("prompt" in block.build));
|
||||
});
|
||||
|
||||
test("createOmniRouteAgentBlock skips roles with empty modelId", () => {
|
||||
const block = createOmniRouteAgentBlock({
|
||||
roles: {
|
||||
build: { modelId: "claude-sonnet-4-5-thinking" },
|
||||
plan: { modelId: " " },
|
||||
review: { modelId: "" },
|
||||
},
|
||||
});
|
||||
assert.deepEqual(Object.keys(block), ["build"]);
|
||||
});
|
||||
|
||||
test("createOmniRouteAgentBlock emits tools as Record<string, boolean> per OC schema", () => {
|
||||
const block = createOmniRouteAgentBlock({
|
||||
roles: {
|
||||
build: {
|
||||
modelId: "claude-sonnet-4-5-thinking",
|
||||
tools: { edit: true, bash: true, web: false },
|
||||
prompt: "Edit files carefully.",
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(block.build.tools, { edit: true, bash: true, web: false });
|
||||
assert.equal(block.build.prompt, "Edit files carefully.");
|
||||
});
|
||||
|
||||
test("createOmniRouteAgentBlock filters invalid tool entries and omits empty maps", () => {
|
||||
const block = createOmniRouteAgentBlock({
|
||||
roles: {
|
||||
build: {
|
||||
modelId: "claude-sonnet-4-5-thinking",
|
||||
// @ts-expect-error — exercising runtime guard against bad input
|
||||
tools: { edit: true, bash: "yes", "": true, web: null },
|
||||
},
|
||||
plan: {
|
||||
modelId: "claude-opus-4-5-thinking",
|
||||
tools: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(block.build.tools, { edit: true });
|
||||
assert.ok(!("tools" in block.plan));
|
||||
});
|
||||
|
||||
test("createOmniRouteModesBlock builds provider-prefixed mode entries", () => {
|
||||
const block = createOmniRouteModesBlock({
|
||||
modes: {
|
||||
build: { modelId: "claude-sonnet-4-5-thinking", tools: { edit: true, bash: true } },
|
||||
plan: { modelId: "claude-opus-4-5-thinking", prompt: "Plan first, code later." },
|
||||
review: { modelId: "gemini-3-flash" },
|
||||
},
|
||||
});
|
||||
assert.equal(block.build.model, "omniroute/claude-sonnet-4-5-thinking");
|
||||
assert.deepEqual(block.build.tools, { edit: true, bash: true });
|
||||
assert.equal(block.plan.prompt, "Plan first, code later.");
|
||||
assert.equal(block.review.model, "omniroute/gemini-3-flash");
|
||||
});
|
||||
|
||||
test("createOmniRouteModesBlock skips modes with empty modelId", () => {
|
||||
const block = createOmniRouteModesBlock({
|
||||
modes: {
|
||||
build: { modelId: "claude-sonnet-4-5-thinking" },
|
||||
plan: { modelId: "" },
|
||||
},
|
||||
});
|
||||
assert.deepEqual(Object.keys(block), ["build"]);
|
||||
});
|
||||
|
||||
test("createOmniRouteModesBlock honours numeric overrides limited to OC schema", () => {
|
||||
const block = createOmniRouteModesBlock({
|
||||
modes: {
|
||||
build: {
|
||||
modelId: "claude-sonnet-4-5-thinking",
|
||||
temperature: 0.7,
|
||||
top_p: 0.9,
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.equal(block.build.temperature, 0.7);
|
||||
assert.equal(block.build.top_p, 0.9);
|
||||
});
|
||||
|
||||
// #3419 — soft-deprecation in favour of @omniroute/opencode-plugin. Guard the
|
||||
// deprecation notice so it can't be silently dropped while the package is kept
|
||||
// publishing (it still works; it is just no longer the recommended path).
|
||||
test("package is marked deprecated in favour of @omniroute/opencode-plugin (#3419)", () => {
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const pkg = JSON.parse(readFileSync(join(here, "..", "package.json"), "utf8"));
|
||||
assert.match(pkg.description, /DEPRECATED/);
|
||||
assert.match(pkg.description, /@omniroute\/opencode-plugin/);
|
||||
|
||||
const readme = readFileSync(join(here, "..", "README.md"), "utf8");
|
||||
assert.match(readme, /Deprecated/i);
|
||||
assert.match(readme, /@omniroute\/opencode-plugin/);
|
||||
});
|
||||
20
@omniroute/opencode-provider/tsconfig.json
Normal file
20
@omniroute/opencode-provider/tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022"],
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"isolatedModules": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src"
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["dist", "node_modules", "tests"]
|
||||
}
|
||||
18
@omniroute/opencode-provider/tsup.config.ts
Normal file
18
@omniroute/opencode-provider/tsup.config.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
export default defineConfig({
|
||||
entry: ["src/index.ts"],
|
||||
format: ["esm", "cjs"],
|
||||
dts: true,
|
||||
clean: true,
|
||||
sourcemap: false,
|
||||
splitting: false,
|
||||
treeshake: true,
|
||||
target: "node22",
|
||||
outDir: "dist",
|
||||
minify: false,
|
||||
});
|
||||
|
||||
// CJS consumers should prefer named imports (`require(pkg).createOmniRouteProvider`).
|
||||
// The `default` export is also exposed for ESM ergonomics, which makes tsup warn
|
||||
// about mixed exports — that's expected and harmless for this package.
|
||||
653
AGENTS.md
653
AGENTS.md
@@ -3,158 +3,585 @@
|
||||
## Project
|
||||
|
||||
Unified AI proxy/router — route any LLM through one endpoint. Multi-provider support
|
||||
(OpenAI, Anthropic, Gemini, DeepSeek, Groq, xAI, Mistral, Fireworks, Cohere, etc.)
|
||||
with **MCP Server** (16 tools for agent control) and **A2A v0.3 Protocol** (Agent-to-Agent orchestration).
|
||||
with **229 provider entries** (OpenAI, Anthropic, Gemini, DeepSeek, Groq, xAI, Mistral, Fireworks,
|
||||
Cohere, NVIDIA, Cerebras, Pollinations, Puter, Cloudflare AI, HuggingFace, DeepInfra,
|
||||
SambaNova, Meta Llama API, Moonshot AI, AI21 Labs, Databricks, Snowflake, and many more)
|
||||
with **MCP Server** (69 tools), **A2A v0.3 Protocol**, and **Electron desktop app**.
|
||||
|
||||
> **Live counts (v3.8.16)**: providers 229 · MCP tools 69 · MCP scopes 13 · A2A skills 6 ·
|
||||
> open-sse services 111 · routing strategies 15 · auto-combo scoring factors 12 ·
|
||||
> DB modules 76 · DB migrations 94 · base tables 17 · search providers 12 ·
|
||||
> i18n locales 42. **Refresh with `npm run check:docs-all`.**
|
||||
|
||||
## Doc Accuracy Discipline (read before writing any doc)
|
||||
|
||||
> **If `grep -rn "name" src/ open-sse/ bin/` returns nothing, the name does not exist. Do not document it.**
|
||||
|
||||
The recurring failure mode in AI-generated docs is _plausible-but-unverified specifics_.
|
||||
Every claim in a `.md` file under `docs/` should be verifiable against the source.
|
||||
|
||||
**Rules (enforced by `npm run check:fabricated-docs`):**
|
||||
|
||||
1. **Never state an API name, endpoint, path, CLI command, or env var without grepping for it first.**
|
||||
```bash
|
||||
grep -rn "theName" src/ open-sse/ bin/
|
||||
# 0 hits → do not document
|
||||
```
|
||||
2. **Never write a line count, file size, migration count, provider count, or strategy count from memory.**
|
||||
```bash
|
||||
wc -l <file> # exact line count
|
||||
ls <dir>/*.ts | wc -l # file count
|
||||
```
|
||||
3. **Every code example should be copy-pasted from real usage or actually run** — not synthesized.
|
||||
Link to a real call site (`path:line`) instead of inventing a signature.
|
||||
4. **Prefer citing real source (`file.ts:line`) over paraphrasing behavior** — verifiable and self-correcting.
|
||||
5. **A shorter doc that is 100% accurate beats a comprehensive one with fabrications.**
|
||||
Wrong docs cost more than missing docs, because people trust and act on them.
|
||||
|
||||
The script `scripts/check/check-fabricated-docs.mjs` extracts every route path, env var, hook
|
||||
name, function name, and file reference from `docs/**/*.md` and verifies each one against the
|
||||
codebase. Run it locally before pushing docs; it runs in CI via `npm run check:docs-all`.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Runtime**: Next.js 16 (App Router), Node.js, ES Modules
|
||||
- **Language**: TypeScript 5.9 (`src/`) + JavaScript (`open-sse/`)
|
||||
- **Runtime**: Next.js 16 (App Router), Node.js `>=20.20.2 <21`, `>=22.22.2 <23`, or `>=24.0.0 <25`, ES Modules (`"type": "module"`)
|
||||
- **Language**: TypeScript 5.9 (`src/`) + JavaScript (`open-sse/`, `electron/`)
|
||||
- **Database**: better-sqlite3 (SQLite) — `DATA_DIR` configurable, default `~/.omniroute/`
|
||||
- **Streaming**: SSE via `open-sse` internal package
|
||||
- **Streaming**: SSE via `open-sse` internal workspace package
|
||||
- **Styling**: Tailwind CSS v4
|
||||
- **Docker**: Multi-stage Dockerfile, 3 profiles (base / cli / host)
|
||||
- **i18n**: next-intl with 30 languages (`src/i18n/messages/`)
|
||||
- **i18n**: next-intl with 42 locales (`src/i18n/messages/`) — refresh with `ls src/i18n/messages/*.json | wc -l`
|
||||
- **Desktop**: Electron (cross-platform: Windows, macOS, Linux)
|
||||
- **Schemas**: Zod v4 for all API / MCP input validation
|
||||
|
||||
---
|
||||
|
||||
## Build, Lint, and Test Commands
|
||||
|
||||
| Command | Description |
|
||||
| ----------------------------------- | ------------------------------------------------------------------ |
|
||||
| `npm run dev` | Start Next.js dev server |
|
||||
| `npm run build` | Production build: `next build` → `.build/next/` + assemble `dist/` |
|
||||
| `npm run build:release` | Clean rebuild + HEAD sentinel (`dist/BUILD_SHA`) — use for deploy |
|
||||
| `npm run start` | Run production build |
|
||||
| `npm run build:cli` | Build CLI package |
|
||||
| `npm run lint` | ESLint on all source files |
|
||||
| `npm run typecheck:core` | TypeScript core type checking |
|
||||
| `npm run typecheck:noimplicit:core` | Strict checking (no implicit any) |
|
||||
| `npm run check` | Run lint + test |
|
||||
| `npm run check:cycles` | Check for circular dependencies |
|
||||
| `npm run electron:dev` | Run Electron app in dev mode |
|
||||
| `npm run electron:build` | Build Electron app for current OS |
|
||||
|
||||
**Build output layout:**
|
||||
|
||||
| Directory | Purpose | Gitignored |
|
||||
| --------- | -------------------------------------------------- | ---------- |
|
||||
| `src/` | Application source (TypeScript / TSX) | No |
|
||||
| `.build/` | Build intermediates (`distDir = .build/next`) | Yes |
|
||||
| `dist/` | Shippable bundle assembled by `assembleStandalone` | Yes |
|
||||
|
||||
The pipeline is a single `next build` pass — intermediates land in `.build/next/`, the
|
||||
assembled bundle in `dist/`. VPS deploys rsync `dist/` into the remote
|
||||
`/usr/lib/node_modules/omniroute/app/` directory (VPS image path is unchanged).
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# All tests (unit + vitest + ecosystem + e2e)
|
||||
npm run test:all
|
||||
|
||||
# Single test file (Node.js native test runner — most tests use this)
|
||||
node --import tsx/esm --test tests/unit/your-file.test.ts
|
||||
node --import tsx/esm --test tests/unit/plan3-p0.test.ts
|
||||
node --import tsx/esm --test tests/unit/fixes-p1.test.ts
|
||||
node --import tsx/esm --test tests/unit/security-fase01.test.ts
|
||||
|
||||
# Integration tests
|
||||
node --import tsx/esm --test tests/integration/*.test.ts
|
||||
|
||||
# Vitest (MCP server, autoCombo)
|
||||
npm run test:vitest
|
||||
|
||||
# E2E with Playwright
|
||||
npm run test:e2e
|
||||
|
||||
# Protocol clients E2E (MCP transports, A2A)
|
||||
npm run test:protocols:e2e
|
||||
|
||||
# Ecosystem compatibility tests
|
||||
npm run test:ecosystem
|
||||
|
||||
# Coverage (see CONTRIBUTING.md)
|
||||
npm run test:coverage
|
||||
```
|
||||
|
||||
**For authoritative coverage requirements, test execution, and PR gates, see [`CONTRIBUTING.md`](CONTRIBUTING.md#running-tests).**
|
||||
|
||||
---
|
||||
|
||||
## Code Style Guidelines
|
||||
|
||||
### Formatting (Prettier — enforced via lint-staged)
|
||||
|
||||
2 spaces · semicolons required · double quotes (`"`) · 100 char width · es5 trailing commas.
|
||||
Always run `prettier --write` on changed files.
|
||||
|
||||
### TypeScript
|
||||
|
||||
- **Target**: ES2022 · **Module**: `esnext` · **Resolution**: `bundler`
|
||||
- `strict: false` — prefer explicit types, don't rely on inference
|
||||
- Path aliases: `@/*` → `src/`, `@omniroute/open-sse` → `open-sse/`, `@omniroute/open-sse/*` → `open-sse/*`
|
||||
|
||||
### ESLint Rules
|
||||
|
||||
- **Security (error, everywhere)**: `no-eval`, `no-implied-eval`, `no-new-func`
|
||||
- **Relaxed in `open-sse/` and `tests/`**: `@typescript-eslint/no-explicit-any` = warn
|
||||
- React hooks rules and `@next/next/no-assign-module-variable` disabled in `open-sse/` and `tests/`
|
||||
|
||||
### Naming
|
||||
|
||||
| Element | Convention | Example |
|
||||
| ------------------- | -------------------------------- | ------------------------------------ |
|
||||
| Files | camelCase / kebab-case | `chatCore.ts`, `tokenHealthCheck.ts` |
|
||||
| React components | PascalCase | `Dashboard.tsx`, `ProviderCard.tsx` |
|
||||
| Functions/variables | camelCase | `getHealth()`, `switchCombo()` |
|
||||
| Constants | UPPER_SNAKE | `MAX_RETRIES`, `DEFAULT_TIMEOUT` |
|
||||
| Interfaces | PascalCase (`I` prefix optional) | `ProviderConfig` |
|
||||
| Enums | PascalCase (members too) | `LogLevel.Error` |
|
||||
|
||||
### Imports
|
||||
|
||||
- **Order**: external → internal (`@/`, `@omniroute/open-sse`) → relative (`./`, `../`)
|
||||
- **No barrel imports** from `localDb.ts` — import from the specific `db/` module instead
|
||||
|
||||
### Error Handling
|
||||
|
||||
- try/catch with specific error types; always log with context (pino logger)
|
||||
- Never silently swallow errors in SSE streams — use abort signals for cleanup
|
||||
- Return proper HTTP status codes (4xx client, 5xx server)
|
||||
|
||||
### Security
|
||||
|
||||
- **NEVER** commit API keys, secrets, or credentials
|
||||
- Validate all user inputs with Zod schemas
|
||||
- Auth middleware required on all API routes
|
||||
- Never log SQLite encryption keys
|
||||
- Sanitize user content (dompurify for HTML)
|
||||
- **Public upstream OAuth identifiers** (Gemini / Antigravity / Windsurf-style client_id/secret + Firebase Web keys extracted from public CLIs): use `resolvePublicCred()` from `open-sse/utils/publicCreds.ts`, **never** as string literals. Full pattern in `docs/security/PUBLIC_CREDS.md`.
|
||||
- **Error responses** (HTTP / SSE / executor / MCP): use `buildErrorBody()` or `sanitizeErrorMessage()` from `open-sse/utils/error.ts`, **never** put raw `err.stack` / `err.message` in a Response body. Full pattern in `docs/security/ERROR_SANITIZATION.md`.
|
||||
- **`exec()` / `spawn()` with runtime values**: pass via the `env` option, **never** string-interpolate paths/values into the script body. Reference: `src/mitm/cert/install.ts::updateNssDatabases`.
|
||||
- Prefer secure-by-default libraries when available — see [tldrsec/awesome-secure-defaults](https://github.com/tldrsec/awesome-secure-defaults) for the curated list (Helmet.js, DOMPurify, ssrf-req-filter, safe-regex, Google Tink, etc.).
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Data Layer (`src/lib/db/`)
|
||||
|
||||
All persistence uses SQLite through domain-specific modules:
|
||||
All persistence uses SQLite through **76 domain-specific modules** in `src/lib/db/`. Top modules:
|
||||
|
||||
| Module | Responsibility |
|
||||
| -------------- | ------------------------------------------ |
|
||||
| `core.ts` | SQLite engine, migrations, WAL, encryption |
|
||||
| `providers.ts` | Provider connections & nodes |
|
||||
| `models.ts` | Model aliases, MITM aliases, custom models |
|
||||
| `combos.ts` | Combo configurations |
|
||||
| `apiKeys.ts` | API key management & validation |
|
||||
| `settings.ts` | Settings, pricing, proxy config |
|
||||
| `backup.ts` | Backup / restore operations |
|
||||
- Core: `core.ts`, `migrationRunner.ts`, `encryption.ts`, `stateReset.ts`
|
||||
- Providers / catalog: `providers.ts`, `models.ts`, `providerLimits.ts`, `compressionAnalytics.ts`
|
||||
- Routing: `combos.ts`, `modelComboMappings.ts`, `domainState.ts`, `commandCodeAuth.ts`
|
||||
- Auth: `apiKeys.ts`, `secrets.ts`, `registeredKeys.ts`, `sessionAccountAffinity.ts`
|
||||
- Usage / billing: `quotaSnapshots.ts`, `creditBalance.ts`, `usage*.ts`, `compressionCacheStats.ts`
|
||||
- Storage: `backup.ts`, `cleanup.ts`, `jsonMigration.ts`, `healthCheck.ts`, `databaseSettings.ts`
|
||||
- Extension modules: `evals.ts`, `webhooks.ts`, `reasoningCache.ts`, `readCache.ts`, `tierConfig.ts`, `compressionCombos.ts`, `compressionScheduler.ts`, `batches.ts`, `files.ts`, `syncTokens.ts`, `proxies.ts`, `oneproxy.ts`, `upstreamProxy.ts`, `versionManager.ts`, `cliToolState.ts`, `prompts.ts`, `detailedLogs.ts`, `contextHandoffs.ts`, `compression.ts`, `stats.ts`
|
||||
|
||||
`src/lib/localDb.ts` is a **re-export layer only** — all 27+ consumers import from it,
|
||||
but the real logic lives in `src/lib/db/`.
|
||||
Live count: `ls src/lib/db/*.ts | wc -l` (currently 76). Drift detection: `npm run check:docs-counts`.
|
||||
Schema migrations live in `db/migrations/` (**94 files** as of v3.8.16) and run via `migrationRunner.ts`.
|
||||
`src/lib/localDb.ts` is a **re-export layer only** — never add logic there.
|
||||
|
||||
#### DB Internals
|
||||
|
||||
- **`core.ts`**: `getDbInstance()` returns a singleton `better-sqlite3` instance with WAL
|
||||
journaling. `SCHEMA_SQL` defines **17 base tables** (verify with `grep -c "CREATE TABLE" src/lib/db/core.ts` minus 1 for the bookkeeping `_omniroute_migrations` table). Helpers: `rowToCamel`, `encryptConnectionFields`.
|
||||
- **`migrationRunner.ts`**: Applies versioned SQL files from `db/migrations/` inside transactions.
|
||||
Tracks applied migrations in `_omniroute_migrations` table.
|
||||
- **Migrations**: 94 files (`001_initial_schema.sql` → `094_*.sql`).
|
||||
Each migration is idempotent and runs in a transaction. Live count: `ls src/lib/db/migrations/*.sql | wc -l`.
|
||||
- **Domain modules** import `getDbInstance()` from `core.ts` for all CRUD operations.
|
||||
Each module owns a specific table/set of tables (e.g., `providers.ts` → `provider_connections`,
|
||||
`combos.ts` → `combos`). Encryption helpers protect sensitive fields at rest.
|
||||
- **`localDb.ts`** re-exports all domain modules — consumers import from here for convenience.
|
||||
|
||||
### API Route Layer (`src/app/api/v1/`)
|
||||
|
||||
Next.js App Router routes — each follows a consistent pattern:
|
||||
|
||||
```
|
||||
Route → CORS preflight → Body validation (Zod) → Optional auth (extractApiKey/isValidApiKey)
|
||||
→ API key policy enforcement (enforceApiKeyPolicy) → Handler delegation (open-sse)
|
||||
```
|
||||
|
||||
| Route | Handler | Notes |
|
||||
| ------------------------------- | ------------------------- | ------------------------------------------------------------- |
|
||||
| `chat/completions/route.ts` | `handleChat()` | + prompt injection guard (clones request) |
|
||||
| `responses/route.ts` | `handleChat()` (unified) | Responses API format |
|
||||
| `embeddings/route.ts` | `handleEmbedding()` | Model listing + creation |
|
||||
| `images/generations/route.ts` | `handleImageGeneration()` | Model listing + creation |
|
||||
| `audio/transcriptions/route.ts` | audio handler | Multipart form data |
|
||||
| `audio/speech/route.ts` | TTS handler | Binary audio response |
|
||||
| `videos/generations/route.ts` | video handler | ComfyUI/SD WebUI |
|
||||
| `music/generations/route.ts` | music handler | ComfyUI workflows |
|
||||
| `moderations/route.ts` | moderation handler | Content safety |
|
||||
| `rerank/route.ts` | rerank handler | Document relevance |
|
||||
| `search/route.ts` | search handler | Web search (12 providers per `open-sse/handlers/search.ts:6`) |
|
||||
|
||||
**No global Next.js middleware file** — interception is route-specific. Auth is optional
|
||||
(controlled by `REQUIRE_API_KEY` env). Prompt injection guard is unique to chat completions.
|
||||
|
||||
### Request Pipeline (`open-sse/`)
|
||||
|
||||
| Handler | Role |
|
||||
| ----------------------- | ------------------------------------------- |
|
||||
| `chatCore.js` | Main chat completions proxy (SSE / non-SSE) |
|
||||
| `responsesHandler.js` | OpenAI Responses API compat |
|
||||
| `responseTranslator.js` | Format translation for Responses API |
|
||||
| `embeddings.js` | Embedding proxy |
|
||||
| `imageGeneration.js` | Image generation proxy |
|
||||
| `sseParser.js` | SSE stream parser |
|
||||
| `usageExtractor.js` | Token usage extraction from responses |
|
||||
The `open-sse/` workspace is the core streaming engine. Full request flow:
|
||||
|
||||
Translation between provider formats: `open-sse/translator/`
|
||||
```
|
||||
Client Request
|
||||
→ src/app/api/v1/.../route.ts (Next.js route)
|
||||
→ open-sse/handlers/chatCore.ts::handleChatCore()
|
||||
→ Semantic/signature cache check
|
||||
→ Rate limit check (rateLimitManager)
|
||||
→ Combo routing? → open-sse/services/combo.ts::handleComboChat()
|
||||
→ resolveComboTargets() → ordered ResolvedComboTarget[]
|
||||
→ For each target: handleSingleModel() (wraps chatCore)
|
||||
→ translateRequest() (open-sse/translator/)
|
||||
→ Convert source format (e.g., OpenAI) → target format (e.g., Claude)
|
||||
→ getExecutor() → provider-specific executor instance
|
||||
→ executor.execute() (BaseExecutor → DefaultExecutor or provider-specific)
|
||||
→ buildUrl() + buildHeaders() + transformRequest()
|
||||
→ fetch() to upstream provider
|
||||
→ Retry logic with exponential backoff
|
||||
→ Response translation back to client format
|
||||
→ If Responses API: responsesTransformer.ts TransformStream
|
||||
→ SSE stream or JSON response to client
|
||||
```
|
||||
|
||||
**Handlers** (`open-sse/handlers/`): `chatCore.ts`, `responsesHandler.ts`, `embeddings.ts`,
|
||||
`imageGeneration.ts`, `videoGeneration.ts`, `musicGeneration.ts`, `audioSpeech.ts`,
|
||||
`audioTranscription.ts`, `moderations.ts`, `rerank.ts`, `search.ts`.
|
||||
|
||||
**Upstream headers**: merged after default auth; same header name replaces executor value.
|
||||
**T5 intra-family fallback** recomputes headers using only the fallback model id.
|
||||
Forbidden header names: `src/shared/constants/upstreamHeaders.ts` — keep sanitize,
|
||||
Zod schemas, and unit tests aligned when editing.
|
||||
|
||||
### Provider Categories
|
||||
|
||||
- **Free** (4): Qoder AI, Qwen Code, Gemini CLI (deprecated), Kiro AI
|
||||
- **OAuth** (14): Claude Code, Antigravity, Codex, GitHub Copilot, Cursor, Kimi Coding, Kilo Code, Cline, Qwen (⚠️ free tier discontinued 2026-04-15), Kiro, Qoder, Gemini, Windsurf (v3.8), GitLab Duo (v3.8)
|
||||
- **API Key** (120+): OpenAI, Anthropic, Gemini, DeepSeek, Groq, xAI, Mistral, Perplexity,
|
||||
Together, Fireworks, Cerebras, Cohere, NVIDIA, Nebius, SiliconFlow, Hyperbolic,
|
||||
HuggingFace, OpenRouter, Vertex AI, Cloudflare AI, Scaleway, AI/ML API, Pollinations,
|
||||
Puter, Longcat, Alibaba, Kimi, Minimax, Blackbox, Synthetic, Kilo Gateway,
|
||||
Z.AI, GLM, Deepgram, AssemblyAI, ElevenLabs, Cartesia, PlayHT, Inworld,
|
||||
NanoBanana, SD WebUI, ComfyUI, Ollama Cloud, Perplexity Search, Serper, Brave, Exa,
|
||||
Tavily, OpenCode Zen/Go, Bailian Coding Plan, DeepInfra, Vercel AI Gateway,
|
||||
Lambda AI, SambaNova, nScale, OVHcloud AI, Baseten, PublicAI, Moonshot AI,
|
||||
Meta Llama API, v0 (Vercel), Morph, Featherless AI, FriendliAI, LlamaGate,
|
||||
Galadriel, Weights & Biases Inference, Volcengine, AI21 Labs, Venice.ai,
|
||||
Codestral, Upstage, Maritalk, Xiaomi MiMo, Inference.net, NanoGPT, Predibase,
|
||||
Bytez, Heroku AI, Databricks, Snowflake Cortex, GigaChat (Sber), CrofAI,
|
||||
AgentRouter, ChatGPT Web, Baidu Qianfan, AWS Polly, RunwayML, GitLab Duo,
|
||||
Amazon Q, Empower, Poe, and many more.
|
||||
- **Self-Hosted** (8+): LM Studio, vLLM, Lemonade, Llamafile, Triton, Docker Model Runner, Xinference, Oobabooga
|
||||
- **Custom**: OpenAI-compatible (`openai-compatible-*`) and Anthropic-compatible (`anthropic-compatible-*`) prefixes
|
||||
|
||||
Providers are registered in `src/shared/constants/providers.ts` with Zod validation at module load.
|
||||
|
||||
### Executors (`open-sse/executors/`)
|
||||
|
||||
Provider-specific request executors: `base.ts`, `default.ts`, `cursor.ts`, `codex.ts`,
|
||||
`antigravity.ts`, `github.ts`, `gemini-cli.ts`, `kiro.ts`, `qoder.ts`, `vertex.ts`,
|
||||
`cloudflare-ai.ts`, `opencode.ts`, `pollinations.ts`, `puter.ts`.
|
||||
|
||||
#### Executor Internals
|
||||
|
||||
- **`base.ts`** (`BaseExecutor`): Abstract base with `buildUrl()`, `buildHeaders()`,
|
||||
`transformRequest()`, retry logic (exponential backoff), and `execute()`. Subclasses
|
||||
override URL/header/transform methods for provider-specific behavior.
|
||||
- **`default.ts`** (`DefaultExecutor extends BaseExecutor`): Handles most OpenAI-compatible
|
||||
providers. Reads provider config from `providerRegistry.ts` to resolve base URL, auth
|
||||
header format, and request transformations.
|
||||
- **`getExecutor()`** (`executors/index.ts`): Factory that returns the correct executor
|
||||
instance based on provider ID. Provider-specific executors (Cursor, Codex, Vertex, etc.)
|
||||
override only what differs from the default.
|
||||
|
||||
### Translator (`open-sse/translator/`)
|
||||
|
||||
Translates between API formats (OpenAI-format ↔ Anthropic, Gemini, etc.).
|
||||
Includes request/response translators with helpers for image handling.
|
||||
|
||||
#### Translator Internals
|
||||
|
||||
- **`translator/index.ts`**: Exports `translateRequest()` and format constants. Called by
|
||||
`chatCore.ts` before executor dispatch.
|
||||
- **Flow**: `translateRequest(body, sourceFormat, targetFormat)` → detects source format
|
||||
(OpenAI, Anthropic, Gemini) → applies the matching translator module → returns
|
||||
transformed body ready for the target provider.
|
||||
- **Response translation** runs in reverse after upstream response, converting back to
|
||||
the client's expected format.
|
||||
|
||||
### Transformer (`open-sse/transformer/`)
|
||||
|
||||
`responsesTransformer.ts` — transforms Responses API format to/from Chat Completions format.
|
||||
|
||||
#### Transformer Internals
|
||||
|
||||
- **`createResponsesApiTransformStream()`**: Returns a `TransformStream` that converts
|
||||
Chat Completions SSE chunks (`data: {"choices":[...]}`) into Responses API SSE events
|
||||
(`response.output_item.added`, `response.output_text.delta`, etc.).
|
||||
- Used when the client sends a Responses API request: the request is internally converted
|
||||
to Chat Completions format, dispatched normally, and the response is piped through this
|
||||
transform stream before reaching the client.
|
||||
|
||||
### Services (`open-sse/services/`)
|
||||
|
||||
111 service modules in `open-sse/services/` (top-level only; 171 including sub-dirs like `autoCombo/` and `compression/`). Refresh: `ls open-sse/services/*.ts | wc -l`. Key modules:
|
||||
`combo.ts` (routing engine), `usage.ts`, `tokenRefresh.ts`,
|
||||
`rateLimitManager.ts`, `accountFallback.ts`, `sessionManager.ts`, `wildcardRouter.ts`,
|
||||
`autoCombo/`, `intentClassifier.ts`, `taskAwareRouter.ts`, `thinkingBudget.ts`,
|
||||
`contextManager.ts`, `modelDeprecation.ts`, `modelFamilyFallback.ts`,
|
||||
`emergencyFallback.ts`, `workflowFSM.ts`, `backgroundTaskDetector.ts`, `ipFilter.ts`,
|
||||
`signatureCache.ts`, `volumeDetector.ts`, `contextHandoff.ts`, `compression/` (prompt
|
||||
compression pipeline), and more.
|
||||
|
||||
#### Prompt Compression Pipeline (`compression/`)
|
||||
|
||||
Modular prompt compression that runs proactively before the existing reactive context manager.
|
||||
|
||||
- **`strategySelector.ts`**: Selects compression mode based on config, compression combo assignments,
|
||||
combo overrides, auto-trigger thresholds, and defaults. Priority: assigned compression combo >
|
||||
combo override > auto-trigger > default mode > off.
|
||||
- **`lite.ts`**: 5 lite-mode techniques: `collapseWhitespace`, `dedupSystemPrompt`,
|
||||
`compressToolResults`, `removeRedundantContent`, `replaceImageUrls`. Target: 10-15% savings at
|
||||
<1ms latency.
|
||||
- **`caveman.ts` / `cavemanRules.ts`**: Caveman-style semantic condensation backed by built-in
|
||||
rules plus file-loaded language packs under `compression/rules/`.
|
||||
- **`engines/rtk/`**: Rule-based terminal/tool-output compression inspired by RTK patterns. Detects
|
||||
command output classes, applies JSON filter packs, deduplicates repeated lines, strips ANSI/code
|
||||
noise, and preserves errors/actionable context. The RTK JSON DSL supports replace,
|
||||
match-output short-circuit, strip/keep, per-line truncation, head/tail/max-line truncation,
|
||||
inline tests, trust-gated project/global custom filters, and optional redacted raw-output
|
||||
retention for authenticated recovery.
|
||||
- **`engines/registry.ts`**: Registers engines (`caveman`, `rtk`) and powers stacked pipelines.
|
||||
- **`stats.ts`**: Per-request compression stats tracking (original tokens, compressed tokens,
|
||||
savings %, techniques used, engine breakdown, compression combo id).
|
||||
- **`types.ts`**: `CompressionMode` (off/lite/standard/aggressive/ultra/rtk/stacked),
|
||||
`CompressionConfig`, `CompressionStats`, `CompressionResult`.
|
||||
- DB settings in `src/lib/db/compression.ts`, compression combos in
|
||||
`src/lib/db/compressionCombos.ts`, API routes under `src/app/api/settings/compression/`,
|
||||
`src/app/api/context/*`, and preview/language-pack routes under `src/app/api/compression/*`.
|
||||
|
||||
#### Combo Routing Engine (`combo.ts`)
|
||||
|
||||
- **`handleComboChat()`**: Entry point for combo-routed requests. Receives the combo config
|
||||
and iterates through targets in order until one succeeds or all fail.
|
||||
- **`resolveComboTargets()`**: Expands a combo configuration into an ordered array of
|
||||
`ResolvedComboTarget[]`, each specifying provider + model + account + credentials.
|
||||
- **Strategies** (15): priority, weighted, fill-first, round-robin, P2C, random, least-used, reset-aware (v3.8),
|
||||
reset-window, cost-optimized, strict-random, auto, lkgp, context-optimized, context-relay. Source: `ROUTING_STRATEGY_VALUES` in `src/shared/constants/routingStrategies.ts`.
|
||||
- Each target calls **`handleSingleModel()`** which wraps `handleChatCore()` with
|
||||
per-target error handling and circuit breaker checks.
|
||||
|
||||
### Domain Layer (`src/domain/`)
|
||||
|
||||
Policy engine modules: `policyEngine.ts`, `comboResolver.ts`, `costRules.ts`,
|
||||
`degradation.ts`, `fallbackPolicy.ts`, `lockoutPolicy.ts`, `modelAvailability.ts`,
|
||||
`providerExpiration.ts`, `quotaCache.ts`, `responses.ts`, `configAudit.ts`.
|
||||
|
||||
### MCP Server (`open-sse/mcp-server/`)
|
||||
|
||||
16 tools for AI agent control via **3 transport modes**:
|
||||
- **stdio** — Local IDE integration (Claude Desktop, Cursor, VS Code)
|
||||
- **SSE** — Remote Server-Sent Events at `/api/mcp/sse`
|
||||
- **Streamable HTTP** — Modern bidirectional HTTP at `/api/mcp/stream`
|
||||
69 tools across 10 tool files (advancedTools: 5, agentSkillTools: 3, compressionTools: 5, gamificationTools: 8, memoryTools: 3, notionTools: 6, obsidianTools: 22, pluginTools: 8, poolTools: 5, skillTools: 4), 3 transports (stdio / SSE / Streamable HTTP). Scoped auth (13 scopes — see `OMNIROUTE_MCP_SCOPES` in `open-sse/mcp-server/README.md:51`), Zod schemas. See [`docs/frameworks/MCP-SERVER.md`](docs/frameworks/MCP-SERVER.md).
|
||||
|
||||
HTTP transports run in-process via `httpTransport.ts` singleton using `WebStandardStreamableHTTPServerTransport`.
|
||||
**Core tools** (20): get_health, list_combos, get_combo_metrics, switch_combo, check_quota,
|
||||
route_request, cost_report, list_models_catalog, web_search, simulate_route, set_budget_guard,
|
||||
set_routing_strategy, set_resilience_profile, test_combo, get_provider_metrics,
|
||||
best_combo_for_task, explain_route, get_session_snapshot, db_health_check, sync_pricing.
|
||||
|
||||
| Category | Tools |
|
||||
| ---------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Essential | `get_health`, `list_combos`, `get_combo_metrics`, `switch_combo`, `check_quota`, `route_request`, `cost_report`, `list_models_catalog` |
|
||||
| Advanced | `simulate_route`, `set_budget_guard`, `set_resilience_profile`, `test_combo`, `get_provider_metrics`, `best_combo_for_task`, `explain_route`, `get_session_snapshot` |
|
||||
**Cache tools** (2): cache_stats, cache_flush.
|
||||
|
||||
- Scoped authorization (9 scopes), audit logging, Zod schemas
|
||||
- IDE configs for Claude Desktop, Cursor, VS Code Copilot
|
||||
**Compression tools** (5): compression_status, compression_configure, set_compression_engine,
|
||||
list_compression_combos, compression_combo_stats.
|
||||
|
||||
**1proxy tools** (3): oneproxy_fetch, oneproxy_rotate, oneproxy_stats.
|
||||
|
||||
**Memory tools** (3): memory_search, memory_add, memory_clear.
|
||||
|
||||
**Skill tools** (4): skills_list, skills_enable, skills_execute, skills_executions.
|
||||
|
||||
#### MCP Internals
|
||||
|
||||
- **Tool registration**: Each tool is an object with `{ name, description, inputSchema: ZodSchema,
|
||||
handler: async (args) => {...} }`. Zod validates inputs before the handler fires.
|
||||
- **`createMcpServer()`** and **`startMcpStdio()`** exported from `mcp-server/index.ts`.
|
||||
`createMcpServer()` wires all tool sets; `startMcpStdio()` launches the stdio transport.
|
||||
- **Transports**: stdio (CLI `omniroute --mcp`), SSE (`/api/mcp/sse`), Streamable HTTP
|
||||
(`/api/mcp/stream`). All share the same tool/scope engine.
|
||||
- **Scopes** (13): Control which tool categories an API key can access. Enforcement happens
|
||||
before handler dispatch.
|
||||
- **Audit**: Every tool invocation is logged to SQLite (`mcp_audit` table) with tool name,
|
||||
args, success/failure, API key attribution, and timestamp.
|
||||
|
||||
### A2A Server (`src/lib/a2a/`)
|
||||
|
||||
Agent-to-Agent v0.3 protocol:
|
||||
JSON-RPC 2.0, SSE streaming, Task Manager with TTL cleanup.
|
||||
Agent Card at `/.well-known/agent.json`.
|
||||
Skills (6): `smartRouting.ts`, `quotaManagement.ts`, `providerDiscovery.ts`, `costAnalysis.ts`, `healthReport.ts`, `listCapabilities.ts`.
|
||||
|
||||
- JSON-RPC 2.0: `message/send`, `message/stream`, `tasks/get`, `tasks/cancel`
|
||||
- Agent Card at `/.well-known/agent.json`
|
||||
- Skills: `smart-routing`, `quota-management`
|
||||
- SSE streaming with 15s heartbeat
|
||||
- Task Manager with state machine and TTL-based cleanup
|
||||
#### A2A Internals
|
||||
|
||||
### Auto-Combo Engine (`open-sse/services/autoCombo/`)
|
||||
- **`taskManager.ts`**: State machine lifecycle for tasks: `submitted → working →
|
||||
completed | failed | canceled`. Tasks have TTL and are cleaned up automatically.
|
||||
- **JSON-RPC methods**: `message/send` (sync), `message/stream` (SSE), `tasks/get`,
|
||||
`tasks/cancel`. Dispatched via `POST /a2a`.
|
||||
- **Skills**: Registered in a DB-backed registry. Each skill receives task context
|
||||
(messages, metadata) and returns structured results. `quotaManagement.ts` summarizes
|
||||
quota; `smartRouting.ts` recommends routing decisions.
|
||||
- **Agent Card**: `/.well-known/agent.json` exposes capabilities, skills, and metadata
|
||||
for client auto-discovery.
|
||||
|
||||
Self-healing routing optimization:
|
||||
- 6-factor scoring, 4 mode packs, bandit exploration
|
||||
- Progressive cooldown, probe-based re-admission
|
||||
### ACP Module (`src/lib/acp/`)
|
||||
|
||||
### Dashboard (`src/app/(dashboard)/`)
|
||||
Agent Communication Protocol registry and manager.
|
||||
|
||||
| Page | Description |
|
||||
| ---------------------------- | -------------------------------------------------------------- |
|
||||
| `/dashboard` | Home with quick start, provider overview |
|
||||
| `/dashboard/endpoint` | **Endpoints** (tabbed): Endpoint Proxy, MCP, A2A, API Endpoints |
|
||||
| `/dashboard/providers` | Provider management and connections |
|
||||
| `/dashboard/combos` | Combo configurations with routing strategies |
|
||||
| `/dashboard/logs` | Request, Proxy, Audit, Console logs (tabbed) |
|
||||
| `/dashboard/analytics` | Usage analytics and evaluations |
|
||||
| `/dashboard/costs` | Cost tracking and breakdown |
|
||||
| `/dashboard/health` | Uptime, circuit breakers, latency |
|
||||
| `/dashboard/cli-tools` | CLI tool integrations (Claude, Codex, Antigravity, etc.) |
|
||||
| `/dashboard/media` | Image, Video, Music generation playground |
|
||||
| `/dashboard/settings` | System settings with multiple tabs |
|
||||
| `/dashboard/api-manager` | API key management with model permissions |
|
||||
### Memory System (`src/lib/memory/`)
|
||||
|
||||
### OAuth & Tokens (`src/lib/oauth/`)
|
||||
Extraction, injection, retrieval, summarization, and store modules for persistent
|
||||
conversational memory across sessions.
|
||||
|
||||
18 modules handling OAuth flows, token refresh, and provider credentials.
|
||||
Default credentials are hardcoded in `src/lib/oauth/constants/oauth.ts`,
|
||||
overridable via env vars or `data/provider-credentials.json`.
|
||||
### Skills System (`src/lib/skills/`)
|
||||
|
||||
### Supporting Systems
|
||||
Extensible skill framework: registry, executor, sandbox, built-in skills,
|
||||
custom skill support, interception, and injection.
|
||||
|
||||
| System | Location |
|
||||
| -------------------------- | ------------------------------------------------- |
|
||||
| Usage tracking & analytics | `src/lib/usageDb.ts`, `src/lib/usageAnalytics.ts` |
|
||||
| Token health checks | `src/lib/tokenHealthCheck.ts` |
|
||||
| Cloud sync | `src/lib/cloudSync.ts` |
|
||||
| Proxy logging | `src/lib/proxyLogger.ts` |
|
||||
| Data paths resolution | `src/lib/dataPaths.ts` |
|
||||
#### Skills Internals
|
||||
|
||||
- **`registry.ts`**: DB-backed skill registration and discovery. Skills have metadata
|
||||
(name, description, version, enabled status) stored in SQLite.
|
||||
- **`executor.ts`**: Execution engine with configurable timeout and retry logic.
|
||||
Receives skill name + input, looks up the skill, runs it in the sandbox.
|
||||
- **`sandbox.ts`**: Isolation layer for custom (user-provided) skills. Limits resource
|
||||
access and execution time.
|
||||
- **Built-in skills**: Ship with OmniRoute (e.g., quota management, routing). Located
|
||||
alongside the registry.
|
||||
- **Interception/Injection**: Skills can intercept requests in the pipeline (pre/post
|
||||
processing) or inject context into prompts.
|
||||
|
||||
### Compliance (`src/lib/compliance/`)
|
||||
|
||||
Policy index for compliance enforcement.
|
||||
|
||||
### MITM Proxy (`src/mitm/`)
|
||||
|
||||
MITM proxy capability with certificate management, DNS handling, and target routing.
|
||||
|
||||
### Middleware (`src/middleware/`)
|
||||
|
||||
Request middleware including `promptInjectionGuard.ts`.
|
||||
|
||||
### Guardrails (`src/lib/guardrails/`)
|
||||
|
||||
Hot-reloadable guardrails framework (3 built-in: pii-masker, prompt-injection, vision-bridge). Fail-open; per-request opt-out via header. See [`docs/security/GUARDRAILS.md`](docs/security/GUARDRAILS.md).
|
||||
|
||||
### Cloud Agents (`src/lib/cloudAgent/`)
|
||||
|
||||
`CloudAgentBase` abstract class + 3 agents (codex-cloud, devin, jules). Tasks persisted in `cloud_agent_tasks`; management auth required. See [`docs/frameworks/CLOUD_AGENT.md`](docs/frameworks/CLOUD_AGENT.md).
|
||||
|
||||
### Evals (`src/lib/evals/`)
|
||||
|
||||
Generic eval framework: `evalRunner.ts`, `runtime.ts`. Targets: combo / model / suite-default. See [`docs/frameworks/EVALS.md`](docs/frameworks/EVALS.md).
|
||||
|
||||
### Webhooks (`src/lib/webhookDispatcher.ts`)
|
||||
|
||||
HMAC-signed delivery, exponential backoff, auto-disable after 10 failures. 7 event types. See [`docs/frameworks/WEBHOOKS.md`](docs/frameworks/WEBHOOKS.md).
|
||||
|
||||
### Authorization Pipeline (`src/server/authz/`)
|
||||
|
||||
`classify → policies → enforce`. 3 route classes (PUBLIC / CLIENT_API / MANAGEMENT). See [`docs/architecture/AUTHZ_GUIDE.md`](docs/architecture/AUTHZ_GUIDE.md).
|
||||
|
||||
### Reasoning Replay (`src/lib/db/reasoningCache.ts` + `open-sse/services/reasoningCache.ts`)
|
||||
|
||||
Hybrid in-memory + SQLite cache for `reasoning_content`. Re-injects on multi-turn for strict providers (DeepSeek V4, Kimi K2, Qwen-Thinking, GLM, xiaomi-mimo). See [`docs/routing/REASONING_REPLAY.md`](docs/routing/REASONING_REPLAY.md).
|
||||
|
||||
### Tunnels (`src/lib/{cloudflaredTunnel,ngrokTunnel}.ts` + `src/app/api/tunnels/`)
|
||||
|
||||
Cloudflare Quick/Named, ngrok, Tailscale Funnel. See [`docs/ops/TUNNELS_GUIDE.md`](docs/ops/TUNNELS_GUIDE.md).
|
||||
|
||||
### Adding a New Provider
|
||||
|
||||
1. Register in `src/shared/constants/providers.ts`
|
||||
2. Add executor in `open-sse/executors/`
|
||||
3. Add translator rules in `open-sse/translator/` (if non-OpenAI format)
|
||||
2. Add executor in `open-sse/executors/` (if custom logic needed)
|
||||
3. Add translator in `open-sse/translator/` (if non-OpenAI format)
|
||||
4. Add OAuth config in `src/lib/oauth/constants/oauth.ts` (if OAuth-based)
|
||||
5. Add models in `open-sse/config/providerRegistry.ts`
|
||||
|
||||
---
|
||||
|
||||
## Subdirectory AGENTS.md Files
|
||||
|
||||
- **[`open-sse/AGENTS.md`](open-sse/AGENTS.md)** — Streaming engine, request pipeline, handlers, and executors
|
||||
- **[`src/lib/db/AGENTS.md`](src/lib/db/AGENTS.md)** — SQLite persistence, domain modules, migrations
|
||||
- **[`open-sse/services/AGENTS.md`](open-sse/services/AGENTS.md)** — Routing engine, combo resolution, strategy selection
|
||||
|
||||
## Reference Documentation (docs/)
|
||||
|
||||
For any non-trivial change, read the matching deep-dive first:
|
||||
|
||||
| Area | Doc |
|
||||
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Repo navigation | [`docs/architecture/REPOSITORY_MAP.md`](docs/architecture/REPOSITORY_MAP.md) |
|
||||
| Architecture | [`docs/architecture/ARCHITECTURE.md`](docs/architecture/ARCHITECTURE.md) |
|
||||
| Engineering reference | [`docs/architecture/CODEBASE_DOCUMENTATION.md`](docs/architecture/CODEBASE_DOCUMENTATION.md) |
|
||||
| Auto-Combo (12-factor, 15 strategies) | [`docs/routing/AUTO-COMBO.md`](docs/routing/AUTO-COMBO.md) |
|
||||
| Resilience (3 layers) | [`docs/architecture/RESILIENCE_GUIDE.md`](docs/architecture/RESILIENCE_GUIDE.md) |
|
||||
| Skills | [`docs/frameworks/SKILLS.md`](docs/frameworks/SKILLS.md) |
|
||||
| Memory | [`docs/frameworks/MEMORY.md`](docs/frameworks/MEMORY.md) |
|
||||
| Cloud agents | [`docs/frameworks/CLOUD_AGENT.md`](docs/frameworks/CLOUD_AGENT.md) |
|
||||
| Guardrails | [`docs/security/GUARDRAILS.md`](docs/security/GUARDRAILS.md) |
|
||||
| Evals | [`docs/frameworks/EVALS.md`](docs/frameworks/EVALS.md) |
|
||||
| Compliance | [`docs/security/COMPLIANCE.md`](docs/security/COMPLIANCE.md) |
|
||||
| Webhooks | [`docs/frameworks/WEBHOOKS.md`](docs/frameworks/WEBHOOKS.md) |
|
||||
| Authz | [`docs/architecture/AUTHZ_GUIDE.md`](docs/architecture/AUTHZ_GUIDE.md) |
|
||||
| Stealth | [`docs/security/STEALTH_GUIDE.md`](docs/security/STEALTH_GUIDE.md) |
|
||||
| Reasoning replay | [`docs/routing/REASONING_REPLAY.md`](docs/routing/REASONING_REPLAY.md) |
|
||||
| Agent protocols (A2A / ACP / Cloud) | [`docs/frameworks/AGENT_PROTOCOLS_GUIDE.md`](docs/frameworks/AGENT_PROTOCOLS_GUIDE.md) |
|
||||
| MCP server | [`docs/frameworks/MCP-SERVER.md`](docs/frameworks/MCP-SERVER.md) |
|
||||
| A2A server | [`docs/frameworks/A2A-SERVER.md`](docs/frameworks/A2A-SERVER.md) |
|
||||
| API reference | [`docs/reference/API_REFERENCE.md`](docs/reference/API_REFERENCE.md) + [`docs/reference/openapi.yaml`](docs/reference/openapi.yaml) |
|
||||
| Provider catalog (auto-generated) | [`docs/reference/PROVIDER_REFERENCE.md`](docs/reference/PROVIDER_REFERENCE.md) |
|
||||
| Tunnels | [`docs/ops/TUNNELS_GUIDE.md`](docs/ops/TUNNELS_GUIDE.md) |
|
||||
| Electron desktop | [`docs/guides/ELECTRON_GUIDE.md`](docs/guides/ELECTRON_GUIDE.md) |
|
||||
| Release flow | [`docs/ops/RELEASE_CHECKLIST.md`](docs/ops/RELEASE_CHECKLIST.md) |
|
||||
|
||||
---
|
||||
|
||||
## Fork / Upstream Workflow
|
||||
|
||||
This repository is a fork of `diegosouzapw/OmniRoute`. Keep fork-only operational
|
||||
changes (for example GHCR image publishing, personal deployment workflows, or local
|
||||
automation) out of upstream contribution PRs.
|
||||
|
||||
When preparing a PR for upstream, always start the work branch from `upstream/main`,
|
||||
not from this fork's `main`:
|
||||
|
||||
```bash
|
||||
git fetch upstream
|
||||
git switch -c <branch-name> upstream/main
|
||||
```
|
||||
|
||||
Only cherry-pick or reapply the changes intended for the upstream PR.
|
||||
|
||||
---
|
||||
|
||||
## Review Focus
|
||||
|
||||
### Security
|
||||
|
||||
- No hardcoded API keys or secrets in commits
|
||||
- Auth middleware on all API routes
|
||||
- Input validation on user-facing endpoints (Zod schemas)
|
||||
- SQLite encryption key must not be logged
|
||||
|
||||
### Architecture
|
||||
|
||||
- DB operations go through `src/lib/db/` modules, never raw SQL in routes
|
||||
- Provider requests flow through `open-sse/handlers/`
|
||||
- Translations use `open-sse/translator/` modules
|
||||
- `localDb.ts` is re-exports only — add new functions to the proper `db/*.ts` module
|
||||
- MCP and A2A pages are embedded as tabs inside `/dashboard/endpoint`, not standalone routes
|
||||
|
||||
### Code Quality
|
||||
|
||||
- Consistent error handling with try/catch
|
||||
- Proper HTTP status codes
|
||||
- No memory leaks in SSE streams (abort signals, cleanup)
|
||||
- Rate limit headers must be parsed correctly
|
||||
- All API inputs validated with Zod schemas
|
||||
|
||||
### Docker
|
||||
|
||||
- Dockerfile has two targets: `runner-base` and `runner-cli`
|
||||
- `docker-compose.yml` — development (3 profiles)
|
||||
- `docker-compose.prod.yml` — isolated production instance (port 20130)
|
||||
- Data persists in named volumes (`omniroute-data` / `omniroute-prod-data`)
|
||||
|
||||
### Review Mode
|
||||
|
||||
- Provide analysis and suggestions only
|
||||
- Focus on bugs, security, performance, and best practices
|
||||
- **DB ops** go through `src/lib/db/` modules, never raw SQL in routes
|
||||
- **Provider requests** flow through `open-sse/handlers/`
|
||||
- **MCP/A2A pages** are tabs inside `/dashboard/endpoint`, not standalone routes
|
||||
- **No memory leaks** in SSE streams (abort signals, cleanup)
|
||||
- **Rate limit headers** must be parsed correctly
|
||||
- All API inputs validated with **Zod schemas**
|
||||
- **Provider constants** validated at module load via Zod (`src/shared/validation/providerSchema.ts`)
|
||||
- **Pricing data** syncs from LiteLLM via `src/lib/pricingSync.ts`
|
||||
- **Memory/Skills** are cross-cutting: affect MCP tools, request pipeline, and A2A skills
|
||||
- **⛔ NEVER close a contributor's PR** after using their code — always merge via GitHub so they get credit. See `.agents/workflows/review-prs.md` for full policy.
|
||||
|
||||
7450
CHANGELOG.md
7450
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
453
CLAUDE.md
Normal file
453
CLAUDE.md
Normal file
@@ -0,0 +1,453 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
npm install # Install deps (auto-generates .env from .env.example)
|
||||
npm run dev # Dev server at http://localhost:20128
|
||||
npm run build # Production build (Next.js 16 standalone)
|
||||
npm run lint # ESLint (0 errors expected; warnings are pre-existing)
|
||||
npm run typecheck:core # TypeScript check (should be clean)
|
||||
npm run typecheck:noimplicit:core # Strict check (no implicit any)
|
||||
npm run test:coverage # Unit tests + coverage gate (60/60/60/60 — statements/lines/functions/branches)
|
||||
npm run check # lint + test combined
|
||||
npm run check:cycles # Detect circular dependencies
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
# Single test file (Node.js native test runner — most tests)
|
||||
node --import tsx/esm --test tests/unit/your-file.test.ts
|
||||
|
||||
# Vitest (MCP server, autoCombo, cache)
|
||||
npm run test:vitest
|
||||
|
||||
# All suites
|
||||
npm run test:all
|
||||
```
|
||||
|
||||
For full test matrix, see `CONTRIBUTING.md` → "Running Tests". For deep architecture, see `AGENTS.md`.
|
||||
|
||||
---
|
||||
|
||||
## Project at a Glance
|
||||
|
||||
**OmniRoute** — unified AI proxy/router. One endpoint, 160+ LLM providers, auto-fallback.
|
||||
|
||||
| Layer | Location | Purpose |
|
||||
| ------------- | ----------------------- | ------------------------------------------------------------------ |
|
||||
| API Routes | `src/app/api/v1/` | Next.js App Router — entry points |
|
||||
| Handlers | `open-sse/handlers/` | Request processing (chat, embeddings, etc) |
|
||||
| Executors | `open-sse/executors/` | Provider-specific HTTP dispatch |
|
||||
| Translators | `open-sse/translator/` | Format conversion (OpenAI↔Claude↔Gemini) |
|
||||
| Transformer | `open-sse/transformer/` | Responses API ↔ Chat Completions |
|
||||
| Services | `open-sse/services/` | Combo routing, rate limits, caching, etc |
|
||||
| Database | `src/lib/db/` | SQLite domain modules (45+ files, 55 migrations) |
|
||||
| Domain/Policy | `src/domain/` | Policy engine, cost rules, fallback logic |
|
||||
| MCP Server | `open-sse/mcp-server/` | 43 tools (30 base + 3 memory + 4 skills + 6 notion), 3 transports, ~13 scopes |
|
||||
| A2A Server | `src/lib/a2a/` | JSON-RPC 2.0 agent protocol |
|
||||
| Skills | `src/lib/skills/` | Extensible skill framework |
|
||||
| Memory | `src/lib/memory/` | Persistent conversational memory |
|
||||
|
||||
Monorepo: `src/` (Next.js 16 app), `open-sse/` (streaming engine workspace), `electron/` (desktop app), `tests/`, `bin/` (CLI entry point).
|
||||
|
||||
---
|
||||
|
||||
## Request Pipeline
|
||||
|
||||
```
|
||||
Client → /v1/chat/completions (Next.js route)
|
||||
→ CORS → Zod validation → auth? → policy check → prompt injection guard
|
||||
→ handleChatCore() [open-sse/handlers/chatCore.ts]
|
||||
→ cache check → rate limit → combo routing?
|
||||
→ resolveComboTargets() → handleSingleModel() per target
|
||||
→ translateRequest() → getExecutor() → executor.execute()
|
||||
→ fetch() upstream → retry w/ backoff
|
||||
→ response translation → SSE stream or JSON
|
||||
→ If Responses API: responsesTransformer.ts TransformStream
|
||||
```
|
||||
|
||||
API routes follow a consistent pattern: `Route → CORS preflight → Zod body validation → Optional auth (extractApiKey/isValidApiKey) → API key policy enforcement → Handler delegation (open-sse)`. No global Next.js middleware — interception is route-specific.
|
||||
|
||||
**Combo routing** (`open-sse/services/combo.ts`): 14 strategies (priority, weighted, fill-first, round-robin, P2C, random, least-used, cost-optimized, reset-aware, strict-random, auto, lkgp, context-optimized, context-relay). Each target calls `handleSingleModel()` which wraps `handleChatCore()` with per-target error handling and circuit breaker checks. See `docs/routing/AUTO-COMBO.md` for the 9-factor Auto-Combo scoring and `docs/architecture/RESILIENCE_GUIDE.md` for the 3 resilience layers.
|
||||
|
||||
---
|
||||
|
||||
## Resilience Runtime State
|
||||
|
||||
OmniRoute has three related but distinct temporary-failure mechanisms. Keep their
|
||||
scope separate when debugging routing behavior. See the
|
||||
[3-layer resilience diagram](./docs/diagrams/exported/resilience-3layers.svg)
|
||||
(source: [docs/diagrams/resilience-3layers.mmd](./docs/diagrams/resilience-3layers.mmd))
|
||||
for an at-a-glance map.
|
||||
|
||||
### Provider Circuit Breaker
|
||||
|
||||
**Scope**: whole provider, e.g. `glm`, `openai`, `anthropic`.
|
||||
|
||||
**Purpose**: stop sending traffic to a provider that is repeatedly failing at the
|
||||
upstream/service level, so one unhealthy provider does not slow down every request.
|
||||
|
||||
**Implementation**:
|
||||
|
||||
- Core class: `src/shared/utils/circuitBreaker.ts`
|
||||
- Chat gate/execution wiring: `src/sse/handlers/chatHelpers.ts`, `src/sse/handlers/chat.ts`
|
||||
- Runtime status API: `src/app/api/monitoring/health/route.ts`
|
||||
- Shared wrappers: `open-sse/services/accountFallback.ts`
|
||||
- Persisted state table: `domain_circuit_breakers`
|
||||
|
||||
**States**:
|
||||
|
||||
- `CLOSED`: normal traffic is allowed.
|
||||
- `OPEN`: provider is temporarily blocked; callers get a provider-circuit-open response
|
||||
or combo routing skips to another target.
|
||||
- `HALF_OPEN`: reset timeout has elapsed; allow a probe request. Success closes the
|
||||
breaker, failure opens it again.
|
||||
|
||||
**Defaults** (`open-sse/config/constants.ts`):
|
||||
|
||||
- OAuth providers: threshold `3`, reset timeout `60s`.
|
||||
- API-key providers: threshold `5`, reset timeout `30s`.
|
||||
- Local providers: threshold `2`, reset timeout `15s`.
|
||||
|
||||
Only provider-level failure statuses should trip the provider breaker:
|
||||
|
||||
```ts
|
||||
(408, 500, 502, 503, 504);
|
||||
```
|
||||
|
||||
Do not trip the whole-provider breaker for normal account/key/model errors like most
|
||||
`401`, `403`, or `429` cases. Those usually belong to connection cooldown or model
|
||||
lockout. A generic API-key provider `403` should be recoverable unless it is classified
|
||||
as a terminal provider/account error.
|
||||
|
||||
The breaker uses lazy recovery, not a background timer. When `OPEN` expires, reads such
|
||||
as `getStatus()`, `canExecute()`, and `getRetryAfterMs()` refresh the state to
|
||||
`HALF_OPEN`, so dashboards and combo candidate builders do not keep excluding an
|
||||
expired provider forever.
|
||||
|
||||
### Connection Cooldown
|
||||
|
||||
**Scope**: one provider connection/account/key.
|
||||
|
||||
**Purpose**: temporarily skip one bad key/account while allowing other connections for
|
||||
the same provider to continue serving requests.
|
||||
|
||||
**Implementation**:
|
||||
|
||||
- Write/update path: `src/sse/services/auth.ts::markAccountUnavailable()`
|
||||
- Account selection/filtering: `src/sse/services/auth.ts::getProviderCredentials...`
|
||||
- Cooldown calculation: `open-sse/services/accountFallback.ts::checkFallbackError()`
|
||||
- Settings: `src/lib/resilience/settings.ts`
|
||||
|
||||
Important fields on provider connections:
|
||||
|
||||
```ts
|
||||
rateLimitedUntil;
|
||||
testStatus: "unavailable";
|
||||
lastError;
|
||||
lastErrorType;
|
||||
errorCode;
|
||||
backoffLevel;
|
||||
```
|
||||
|
||||
During account selection, a connection is skipped while:
|
||||
|
||||
```ts
|
||||
new Date(rateLimitedUntil).getTime() > Date.now();
|
||||
```
|
||||
|
||||
Cooldowns are also lazy: when `rateLimitedUntil` is in the past, the connection becomes
|
||||
eligible again. On successful use, `clearAccountError()` clears `testStatus`,
|
||||
`rateLimitedUntil`, error fields, and `backoffLevel`.
|
||||
|
||||
Default connection cooldown behavior:
|
||||
|
||||
- OAuth base cooldown: `5s`.
|
||||
- API-key base cooldown: `3s`.
|
||||
- API-key `429` should prefer upstream retry hints (`Retry-After`, reset headers, or
|
||||
parseable reset text) when available.
|
||||
- Repeated recoverable failures use exponential backoff:
|
||||
|
||||
```ts
|
||||
baseCooldownMs * 2 ** failureIndex;
|
||||
```
|
||||
|
||||
The anti-thundering-herd guard prevents concurrent failures on the same connection from
|
||||
repeatedly extending the cooldown or double-incrementing `backoffLevel`.
|
||||
|
||||
Terminal states are not cooldowns. `banned`, `expired`, and `credits_exhausted` are
|
||||
intended to stay unavailable until credentials/settings change or an operator resets
|
||||
them. Do not overwrite terminal states with transient cooldown state.
|
||||
|
||||
### Model Lockout
|
||||
|
||||
**Scope**: provider + connection + model.
|
||||
|
||||
**Purpose**: avoid disabling a whole connection when only one model is unavailable or
|
||||
quota-limited for that connection.
|
||||
|
||||
Examples:
|
||||
|
||||
- Per-model quota providers returning `429`.
|
||||
- Local providers returning `404` for one missing model.
|
||||
- Provider-specific mode/model permission failures such as selected Grok modes.
|
||||
|
||||
Model lockout lives in `open-sse/services/accountFallback.ts` and lets the same
|
||||
connection continue serving other models.
|
||||
|
||||
### Debugging Guidance
|
||||
|
||||
- If all keys for a provider are skipped, inspect both provider breaker state and each
|
||||
connection's `rateLimitedUntil`/`testStatus`.
|
||||
- If a provider appears permanently excluded after the reset window, check whether code
|
||||
is reading raw `state` instead of using `getStatus()`/`canExecute()`.
|
||||
- If one provider key fails but others should work, prefer connection cooldown over
|
||||
provider breaker.
|
||||
- If only one model fails, prefer model lockout over connection cooldown.
|
||||
- If a state should self-recover, it should have a future timestamp/reset timeout and a
|
||||
read path that refreshes expired state. Permanent statuses require manual credential
|
||||
or config changes.
|
||||
|
||||
---
|
||||
|
||||
## Key Conventions
|
||||
|
||||
### Code Style
|
||||
|
||||
- **2 spaces**, semicolons, double quotes, 100 char width, es5 trailing commas (enforced by lint-staged via Prettier)
|
||||
- **Imports**: external → internal (`@/`, `@omniroute/open-sse`) → relative
|
||||
- **Naming**: files=camelCase/kebab, components=PascalCase, constants=UPPER_SNAKE
|
||||
- **ESLint**: `no-eval`, `no-implied-eval`, `no-new-func` = error everywhere; `no-explicit-any` = warn in `open-sse/` and `tests/`
|
||||
- **TypeScript**: `strict: false`, target ES2022, module esnext, resolution bundler. Prefer explicit types.
|
||||
|
||||
### Database
|
||||
|
||||
- **Always** go through `src/lib/db/` domain modules — **never** write raw SQL in routes or handlers
|
||||
- **Never** add logic to `src/lib/localDb.ts` (re-export layer only)
|
||||
- **Never** barrel-import from `localDb.ts` — import specific `db/` modules instead
|
||||
- DB singleton: `getDbInstance()` from `src/lib/db/core.ts` (WAL journaling)
|
||||
- Migrations: `src/lib/db/migrations/` — versioned SQL files, idempotent, run in transactions
|
||||
|
||||
### Error Handling
|
||||
|
||||
- try/catch with specific error types, log with pino context
|
||||
- Never swallow errors in SSE streams — use abort signals for cleanup
|
||||
- Return proper HTTP status codes (4xx/5xx)
|
||||
|
||||
### Security
|
||||
|
||||
- **Never** use `eval()`, `new Function()`, or implied eval
|
||||
- Validate all inputs with Zod schemas
|
||||
- Encrypt credentials at rest (AES-256-GCM)
|
||||
- Upstream header denylist: `src/shared/constants/upstreamHeaders.ts` — keep sanitize, Zod schemas, and unit tests aligned when editing
|
||||
- **Public upstream credentials** (Gemini/Antigravity/Windsurf-style OAuth client_id/secret + Firebase Web keys extracted from public CLIs): **MUST** be embedded via `resolvePublicCred()` from `open-sse/utils/publicCreds.ts` — **never** as string literals. See `docs/security/PUBLIC_CREDS.md` for the mandatory pattern.
|
||||
- **Error responses** (HTTP / SSE / executor / MCP handler): **MUST** route through `buildErrorBody()` or `sanitizeErrorMessage()` from `open-sse/utils/error.ts` — **never** put raw `err.stack` or `err.message` in a response body. See `docs/security/ERROR_SANITIZATION.md`.
|
||||
- **Shell commands built from variables**: when calling `exec()`/`spawn()` with a script that needs runtime values, pass them via the `env` option (shell-escaped automatically) — **never** string-interpolate untrusted/external paths into the script body. Reference: `src/mitm/cert/install.ts::updateNssDatabases`.
|
||||
- **Secure-by-default libraries** ([tldrsec/awesome-secure-defaults](https://github.com/tldrsec/awesome-secure-defaults)): prefer Helmet.js, DOMPurify, ssrf-req-filter, safe-regex, Google Tink over custom implementations whenever adding new security-sensitive surfaces.
|
||||
|
||||
---
|
||||
|
||||
## Common Modification Scenarios
|
||||
|
||||
### Adding a New Provider
|
||||
|
||||
1. Register in `src/shared/constants/providers.ts` (Zod-validated at load)
|
||||
2. Add executor in `open-sse/executors/` if custom logic needed (extend `BaseExecutor`)
|
||||
3. Add translator in `open-sse/translator/` if non-OpenAI format
|
||||
4. Add OAuth config in `src/lib/oauth/constants/oauth.ts` if OAuth-based — if the upstream CLI ships a public client_id/secret, embed via `resolvePublicCred()` (see `docs/security/PUBLIC_CREDS.md`), **never** as a literal
|
||||
5. Register models in `open-sse/config/providerRegistry.ts`
|
||||
6. Write tests in `tests/unit/` (include the publicCreds shape assertion if you added a new embedded default)
|
||||
|
||||
### Adding a New API Route
|
||||
|
||||
1. Create directory under `src/app/api/v1/your-route/`
|
||||
2. Create `route.ts` with `GET`/`POST` handlers
|
||||
3. Follow pattern: CORS → Zod body validation → optional auth → handler delegation
|
||||
4. Handler goes in `open-sse/handlers/` (import from there, not inline)
|
||||
5. Error responses use `buildErrorBody()` / `errorResponse()` from `open-sse/utils/error.ts` (auto-sanitized — never put `err.stack` or `err.message` raw in the body). See `docs/security/ERROR_SANITIZATION.md`.
|
||||
6. Add tests — including at least one assertion that error responses do not leak stack traces (`!body.error.message.includes("at /")`)
|
||||
|
||||
### Adding a New DB Module
|
||||
|
||||
1. Create `src/lib/db/yourModule.ts` — import `getDbInstance` from `./core.ts`
|
||||
2. Export CRUD functions for your domain table(s)
|
||||
3. Add migration in `src/lib/db/migrations/` if new tables needed
|
||||
4. Re-export from `src/lib/localDb.ts` (add to the re-export list only)
|
||||
5. Write tests
|
||||
|
||||
### Adding a New MCP Tool
|
||||
|
||||
1. Add tool definition in `open-sse/mcp-server/tools/` with Zod input schema + async handler
|
||||
2. Register in tool set (wired by `createMcpServer()`)
|
||||
3. Assign to appropriate scope(s)
|
||||
4. Write tests (tool invocation logged to `mcp_audit` table)
|
||||
|
||||
### Adding a New A2A Skill
|
||||
|
||||
1. Create skill in `src/lib/a2a/skills/` (5 already exist: smart-routing, quota-management, provider-discovery, cost-analysis, health-report)
|
||||
2. Skill receives task context (messages, metadata) → returns structured result
|
||||
3. Register in `A2A_SKILL_HANDLERS` in `src/lib/a2a/taskExecution.ts`
|
||||
4. Expose in `src/app/.well-known/agent.json/route.ts` (Agent Card)
|
||||
5. Write tests in `tests/unit/`
|
||||
6. Document in `docs/frameworks/A2A-SERVER.md` skill table
|
||||
|
||||
### Adding a New Cloud Agent
|
||||
|
||||
1. Create agent class in `src/lib/cloudAgent/agents/` extending `CloudAgentBase` (3 already exist: codex-cloud, devin, jules)
|
||||
2. Implement `createTask`, `getStatus`, `approvePlan`, `sendMessage`, `listSources`
|
||||
3. Register in `src/lib/cloudAgent/registry.ts`
|
||||
4. Add OAuth/credentials handling if needed (`src/lib/oauth/providers/`)
|
||||
5. Tests + document in `docs/frameworks/CLOUD_AGENT.md`
|
||||
|
||||
### Adding a New Embedded Service
|
||||
|
||||
1. Create installer in `src/lib/services/installers/{name}.ts` modeled on `ninerouter.ts` (use `runNpm` from `installers/utils.ts` — no shell interpolation, hard rule #13).
|
||||
2. Register the service in `src/lib/services/bootstrap.ts` (add to `SERVICES[]` array and extend `buildSpawnArgsFactory()`).
|
||||
3. Add a DB seed row for the new service in `src/lib/db/migrations/` (`version_manager` table, `status='not_installed'`, `auto_start=0`).
|
||||
4. Create 7 API endpoints under `src/app/api/services/{name}/` (`_lib.ts`, `install`, `start`, `stop`, `restart`, `update`, `status`, `auto-start`). All delegate errors through `createErrorResponse()`. The shared `logs` endpoint is already wired via `[name]/logs/route.ts`.
|
||||
5. Verify `/api/services/` is in `LOCAL_ONLY_API_PREFIXES` in `src/server/authz/routeGuard.ts`; add a test asserting `isLocalOnlyPath()` returns `true` for the new prefix if you add one (hard rule #17).
|
||||
6. Add a UI tab in `src/app/(dashboard)/dashboard/providers/services/tabs/` reusing `ServiceStatusCard`, `ServiceLifecycleButtons`, `ServiceLogsPanel`.
|
||||
7. Document in `docs/frameworks/EMBEDDED-SERVICES.md` (update §1 service table + §4 API reference) and `docs/reference/openapi.yaml`.
|
||||
8. Write tests: unit (`tests/unit/services/`), integration (`tests/integration/services/`, gated by `RUN_SERVICES_INT=1`), and update `docs/ops/RELEASE_CHECKLIST.md` smoke section.
|
||||
|
||||
### Adding a New Guardrail / Eval / Skill / Webhook event
|
||||
|
||||
- Guardrail: `src/lib/guardrails/` → docs: `docs/security/GUARDRAILS.md`
|
||||
- Eval suite: `src/lib/evals/` → docs: `docs/frameworks/EVALS.md`
|
||||
- Skill (sandbox): `src/lib/skills/` → docs: `docs/frameworks/SKILLS.md`
|
||||
- Webhook event: `src/lib/webhookDispatcher.ts` → docs: `docs/frameworks/WEBHOOKS.md`
|
||||
|
||||
---
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
For any non-trivial change, read the matching deep-dive first:
|
||||
|
||||
| Area | Doc |
|
||||
| -------------------------------------------- | ----------------------------------------------------------------- |
|
||||
| Repo navigation | `docs/architecture/REPOSITORY_MAP.md` |
|
||||
| Architecture | `docs/architecture/ARCHITECTURE.md` |
|
||||
| Engineering reference | `docs/architecture/CODEBASE_DOCUMENTATION.md` |
|
||||
| Auto-Combo (9-factor scoring, 14 strategies) | `docs/routing/AUTO-COMBO.md` |
|
||||
| Resilience (3 mechanisms) | `docs/architecture/RESILIENCE_GUIDE.md` |
|
||||
| Reasoning replay | `docs/routing/REASONING_REPLAY.md` |
|
||||
| Skills framework | `docs/frameworks/SKILLS.md` |
|
||||
| Memory system (FTS5 + Qdrant) | `docs/frameworks/MEMORY.md` |
|
||||
| Cloud agents | `docs/frameworks/CLOUD_AGENT.md` |
|
||||
| Guardrails (PII / injection / vision) | `docs/security/GUARDRAILS.md` |
|
||||
| Public upstream credentials (Gemini/etc.) | `docs/security/PUBLIC_CREDS.md` |
|
||||
| Error message sanitization | `docs/security/ERROR_SANITIZATION.md` |
|
||||
| Evals | `docs/frameworks/EVALS.md` |
|
||||
| Compliance / audit | `docs/security/COMPLIANCE.md` |
|
||||
| Webhooks | `docs/frameworks/WEBHOOKS.md` |
|
||||
| Authorization pipeline | `docs/architecture/AUTHZ_GUIDE.md` |
|
||||
| Stealth (TLS / fingerprint) | `docs/security/STEALTH_GUIDE.md` |
|
||||
| Agent protocols (A2A / ACP / Cloud) | `docs/frameworks/AGENT_PROTOCOLS_GUIDE.md` |
|
||||
| MCP server | `docs/frameworks/MCP-SERVER.md` |
|
||||
| A2A server | `docs/frameworks/A2A-SERVER.md` |
|
||||
| API reference + OpenAPI | `docs/reference/API_REFERENCE.md` + `docs/reference/openapi.yaml` |
|
||||
| Provider catalog (auto-generated) | `docs/reference/PROVIDER_REFERENCE.md` |
|
||||
| Release flow | `docs/ops/RELEASE_CHECKLIST.md` |
|
||||
| Embedded services | `docs/frameworks/EMBEDDED-SERVICES.md` |
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
| What | Command |
|
||||
| ----------------------- | --------------------------------------------------------------------------- |
|
||||
| Unit tests | `npm run test:unit` |
|
||||
| Single file | `node --import tsx/esm --test tests/unit/file.test.ts` |
|
||||
| Vitest (MCP, autoCombo) | `npm run test:vitest` |
|
||||
| E2E (Playwright) | `npm run test:e2e` |
|
||||
| Protocol E2E (MCP+A2A) | `npm run test:protocols:e2e` |
|
||||
| Ecosystem | `npm run test:ecosystem` |
|
||||
| Coverage gate | `npm run test:coverage` (60/60/60/60 — statements/lines/functions/branches) |
|
||||
| Coverage report | `npm run coverage:report` |
|
||||
|
||||
**PR rule**: If you change production code in `src/`, `open-sse/`, `electron/`, or `bin/`, you must include or update tests in the same PR.
|
||||
|
||||
**Test layer preference**: unit first → integration (multi-module or DB state) → e2e (UI/workflow only). Encode bug reproductions as automated tests before or alongside the fix.
|
||||
|
||||
**Both test runners must pass**: `npm run test:unit` (Node native — most tests) AND `npm run test:vitest` (MCP server, autoCombo, cache) cover **non-overlapping files**. Both must be green before merging. A PR where only one suite passes may silently ship broken MCP tools or routing regressions.
|
||||
|
||||
**Bug fix / issue triage protocol (Hard Rule #18)**: Every fix for a reported issue must be validated by one of the following — no exceptions:
|
||||
1. **TDD (preferred)** — write a failing test reproducing the bug → fix it → confirm the test passes. The test becomes the permanent regression guard. Touch only the files the test proves need changing; nothing more.
|
||||
2. **Real-environment test (when TDD is not possible)** — deploy to the production VPS (`root@192.168.0.15`) and run a documented live test. Record the exact command + result in the PR description. Applies to: OAuth upstream flows, Cloudflare/WS upstream behavior, UI-only regressions, hardware-dependent behavior.
|
||||
3. "It worked locally without a test" does not count. A fix without a test or a VPS validation record is not a fix — it is a guess.
|
||||
|
||||
Why this matters: fixing bug A while opening bug B is worse than not fixing at all. The TDD/VPS gate enforces surgical scope — you touch only what the failing test proves is broken. Examples where this paid off: #3090 (claude-web 403), #3113 (WS HTTP fallback), #3052 (heap-guard auto-calibration).
|
||||
|
||||
**Copilot coverage policy**: When a PR changes production code and coverage is below 60% (statements/lines/functions/branches), do not just report — add or update tests, rerun the coverage gate, then ask for confirmation. Include commands run, changed test files, and final coverage result in the PR report.
|
||||
|
||||
---
|
||||
|
||||
## Git Workflow
|
||||
|
||||
```bash
|
||||
# Never commit directly to main
|
||||
git checkout -b feat/your-feature
|
||||
git commit -m "feat: describe your change"
|
||||
git push -u origin feat/your-feature
|
||||
```
|
||||
|
||||
**Branch prefixes**: `feat/`, `fix/`, `refactor/`, `docs/`, `test/`, `chore/`
|
||||
|
||||
**Commit format** (Conventional Commits): `feat(db): add circuit breaker` — scopes: `db`, `sse`, `oauth`, `dashboard`, `api`, `cli`, `docker`, `ci`, `mcp`, `a2a`, `memory`, `skills`
|
||||
|
||||
**Husky hooks**:
|
||||
|
||||
- **pre-commit**: lint-staged + `check-docs-sync` + `check:any-budget:t11`
|
||||
- **pre-push**: `npm run test:unit`
|
||||
|
||||
---
|
||||
|
||||
## Environment
|
||||
|
||||
- **Runtime**: Node.js ≥20.20.2 <21 || ≥22.22.2 <23 || ≥24 <25, ES Modules
|
||||
- **TypeScript**: 5.9+, target ES2022, module esnext, resolution bundler
|
||||
- **Path aliases**: `@/*` → `src/`, `@omniroute/open-sse` → `open-sse/`, `@omniroute/open-sse/*` → `open-sse/*`
|
||||
- **Default port**: 20128 (API + dashboard on same port)
|
||||
- **Data directory**: `DATA_DIR` env var, defaults to `~/.omniroute/`
|
||||
- **Key env vars**: `PORT`, `JWT_SECRET`, `API_KEY_SECRET`, `INITIAL_PASSWORD`, `REQUIRE_API_KEY`, `APP_LOG_LEVEL`
|
||||
- Setup: `cp .env.example .env` then generate `JWT_SECRET` (`openssl rand -base64 48`) and `API_KEY_SECRET` (`openssl rand -hex 32`)
|
||||
|
||||
---
|
||||
|
||||
## Hard Rules
|
||||
|
||||
1. Never commit secrets or credentials
|
||||
2. Never add logic to `localDb.ts`
|
||||
3. Never use `eval()` / `new Function()` / implied eval
|
||||
4. Never commit directly to `main`
|
||||
5. Never write raw SQL in routes — use `src/lib/db/` modules
|
||||
6. Never silently swallow errors in SSE streams
|
||||
7. Always validate inputs with Zod schemas
|
||||
8. Always include tests when changing production code
|
||||
9. Coverage must stay ≥60% (statements, lines, functions, branches).
|
||||
10. Never bypass Husky hooks (`--no-verify`, `--no-gpg-sign`) without explicit operator approval.
|
||||
11. Never embed public upstream OAuth client_id/secret or Firebase Web keys as string literals — always go through `resolvePublicCred()` (`open-sse/utils/publicCreds.ts`). See `docs/security/PUBLIC_CREDS.md`.
|
||||
12. Never return raw `err.stack` / `err.message` in HTTP / SSE / executor responses — always route through `buildErrorBody()` or `sanitizeErrorMessage()` (`open-sse/utils/error.ts`). See `docs/security/ERROR_SANITIZATION.md`.
|
||||
13. Never string-interpolate external paths or runtime values into shell scripts passed to `exec()`/`spawn()` — pass via the `env` option instead. Reference: `src/mitm/cert/install.ts::updateNssDatabases`.
|
||||
14. Never dismiss a CodeQL / Secret-Scanning alert without (a) first checking the pattern docs above to see if the helper applies, and (b) recording the technical justification in the dismissal comment. Precedent: `js/stack-trace-exposure` raised on callsites that already route through `sanitizeErrorMessage()` is a known CodeQL limitation (custom sanitizers not recognized) — dismiss as `false positive` referencing `docs/security/ERROR_SANITIZATION.md`.
|
||||
15. Never expose routes that spawn child processes (`/api/mcp/`, `/api/cli-tools/runtime/`) without `isLocalOnlyPath()` classification in `src/server/authz/routeGuard.ts`. Loopback enforcement happens unconditionally before any auth check — leaked JWT via tunnel cannot trigger process spawning. See `docs/security/ROUTE_GUARD_TIERS.md`.
|
||||
16. Never include `Co-Authored-By` trailers that credit an AI assistant, LLM, or automation account (e.g. names containing "Claude", "GPT", "Copilot", "Bot"; emails at `anthropic.com` / `openai.com` / bot-owned `noreply.github.com` addresses). Such trailers route attribution to the bot account on GitHub, hiding the real author (`diegosouzapw`) in PR history. Human collaborators — including upstream PR authors and issue reporters being ported into OmniRoute — MAY and SHOULD be credited with standard `Co-authored-by: Name <email>` trailers; the upstream-port workflows (`/port-upstream-features`, `/port-upstream-issues`) depend on this.
|
||||
17. Never expose routes under `/api/services/` or `/dashboard/providers/services/*/embed/` without `isLocalOnlyPath()` classification in `src/server/authz/routeGuard.ts`. These routes can spawn child processes (`npm install`, `node`). Loopback enforcement happens unconditionally before any auth check — a leaked JWT via tunnel cannot trigger process spawning. See `docs/security/ROUTE_GUARD_TIERS.md`.
|
||||
18. Every bug fix must be validated before shipping: a failing-then-passing unit/integration test (TDD) OR a documented live test on the production VPS (192.168.0.15). A fix without either is not merged. See Testing → "Bug fix / issue triage protocol" for the full decision tree.
|
||||
|
||||
---
|
||||
|
||||
## PII & Stream Sanitization Learnings
|
||||
|
||||
### 1. Regex Security (ReDoS)
|
||||
All regex patterns matching variable-length strings (e.g. IPv6 address, credit cards) must use strictly bounded, non-overlapping sequences (e.g., limit occurrences with bounded ranges `{1,7}`) to prevent catastrophic backtracking when processing untrusted inputs.
|
||||
|
||||
### 2. SSE Snapshot Handling
|
||||
When parsing streaming LLM responses (e.g. Responses API), check if a chunk represents a final snapshot (`done` or `completed` events). Snapshot text must be sanitized directly as a standalone string (bypassing rolling delta buffers) to prevent text duplication at the end of the stream.
|
||||
|
||||
### 3. Database Handles in Tests
|
||||
Ensure that any unit tests that trigger database migrations or establish SQLite connections call `resetDbInstance()` and properly clean up/close all DB handles in a `test.after(...)` hook. Failure to release database connection handles will cause Node's native test runner to hang indefinitely.
|
||||
131
CODE_OF_CONDUCT.md
Normal file
131
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement by opening a
|
||||
private security advisory at
|
||||
<https://github.com/diegosouzapw/OmniRoute/security/advisories/new>
|
||||
or by emailing the maintainer at diegosouza.pw@outlook.com.
|
||||
For security-sensitive incidents, see [`SECURITY.md`](SECURITY.md).
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.1, available at
|
||||
https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
266
CONTRIBUTING.md
266
CONTRIBUTING.md
@@ -8,7 +8,7 @@ Thank you for your interest in contributing! This guide covers everything you ne
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Node.js** 20+ (recommended: 22 LTS)
|
||||
- **Node.js** `>=22.22.3 <23`, or `>=24.0.0 <27` (recommended: 24 LTS)
|
||||
- **npm** 10+
|
||||
- **Git**
|
||||
|
||||
@@ -33,13 +33,24 @@ echo "API_KEY_SECRET=$(openssl rand -hex 32)" >> .env
|
||||
|
||||
Key variables for development:
|
||||
|
||||
| Variable | Development Default | Description |
|
||||
| ---------------------- | ----------------------- | ------------------------- |
|
||||
| `PORT` | `3000` | Server port |
|
||||
| `NEXT_PUBLIC_BASE_URL` | `http://localhost:3000` | Base URL for frontend |
|
||||
| `JWT_SECRET` | (generate above) | JWT signing secret |
|
||||
| `INITIAL_PASSWORD` | `123456` | First login password |
|
||||
| `ENABLE_REQUEST_LOGS` | `false` | Enable debug request logs |
|
||||
| Variable | Development Default | Description |
|
||||
| ---------------------- | ------------------------ | --------------------- |
|
||||
| `PORT` | `20128` | Server port |
|
||||
| `NEXT_PUBLIC_BASE_URL` | `http://localhost:20128` | Base URL for frontend |
|
||||
| `JWT_SECRET` | (generate above) | JWT signing secret |
|
||||
| `INITIAL_PASSWORD` | `CHANGEME` | First login password |
|
||||
| `APP_LOG_LEVEL` | `info` | Log verbosity level |
|
||||
|
||||
### Dashboard Settings
|
||||
|
||||
The dashboard provides UI toggles for features that can also be configured via environment variables:
|
||||
|
||||
| Setting Location | Toggle | Description |
|
||||
| ------------------- | ------------------ | ------------------------------ |
|
||||
| Settings → Advanced | Debug Mode | Enable debug request logs (UI) |
|
||||
| Settings → General | Sidebar Visibility | Show/hide sidebar sections |
|
||||
|
||||
These settings are stored in the database and persist across restarts, overriding env var defaults when set.
|
||||
|
||||
### Running Locally
|
||||
|
||||
@@ -48,17 +59,44 @@ Key variables for development:
|
||||
npm run dev
|
||||
|
||||
# Production build
|
||||
npm run build
|
||||
npm run build # next build → .build/next/ then assembleStandalone → dist/
|
||||
npm run start
|
||||
|
||||
# Release build (clean rebuild + HEAD sentinel — required for deploy)
|
||||
npm run build:release # rm -rf .build dist && build + writes dist/BUILD_SHA
|
||||
|
||||
# Common port configuration
|
||||
PORT=20128 NEXT_PUBLIC_BASE_URL=http://localhost:20128 npm run dev
|
||||
```
|
||||
|
||||
### Build Output Layout
|
||||
|
||||
| Directory | Contents | Tracked |
|
||||
| ---------- | ------------------------------------------- | ------- |
|
||||
| `src/` | Application source (TypeScript / TSX) | Yes |
|
||||
| `.build/` | Intermediates — `next build` output (gitignored, `distDir = .build/next`) | No |
|
||||
| `dist/` | Shippable bundle — assembled by `assembleStandalone` (gitignored) | No |
|
||||
|
||||
The build pipeline is a single pass:
|
||||
|
||||
```
|
||||
npm run build
|
||||
└─ next build → .build/next/standalone (Next.js output)
|
||||
└─ assembleStandalone() (copies standalone + static + public + native assets)
|
||||
└─ output: dist/ (server.js, .next/static/, public/, node_modules/)
|
||||
```
|
||||
|
||||
`npm run build:release` additionally cleans both directories first and writes
|
||||
`dist/BUILD_SHA` (= `git rev-parse --short HEAD`) as a deploy integrity sentinel.
|
||||
|
||||
> **VPS deploy note:** the remote image directory `/usr/lib/node_modules/omniroute/app/`
|
||||
> is unchanged. The deploy skills rsync the contents of `dist/` into it.
|
||||
> Only the in-repo build output path moved (`app/` → `dist/`).
|
||||
|
||||
Default URLs:
|
||||
|
||||
- **Dashboard**: `http://localhost:3000/dashboard`
|
||||
- **API**: `http://localhost:3000/v1`
|
||||
- **Dashboard**: `http://localhost:20128/dashboard`
|
||||
- **API**: `http://localhost:20128/v1`
|
||||
|
||||
---
|
||||
|
||||
@@ -97,50 +135,80 @@ test: add observability unit tests
|
||||
refactor(db): consolidate rate limit tables
|
||||
```
|
||||
|
||||
Scopes: `db`, `sse`, `oauth`, `dashboard`, `api`, `cli`, `docker`, `ci`.
|
||||
Scopes (v3.8): `db`, `sse`, `oauth`, `dashboard`, `api`, `cli`, `docker`, `ci`, `mcp`, `a2a`, `memory`, `skills`, `cloud-agent`, `guardrails`, `compression`, `auto-combo`, `resilience`, `providers`, `executors`, `translator`, `domain`, `authz`.
|
||||
|
||||
---
|
||||
|
||||
## Running Tests
|
||||
|
||||
```bash
|
||||
# All unit tests
|
||||
npm test
|
||||
npm run test:unit
|
||||
# All tests (unit + vitest + ecosystem + e2e)
|
||||
npm run test:all
|
||||
|
||||
# Specific test suites
|
||||
npm run test:security # Security tests
|
||||
npm run test:fixes # Fix verification tests
|
||||
# Single test file (Node.js native test runner — most tests use this)
|
||||
node --import tsx/esm --test tests/unit/your-file.test.ts
|
||||
|
||||
# With coverage
|
||||
npm run test:coverage
|
||||
# Vitest (MCP server, autoCombo, cache)
|
||||
npm run test:vitest
|
||||
|
||||
# E2E tests (requires Playwright)
|
||||
npm run test:e2e
|
||||
|
||||
# Protocol clients E2E (MCP transports, A2A)
|
||||
npm run test:protocols:e2e
|
||||
|
||||
# Ecosystem compatibility tests
|
||||
npm run test:ecosystem
|
||||
|
||||
# Coverage gate: 75% statements/lines/functions, 70% branches
|
||||
npm run test:coverage
|
||||
npm run coverage:report
|
||||
|
||||
# Lint + format check
|
||||
npm run lint
|
||||
npm run check
|
||||
```
|
||||
|
||||
Current test status: **368+ unit tests** covering:
|
||||
Coverage notes:
|
||||
|
||||
- `npm run test:coverage` measures source coverage for the main unit test suite, excludes `tests/**`, and includes `open-sse/**`
|
||||
- Pull requests must keep the coverage gate at **75%+** statements/lines/functions and **70%+** branches
|
||||
- If a PR changes production code in `src/`, `open-sse/`, `electron/`, or `bin/`, it must add or update automated tests in the same PR
|
||||
- `npm run coverage:report` prints the detailed file-by-file report from the latest coverage run
|
||||
- `npm run test:coverage:legacy` preserves the older metric for historical comparison
|
||||
- See `docs/ops/COVERAGE_PLAN.md` for the phased coverage improvement roadmap
|
||||
|
||||
### Pull Request Requirements
|
||||
|
||||
Before opening or merging a PR:
|
||||
|
||||
- Run `npm run test:unit`
|
||||
- Run `npm run test:coverage`
|
||||
- Ensure the coverage gate stays at **75%+** statements/lines/functions, **70%+** branches
|
||||
- Include the changed or added test files in the PR description when production code changed
|
||||
- Check the SonarQube result on the PR when the project secrets are configured in CI
|
||||
|
||||
Current test status: **122 unit test files** covering:
|
||||
|
||||
- Provider translators and format conversion
|
||||
- Rate limiting, circuit breaker, and resilience
|
||||
- Semantic cache, idempotency, progress tracking
|
||||
- Database operations and schema
|
||||
- Database operations and schema (21 DB modules)
|
||||
- OAuth flows and authentication
|
||||
- API endpoint validation
|
||||
- API endpoint validation (Zod v4)
|
||||
- MCP server tools and scope enforcement
|
||||
- Memory and Skills systems
|
||||
|
||||
---
|
||||
|
||||
## Code Style
|
||||
|
||||
- **ESLint** — Run `npm run lint` before committing
|
||||
- **Prettier** — Auto-formatted via `lint-staged` on commit
|
||||
- **TypeScript** — All `src/` code uses `.ts`/`.tsx`; document with TSDoc (`@param`, `@returns`, `@throws`)
|
||||
- **Prettier** — Auto-formatted via `lint-staged` on commit (2 spaces, semicolons, double quotes, 100 char width, es5 trailing commas)
|
||||
- **TypeScript** — All `src/` code uses `.ts`/`.tsx`; `open-sse/` uses `.ts`/`.js`; document with TSDoc (`@param`, `@returns`, `@throws`)
|
||||
- **No `eval()`** — ESLint enforces `no-eval`, `no-implied-eval`, `no-new-func`
|
||||
- **Zod validation** — Use Zod schemas for API input validation
|
||||
- **Zod validation** — Use Zod v4 schemas for all API input validation
|
||||
- **Naming**: Files = camelCase/kebab-case, components = PascalCase, constants = UPPER_SNAKE
|
||||
|
||||
---
|
||||
|
||||
@@ -148,91 +216,97 @@ Current test status: **368+ unit tests** covering:
|
||||
|
||||
```
|
||||
src/ # TypeScript (.ts / .tsx)
|
||||
├── app/ # Next.js App Router
|
||||
│ ├── (dashboard)/ # Dashboard pages (.tsx)
|
||||
│ ├── api/ # API routes (.ts)
|
||||
├── app/ # Next.js 16 App Router
|
||||
│ ├── (dashboard)/ # Dashboard pages (23 sections)
|
||||
│ ├── api/ # API routes (51 directories)
|
||||
│ └── login/ # Auth pages (.tsx)
|
||||
├── domain/ # Domain types and response helpers (.ts)
|
||||
├── domain/ # Policy engine (policyEngine, comboResolver, costRules, etc.)
|
||||
├── lib/ # Core business logic (.ts)
|
||||
│ ├── db/ # SQLite database layer
|
||||
│ ├── oauth/ # OAuth services per provider
|
||||
│ ├── cacheLayer.ts # LRU cache
|
||||
│ ├── semanticCache.ts # Semantic response cache
|
||||
│ ├── idempotencyLayer.ts # Request deduplication
|
||||
│ └── localDb.ts # Settings facade (LowDB for config, SQLite for domain data)
|
||||
│ ├── a2a/ # Agent-to-Agent v0.3 protocol server
|
||||
│ ├── acp/ # Agent Communication Protocol registry
|
||||
│ ├── compliance/ # Compliance policy engine
|
||||
│ ├── db/ # SQLite database layer (21 modules + 16 migrations)
|
||||
│ ├── memory/ # Persistent conversational memory
|
||||
│ ├── oauth/ # OAuth providers, services, and utilities
|
||||
│ ├── skills/ # Extensible skill framework
|
||||
│ ├── usage/ # Usage tracking and cost calculation
|
||||
│ └── localDb.ts # Re-export layer only — never add logic here
|
||||
├── middleware/ # Request middleware (promptInjectionGuard)
|
||||
├── mitm/ # MITM proxy (cert, DNS, target routing)
|
||||
├── shared/
|
||||
│ ├── components/ # React components (.tsx)
|
||||
│ ├── middleware/ # Correlation IDs, etc.
|
||||
│ ├── utils/ # Circuit breaker, sanitizer, etc.
|
||||
│ └── validation/ # Zod schemas
|
||||
└── sse/ # SSE chat handlers (.ts)
|
||||
│ ├── constants/ # Provider definitions (177), MCP scopes, 14 routing strategies
|
||||
│ ├── utils/ # Circuit breaker, sanitizer, auth helpers
|
||||
│ └── validation/ # Zod v4 schemas
|
||||
└── sse/ # SSE proxy pipeline
|
||||
|
||||
open-sse/ # @omniroute/open-sse workspace (JavaScript)
|
||||
├── handlers/ # chatCore.js — main request handler
|
||||
├── services/ # Rate limit, fallback
|
||||
├── translators/ # Format converters (OpenAI ↔ Claude ↔ Gemini)
|
||||
└── utils/ # Progress tracker, stream helpers
|
||||
open-sse/ # @omniroute/open-sse workspace
|
||||
├── executors/ # 14 provider-specific request executors
|
||||
├── handlers/ # 11 request handlers (chat, responses, embeddings, images, etc.)
|
||||
├── mcp-server/ # MCP server (25 tools, 3 transports, 10 scopes)
|
||||
├── services/ # 36+ services (combo, autoCombo, rateLimitManager, etc.)
|
||||
├── translator/ # Format translators (OpenAI ↔ Claude ↔ Gemini ↔ Responses ↔ Ollama)
|
||||
├── transformer/ # Responses API transformer
|
||||
└── utils/ # 22 utility modules (stream, TLS, proxy, logging)
|
||||
|
||||
electron/ # Electron desktop app (cross-platform)
|
||||
|
||||
tests/
|
||||
├── unit/ # Node.js test runner (.test.mjs)
|
||||
└── e2e/ # Playwright tests
|
||||
├── unit/ # Node.js test runner (122 test files)
|
||||
├── integration/ # Integration tests
|
||||
├── e2e/ # Playwright tests
|
||||
├── security/ # Security tests
|
||||
├── translator/ # Translator-specific tests
|
||||
└── load/ # Load tests
|
||||
|
||||
docs/ # Documentation
|
||||
├── USER_GUIDE.md # Provider setup, CLI integration
|
||||
├── API_REFERENCE.md # All endpoints
|
||||
├── TROUBLESHOOTING.md # Common issues
|
||||
├── ARCHITECTURE.md # System architecture
|
||||
└── adr/ # Architecture Decision Records
|
||||
docs/
|
||||
├── adr/ # Architecture Decision Records
|
||||
├── architecture/ # System architecture & resilience
|
||||
├── comparison/ # OmniRoute vs alternatives
|
||||
├── compression/ # Compression guides & rules
|
||||
├── dev/ # Development guides
|
||||
├── diagrams/ # Architecture diagrams
|
||||
├── frameworks/ # MCP, A2A, OpenCode, Memory, Skills
|
||||
├── guides/ # User guide, Docker, setup, troubleshooting
|
||||
├── i18n/ # Internationalized README translations
|
||||
├── marketing/ # Marketing materials
|
||||
├── ops/ # Deployment, proxy, coverage, releases
|
||||
├── providers/ # Provider-specific docs
|
||||
├── reference/ # API reference, env vars, CLI tools, free tiers
|
||||
├── releases/ # Release notes
|
||||
├── routing/ # Auto-combo engine, reasoning replay
|
||||
├── screenshots/ # Dashboard screenshots
|
||||
├── security/ # Guardrails, compliance, stealth, tokens
|
||||
└── specs/ # Design specs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Adding a New Provider
|
||||
|
||||
### Step 1: OAuth Service (if using OAuth)
|
||||
### Step 1: Register Provider Constants
|
||||
|
||||
Create `src/lib/oauth/services/your-provider.ts` extending `OAuthService`:
|
||||
Add to `src/shared/constants/providers.ts` — Zod-validated at module load.
|
||||
|
||||
```typescript
|
||||
import { OAuthService } from "../OAuthService";
|
||||
### Step 2: Add Executor (if custom logic needed)
|
||||
|
||||
export class YourProviderService extends OAuthService {
|
||||
constructor() {
|
||||
super({
|
||||
name: "your-provider",
|
||||
authUrl: "https://provider.com/oauth/authorize",
|
||||
tokenUrl: "https://provider.com/oauth/token",
|
||||
clientId: "...",
|
||||
scopes: ["..."],
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
Create executor in `open-sse/executors/your-provider.ts` extending the base executor.
|
||||
|
||||
### Step 2: Register Provider
|
||||
### Step 3: Add Translator (if non-OpenAI format)
|
||||
|
||||
Add to `src/lib/oauth/providers.ts`:
|
||||
Create request/response translators in `open-sse/translator/`.
|
||||
|
||||
```typescript
|
||||
import { YourProviderService } from "./services/your-provider";
|
||||
// Add to the providers map
|
||||
```
|
||||
### Step 4: Add OAuth Config (if OAuth-based)
|
||||
|
||||
### Step 3: Add Constants
|
||||
Add OAuth credentials in `src/lib/oauth/constants/oauth.ts` and service in `src/lib/oauth/services/`.
|
||||
|
||||
Add provider constants in `src/lib/providerConstants.ts`:
|
||||
If the upstream provider distributes a public OAuth client_id/secret or Firebase Web API key inside its public CLI / browser bundle, **do not** embed it as a string literal. Use `resolvePublicCred()` from `open-sse/utils/publicCreds.ts` and add a masked byte entry to `EMBEDDED_DEFAULTS`. The full mandatory workflow is documented in [`docs/security/PUBLIC_CREDS.md`](./docs/security/PUBLIC_CREDS.md).
|
||||
|
||||
- Provider prefix (e.g., `yp/`)
|
||||
- Default models
|
||||
- Pricing info
|
||||
Inside handlers/executors, error messages reaching the client must go through `buildErrorBody()` / `sanitizeErrorMessage()` from `open-sse/utils/error.ts` — never put raw `err.stack` or `err.message` in a Response body. See [`docs/security/ERROR_SANITIZATION.md`](./docs/security/ERROR_SANITIZATION.md).
|
||||
|
||||
### Step 4: Add Translator (if non-OpenAI format)
|
||||
### Step 5: Register Models
|
||||
|
||||
Create translator in `open-sse/translators/` if the provider uses a custom API format.
|
||||
|
||||
### Step 5: Add Timeout
|
||||
|
||||
Add request timeout configuration in `src/shared/utils/requestTimeout.ts`.
|
||||
Add model definitions in `open-sse/config/providerRegistry.ts`.
|
||||
|
||||
### Step 6: Add Tests
|
||||
|
||||
@@ -251,23 +325,33 @@ Write unit tests in `tests/unit/` covering at minimum:
|
||||
- [ ] Build succeeds (`npm run build`)
|
||||
- [ ] TypeScript types added for new public functions and interfaces
|
||||
- [ ] No hardcoded secrets or fallback values
|
||||
- [ ] Public upstream credentials embedded via `resolvePublicCred()` (see [`docs/security/PUBLIC_CREDS.md`](./docs/security/PUBLIC_CREDS.md)), never as literals
|
||||
- [ ] Error responses route through `buildErrorBody()` / `sanitizeErrorMessage()` — no raw stack traces in response bodies (see [`docs/security/ERROR_SANITIZATION.md`](./docs/security/ERROR_SANITIZATION.md))
|
||||
- [ ] Shell commands (`exec` / `spawn`) pass runtime values via `env`, not via string interpolation
|
||||
- [ ] All inputs validated with Zod schemas
|
||||
- [ ] CHANGELOG updated (if user-facing change)
|
||||
- [ ] Documentation updated (if applicable)
|
||||
- [ ] No new CodeQL / Secret-Scanning alerts opened, or each one dismissed with technical justification referencing the relevant `docs/security/` doc
|
||||
- [ ] Routes that spawn child processes (`/api/mcp/`, `/api/cli-tools/runtime/`) classified as `isLocalOnlyPath()` in `src/server/authz/routeGuard.ts` — see [Hard Rule #15](docs/security/ROUTE_GUARD_TIERS.md)
|
||||
- [ ] No `Co-Authored-By` trailers in commit messages — commits must appear solely under the repository owner's Git identity (Hard Rule #16)
|
||||
|
||||
---
|
||||
|
||||
## Releasing
|
||||
|
||||
When a new GitHub Release is created (e.g. `v0.4.0`), the package is **automatically published to npm** via GitHub Actions:
|
||||
Releases are managed via the `/generate-release` workflow. When a new GitHub Release is created, the package is **automatically published to npm** via GitHub Actions.
|
||||
|
||||
```bash
|
||||
gh release create v0.4.0 --title "v0.4.0" --generate-notes
|
||||
```
|
||||
For VPS deploys, use `npm run build:release` (not `npm run build`) — it performs a clean
|
||||
rebuild, assembles the bundle into `dist/`, and writes the `dist/BUILD_SHA` sentinel.
|
||||
Then use the `/deploy-vps-*-cc` skills which rsync `dist/` to the remote `app/` directory.
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
- **Architecture**: See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)
|
||||
- **Architecture**: See [`docs/architecture/ARCHITECTURE.md`](docs/architecture/ARCHITECTURE.md)
|
||||
- **API Reference**: See [`docs/reference/API_REFERENCE.md`](docs/reference/API_REFERENCE.md)
|
||||
- **Security docs**: [`docs/security/CLI_TOKEN.md`](docs/security/CLI_TOKEN.md), [`docs/security/ROUTE_GUARD_TIERS.md`](docs/security/ROUTE_GUARD_TIERS.md), [`docs/security/ERROR_SANITIZATION.md`](docs/security/ERROR_SANITIZATION.md), [`docs/security/PUBLIC_CREDS.md`](docs/security/PUBLIC_CREDS.md)
|
||||
- **Ops docs**: [`docs/ops/SQLITE_RUNTIME.md`](docs/ops/SQLITE_RUNTIME.md)
|
||||
- **Issues**: [github.com/diegosouzapw/OmniRoute/issues](https://github.com/diegosouzapw/OmniRoute/issues)
|
||||
- **ADRs**: See `docs/adr/` for architectural decision records
|
||||
|
||||
155
Dockerfile
155
Dockerfile
@@ -1,16 +1,52 @@
|
||||
FROM node:22-bookworm-slim AS builder
|
||||
# ── Common base with runtime deps ──────────────────────────────────────────
|
||||
FROM node:24-trixie-slim AS base
|
||||
WORKDIR /app
|
||||
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=shared \
|
||||
--mount=type=cache,target=/var/lib/apt/lists,sharing=shared \
|
||||
apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libsecret-1-0 ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# ── Builder ────────────────────────────────────────────────────────────────
|
||||
FROM base AS builder
|
||||
|
||||
# Build tools for native module compilation
|
||||
# apt-get update needed here because base's rm -rf clears the shared cache
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=shared \
|
||||
--mount=type=cache,target=/var/lib/apt/lists,sharing=shared \
|
||||
apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY package*.json ./
|
||||
COPY scripts/postinstall.mjs ./scripts/postinstall.mjs
|
||||
COPY scripts/native-binary-compat.mjs ./scripts/native-binary-compat.mjs
|
||||
RUN if [ -f package-lock.json ]; then npm ci --no-audit --no-fund; else npm install --no-audit --no-fund; fi
|
||||
COPY scripts/build/postinstall.mjs ./scripts/build/postinstall.mjs
|
||||
COPY scripts/build/postinstallSupport.mjs ./scripts/build/postinstallSupport.mjs
|
||||
COPY scripts/build/native-binary-compat.mjs ./scripts/build/native-binary-compat.mjs
|
||||
ENV NPM_CONFIG_LEGACY_PEER_DEPS=true
|
||||
# --ignore-scripts blocks broad dependency install/postinstall hooks, closing
|
||||
# the supply-chain attack surface where a transitive dep can run arbitrary code
|
||||
# at install time. better-sqlite3 still needs a native binding for the target
|
||||
# platform, so rebuild and smoke-test only that known runtime dependency below.
|
||||
#
|
||||
# We REQUIRE a committed package-lock.json so resolved dependency versions
|
||||
# are reproducible.
|
||||
RUN test -f package-lock.json \
|
||||
|| (echo "package-lock.json is required for reproducible Docker builds" >&2 && exit 1)
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm ci --no-audit --no-fund --legacy-peer-deps --ignore-scripts \
|
||||
&& npm rebuild better-sqlite3 \
|
||||
&& node -e "require('better-sqlite3')(':memory:').close()"
|
||||
|
||||
# Use Turbopack for significant build speedup
|
||||
ENV OMNIROUTE_USE_TURBOPACK=1
|
||||
|
||||
COPY . ./
|
||||
RUN mkdir -p /app/data && npm run build
|
||||
RUN --mount=type=cache,target=/app/.build/next/cache \
|
||||
mkdir -p /app/data && npm run build
|
||||
|
||||
FROM node:22-bookworm-slim AS runner-base
|
||||
WORKDIR /app
|
||||
# ── Runner base ────────────────────────────────────────────────────────────
|
||||
FROM base AS runner-base
|
||||
|
||||
LABEL org.opencontainers.image.title="omniroute" \
|
||||
org.opencontainers.image.description="Unified AI proxy — route any LLM through one endpoint" \
|
||||
@@ -21,36 +57,113 @@ LABEL org.opencontainers.image.title="omniroute" \
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=20128
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
ENV NODE_OPTIONS="--max-old-space-size=256"
|
||||
ENV OMNIROUTE_MEMORY_MB=1024
|
||||
ENV NODE_OPTIONS="--max-old-space-size=${OMNIROUTE_MEMORY_MB}"
|
||||
|
||||
# Data directory inside Docker — must match the volume mount in docker-compose.yml
|
||||
ENV DATA_DIR=/app/data
|
||||
RUN mkdir -p /app/data
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
# Explicitly copy @swc/helpers — not always traced by standalone output but needed at runtime
|
||||
COPY --from=builder /app/node_modules/@swc/helpers ./node_modules/@swc/helpers
|
||||
COPY --from=builder /app/scripts/run-standalone.mjs ./run-standalone.mjs
|
||||
COPY --from=builder /app/scripts/runtime-env.mjs ./runtime-env.mjs
|
||||
COPY --from=builder /app/scripts/bootstrap-env.mjs ./bootstrap-env.mjs
|
||||
COPY --from=builder /app/scripts/healthcheck.mjs ./healthcheck.mjs
|
||||
# `npm run build` (build-next-isolated → assembleStandalone) bundles ALL runtime
|
||||
# files into .build/next/standalone/ — .next, node_modules, migrations, scripts,
|
||||
# docs, and the previously hand-COPY'd modules below (@swc/helpers, pino-*, split2,
|
||||
# migrations). assembleStandalone copies them straight from the builder's
|
||||
# node_modules, so they are present regardless of NFT/Turbopack trace behaviour.
|
||||
# The old per-module overrides were therefore pure duplication and were removed
|
||||
# (build-output-isolation cleanup). See scripts/build/assembleStandalone.mjs
|
||||
# (EXTRA_MODULE_ENTRIES) for the single source of truth.
|
||||
COPY --from=builder /app/.build/next/standalone ./
|
||||
# better-sqlite3 is the one exception still copied explicitly: assembleStandalone
|
||||
# only syncs its native build/ dir; the JS wrapper (lib/, package.json) is left to
|
||||
# Next.js tracing. bootstrap-env requires SQLite BEFORE the standalone server
|
||||
# starts, so guarantee the complete package independent of trace behaviour.
|
||||
COPY --from=builder /app/node_modules/better-sqlite3 ./node_modules/better-sqlite3
|
||||
# migrations land at <standalone>/migrations via assembleStandalone; point the runtime at them.
|
||||
ENV OMNIROUTE_MIGRATIONS_DIR=/app/migrations
|
||||
|
||||
# Docker healthcheck script — not traced by Next.js standalone output, so copy
|
||||
# it explicitly. The HEALTHCHECK CMD references it as `node healthcheck.mjs`.
|
||||
COPY --from=builder /app/scripts/dev/healthcheck.mjs ./healthcheck.mjs
|
||||
|
||||
# Hand /app over to the baked-in `node` non-root user (UID/GID 1000) so the
|
||||
# runtime process never holds root privileges. The chown happens after all
|
||||
# COPYs so it covers files originally owned by root in the builder stage.
|
||||
RUN chown -R node:node /app
|
||||
|
||||
EXPOSE 20128
|
||||
|
||||
# Drop to non-root before ENTRYPOINT/CMD so every derived stage (runner-cli,
|
||||
# runner-web) also runs as a non-root user unless they explicitly switch back.
|
||||
USER node
|
||||
|
||||
# Warns if the mounted data volume has wrong ownership
|
||||
COPY --chmod=755 scripts/check-permissions.sh /tmp/check-permissions.sh
|
||||
ENTRYPOINT ["/tmp/check-permissions.sh"]
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD ["node", "healthcheck.mjs"]
|
||||
|
||||
CMD ["node", "run-standalone.mjs"]
|
||||
CMD ["node", "dev/run-standalone.mjs"]
|
||||
|
||||
# ── Runner Web (web-cookie providers: Gemini Web, Claude Turnstile) ───────────
|
||||
#
|
||||
# Two image flavors:
|
||||
# runner-base → omniroute:VERSION Lean base (~500 MB). No browsers.
|
||||
# runner-web → omniroute:VERSION-web +Chromium/Playwright (~800 MB).
|
||||
#
|
||||
# Use runner-web when you need web-cookie providers (gemini-web, claude-web,
|
||||
# claude-turnstile). For all other providers runner-base is sufficient.
|
||||
#
|
||||
# Build:
|
||||
# docker build --target runner-web -t omniroute:web .
|
||||
# Compose:
|
||||
# build:
|
||||
# context: .
|
||||
# target: runner-web
|
||||
FROM runner-base AS runner-web
|
||||
|
||||
USER root
|
||||
|
||||
# Copy playwright and playwright-core from the builder stage.
|
||||
# The slim runtime image does not have playwright in node_modules, so npx falls
|
||||
# back to a registry download — unreliable on CI runners (exits 127 on failure).
|
||||
# Copying from the builder avoids any network access at image-build time and also
|
||||
# ensures the same playwright version is available at runtime for web-session providers.
|
||||
COPY --from=builder /app/node_modules/playwright-core ./node_modules/playwright-core
|
||||
COPY --from=builder /app/node_modules/playwright ./node_modules/playwright
|
||||
|
||||
# Install Playwright browser binaries + OS dependencies under root, then hand
|
||||
# ownership of the browsers cache to the node user.
|
||||
# PLAYWRIGHT_BROWSERS_PATH overrides the default ~/.cache/ms-playwright so the
|
||||
# browsers land under /home/node which persists across image layers and is
|
||||
# accessible to the non-root runtime user.
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/home/node/.cache/ms-playwright
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
|
||||
apt-get update \
|
||||
&& node node_modules/playwright/cli.js install chromium --with-deps \
|
||||
&& chown -R node:node /home/node/.cache \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
USER node
|
||||
|
||||
FROM runner-base AS runner-cli
|
||||
|
||||
# Drop back to root briefly so we can install system + global npm packages,
|
||||
# then return to the `node` non-root user before the CMD inherited from
|
||||
# runner-base runs.
|
||||
USER root
|
||||
|
||||
# Install system dependencies required by openclaw (git+ssh references).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git ca-certificates \
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \
|
||||
apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git ca-certificates docker.io docker-compose \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& git config --system url."https://github.com/".insteadOf "ssh://git@github.com/"
|
||||
|
||||
# Install CLI tools globally. Separate layer from apt for better cache reuse.
|
||||
RUN npm install -g --no-audit --no-fund @openai/codex @anthropic-ai/claude-code droid openclaw@latest
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm install -g --no-audit --no-fund @openai/codex @anthropic-ai/claude-code droid openclaw@latest
|
||||
|
||||
USER node
|
||||
|
||||
50
GEMINI.md
Normal file
50
GEMINI.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Security and Cleanliness Rules for AI Assistants
|
||||
|
||||
> **Scope:** rules for Gemini-based agents. For Claude Code, see `CLAUDE.md`. For other AI assistants, see `AGENTS.md`.
|
||||
|
||||
## 1. File Placement & Organization
|
||||
|
||||
- **Test Files**: ALL unit tests, integration tests, ecosystem tests, or Vitest files MUST strictly be placed within the `tests/` directory (e.g., `tests/unit/`, `tests/integration/`). NEVER create test files in the project root (`/`).
|
||||
- **Scripts and Utilities**: ALL maintenance, debugging, generation, or experimental scripts (`.cjs`, `.mjs`, `.js`, `.ts`) MUST be placed strictly inside one of the `scripts/` subfolders (`build/`, `dev/`, `check/`, `docs/`, `i18n/`, `ad-hoc/`). One-shot or experimental code goes under `scripts/ad-hoc/`. NEVER dump loose scripts in the project root (`/`) or the top-level `scripts/` folder.
|
||||
|
||||
**The Project Root MUST ONLY CONTAIN:**
|
||||
|
||||
- Configuration files (`vitest.config.ts`, `next.config.mjs`, `eslint.config.mjs`, `tsconfig*.json`, `playwright.config.ts`, `prettier.config.mjs`, `postcss.config.mjs`, `sonar-project.properties`, `fly.toml`, `docker-compose*.yml`, `Dockerfile`)
|
||||
- Dependency files (`package.json`, `package-lock.json`)
|
||||
- Documentation files (`README.md`, `CHANGELOG.md`, `LICENSE`, `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, `CONTRIBUTING.md`, `SECURITY.md`, `CODE_OF_CONDUCT.md`, `llm.txt`, `Tuto_Qdrant.md`)
|
||||
- CI/CD files and ignore definitions (`.gitignore`, `.dockerignore`, `.npmignore`, `.npmrc`, `.node-version`, `.nvmrc`, `.env.example`)
|
||||
|
||||
When creating _any_ validation tests or one-off logic scripts, default to using `scripts/ad-hoc/` or the `tests/unit/` directories according to your goals. Do not pollute the `/` root context.
|
||||
|
||||
## 2. Hard Rules (mirror of `CLAUDE.md`)
|
||||
|
||||
1. **Never commit secrets or credentials.** Use `.env` (auto-generated from `.env.example`) or a vault. Passwords, OAuth secrets, API keys, and Cookie values must never appear in committed files.
|
||||
2. **Never add logic to `src/lib/localDb.ts`.** It is a re-export barrel only.
|
||||
3. **Never use `eval()`, `new Function()`, or any implied eval.** ESLint enforces this.
|
||||
4. **Never commit directly to `main`.** Use `feat/`, `fix/`, `refactor/`, `docs/`, `test/`, or `chore/` branches.
|
||||
5. **Never write raw SQL in routes** — always go through `src/lib/db/` domain modules.
|
||||
6. **Never silently swallow errors in SSE streams** — propagate them or abort the stream cleanly.
|
||||
7. **Never bypass Husky hooks** (`--no-verify`, `--no-gpg-sign`) without explicit operator approval.
|
||||
8. **Always validate inputs with Zod schemas** from `src/shared/validation/schemas.ts`.
|
||||
9. **Always include tests when changing production code** (`src/`, `open-sse/`, `electron/`, `bin/`).
|
||||
10. **Coverage must stay** ≥ 75 % statements / 75 % lines / 75 % functions / 70 % branches (real measured: ~82 %).
|
||||
|
||||
## 3. Codebase navigation
|
||||
|
||||
| Task | Read this first |
|
||||
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Understand the codebase | `docs/architecture/REPOSITORY_MAP.md` |
|
||||
| Architecture overview | `docs/architecture/ARCHITECTURE.md` |
|
||||
| Engineering reference | `docs/architecture/CODEBASE_DOCUMENTATION.md` |
|
||||
| Add a feature | `CONTRIBUTING.md` + the matching `docs/<area>.md` |
|
||||
| Per-area deep dives | `docs/frameworks/SKILLS.md`, `docs/frameworks/MEMORY.md`, `docs/frameworks/EVALS.md`, `docs/security/GUARDRAILS.md`, `docs/security/COMPLIANCE.md`, `docs/frameworks/CLOUD_AGENT.md`, `docs/frameworks/MCP-SERVER.md`, `docs/frameworks/A2A-SERVER.md`, `docs/architecture/AUTHZ_GUIDE.md`, `docs/architecture/RESILIENCE_GUIDE.md`, `docs/routing/AUTO-COMBO.md`, `docs/frameworks/WEBHOOKS.md`, `docs/routing/REASONING_REPLAY.md`, `docs/security/STEALTH_GUIDE.md`, `docs/ops/TUNNELS_GUIDE.md`, `docs/guides/ELECTRON_GUIDE.md`, `docs/reference/PROVIDER_REFERENCE.md` |
|
||||
| Release flow | `docs/ops/RELEASE_CHECKLIST.md` |
|
||||
|
||||
## 4. Local development access
|
||||
|
||||
The dashboard is reachable at the operator's chosen URL/port (default `http://localhost:20128`). Credentials are operator-specific:
|
||||
|
||||
- **Initial admin password** is read from the `INITIAL_PASSWORD` env var on first install (defaults to `CHANGEME` in `.env.example`; rotate immediately after first login).
|
||||
- **Local VPS / shared dev environments**: ask the operator for the URL and current credentials — they live in their personal vault, NOT in this repo.
|
||||
|
||||
> Any credential observed in a previous version of this file was a non-production demo value; treat it as compromised and do not reuse it.
|
||||
209
PLANO-QUALITY-GATES-FASE6A.md
Normal file
209
PLANO-QUALITY-GATES-FASE6A.md
Normal file
@@ -0,0 +1,209 @@
|
||||
# Fase 6A — Auditoria Crítica das Fases 0–6: o que deixamos passar
|
||||
|
||||
> **Para workers agênticos:** SUB-SKILL OBRIGATÓRIA: `superpowers:subagent-driven-development` (recomendado) ou `superpowers:executing-plans`, tarefa-a-tarefa. Tarefas P0/P1 maiores devem ser **expandidas em sub-plano bite-sized próprio** (`writing-plans`) no momento da execução. Hard Rule #18 (TDD/VPS) em tudo. Auditar subagentes (trust-but-verify) após cada task.
|
||||
|
||||
> # ⏳ PORTÃO DE ATIVAÇÃO — NÃO INICIAR ANTES DE **2026-06-16**
|
||||
> Mesma janela da Fase 7 (decisão do owner 2026-06-09: 1 semana de uso em produção das Fases 0–6 antes de evoluir). **Ordem na ativação: Fase 6A ANTES da Fase 7** — primeiro consertamos/endurecemos o que já existe, depois adicionamos ferramentas novas.
|
||||
> **Exceção possível (decisão do owner):** as tasks **6A.1 e 6A.2 são bugs pré-existentes descobertos pela auditoria** (testes que nunca rodam + suíte vitest fora do CI), não "gates novos" — podem ser antecipados como fix avulso se o owner preferir não esperar a janela.
|
||||
|
||||
**Goal:** Fechar os furos que a auditoria crítica pós-implementação (2026-06-09, análise inline dos 18 gates + motor + CI + baselines) encontrou nas Fases 0–6 — antes de adicionar qualquer ferramenta nova na Fase 7.
|
||||
|
||||
**Architecture:** Zero ferramenta nova (tudo homegrown, padrão `check-*.mjs` + motor existente). Três frentes: (1) **bugs sistêmicos de runner** descobertos (testes órfãos, vitest fora do CI); (2) **endurecimento do padrão de catraca** (stale-allowlist enforcement + require-tighten, validados pela prática da Notion); (3) **expansão de escopo** dos gates existentes (diretórios/superfícies que ficaram de fora).
|
||||
|
||||
**Tech Stack:** Node ≥20 ESM, ESLint 9 flat, c8, jscpd@4 (a pinar), GitHub Actions, Node native test runner, vitest. Nada novo em `dependency-allowlist.json` exceto a promoção do jscpd a devDependency (Task 6A.12).
|
||||
|
||||
---
|
||||
|
||||
## Origem: o que a auditoria encontrou (resumo dos achados)
|
||||
|
||||
Método: releitura inline de todos os `scripts/check/*.{mjs,ts}` criados nas Fases 0–6, `scripts/quality/*`, baselines, `ci.yml`, `package.json`, hooks Husky e docs — sem subagentes — mais validação por pesquisa (sistema de ratcheting da Notion; práticas de suppression-hygiene de linters).
|
||||
|
||||
| # | Achado | Gravidade | Task |
|
||||
|---|--------|-----------|------|
|
||||
| A1 | **≈135 arquivos `*.test.ts` em subdiretórios de `tests/unit/` não são coletados por NENHUM runner** — `test:unit`, `test:coverage` e os shards do CI usam o glob não-recursivo `tests/unit/*.test.ts`; o vitest só inclui `autoCombo/**` (+ `.tsx`). Inclui `authz/routeGuard.test.ts` (Hard Rules #15/#17), 50 testes de `compression/`, 12 de `services/`, 10 de `gamification/`, 6 de `guardrails/`, 5 de `security/`. **Amostra rodada na auditoria: 2 asserts de `routeGuard.test.ts` FALHAM hoje** ("management policy allows /api/services/ (e /api/copilot/chat) from localhost with valid CLI token") — o arquivo apodreceu sem ninguém ver, provavelmente desde o redesign do peer-stamp (2026-05-31) | **P0 — falso verde sistêmico** | 6A.1 |
|
||||
| A2 | **Nenhum workflow roda `test:vitest`** (`grep -rln vitest .github/workflows/` = vazio). O CLAUDE.md afirma "Both test runners must pass… before merging", mas a suíte vitest (MCP server 43 tools, autoCombo, cache, componentes) está 100% fora da esteira | **P0** | 6A.2 |
|
||||
| B1 | **Nenhum gate falha quando uma entrada de allowlist deixa de ser necessária.** Os 18 gates congelam ~90 violações em `KNOWN_*`; quando alguém corrige a violação (ex.: criar `/api/gamification/level` da issue #3484, remover `krutrim` da #3483), a entrada vira um furo aberto — a regressão pode VOLTAR sem revisão. Só `check-error-helper` tem detecção parcial (WARN de arquivo inexistente, que ninguém lê). Prática validada: linters maduros "yell when an exclusion exists that doesn't break the rule" | **P0 — corrói a catraca com o tempo** | 6A.3 |
|
||||
| B2 | **Melhoria não-capturada vira folga permanente no motor**: sem `--update` manual, uma métrica que melhorou pode regredir de volta até o baseline antigo sem ninguém ver. A Notion auto-decrementa budgets no pre-commit; nosso motor não exige aperto | P1 | 6A.5 |
|
||||
| B3 | EPS único (0.01) para todas as métricas; o plano da Fase 4 pedia epsilon maior para `coverage.branches` (não-determinismo do v8) e não foi implementado | P1 | 6A.5 |
|
||||
| B4 | Métrica coletada sem entrada no baseline é ignorada em silêncio (coletor novo esquecido do baseline = falso conforto) | P2 | 6A.5 |
|
||||
| C1 | `check-fetch-targets` só varre `src/app/(dashboard)` — **20+ arquivos com `fetch("/api/…")` fora do escopo**: `src/shared/components/` (Sidebar, CommandPalette, modais…), `src/app/connect/`, `src/app/status/`, `src/lib/evals/` | P1 | 6A.7 |
|
||||
| C2 | `check-fetch-targets` ignora 100% dos template literals (`` fetch(`/api/x/${id}`) ``) — nem o prefixo estático é validado | P1 | 6A.7 |
|
||||
| C3 | `check-fetch-targets` não valida o método HTTP (fetch `POST` → rota só com `GET` = 405 em runtime, gate verde) | P2 | 6A.7 |
|
||||
| C4 | `check-deps` cobre só `package.json` raiz + `electron/` — **`@omniroute/opencode-plugin` (dep `zod` + 5 devDeps, pacote PUBLICADO no npm), `@omniroute/opencode-provider` e `open-sse/` ficam fora** | P1 | 6A.8 |
|
||||
| C5 | `check-public-creds` escaneia só 2 arquivos hardcoded — credencial literal em arquivo NOVO (executor, oauth provider) passa batida | P1 | 6A.8 |
|
||||
| C6 | `check-error-helper` cobre `open-sse/executors` + `handlers` — a Hard Rule #12 também fala de **MCP handlers** (`open-sse/mcp-server/`) e rotas HTTP (`src/app/api/`), fora do escopo | P1 | 6A.8 |
|
||||
| C7 | `check-file-size` e `check-complexity` varrem `src` + `open-sse` — `electron/` e `bin/` fora (god-file pode nascer lá) | P2 | 6A.11 |
|
||||
| C8 | `check-known-symbols` cobre executors/strategies/translators — **faltam as 3 superfícies de despacho por-string restantes: MCP tools (43), A2A skills (5, `A2A_SKILL_HANDLERS`), cloud agents (3, registry)** | P1 | 6A.9 |
|
||||
| C10 | `check-route-guard-membership` depende da lista manual `SPAWN_CAPABLE_ROUTE_ROOTS` (3 raízes) — rota nova que spawna processo FORA dessas raízes é invisível ao gate | P1 | 6A.8 |
|
||||
| C11 | `check-openapi-coverage` (THRESHOLD=36%) e `check-ui-keys-coverage` (65%) são pisos fixos manuais — não ratcheteiam; rotas/strings novas sem doc/i18n passam enquanto o % não cai do piso | P2 | 6A.11 |
|
||||
| C12 | `check-test-masking`: (a) `--diff-filter=M` não vê teste **DELETADO** (o masking mais brutal); (b) não vê `.skip`/`.todo`/`.only` adicionados (mantêm os asserts no texto, mas nunca rodam); (c) tautologia só cobre `assert.ok(true)` | P1 | 6A.10 |
|
||||
| D1 | **`ci.yml` roda gates apenas em `pull_request → main`** — todo o ciclo de PRs feature→`release/vX` passa SEM gate; as violações acumulam por semanas e estouram juntas no merge release→main (observado no gate da v3.8.18: 4 fixes de typecheck + ReDoS de última hora) | P1 — decisão do owner | 6A.6 |
|
||||
| D2 | `.husky/pre-push` está 100% comentado, mas o CLAUDE.md afirma "pre-push: npm run test:unit" (drift doc↔real) | P2 | 6A.12 |
|
||||
| D3 | **CLAUDE.md não menciona nenhum dos 18 gates** — um agente futuro não sabe que existem, qual a política de allowlist ("corrija, não congele"), nem como apertar baselines. Hard Rule #9 ainda diz "≥60%" (a catraca real é 80/80/82/73) | **P0 — anti-alucinação para os próprios agentes** | 6A.4 |
|
||||
| D4 | `check-duplication` roda `npx --yes jscpd@4` — pacote **não pinado por lockfile**, baixado do registry a cada run do CI (supply-chain + flakiness + latência); contraria o espírito do próprio `check-deps` | P2 | 6A.12 |
|
||||
| D5 | A skill `/quality-scan` roda ~20 comandos um a um — falta um runner agregador paralelo | P2 | 6A.12 |
|
||||
| D6 | Baselines de coverage com folga de ~2,5pt (80/80/82/73 vs real ~82,6/82,6/84,2/75,2) — a nota "_aperte após o 1º run verde_" existe no JSON mas não é tarefa de ninguém | P1 | 6A.5 |
|
||||
| E4 | Sem guarda contra artefato trackeado por engano — `node_modules` symlink já foi commitado 2× neste repo (`git add -A` em worktree) | P2 | 6A.12 |
|
||||
|
||||
**Decisões conscientes de NÃO fazer (avaliadas e descartadas, com motivo):**
|
||||
- **Gate de idempotência de migrations via regex** — SQLite não tem `ADD COLUMN IF NOT EXISTS`; idempotência vive em try/catch do runner; regex seria frágil (FP/FN). O `check-migration-numbering` + revisão humana bastam.
|
||||
- **Endurecer `check-docs-counts-sync` para fail** — contagens em prosa são heurísticas; soft-fail é o design correto. A cobertura de MCP tools entra pela 6A.9 (símbolos, não prosa).
|
||||
- **Sentido inverso do provider-consistency (providers.ts → REGISTRY)** — muitos providers canônicos legitimamente não têm entrada no REGISTRY (web/OAuth-only); a allowlist nasceria com dezenas de entradas e baixa razão sinal/ruído. Reavaliar quando o refactor #3501 tocar o split de providers.
|
||||
- **Complexidade por-função/por-arquivo (formato any-budget)** — upgrade real, mas o count global + `max-lines-per-function` já bloqueiam o grosso; o formato per-file entra junto com `sonarjs/cognitive-complexity` na Fase 7 Task 5 para não pagar duas migrações de baseline.
|
||||
|
||||
---
|
||||
|
||||
# Tasks
|
||||
|
||||
## P0 — bugs sistêmicos + documentação
|
||||
|
||||
### Task 6A.1 — `check-test-discovery` + religamento triado dos ~135 testes órfãos ⭐
|
||||
|
||||
**O achado nº1 da auditoria.** Testes que não rodam são o falso verde definitivo — todo o investimento anti test-masking da Fase 4 protege asserts de testes que **nem executam**.
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/check/check-test-discovery.mjs` + `tests/unit/check-test-discovery.test.ts`
|
||||
- Modify: `package.json` (globs de `test:unit`, `test:coverage`), `.github/workflows/ci.yml` (globs dos shards 8×/node24/node26), `vitest.mcp.config.ts` ou `vitest.config.ts` (se algum subdir for re-homed para vitest)
|
||||
- Create: `test-discovery-baseline.json` (órfãos ainda-não-religados, catraca `down` até zerar)
|
||||
|
||||
**Approach (expandir em sub-plano na execução):**
|
||||
1. **Gate primeiro (TDD):** `check-test-discovery.mjs` enumera todo `**/*.{test,spec}.{ts,tsx}` do repo (fora de `node_modules`/`.next`) e verifica que cada arquivo é coletado por ≥1 runner: (a) globs do node test runner extraídos de `package.json`/`ci.yml`; (b) `include` dos dois `vitest.*config.ts`; (c) projetos Playwright. Órfão fora do baseline → exit 1. O baseline congela os órfãos atuais (catraca: não pode SUBIR; religamentos a fazem cair até `{}`).
|
||||
2. **Inventário verde/vermelho:** rodar cada subdir órfão isoladamente (`node --import tsx --test tests/unit/<dir>/*.test.ts`), registrar passa/falha. *Não* ligar tudo de uma vez — a amostra já provou que há vermelhos (`authz/routeGuard.test.ts`: 2 asserts).
|
||||
3. **Religar os verdes:** trocar o glob principal para recursivo — `"tests/unit/**/*.test.ts"` ENTRE ASPAS (expandido pelo test runner do Node, não pelo shell; **Step 0: validar o suporte a glob do runner na menor versão de Node suportada pelo repo** — fallback: listar os subdirs explicitamente) — em `test:unit`, `test:coverage` e nos 3 lugares do `ci.yml` (shards 8×, node24, node26). Remover religados do baseline.
|
||||
4. **Triar os vermelhos (Hard Rule #18 em cada um):** teste desatualizado → atualizar para o comportamento real (e provar que o comportamento real é o desejado); bug real revelado → fix TDD; teste de feature morta → deletar com justificativa no commit. Os 2 asserts do `routeGuard.test.ts` ("allows … with valid CLI token") são o primeiro caso: provável drift do peer-stamp de 2026-05-31 — MAS, por ser superfície de segurança (#15/#17), confirmar com cuidado que é o teste que está errado, não o guard.
|
||||
5. **Recalibrar cobertura:** religar ≈135 arquivos muda o denominador/numerador da cobertura — re-medir e apertar `quality-baseline.json` via `--update` no mesmo PR (resolve também o D6).
|
||||
|
||||
**Acceptance:** `check-test-discovery` no CI (job lint); zero órfãos fora do baseline; baseline decrescente documentado; suíte verde com os religados; cobertura recalibrada.
|
||||
|
||||
### Task 6A.2 — vitest no CI
|
||||
|
||||
**Files:** `.github/workflows/ci.yml` (job novo `test-vitest`, paralelo aos shards; NÃO tocar nos triggers — apenas adicionar job).
|
||||
|
||||
**Approach:** job com `npm ci` + `npm run test:vitest` (+ `test:vitest:ui` se o tempo couber; senão segundo step). Rodar localmente primeiro para garantir verde (a suíte passa hoje fora da esteira — confirmar). Se houver vermelho pré-existente, triagem antes do wire (mesmo protocolo da 6A.1 passo 4).
|
||||
|
||||
**Acceptance:** PR→main roda as DUAS suítes; o claim do CLAUDE.md ("both must be green") vira verdade mecânica.
|
||||
|
||||
### Task 6A.3 — Stale-allowlist enforcement em todos os gates (suppression hygiene)
|
||||
|
||||
**O endurecimento sistêmico nº1.** Padrão validado (ESLint `--report-unused-disable-directives`; Notion): exclusão que não exclui nada vivo é dívida fantasma e furo de regressão.
|
||||
|
||||
**Files:** todos os gates com allowlist + seus testes:
|
||||
`check-fetch-targets` (KNOWN_MISSING, 7) · `check-provider-consistency` (KNOWN_REGISTRY_ONLY, 1) · `check-openapi-routes` (KNOWN_STALE_SPEC, 1) · `check-public-creds` (KNOWN_LITERAL_CREDS, 5) · `check-db-rules` (KNOWN_UNEXPORTED 25 + KNOWN_RAW_SQL 15) · `check-docs-symbols` (KNOWN_STALE_DOC_REFS, 30) · `check-migration-numbering` (KNOWN_GAPS/DUPLICATES) · `check-error-helper` (KNOWN_MISSING_ERROR_HELPER, 7 — promover o WARN existente a FAIL e cobrir também "arquivo existe mas não viola mais") · `check-deps` (dependency-allowlist: entrada sem dep correspondente em manifest algum = stale) · `check-file-size` (entrada `frozen` cujo arquivo foi deletado/renomeado) · `check-route-guard-membership` (KNOWN_UNCLASSIFIED — vazio hoje; implementar o check para quando deixar de ser).
|
||||
|
||||
**Approach (mecânica única, TDD por gate):** após a detecção normal, re-avaliar cada entrada da allowlist: *"se esta entrada não existisse, o gate flagaria algo?"* — para allowlists de path/valor isso é `violationsDetectadas.has(entry)`; para arquivos, existência + violação presente. Entrada que não suprime nada → **exit 1** com mensagem `entrada obsoleta — a violação foi corrigida; REMOVA a entrada para travar a correção`. Extrair helper comum `reportStaleEntries(allowlist, liveViolations, gateName)` em `scripts/check/lib/allowlist.mjs` para não duplicar 11×.
|
||||
|
||||
**Acceptance:** corrigir qualquer violação congelada (ex.: as issues #3483–#3501) passa a EXIGIR a remoção da entrada no mesmo PR; teste sintético prova fail-on-stale em cada gate.
|
||||
|
||||
### Task 6A.4 — Documentar os gates no CLAUDE.md (+ corrigir drifts de doc)
|
||||
|
||||
**Files:** `CLAUDE.md`, `AGENTS.md` (se houver seção espelho), `docs/architecture/` (página `QUALITY_GATES.md` referenciada pela tabela de docs).
|
||||
|
||||
**Approach:** (1) seção nova "Quality Gates & Ratchets" no CLAUDE.md: tabela dos gates (nome → o que trava → allowlist/baseline), a política **"corrija a causa; allowlist só com justificativa + issue"**, como apertar (`npm run quality:ratchet -- --update`, `check:<gate> -- --update`), e o que fazer quando um gate falha num PR. (2) Corrigir: Hard Rule #9 (60% → "catraca de cobertura: nunca abaixo do baseline congelado em `quality-baseline.json`; piso absoluto 60"), claim do pre-push (refletir o real pós-6A.12), claim "both runners" (verdade pós-6A.2). (3) Página `docs/architecture/QUALITY_GATES.md` com o detalhe operacional (o CLAUDE.md fica curto, linka). Rodar `check:docs-all` após editar (o próprio docs-sync valida).
|
||||
|
||||
**Acceptance:** agente novo lendo o CLAUDE.md descobre os gates e a política sem ler scripts; `check:docs-all` verde.
|
||||
|
||||
## P1 — endurecimento do motor + escopos
|
||||
|
||||
### Task 6A.5 — Motor v2: `--require-tighten`, eps por métrica, métricas órfãs
|
||||
|
||||
**Files:** `scripts/quality/check-quality-ratchet.mjs`, `quality-baseline.json` (schema), `tests/unit/quality-ratchet.test.ts`, `.github/workflows/ci.yml` (flag no job quality-gate).
|
||||
|
||||
**Approach (TDD):**
|
||||
1. Schema por métrica ganha campos opcionais: `eps` (default 0.01) e `tightenSlack` (default: igual a `eps`).
|
||||
2. Novo modo `--require-tighten` (ligado no CI): se `atual` melhor que `baseline` além de `tightenSlack`, **exit 1** com `melhorou de X para Y — rode 'npm run quality:ratchet -- --update' e commite o baseline apertado neste PR`. Métricas determinísticas (`eslintWarnings`) usam slack 0; cobertura usa slack 1.5 (flutuação v8). É o "auto-decrement" da Notion adaptado a CI sem bot de commit.
|
||||
3. Warning para métricas presentes em `quality-metrics.json` sem entrada no baseline (coletor órfão).
|
||||
4. Calibrar os 4 `coverage.*` para o real medido (fecha D6 — coordenar com a 6A.1 passo 5, que muda a base).
|
||||
|
||||
**Acceptance:** melhoria sem aperto de baseline falha no CI; flutuação de coverage dentro do slack não falha; testes cobrem os 3 comportamentos novos.
|
||||
|
||||
### Task 6A.6 — `quality.yml`: gates rápidos em PRs → `release/**` ⚠️ DECISÃO DO OWNER
|
||||
|
||||
**Contexto sensível:** o owner já reverteu mudança de trigger no `ci.yml` ("não mexe na CI"). Esta task **não toca o `ci.yml`** — cria um workflow NOVO e enxuto. Ainda assim, **passo 0 = confirmação explícita do owner**.
|
||||
|
||||
**Files:** Create: `.github/workflows/quality.yml`.
|
||||
|
||||
**Approach:** `on: pull_request: branches: ["release/**"]`; um job único (~1–2 min) só com os gates determinísticos filesystem-only: provider-consistency, fetch-targets, openapi-routes, docs-symbols, deps, file-size, error-helper, migration-numbering, public-creds, db-rules, known-symbols, route-guard-membership, test-discovery (pós-6A.1) + `check:any-budget:t11`. SEM lint/test/build (continuam só no PR→main). Ganho: a violação aparece no PR que a introduz, não semanas depois no gate do release (padrão observado: 4 fixes de última hora no release da v3.8.18).
|
||||
|
||||
**Acceptance:** PR de teste contra a release branch com uma rota inventada falha em <2 min; PRs limpos não ganham mais que ~2 min de CI.
|
||||
|
||||
### Task 6A.7 — `check-fetch-targets` v2: escopo completo + prefixo de template + método HTTP
|
||||
|
||||
**Files:** `scripts/check/check-fetch-targets.mjs`, `tests/unit/check-fetch-targets.test.ts`.
|
||||
|
||||
**Approach (TDD):**
|
||||
1. **Escopo:** varrer todo `src/**/*.{ts,tsx}` client-side (excluindo `src/app/api/**`, testes, `src/lib/db`), não só `(dashboard)` — congela os misses pré-existentes que aparecerem em `KNOWN_MISSING` (com triagem/issue por cluster, igual Fase 2).
|
||||
2. **Template literals:** extrair o prefixo estático de `` fetch(`/api/x/y/${id}…`) `` e validar por **prefix-match** contra as rotas reais (existe alguma rota cujo path começa com `/api/x/y/`?). Pega diretório inteiro alucinado; não tenta resolver o sufixo dinâmico.
|
||||
3. **Método HTTP (heurístico, mesma chamada):** quando o 2º argumento literal contém `method: "POST"` (etc.), verificar que o `route.ts` resolvido exporta a função correspondente (`grep` por `export (async )?function POST` / `export const POST`). Sem method literal → assume GET-ok (rota existe basta). Casos dinâmicos → skip silencioso.
|
||||
|
||||
**Acceptance:** fixture com fetch em `src/shared/components` + template com prefixo falso + `method: "DELETE"` para rota só-GET — 3 detecções; repo real verde com os novos congelados documentados.
|
||||
|
||||
### Task 6A.8 — Escopo dos gates de segurança: error-helper, public-creds, route-guard, deps
|
||||
|
||||
**Files:** `check-error-helper.mjs`, `check-public-creds.mjs`, `check-route-guard-membership.ts`, `check-deps.mjs` + testes.
|
||||
|
||||
**Approach (TDD, um sub-commit por gate):**
|
||||
1. **error-helper** (+Rule #12 completa): incluir `open-sse/mcp-server/**` e `src/app/api/**/route.ts` no SCAN_DIRS; rodar; congelar os achados novos em KNOWN com comentário-justificativa cada (e issue por cluster).
|
||||
2. **public-creds**: além dos 2 arquivos âncora, varrer `open-sse/**` e `src/lib/oauth/**` com a mesma `CRED_KEY_RE` (linha a linha, barato); congelar achados. Limitação documentada: `const CLIENT_ID = "…"` (variável solta) continua fora — o gitleaks da Fase 7 cobre essa classe.
|
||||
3. **route-guard**: novo sub-check — todo `route.ts` (qualquer raiz) cujo fonte OU imports de 1º nível relativos contenham `child_process`/`spawn(`/`execFile(`/`worker_threads` deve ser classificado local-only por `isLocalOnlyPath()`. Mata a dependência da lista manual de 3 raízes.
|
||||
4. **deps**: `MANIFESTS` → descoberta automática de todo `package.json` do repo (fora `node_modules`/`.next`): hoje raiz, `electron/`, `open-sse/`, `@omniroute/opencode-plugin/` (dep `zod` entra na allowlist), `@omniroute/opencode-provider/`. Workspace novo amanhã entra sozinho.
|
||||
|
||||
**Acceptance:** fixtures sintéticas por gate; repo real verde com achados congelados + issues; dep nova em QUALQUER manifest do repo dispara o gate.
|
||||
|
||||
### Task 6A.9 — `check-known-symbols` v2: MCP tools, A2A skills, cloud agents
|
||||
|
||||
**Files:** `scripts/check/check-known-symbols.ts`, `tests/unit/check-known-symbols.test.ts`.
|
||||
|
||||
**Approach (TDD, mesmo padrão das 3 superfícies existentes — Step 0 de verificação dos exports reais antes de codar):**
|
||||
1. **MCP tools:** enumerar os tools registrados (via `createMcpServer()` ou parse determinístico do tool-set em `open-sse/mcp-server/tools/`) e congelar o snapshot de nomes (catraca: tool sumir = fail; tool novo = report). Cruzar com os scopes (~13) — tool sem scope atribuído = fail.
|
||||
2. **A2A skills:** chaves de `A2A_SKILL_HANDLERS` (`src/lib/a2a/taskExecution.ts`) ↔ skills expostas no Agent Card (`src/app/.well-known/agent.json/route.ts`) — divergência = fail.
|
||||
3. **Cloud agents:** entradas do `src/lib/cloudAgent/registry.ts` ↔ classes em `agents/` — incompleto/órfão = fail.
|
||||
|
||||
**Acceptance:** remover um tool/skill/agent do registro quebra o gate; adicionar reporta (e `check-docs-counts-sync` continua cuidando da prosa).
|
||||
|
||||
## P2 — refinamentos
|
||||
|
||||
### Task 6A.10 — `check-test-masking` v2: deleções, skips, tautologias
|
||||
|
||||
**Files:** `scripts/check/check-test-masking.mjs`, `tests/unit/check-test-masking.test.ts`.
|
||||
|
||||
**Approach (TDD):** (a) `--diff-filter=M` → `MDR` (com `-M` para rename-detection): arquivo de teste **deletado** = flag automático ("N asserts removidos — arquivo deletado"); renamed = comparar contra o path antigo. (b) Contar `\.(skip|todo|only)\s*\(` + `\{\s*skip:\s*true` base vs HEAD — **aumento líquido de skips = flag** (skip novo esconde asserts sem removê-los); `.only` novo = flag sempre (filtra o resto da suíte). (c) Tautologias extras: `expect(true).toBe(true)`, `assert.equal(1, 1)`, `expect(x).toBeDefined()` como ÚNICO assert do teste.
|
||||
|
||||
**Acceptance:** fixtures para os 3 bypasses (delete, skip, only) — todos flagados; suíte real verde.
|
||||
|
||||
### Task 6A.11 — Pisos manuais → catraca do motor + escopo electron/bin
|
||||
|
||||
**Files:** `scripts/quality/collect-metrics.mjs`, `quality-baseline.json`, `check-openapi-coverage.mjs`, `scripts/i18n/check-ui-keys-coverage.mjs` (só leitura do valor), `check-file-size.mjs`, `eslint.complexity.config.mjs` + baselines.
|
||||
|
||||
**Approach:** (1) coletor emite `openapiCoverage.pct` e `i18nUiCoverage.pct` → baseline `{direction: up}` com o valor real atual (36→real, 65→real); os THRESHOLDs fixos viram redundância de segurança (mantidos). Rotas/strings novas sem doc/i18n agora REGRIDEM o % e falham. (2) `check-file-size` e `check-complexity`: adicionar `electron/` e `bin/` ao scan (congelar os >cap que existirem).
|
||||
|
||||
**Acceptance:** rota nova não-documentada derruba `openapiCoverage.pct` → gate falha; god-file novo em `electron/` falha.
|
||||
|
||||
### Task 6A.12 — Higiene operacional (4 itens pequenos)
|
||||
|
||||
**Files:** `package.json`, `dependency-allowlist.json`, `.husky/pre-push`, Create: `scripts/check/check-tracked-artifacts.mjs`, `scripts/quality/run-all-gates.mjs`; Modify: `.agents/skills/quality-scan/SKILL.md`.
|
||||
|
||||
**Approach:**
|
||||
1. **jscpd pinado:** `jscpd@^4` como devDependency (entra no lockfile + allowlist); `check-duplication` chama o binário local em vez de `npx --yes jscpd@4` (remove download de registry no CI + supply-chain risk + flakiness).
|
||||
2. **pre-push barato:** reativar com APENAS os gates determinísticos rápidos (<10s: fetch-targets, openapi-routes, db-rules, public-creds, migration-numbering, file-size, deps, error-helper) — NÃO `test:unit` (lento; CI cobre). Atualizar o claim do CLAUDE.md (coordenar com 6A.4).
|
||||
3. **check-tracked-artifacts:** falhar se `git ls-files` contém `node_modules/`, `.next/`, `coverage/`, `quality-metrics.json` ou symlink para fora do repo (o incidente do symlink trackeado já aconteceu 2×). Wire no lint job + pre-commit (é instantâneo).
|
||||
4. **Runner agregador:** `scripts/quality/run-all-gates.mjs` roda os gates em paralelo (pool ~4), agrega `{gate, exitCode, lastLine, durationMs}` e imprime a tabela consolidada; `npm run quality:scan`. A skill `/quality-scan` passa a chamá-lo (atualizar SKILL.md).
|
||||
|
||||
**Acceptance:** `npm run quality:scan` < 3 min com tabela única; pre-push roda <10s; `git add node_modules && commit` falha no pre-commit.
|
||||
|
||||
---
|
||||
|
||||
## Ordem de execução recomendada (na ativação, 2026-06-16+)
|
||||
|
||||
1. **6A.1 + 6A.2** (bugs de runner — destravam números reais de cobertura para o resto)
|
||||
2. **6A.3 + 6A.4** (stale-enforcement + docs — endurecem o que já roda)
|
||||
3. **6A.5** (motor v2) → **6A.6** (quality.yml, após OK do owner)
|
||||
4. **6A.7 → 6A.9** (escopos)
|
||||
5. **6A.10 → 6A.12** (refinamentos)
|
||||
6. Só então **Fase 7** (ferramentas novas sobre uma fundação consertada)
|
||||
|
||||
## Self-Review
|
||||
- **Cobertura dos achados:** todos os achados A*/B*/C*/D*/E* da tabela têm task (coluna Task); os descartados estão em "Decisões conscientes de NÃO fazer" com motivo. ✓
|
||||
- **Zero dependência nova** exceto a promoção do jscpd (que já roda hoje via npx, não-pinado — a task REDUZ risco). ✓
|
||||
- **Sem flag-day:** toda expansão de escopo congela os achados pré-existentes (allowlist + issue), igual Fases 0–6; o stale-enforcement só exige remoção quando a correção JÁ aconteceu. ✓
|
||||
- **Consistência com o motor:** novas métricas (`openapiCoverage.pct`, `i18nUiCoverage.pct`) usam o formato `{value, direction}`; `eps`/`tightenSlack` são opcionais e retrocompatíveis. ✓
|
||||
- **Não-duplicação com a Fase 7:** cognitive-complexity per-file, gitleaks (creds não-públicas), knip, osv — tudo continua na Fase 7; a 6A só conserta/endurece o existente. ✓
|
||||
182
PLANO-QUALITY-GATES-FASE7.md
Normal file
182
PLANO-QUALITY-GATES-FASE7.md
Normal file
@@ -0,0 +1,182 @@
|
||||
# Fase 7 — Quality Gates: Segurança, Dead-Code, Mutação & Ferramental Community
|
||||
|
||||
> **Para workers agênticos:** SUB-SKILL OBRIGATÓRIA: `superpowers:subagent-driven-development` (recomendado) ou `superpowers:executing-plans`, tarefa-a-tarefa. Cada tarefa aqui é um subsistema independente → **expandir em sub-plano bite-sized próprio** no momento da execução. Hard Rule #18 (TDD/VPS) em tudo.
|
||||
|
||||
> # ⏳ PORTÃO DE ATIVAÇÃO — NÃO INICIAR ANTES DE **2026-06-16**
|
||||
> **Este plano está GUARDADO, não ativo.** Decisão do owner (2026-06-09): finalizar 100% as Fases 0–6 (PR #3471), **usar em produção por 1 semana** para validar na prática, e só então evoluir. **Data cravada de início da Fase 7: 2026-06-16.** Não ativar antes — o objetivo da semana é coletar sinal real (falsos-positivos dos gates, custo de CI, atrito) antes de adicionar mais.
|
||||
> **Pré-condições para ativar:** (1) PR #3471 (Fases 0–6) mergeada e rodada ≥1 semana; (2) re-home do PR para `release/v3.8.18` resolvido; (3) as issues #3483–#3501 com decisões aplicadas ou conscientemente adiadas; (4) **Fase 6A executada (ou conscientemente re-priorizada)** — a auditoria crítica de 2026-06-09 ([`PLANO-QUALITY-GATES-FASE6A.md`](./PLANO-QUALITY-GATES-FASE6A.md)) encontrou bugs sistêmicos de runner (≈135 testes órfãos, vitest fora do CI) e furos de escopo nos gates existentes que devem ser consertados ANTES de adicionar ferramentas novas por cima.
|
||||
|
||||
**Goal:** Maximizar a cobertura de quality gates do OmniRoute adicionando catracas de **segurança** (Sonar/osv/CodeQL → zero na timeline), **dead-code**, **complexidade cognitiva**, **type-coverage**, **mutação**, **bundle-size**, **a11y** e completando o anti-slopsquatting — usando **somente ferramentas Community/OSS** (projeto é open-source, zero SaaS pago, dados na box).
|
||||
|
||||
**Architecture:** Reusa o motor existente — toda métrica numérica entra como `{value, direction}` em `quality-baseline.json` (catraca só-regressão) ou vira um `scripts/check/check-*.mjs` dedicado (padrão `check-t11-any-budget.mjs`). Gates pesados vão no job paralelo `quality-gate`; gates rápidos no `lint`; mutação/visual em job nightly separado. Tudo só-regressão (sem flag-day).
|
||||
|
||||
**Tech Stack (tudo OSS/Community):** SonarQube **Community Build** (self-hosted) · osv-scanner (Google) · CodeQL (GitHub, grátis p/ público) · knip · eslint-plugin-sonarjs · type-coverage · lockfile-lint · dpdm · Stryker (`@stryker-mutator/*`) · size-limit · `@axe-core/playwright` · semcheck · agent-lsp (MCP) · Qlty CLI (OSS, opcional) · **gitleaks** (secret scanning, MIT; avaliar o sucessor drop-in Betterleaks, 2026-03) · **actionlint + zizmor** (lint + auditoria de segurança dos workflows) · **license-compliance** (allowlist SPDX de licenças). ESLint 9 flat · c8 · Node native test runner · GitHub Actions.
|
||||
|
||||
---
|
||||
|
||||
## Princípio (igual às Fases 0–6)
|
||||
|
||||
Toda catraca é **só-regressão**: congela o baseline atual, bloqueia QUALQUER piora, decai a zero/melhor com o tempo via `--update`. Nenhum gate exige limpeza imediata (flag-day). Cada ferramenta nova que vira dependência **deve ser adicionada a `dependency-allowlist.json`** (o gate `check-deps` da Fase 2 vai exigir — é o ponto de revisão humana).
|
||||
|
||||
## Mapa de arquivos (criar/modificar)
|
||||
|
||||
| Arquivo | Responsabilidade |
|
||||
|---|---|
|
||||
| `quality-baseline.json` (modificar) | + `vulnCount`, `codeqlAlerts`, `sonarIssues`, `cognitiveComplexity`, `typeCoveragePct`, `deadExports` |
|
||||
| `scripts/quality/collect-metrics.mjs` (modificar) | + coletores: osv-scanner, CodeQL count, Sonar API, knip, type-coverage, sonarjs |
|
||||
| `scripts/check/check-vuln-ratchet.mjs` (criar) | osv-scanner → vulnCount (catraca) |
|
||||
| `scripts/check/check-dead-code.mjs` (criar) | knip → exports/files/deps mortos (catraca) |
|
||||
| `scripts/check/check-cognitive-complexity.mjs` + `eslint.sonarjs.config.mjs` (criar) | sonarjs/cognitive-complexity em config isolado (não polui o count principal) |
|
||||
| `scripts/check/check-type-coverage.mjs` (criar) | type-coverage % (catraca up) |
|
||||
| `scripts/check/check-lockfile.mjs` (criar) | lockfile-lint (host/https/integrity) |
|
||||
| `scripts/check/check-pr-evidence.mjs` (criar) | exige output de comando no corpo do PR (Rule #18 mecânica) |
|
||||
| `scripts/check/check-bundle-size.mjs` + `.size-limit.json` (criar) | size-limit → orçamento de bundle |
|
||||
| `tests/e2e/a11y.spec.ts` (criar) | `@axe-core/playwright` nas páginas-chave |
|
||||
| `stryker.conf.json` (criar) | mutação nos ~8 módulos críticos (nightly) |
|
||||
| `sonar-project.properties` (modificar) | remover `coverage`/`cpd` exclusions; ativar new-code gate |
|
||||
| `.github/workflows/ci.yml` (modificar) | wirar novos gates (lint / quality-gate / nightly) + `qualitygate.wait` no Sonar |
|
||||
| `semcheck.yaml` (criar) | semcheck: docs↔código (camada fuzzy LLM, opcional) |
|
||||
| `.mcp.json` / config de agentes (modificar) | registrar agent-lsp (LSP-in-the-loop) |
|
||||
| `.gitleaks.toml` + `scripts/check/check-secrets.mjs` (criar) | gitleaks → catraca de findings de secret (Task 18) |
|
||||
| `.github/workflows/quality.yml` ou job lint (modificar) | actionlint + zizmor sobre `.github/workflows/**` (Task 19) |
|
||||
| `scripts/check/check-licenses.mjs` + `.license-allowlist.json` (criar) | allowlist SPDX das licenças das deps (Task 20) |
|
||||
| `dependency-allowlist.json` (modificar) | + osv-scanner, knip, sonarjs, type-coverage, lockfile-lint, stryker, size-limit, axe-core, dpdm, license-compliance |
|
||||
|
||||
---
|
||||
|
||||
## Tarefas (cada uma = 1 sub-plano bite-sized na execução)
|
||||
|
||||
### Task 1 — Ativar SonarQube Community + "Clean as You Code" (gate de segurança nativo)
|
||||
- **Tool:** SonarQube Community Build (self-hosted, grátis).
|
||||
- **Files:** `sonar-project.properties`, `.github/workflows/ci.yml` (job `sonarqube`).
|
||||
- **Approach:** setar secrets `SONAR_TOKEN`/`SONAR_HOST_URL`; **remover** `sonar.coverage.exclusions=**/*` e `sonar.cpd.exclusions=**/*` (hoje neutralizam o Sonar); ativar o quality gate **new-code / "Clean as You Code"** (código novo não pode adicionar issue/bug/vuln/hotspot; legado grandfathered) + adicionar `-Dsonar.qualitygate.wait=true` para **bloquear** o PR (hoje o job é inerte: secrets-gated, sem wait).
|
||||
- **Acceptance:** PR que introduz um code-smell/bug/vuln em código novo falha o gate; legado não bloqueia. Documentar suppressions legítimas (já há h1–h6 no properties).
|
||||
|
||||
### Task 2 — Catraca de vulnerabilidades (osv-scanner)
|
||||
- **Tool:** osv-scanner (Google/OSV, OSS) — `--format json`, on-box.
|
||||
- **Files:** `scripts/check/check-vuln-ratchet.mjs`, `quality-baseline.json` (+`vulnCount`), `collect-metrics.mjs`, `ci.yml` (job `quality-gate`), `dependency-allowlist.json`.
|
||||
- **Approach:** rodar `osv-scanner --format json` sobre os lockfiles → contar vulns → métrica `vulnCount {direction: down}`. Catraca: não pode subir, decai a zero. Mantém o `npm audit` escalonado da Fase 0 como bloqueio de crítico imediato; osv é o ratchet de timeline.
|
||||
- **Acceptance:** nova dep com vuln conhecida sobe o count → falha; remediar/remover baixa → `--update`.
|
||||
|
||||
### Task 3 — Catraca de alertas CodeQL
|
||||
- **Tool:** GitHub CodeQL (já roda; grátis p/ repo público).
|
||||
- **Files:** `scripts/check/check-codeql-ratchet.mjs`, `quality-baseline.json` (+`codeqlAlerts`), `ci.yml`.
|
||||
- **Approach:** puxar a contagem de alertas abertos via `gh api /repos/{owner}/{repo}/code-scanning/alerts?state=open` → métrica `codeqlAlerts {down}`. (Respeitar Hard Rule #14 — dismiss só com justificativa; alertas dismissed não contam.)
|
||||
- **Acceptance:** novo alerta CodeQL sobe o count → sinaliza; resolver baixa.
|
||||
|
||||
### Task 4 — Dead-code / unused-exports / unused-deps (knip)
|
||||
- **Tool:** knip (OSS, v6+) — `--reporter json`.
|
||||
- **Files:** `scripts/check/check-dead-code.mjs`, `quality-baseline.json` (+`deadExports`/`unusedDeps`), `knip.json` (config), `collect-metrics.mjs`, `ci.yml`, `dependency-allowlist.json`.
|
||||
- **Approach:** `knip --reporter json` sobre os workspaces `src/`+`open-sse/` → contar unused files/exports/deps → catraca `down`. Config knip ciente do monorepo + Next 16.
|
||||
- **Acceptance:** novo export/dep morto sobe → falha; remoção baixa.
|
||||
|
||||
### Task 5 — Complexidade cognitiva (eslint-plugin-sonarjs, config isolado)
|
||||
- **Tool:** eslint-plugin-sonarjs (OSS) — `sonarjs/cognitive-complexity`.
|
||||
- **Files:** `eslint.sonarjs.config.mjs` (config standalone, NÃO o principal — não polui o `eslintWarnings=3482`), `scripts/check/check-cognitive-complexity.mjs`, `quality-baseline.json` (+`cognitiveComplexity`), `ci.yml` (job `quality-gate`), `dependency-allowlist.json`.
|
||||
- **Approach:** mesmo molde do `check-complexity` (Fase 6) mas com `sonarjs/cognitive-complexity` num config isolado; contar violações → catraca `down`. (Complementa a complexidade ciclomática core já existente.)
|
||||
- **Acceptance:** função acima do limite cognitivo sobe o count → falha.
|
||||
|
||||
### Task 6 — Type-coverage ratchet
|
||||
- **Tool:** type-coverage (OSS).
|
||||
- **Files:** `scripts/check/check-type-coverage.mjs`, `quality-baseline.json` (+`typeCoveragePct {up}`), `dependency-allowlist.json`.
|
||||
- **Approach:** `type-coverage --detail --json` → % de símbolos tipados → catraca `up`. Complementa o `check:any-budget` (count de `any` por arquivo) com a visão %-global.
|
||||
- **Acceptance:** queda do % tipado → falha.
|
||||
|
||||
### Task 7 — Lockfile policy (lockfile-lint)
|
||||
- **Tool:** lockfile-lint (OSS, v5).
|
||||
- **Files:** `scripts/check/check-lockfile.mjs`, `ci.yml` (lint), `dependency-allowlist.json`.
|
||||
- **Approach:** `lockfile-lint --path package-lock.json --type npm --validate-https --validate-integrity --allowed-hosts npm` → gate pass/fail (não é ratchet; é política anti-poisoning). Complementa o `check-deps` (Fase 2).
|
||||
- **Acceptance:** lockfile com host não-https/sem integrity → falha.
|
||||
|
||||
### Task 8 — Completar anti-slopsquatting (registry-existence + age-cooldown)
|
||||
- **Tool:** npm registry API (`npm view <pkg> time.created`).
|
||||
- **Files:** `scripts/check/check-deps.mjs` (estender), test.
|
||||
- **Approach:** além do allowlist-diff atual, para uma dep NOVA: verificar que existe no registry E que foi publicada há ≥72h (age-cooldown contra "registra o nome alucinado em horas"). Base: CSA 2026 (19,7% de nomes alucinados; 43% reaparecem).
|
||||
- **Acceptance:** dep nova inexistente no registry ou publicada há <72h → falha (a menos que allowlistada com justificativa).
|
||||
|
||||
### Task 9 — Pisos de cobertura por módulo crítico (peça adiada da Fase 4)
|
||||
- **Files:** `scripts/quality/collect-metrics.mjs` (estender), `quality-baseline.json`.
|
||||
- **Approach:** emitir `coverage.<modulo>.lines` (lido do `coverage-summary.json` por-arquivo) para ~8 módulos de alto risco: `open-sse/handlers/chatCore.ts`, `open-sse/services/combo.ts`, `open-sse/services/accountFallback.ts`, `src/sse/services/auth.ts`, `src/server/authz/routeGuard.ts`, `open-sse/utils/error.ts`, `open-sse/utils/publicCreds.ts`, `src/shared/utils/circuitBreaker.ts`. Cada um vira métrica `up`. **Calibrar a partir do coverage mergeado real do 1º run verde na main.**
|
||||
- **Acceptance:** queda de cobertura num módulo crítico → falha, mesmo que o global não caia.
|
||||
|
||||
### Task 10 — Evidence-in-PR-body (peça adiada da Fase 5)
|
||||
- **Files:** `scripts/check/check-pr-evidence.mjs`, `ci.yml` (job `pr-test-policy`).
|
||||
- **Approach:** se o corpo do PR afirma "tests pass"/"added endpoint X"/"fixed Y" sem um bloco de **output de comando** anexado (typecheck/test/grep), falha (torna a Rule #18 mecânica — "evidence before assertions"). Heurístico, no contexto de PR.
|
||||
- **Acceptance:** PR alegando sucesso sem output anexado → falha.
|
||||
|
||||
### Task 11 — Mutation testing nos módulos críticos (Stryker, nightly)
|
||||
- **Tool:** Stryker (`@stryker-mutator/core` + runner; OSS).
|
||||
- **Files:** `stryker.conf.json`, `ci.yml` (job NIGHTLY separado — não no PR), `dependency-allowlist.json`.
|
||||
- **Approach:** escopar Stryker aos ~8 módulos críticos da Task 9 (não repo-wide — é caro + c8 já OOM-prone). Mutantes sobreviventes = **testes tautológicos** (passam sem provar nada) → complementa o `check-test-masking` da Fase 4. Rodar nightly/weekly, não por-PR.
|
||||
- **Acceptance:** mutation score por módulo crítico vira métrica (catraca `up`, nightly).
|
||||
|
||||
### Task 12 — Bundle-size / perf budget (size-limit)
|
||||
- **Tool:** size-limit (OSS).
|
||||
- **Files:** `.size-limit.json`, `scripts/check/check-bundle-size.mjs`, `ci.yml`, `dependency-allowlist.json`.
|
||||
- **Approach:** definir orçamento por bundle Next 16; size-limit emite tamanhos → catraca `down` (bundle não pode inchar).
|
||||
- **Acceptance:** PR que estoura o orçamento de bundle → falha.
|
||||
|
||||
### Task 13 — a11y gate (axe-core + Playwright)
|
||||
- **Tool:** `@axe-core/playwright` (OSS; Playwright já existe).
|
||||
- **Files:** `tests/e2e/a11y.spec.ts`, `ci.yml` (job `test-e2e`), `dependency-allowlist.json`.
|
||||
- **Approach:** rodar axe nas páginas-chave do dashboard; congelar violações atuais (catraca `down`). Atende o item a11y/visual do plano t15.
|
||||
- **Acceptance:** nova violação a11y → falha; correção baixa.
|
||||
|
||||
### Task 14 — semcheck (camada fuzzy docs↔código, opcional/LLM)
|
||||
- **Tool:** semcheck (OSS, MIT) — `fail-on-issues`.
|
||||
- **Files:** `semcheck.yaml`, `ci.yml` (advisory).
|
||||
- **Approach:** regras ligando `docs/**` ao módulo de código que documentam; pega docs que descrevem o que o código NÃO faz (camada fuzzy sobre o determinístico `check-docs-symbols` da Fase 6). É LLM → rodar advisory/non-blocking ou em label, por custo.
|
||||
- **Acceptance:** doc que descreve comportamento inexistente → flag (advisory).
|
||||
|
||||
### Task 15 — agent-lsp (LSP-in-the-loop para os agentes)
|
||||
- **Tool:** agent-lsp (MCP server, OSS).
|
||||
- **Files:** config MCP dos agentes (`.mcp.json`/equivalente).
|
||||
- **Approach:** expor `tsserver`/agent-lsp aos agentes para `blast_radius`/diagnostics/`preview_edit` ANTES de escrever — vira "símbolo inventado" de catch-de-review para impossibilidade-no-edit. Pareia com `typecheck:core` como gate pré-PR (compile-before-claim).
|
||||
- **Acceptance:** agentes resolvem símbolo/import via LSP; menos alucinação de símbolo na origem.
|
||||
|
||||
### Task 16 — dpdm circular-deps JSON cross-check (opcional)
|
||||
- **Tool:** dpdm (OSS, v4) — `--circular --output`.
|
||||
- **Approach:** cross-check JSON de ciclos complementando o `check-cycles.mjs` existente (AST-TS mais preciso). Catraca de contagem de ciclos. Baixa prioridade (já temos check-cycles).
|
||||
|
||||
### Task 17 — Avaliar Qlty CLI como consolidador (opcional, spike)
|
||||
- **Tool:** Qlty CLI (OSS, grátis).
|
||||
- **Approach:** spike: avaliar se Qlty (Baseline analysis + 70 analyzers) substitui N scripts caseiros sem perder o controle/determinismo. Decisão build-vs-buy. Não obrigatório.
|
||||
|
||||
### Task 18 — Secret scanning local (gitleaks) ➕ *adicionada pela auditoria 6A (2026-06-09)*
|
||||
- **Tool:** gitleaks (OSS, MIT — binário Go, on-box). Nota 2026: o criador original (Zach Rice) lançou o **Betterleaks** (2026-03) como drop-in replacement (flags/config compatíveis) — avaliar os dois no Step 0 e escolher 1.
|
||||
- **Files:** `.gitleaks.toml`, `scripts/check/check-secrets.mjs`, `quality-baseline.json` (+`secretFindings {down}`), `ci.yml` (job quality-gate), pre-commit (modo `--staged`, é rápido).
|
||||
- **Approach:** complementa o `check-public-creds` da Fase 6 (que cobre apenas credenciais PÚBLICAS por chave de objeto em 2 arquivos): gitleaks pega a classe geral — `const API_KEY = "sk-…"`, tokens em config/teste/docs, secrets em histórico. Rodar `gitleaks dir --report-format json` → contar findings → catraca `down`. Findings legítimos (creds públicas já congeladas no check-public-creds, fixtures de teste) vão para `.gitleaks.toml` `[allowlist]` com comentário — sujeitos ao stale-enforcement da 6A.3 (conceitual: revisar allowlist a cada release).
|
||||
- **Acceptance:** secret real plantado em fixture é detectado; baseline congela os findings atuais; novo finding falha o gate.
|
||||
|
||||
### Task 19 — Lint + auditoria de segurança dos workflows (actionlint + zizmor) ➕ *adicionada pela auditoria 6A*
|
||||
- **Tools:** actionlint (OSS — correção/sintaxe/shellcheck dos YAML) + zizmor (OSS, zizmorcore — 24+ audits de segurança: unpinned actions, script injection, `pull_request_target` perigoso, cache poisoning). Complementares por design; o repo tem 10 workflows sem NENHUMA validação hoje.
|
||||
- **Motivação 2026:** o incidente trivy-action/LiteLLM (2026-03) explorou exatamente uma misconfiguração de `pull_request_target` que o zizmor detecta estaticamente. Os release-workflows do OmniRoute (npm/Docker/Electron publish) são alvo de alto valor.
|
||||
- **Files:** `ci.yml` ou `quality.yml` (steps actionlint + zizmor), `zizmor.yml` (config/ignores justificados), `quality-baseline.json` (+`zizmorFindings {down}` — começar advisory, congelar baseline, depois bloquear).
|
||||
- **Approach:** actionlint = pass/fail imediato (sintaxe não tem "legado aceitável"); zizmor = catraca `down` no padrão do motor (os findings atuais — provavelmente actions não-pinadas por SHA — são dívida congelada que decai).
|
||||
- **Acceptance:** workflow novo com `pull_request_target` + checkout de código do PR falha; action não-pinada NOVA sobe o count e falha.
|
||||
|
||||
### Task 20 — License compliance (allowlist SPDX) ➕ *adicionada pela auditoria 6A*
|
||||
- **Tool:** license-compliance ou @onebeyond/license-checker (ambos OSS, npm). Projeto é **MIT** — deps com copyleft forte (GPL/AGPL) em produção são risco de compliance para os usuários do proxy.
|
||||
- **Files:** `scripts/check/check-licenses.mjs`, `.license-allowlist.json` (SPDX permitidas: MIT, Apache-2.0, BSD-2/3, ISC, 0BSD, …), `ci.yml` (lint job), `dependency-allowlist.json`.
|
||||
- **Approach:** rodar sobre as `dependencies` de produção (devDependencies = relatório advisory); licença fora da allowlist → fail com o caminho da dep. Exceções pontuais (dual-license, LGPL avaliada) entram na allowlist por **pacote** com justificativa — pareia com o `check-deps` da Fase 2 (lá controla O QUE entra; aqui, SOB QUAL licença).
|
||||
- **Acceptance:** dep GPL-3.0 sintética em fixture falha; árvore atual passa com a allowlist calibrada.
|
||||
|
||||
---
|
||||
|
||||
## Wiring & CI (resumo)
|
||||
- **lint job:** check-lockfile, check-cognitive-complexity (rápido?), check-type-coverage, **check-licenses (Task 20)**, **actionlint (Task 19)**.
|
||||
- **quality-gate job (paralelo):** check-vuln-ratchet, check-dead-code, check-codeql-ratchet, check-cognitive-complexity (se lento), check-bundle-size, **check-secrets (Task 18)**, **zizmor (Task 19)**.
|
||||
- **pr-test-policy job:** check-pr-evidence.
|
||||
- **sonarqube job:** Clean-as-You-Code + `qualitygate.wait`.
|
||||
- **NIGHTLY job (novo):** Stryker (mutação), semcheck (advisory), a11y full.
|
||||
- Todas as métricas numéricas → `quality-baseline.json` (motor da Fase 1, com `eps`/`tightenSlack` da 6A.5). Toda dep nova → `dependency-allowlist.json`. Toda allowlist nova nasce com o stale-enforcement da 6A.3.
|
||||
|
||||
## Self-Review
|
||||
- **Cobertura do spec:** 7 gates sugeridos = Task 1-3 (segurança), 4 (knip), 9 (coverage por módulo), 10 (evidence), 11 (mutação), 12 (bundle), 13 (a11y). "Todas as ferramentas discutidas" = Tasks 1-8, 11-17 (Sonar/osv/CodeQL/knip/sonarjs/type-coverage/lockfile/dpdm/stryker/size-limit/axe/semcheck/agent-lsp/Qlty). Auditoria 6A (2026-06-09) acrescentou Tasks 18-20 (gitleaks, actionlint+zizmor, license compliance). ✓
|
||||
- **Community/OSS only:** confirmado — Sonar Community Build, todos os demais OSS (gitleaks MIT, zizmor/actionlint OSS, license-compliance npm), zero SaaS pago. ✓
|
||||
- **Sem flag-day:** toda catraca é só-regressão, calibrada do estado atual (zizmor/gitleaks começam advisory→baseline→bloqueio). ✓
|
||||
- **Consistência:** todas as métricas usam o formato `{value, direction}` do motor da Fase 1; deps novas passam pelo `check-deps`+`dependency-allowlist.json`. ✓
|
||||
- **Não-sobreposição com a 6A:** a 6A conserta/endurece o EXISTENTE (runners, stale-allowlists, escopos); a Fase 7 só adiciona ferramenta nova. gitleaks (Task 18) complementa — não substitui — o check-public-creds expandido pela 6A.8. ✓
|
||||
|
||||
## Handoff (na ativação, 2026-06-16+)
|
||||
**Ordem: Fase 6A primeiro** ([`PLANO-QUALITY-GATES-FASE6A.md`](./PLANO-QUALITY-GATES-FASE6A.md)) — consertar os runners (testes órfãos + vitest no CI) e endurecer as catracas existentes muda os baselines (cobertura recalibrada) sobre os quais várias tasks daqui (1, 9, 11) calibram. Depois: começar pela **Task 1-3 (catraca de segurança)**, **Task 4 (knip)** e **Task 19 (zizmor — protege os release-workflows)** — maior retorno. Cada Task vira um sub-plano `writing-plans` bite-sized próprio. Recomendado: Subagent-Driven, 1 subagente por Task, com auditoria (trust-but-verify) e o ratchet `eslintWarnings`/`check-deps` validando que cada adição não regride o que já temos.
|
||||
688
PLANO-QUALITY-GATES.md
Normal file
688
PLANO-QUALITY-GATES.md
Normal file
@@ -0,0 +1,688 @@
|
||||
# Plano de Implementação — Quality Gates & Catraca Anti-Alucinação
|
||||
|
||||
> **Para workers agênticos:** SUB-SKILL OBRIGATÓRIA: use `superpowers:subagent-driven-development` (recomendado) ou `superpowers:executing-plans` para executar este plano tarefa-a-tarefa. Os passos usam checkbox (`- [ ]`) para rastreio. **Cada fix de bug obedece à Hard Rule #18** (teste falha→passa OU validação ao vivo no VPS). Não burle Husky (`--no-verify`) sem aprovação. Veja o diagnóstico completo em [`RELATORIO-QUALITY-GATES.md`](./RELATORIO-QUALITY-GATES.md).
|
||||
|
||||
**Goal:** Generalizar a catraca de qualidade do OmniRoute (hoje só para `any`) para todas as métricas relevantes — cobertura, duplicação, tamanho de arquivo, complexidade — e adicionar gates determinísticos anti-alucinação, tudo no padrão `check-*.mjs` já existente, sem SaaS novo.
|
||||
|
||||
**Architecture:** Camadas incrementais. (0) reativa/reconcilia o que já existe; (1) constrói o **motor de catraca** (`quality-baseline.json` commitado + coletor + comparador genérico que clona o `check-t11-any-budget.mjs`); (2) adiciona gates determinísticos que matam os ímãs de alucinação (provider-consistency, fetch-targets, openapi-routes); (3) catraca de duplicação+tamanho; (4) catraca de cobertura + anti test-masking; (5) skill `/babysit` + evidência. Toda catraca é **só-regressão** (baseline congelado) — nunca um piso absoluto que exija limpeza flag-day.
|
||||
|
||||
**Tech Stack:** Node ≥20 ESM (`.mjs`/`.ts` via `tsx`), ESLint 9 flat config, c8, jscpd v5, eslint-plugin-sonarjs v4, GitHub Actions, Node native test runner (`node --import tsx --test`), `gh` CLI + GraphQL.
|
||||
|
||||
**Escopo / sub-planos (scope-check):** Fases 0, 1 e 2 estão totalmente bite-sized aqui. Fases 3, 4 e 5 são subsistemas independentes — cada uma deve ser **expandida no próprio sub-plano** (via `writing-plans`) no momento da execução, a partir das specs/critérios de aceitação definidos aqui. Cada fase entrega software funcional e testável por si só.
|
||||
|
||||
---
|
||||
|
||||
## Mapa de arquivos (o que será criado/modificado)
|
||||
|
||||
| Arquivo | Responsabilidade |
|
||||
|---------|------------------|
|
||||
| `quality-baseline.json` (criar, **commitar**) | Baseline congelado: por métrica `{value, direction}` (`down`=menor-é-melhor, `up`=maior-é-melhor) |
|
||||
| `scripts/quality/collect-metrics.mjs` (criar) | Roda os coletores → emite `quality-metrics.json` |
|
||||
| `scripts/quality/check-quality-ratchet.mjs` (criar) | Comparador genérico: falha em qualquer regressão; com `--update` ratcheta o baseline |
|
||||
| `scripts/check/check-fetch-targets.mjs` (criar) | Todo `fetch("/api/...")` do dashboard resolve para um `route.ts` real |
|
||||
| `scripts/check/check-provider-consistency.ts` (criar) | ids de provider batem entre `providers.ts` ↔ `providerRegistry.ts` ↔ `validation.ts` |
|
||||
| `scripts/check/check-openapi-routes.mjs` (criar) | Toda `path` do `openapi.yaml` ↔ `route.ts` real (bidirecional) |
|
||||
| `scripts/check/check-deps.mjs` (criar) | Anti-slopsquatting: allowlist + existência no registry + age-cooldown |
|
||||
| `.github/workflows/ci.yml` (modificar) | Novo job `quality-gate`; reconciliar gate de cobertura; escalonar audit; plugar scripts órfãos |
|
||||
| `.husky/pre-commit` (modificar) | Reativar a parte barata |
|
||||
| `package.json` (modificar) | Novos scripts `check:*` / `quality:*` |
|
||||
| `eslint.config.mjs` (modificar, Fase 3) | `max-lines`, `max-lines-per-function`, `complexity`, `sonarjs/cognitive-complexity` (warn) |
|
||||
| `.claude/skills/babysit/SKILL.md` (criar, Fase 5) | Skill `/babysit` |
|
||||
| `tests/unit/quality-ratchet.test.ts` etc. (criar) | Testes TDD de cada gate |
|
||||
|
||||
---
|
||||
|
||||
# FASE 0 — Reativar & Reconciliar (quick wins, sem tooling novo)
|
||||
|
||||
### Task 0.1: Reconciliar o gate de cobertura do CI (40 → baseline real)
|
||||
|
||||
**Contexto:** `ci.yml:377` gata em `40/40/40/40`; local gata `60`; comentário renderiza `60`; baseline real ≈ 79–82%. O 40 torna o gate quase banguela.
|
||||
|
||||
**Files:**
|
||||
- Modify: `.github/workflows/ci.yml:376-377`
|
||||
|
||||
- [ ] **Step 1: Confirmar o baseline real de cobertura**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
npm run test:coverage 2>&1 | tail -20
|
||||
node -e "const c=require('./coverage/coverage-summary.json').total; console.log(c.statements.pct,c.lines.pct,c.functions.pct,c.branches.pct)"
|
||||
```
|
||||
Expected: 4 números (ex.: `79.8 79.8 82.2 75.2`). Anote-os.
|
||||
|
||||
- [ ] **Step 2: Subir o gate do CI para `baseline_real - 2` (headroom anti-flake)**
|
||||
|
||||
Em `.github/workflows/ci.yml`, troque a linha `--statements 40 --lines 40 --functions 40 --branches 40` pelos valores `(real-2)` de cada métrica (ex.: `--statements 77 --lines 77 --functions 80 --branches 73`). Mantenha como **piso**; a catraca da Fase 4 cuidará do "não-cair".
|
||||
|
||||
- [ ] **Step 3: Alinhar o script local e o display do comentário** para os mesmos números (procure `60` em `package.json` `test:coverage` e em `scripts/check/test-report-summary.mjs`).
|
||||
|
||||
- [ ] **Step 4: Verificar que o CI não quebra** — abrir um PR de teste (ou rodar `act`/push numa branch) e confirmar que o job `test-coverage` fica verde com o novo piso.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
```bash
|
||||
git add .github/workflows/ci.yml package.json scripts/check/test-report-summary.mjs
|
||||
git commit -m "fix(ci): reconcile coverage gate to real baseline (40->~78) across CI/local/report"
|
||||
```
|
||||
|
||||
### Task 0.2: Escalonar `npm audit` (critical=bloqueia / high=avisa)
|
||||
|
||||
**Files:** Modify: `package.json:112`
|
||||
|
||||
- [ ] **Step 1: Trocar o script `audit:deps`** de `npm audit --audit-level=moderate && npm run audit:electron` para:
|
||||
```json
|
||||
"audit:deps": "npm audit --audit-level=critical && (npm audit --audit-level=high || echo '::warning::high-severity advisories present (non-blocking)') && npm run audit:electron",
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rodar e observar o comportamento**
|
||||
```bash
|
||||
npm run audit:deps; echo "exit=$?"
|
||||
```
|
||||
Expected: `exit=0` se não houver critical; mensagem de warning se houver high.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
```bash
|
||||
git add package.json && git commit -m "chore(ci): tier npm audit (critical blocks, high warns)"
|
||||
```
|
||||
|
||||
### Task 0.3: Plugar os 3 scripts órfãos no CI
|
||||
|
||||
**Contexto:** `check:cli-i18n`, `check:openapi-coverage`, `check:openapi-security-tiers` existem, dão `exit 1`, mas não rodam em lugar nenhum (Hard Rules #15/#17).
|
||||
|
||||
**Files:** Modify: `.github/workflows/ci.yml` (job `docs-sync-strict` ou `lint`)
|
||||
|
||||
- [ ] **Step 1: Rodar os 3 localmente para confirmar verde no estado atual**
|
||||
```bash
|
||||
npm run check:cli-i18n && npm run check:openapi-coverage && npm run check:openapi-security-tiers; echo "exit=$?"
|
||||
```
|
||||
Expected: `exit=0` (se algum falhar, corrija a deriva antes de plugar).
|
||||
|
||||
- [ ] **Step 2: Adicionar os 3 como steps** no job `docs-sync-strict` do `ci.yml`, após `check:docs-all`.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
```bash
|
||||
git add .github/workflows/ci.yml && git commit -m "ci: wire orphaned gates (cli-i18n, openapi-coverage, openapi-security-tiers)"
|
||||
```
|
||||
|
||||
### Task 0.4: Reativar a parte barata do pre-commit do Husky
|
||||
|
||||
**Files:** Modify: `.husky/pre-commit`
|
||||
|
||||
- [ ] **Step 1: Descomentar SÓ as 3 linhas baratas e determinísticas:**
|
||||
```sh
|
||||
npx lint-staged
|
||||
node scripts/check/check-docs-sync.mjs
|
||||
npm run check:any-budget:t11
|
||||
```
|
||||
(Deixe i18n/openapi comentados por enquanto — eles são mais lentos; rodam no CI.)
|
||||
|
||||
- [ ] **Step 2: Testar o hook** com um commit trivial e medir o tempo:
|
||||
```bash
|
||||
time git commit --allow-empty -m "chore: test pre-commit hook"
|
||||
git reset --soft HEAD~1
|
||||
```
|
||||
Expected: hook roda lint-staged + 2 checks em poucos segundos.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
```bash
|
||||
git add .husky/pre-commit && git commit -m "chore(husky): re-enable cheap pre-commit gates (lint-staged, docs-sync, any-budget)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# FASE 1 — Motor de Catraca (o coração) ⭐
|
||||
|
||||
> Generaliza o `check-t11-any-budget.mjs` (catraca de `any` por arquivo) para um motor de catraca genérico, multi-métrica, que lê um baseline commitado e falha em qualquer regressão. Começa com 2 métricas (warnings de ESLint + cobertura) e é estendido nas fases seguintes.
|
||||
|
||||
### Task 1.1: Comparador genérico de catraca (TDD)
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/quality/check-quality-ratchet.mjs`
|
||||
- Test: `tests/unit/quality-ratchet.test.ts`
|
||||
|
||||
- [ ] **Step 1: Escrever o teste que falha**
|
||||
```ts
|
||||
// tests/unit/quality-ratchet.test.ts
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
const SCRIPT = path.resolve("scripts/quality/check-quality-ratchet.mjs");
|
||||
|
||||
function run(baseline, metrics, extraArgs = []) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ratchet-"));
|
||||
const bPath = path.join(dir, "baseline.json");
|
||||
const mPath = path.join(dir, "metrics.json");
|
||||
fs.writeFileSync(bPath, JSON.stringify(baseline));
|
||||
fs.writeFileSync(mPath, JSON.stringify(metrics));
|
||||
try {
|
||||
const out = execFileSync("node", [SCRIPT, "--baseline", bPath, "--metrics", mPath, ...extraArgs], { encoding: "utf8" });
|
||||
return { code: 0, out, dir, bPath };
|
||||
} catch (e) {
|
||||
return { code: e.status, out: (e.stdout || "") + (e.stderr || ""), dir, bPath };
|
||||
}
|
||||
}
|
||||
|
||||
test("passes when metrics equal baseline", () => {
|
||||
const b = { metrics: { eslintWarnings: { value: 100, direction: "down" }, "coverage.lines": { value: 80, direction: "up" } } };
|
||||
assert.equal(run(b, { eslintWarnings: 100, "coverage.lines": 80 }).code, 0);
|
||||
});
|
||||
|
||||
test("fails when a 'down' metric regresses (more warnings)", () => {
|
||||
const b = { metrics: { eslintWarnings: { value: 100, direction: "down" } } };
|
||||
const r = run(b, { eslintWarnings: 101 });
|
||||
assert.equal(r.code, 1);
|
||||
assert.match(r.out, /eslintWarnings/);
|
||||
});
|
||||
|
||||
test("fails when an 'up' metric regresses (coverage drops)", () => {
|
||||
const b = { metrics: { "coverage.lines": { value: 80, direction: "up" } } };
|
||||
assert.equal(run(b, { "coverage.lines": 79 }).code, 1);
|
||||
});
|
||||
|
||||
test("passes on improvement; --update ratchets the baseline", () => {
|
||||
const b = { metrics: { eslintWarnings: { value: 100, direction: "down" } } };
|
||||
const r = run(b, { eslintWarnings: 90 }, ["--update"]);
|
||||
assert.equal(r.code, 0);
|
||||
const updated = JSON.parse(fs.readFileSync(r.bPath, "utf8"));
|
||||
assert.equal(updated.metrics.eslintWarnings.value, 90);
|
||||
});
|
||||
|
||||
test("fails (code 2) when a baseline metric is missing from collected metrics", () => {
|
||||
const b = { metrics: { eslintWarnings: { value: 100, direction: "down" } } };
|
||||
assert.equal(run(b, {}).code, 1);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rodar o teste e ver falhar**
|
||||
```bash
|
||||
node --import tsx --test tests/unit/quality-ratchet.test.ts
|
||||
```
|
||||
Expected: FAIL (script não existe ainda).
|
||||
|
||||
- [ ] **Step 3: Implementar o comparador**
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
// scripts/quality/check-quality-ratchet.mjs
|
||||
// Catraca genérica multi-métrica. Clona o espírito de check-t11-any-budget.mjs:
|
||||
// um baseline congelado por métrica; falha em qualquer regressão; só anda num sentido.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const cwd = process.cwd();
|
||||
function getArg(name, fallback) {
|
||||
const i = process.argv.indexOf(name);
|
||||
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
|
||||
}
|
||||
const BASELINE = path.resolve(getArg("--baseline", path.join(cwd, "quality-baseline.json")));
|
||||
const METRICS = path.resolve(getArg("--metrics", path.join(cwd, "quality-metrics.json")));
|
||||
const SUMMARY = getArg("--summary", null);
|
||||
const UPDATE = process.argv.includes("--update");
|
||||
const EPS = 0.01;
|
||||
|
||||
function load(p) {
|
||||
if (!fs.existsSync(p)) { console.error(`[quality-ratchet] arquivo ausente: ${p}`); process.exit(2); }
|
||||
return JSON.parse(fs.readFileSync(p, "utf8"));
|
||||
}
|
||||
|
||||
const baseline = load(BASELINE);
|
||||
const metrics = load(METRICS);
|
||||
const failures = [];
|
||||
const improvements = [];
|
||||
const rows = [];
|
||||
|
||||
for (const [key, spec] of Object.entries(baseline.metrics)) {
|
||||
const current = metrics[key];
|
||||
const base = spec.value;
|
||||
const dir = spec.direction; // "down" = menor-é-melhor | "up" = maior-é-melhor
|
||||
if (current === undefined) { failures.push(`métrica "${key}" ausente em ${path.basename(METRICS)}`); rows.push([key, base, "—", "MISSING"]); continue; }
|
||||
let status = "ok";
|
||||
if (dir === "down") {
|
||||
if (current > base + EPS) { failures.push(`${key}: ${current} > baseline ${base} (não pode aumentar)`); status = "REGRESSÃO"; }
|
||||
else if (current < base - EPS) { improvements.push([key, current]); status = "↑ melhorou"; }
|
||||
} else {
|
||||
if (current < base - EPS) { failures.push(`${key}: ${current} < baseline ${base} (não pode cair)`); status = "REGRESSÃO"; }
|
||||
else if (current > base + EPS) { improvements.push([key, current]); status = "↑ melhorou"; }
|
||||
}
|
||||
rows.push([key, base, current, status]);
|
||||
}
|
||||
|
||||
if (SUMMARY) {
|
||||
const md = ["# Quality Ratchet", "", "| Métrica | Baseline | Atual | Status |", "|---|---|---|---|",
|
||||
...rows.map(([k, b, c, s]) => `| ${k} | ${b} | ${c} | ${s} |`), "",
|
||||
failures.length ? `**${failures.length} regressão(ões) — gate BLOQUEADO.**` : "**Sem regressões — gate OK.**"].join("\n");
|
||||
fs.mkdirSync(path.dirname(SUMMARY), { recursive: true });
|
||||
fs.writeFileSync(SUMMARY, md + "\n");
|
||||
}
|
||||
|
||||
if (UPDATE && failures.length === 0 && improvements.length) {
|
||||
for (const [key, val] of improvements) baseline.metrics[key].value = val;
|
||||
fs.writeFileSync(BASELINE, JSON.stringify(baseline, null, 2) + "\n");
|
||||
console.log(`[quality-ratchet] baseline ratcheado: ${improvements.length} métrica(s) melhoraram`);
|
||||
}
|
||||
|
||||
if (failures.length) { console.error("[quality-ratchet] FALHOU:\n" + failures.map((f) => " ✗ " + f).join("\n")); process.exit(1); }
|
||||
console.log(`[quality-ratchet] OK (${rows.length} métricas, ${improvements.length} melhoraram)`);
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Rodar o teste e ver passar**
|
||||
```bash
|
||||
node --import tsx --test tests/unit/quality-ratchet.test.ts
|
||||
```
|
||||
Expected: PASS (5/5).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
```bash
|
||||
git add scripts/quality/check-quality-ratchet.mjs tests/unit/quality-ratchet.test.ts
|
||||
git commit -m "feat(quality): generic ratchet comparator (multi-metric, regression-only)"
|
||||
```
|
||||
|
||||
### Task 1.2: Coletor de métricas (ESLint warnings + cobertura)
|
||||
|
||||
**Files:** Create: `scripts/quality/collect-metrics.mjs`
|
||||
|
||||
- [ ] **Step 1: Implementar o coletor**
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
// scripts/quality/collect-metrics.mjs — emite quality-metrics.json
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
const cwd = process.cwd();
|
||||
const out = {};
|
||||
|
||||
// 1) ESLint: contagem de warnings (errors devem ser 0; o lint já gata isso)
|
||||
function eslintCounts() {
|
||||
let stdout;
|
||||
try {
|
||||
stdout = execFileSync("npx", ["eslint", ".", "--format", "json"], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
|
||||
} catch (e) { stdout = e.stdout?.toString() || "[]"; } // eslint sai !=0 quando há errors
|
||||
const results = JSON.parse(stdout);
|
||||
out.eslintWarnings = results.reduce((n, r) => n + (r.warningCount || 0), 0);
|
||||
out.eslintErrors = results.reduce((n, r) => n + (r.errorCount || 0), 0);
|
||||
}
|
||||
|
||||
// 2) Cobertura: lê coverage/coverage-summary.json se existir
|
||||
function coverage() {
|
||||
const p = path.join(cwd, "coverage", "coverage-summary.json");
|
||||
if (!fs.existsSync(p)) return;
|
||||
const t = JSON.parse(fs.readFileSync(p, "utf8")).total;
|
||||
out["coverage.statements"] = t.statements.pct;
|
||||
out["coverage.lines"] = t.lines.pct;
|
||||
out["coverage.functions"] = t.functions.pct;
|
||||
out["coverage.branches"] = t.branches.pct;
|
||||
}
|
||||
|
||||
eslintCounts();
|
||||
coverage();
|
||||
fs.writeFileSync(path.join(cwd, "quality-metrics.json"), JSON.stringify(out, null, 2) + "\n");
|
||||
console.log("[collect-metrics]", JSON.stringify(out));
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rodar e inspecionar a saída**
|
||||
```bash
|
||||
node scripts/quality/collect-metrics.mjs && cat quality-metrics.json
|
||||
```
|
||||
Expected: JSON com `eslintWarnings`, `eslintErrors` e (se houver coverage) os 4 `coverage.*`. **Anote `eslintWarnings`.**
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
```bash
|
||||
git add scripts/quality/collect-metrics.mjs && echo "quality-metrics.json" >> .gitignore
|
||||
git add .gitignore && git commit -m "feat(quality): metrics collector (eslint warnings + coverage)"
|
||||
```
|
||||
|
||||
### Task 1.3: Congelar o baseline inicial
|
||||
|
||||
**Files:** Create: `quality-baseline.json` (**commitado**)
|
||||
|
||||
- [ ] **Step 1: Gerar o baseline a partir das métricas reais** (use os números anotados):
|
||||
```json
|
||||
{
|
||||
"_comment": "Catraca: 'down' nao pode aumentar, 'up' nao pode cair. Atualize via 'npm run quality:ratchet -- --update' (so em melhora).",
|
||||
"metrics": {
|
||||
"eslintWarnings": { "value": <N_REAL>, "direction": "down" },
|
||||
"coverage.statements": { "value": <S>, "direction": "up" },
|
||||
"coverage.lines": { "value": <L>, "direction": "up" },
|
||||
"coverage.functions": { "value": <F>, "direction": "up" },
|
||||
"coverage.branches": { "value": <B>, "direction": "up" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Validar a catraca contra si mesma**
|
||||
```bash
|
||||
node scripts/quality/collect-metrics.mjs
|
||||
node scripts/quality/check-quality-ratchet.mjs; echo "exit=$?"
|
||||
```
|
||||
Expected: `[quality-ratchet] OK` e `exit=0`.
|
||||
|
||||
- [ ] **Step 3: Provar que pega regressão** (teste manual): edite `quality-metrics.json` somando 1 a `eslintWarnings`, rode o comparador, confirme `exit=1`, depois descarte a edição.
|
||||
|
||||
- [ ] **Step 4: Adicionar scripts npm**
|
||||
```json
|
||||
"quality:collect": "node scripts/quality/collect-metrics.mjs",
|
||||
"quality:ratchet": "node scripts/quality/check-quality-ratchet.mjs",
|
||||
"quality:gate": "npm run quality:collect && npm run quality:ratchet"
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
```bash
|
||||
git add quality-baseline.json package.json
|
||||
git commit -m "feat(quality): freeze initial quality baseline (eslint warnings + coverage)"
|
||||
```
|
||||
|
||||
### Task 1.4: Wire no CI (job + artefato + comentário no PR)
|
||||
|
||||
**Files:** Modify: `.github/workflows/ci.yml`
|
||||
|
||||
- [ ] **Step 1: Adicionar job `quality-gate`** (depois de `test-coverage`, para reusar `coverage/coverage-summary.json`):
|
||||
```yaml
|
||||
quality-gate:
|
||||
name: Quality Ratchet
|
||||
runs-on: ubuntu-latest
|
||||
needs: test-coverage
|
||||
if: ${{ always() && needs.test-coverage.result == 'success' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: '24', cache: 'npm' }
|
||||
- run: npm ci
|
||||
- uses: actions/download-artifact@v4
|
||||
with: { name: coverage-report, path: coverage/ }
|
||||
- run: npm run quality:collect
|
||||
- run: node scripts/quality/check-quality-ratchet.mjs --summary .artifacts/quality-ratchet.md
|
||||
- if: always()
|
||||
run: cat .artifacts/quality-ratchet.md >> "$GITHUB_STEP_SUMMARY"
|
||||
- if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with: { name: quality-ratchet, path: .artifacts/quality-ratchet.md }
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Adicionar comentário no PR** clonando o job `coverage-pr-comment` (marcador `<!-- omniroute-quality-ratchet -->`, lê `.artifacts/quality-ratchet.md`). Reuse o mesmo `github-script` de upsert de comentário.
|
||||
|
||||
- [ ] **Step 3: Validar num PR de teste** — confirmar que o job aparece, o step summary mostra a tabela, e o comentário é postado.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
```bash
|
||||
git add .github/workflows/ci.yml
|
||||
git commit -m "ci(quality): add quality-ratchet job with PR comment + artifact"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# FASE 2 — Gates Determinísticos Anti-Alucinação
|
||||
|
||||
> Cada gate ataca um ímã de alucinação específico (ver §2.4 do relatório). Todos no padrão `check-*.mjs`. **`check-fetch-targets` vem com código completo** (parsing determinístico de arquivos, sem risco de inventar nomes de export). **`check-provider-consistency` e `check-openapi-routes` começam com um Step 0 de verificação dos nomes reais** — propositalmente, porque fabricar a forma do import/spec seria o exato anti-padrão que este plano combate.
|
||||
|
||||
### Task 2.1: `check-fetch-targets.mjs` — toda rota chamada pelo dashboard existe (TDD)
|
||||
|
||||
**Ataca:** ímã nº2 (300 paths `fetch("/api/...")` sem ligação com as rotas).
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/check/check-fetch-targets.mjs`
|
||||
- Test: `tests/unit/check-fetch-targets.test.ts`
|
||||
|
||||
- [ ] **Step 1: Escrever o teste que falha**
|
||||
```ts
|
||||
// tests/unit/check-fetch-targets.test.ts
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert";
|
||||
import { resolveApiPathToRoute } from "../../scripts/check/check-fetch-targets.mjs";
|
||||
|
||||
test("matches a static route file", () => {
|
||||
const files = new Set(["src/app/api/usage/route.ts"]);
|
||||
assert.equal(resolveApiPathToRoute("/api/usage", files), true);
|
||||
});
|
||||
|
||||
test("matches a dynamic [param] segment", () => {
|
||||
const files = new Set(["src/app/api/providers/[id]/models/route.ts"]);
|
||||
assert.equal(resolveApiPathToRoute("/api/providers/abc-123/models", files), true);
|
||||
});
|
||||
|
||||
test("rejects a hallucinated route", () => {
|
||||
const files = new Set(["src/app/api/usage/route.ts"]);
|
||||
assert.equal(resolveApiPathToRoute("/api/providers/refresh", files), false);
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rodar e ver falhar**
|
||||
```bash
|
||||
node --import tsx --test tests/unit/check-fetch-targets.test.ts
|
||||
```
|
||||
Expected: FAIL (módulo não existe).
|
||||
|
||||
- [ ] **Step 3: Implementar o gate**
|
||||
```js
|
||||
#!/usr/bin/env node
|
||||
// scripts/check/check-fetch-targets.mjs
|
||||
// Todo fetch("/api/...") em src/app/(dashboard) deve resolver para um route.ts real.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const cwd = process.cwd();
|
||||
const DASH = path.join(cwd, "src/app/(dashboard)");
|
||||
const API = path.join(cwd, "src/app/api");
|
||||
|
||||
// allowlist de paths dinâmicos/externos que o checker não consegue resolver estaticamente
|
||||
const IGNORE = [/^\/api\/v1\//, /\$\{/, /` \+/]; // /v1 é a superfície OpenAI-compat; templates
|
||||
|
||||
function walk(dir, acc = []) {
|
||||
if (!fs.existsSync(dir)) return acc;
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) walk(p, acc);
|
||||
else if (/\.(ts|tsx)$/.test(e.name)) acc.push(p);
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
function collectRouteFiles() {
|
||||
return new Set(walk(API).filter((p) => /route\.tsx?$/.test(p)).map((p) => path.relative(cwd, p).replace(/\\/g, "/")));
|
||||
}
|
||||
|
||||
export function resolveApiPathToRoute(apiPath, routeFiles) {
|
||||
// apiPath ex.: /api/providers/abc/models → src/app/api/providers/[id]/models/route.ts
|
||||
const segs = apiPath.replace(/^\//, "").replace(/[?#].*$/, "").split("/"); // ["api","providers","abc","models"]
|
||||
for (const rf of routeFiles) {
|
||||
const rsegs = rf.replace(/^src\/app\//, "").replace(/\/route\.tsx?$/, "").split("/"); // ["api","providers","[id]","models"]
|
||||
if (rsegs.length !== segs.length) continue;
|
||||
const ok = rsegs.every((rs, i) => rs === segs[i] || /^\[.*\]$/.test(rs));
|
||||
if (ok) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractFetchPaths(file) {
|
||||
const src = fs.readFileSync(file, "utf8");
|
||||
const re = /(?:fetch|fetchJson|apiFetch)\(\s*["'`](\/api\/[^"'`?]+)/g;
|
||||
const out = [];
|
||||
let m;
|
||||
while ((m = re.exec(src))) out.push(m[1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const routeFiles = collectRouteFiles();
|
||||
const misses = [];
|
||||
for (const f of walk(DASH)) {
|
||||
for (const apiPath of extractFetchPaths(f)) {
|
||||
if (IGNORE.some((rx) => rx.test(apiPath))) continue;
|
||||
if (!resolveApiPathToRoute(apiPath, routeFiles)) misses.push(`${path.relative(cwd, f)} → ${apiPath}`);
|
||||
}
|
||||
}
|
||||
if (misses.length) {
|
||||
console.error(`[check-fetch-targets] ${misses.length} fetch(es) para rota inexistente:\n` + misses.map((m) => " ✗ " + m).join("\n"));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`[check-fetch-targets] OK (${routeFiles.size} rotas conhecidas)`);
|
||||
}
|
||||
|
||||
if (import.meta.url === `file://${process.argv[1]}`) main();
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Rodar o teste unitário e ver passar**
|
||||
```bash
|
||||
node --import tsx --test tests/unit/check-fetch-targets.test.ts
|
||||
```
|
||||
Expected: PASS (3/3).
|
||||
|
||||
- [ ] **Step 5: Rodar o gate no repo real** (modo descoberta — pode encontrar misses legítimos)
|
||||
```bash
|
||||
node scripts/check/check-fetch-targets.mjs; echo "exit=$?"
|
||||
```
|
||||
Se encontrar misses reais: triagem — ou são rotas faltantes (bug), ou paths dinâmicos a adicionar ao `IGNORE`. **Não** mascare; documente cada exceção no `IGNORE` com comentário.
|
||||
|
||||
- [ ] **Step 6: Adicionar script + commit**
|
||||
```json
|
||||
"check:fetch-targets": "node scripts/check/check-fetch-targets.mjs"
|
||||
```
|
||||
```bash
|
||||
git add scripts/check/check-fetch-targets.mjs tests/unit/check-fetch-targets.test.ts package.json
|
||||
git commit -m "feat(check): gate that every dashboard fetch() targets a real API route"
|
||||
```
|
||||
|
||||
### Task 2.2: `check-provider-consistency.ts` — ids batem entre os 3 arquivos
|
||||
|
||||
**Ataca:** ímã nº1 (split de provider; 229 vs 155 vs N já divergem).
|
||||
|
||||
**Files:** Create: `scripts/check/check-provider-consistency.ts` (rodado via `tsx`); Test: `tests/unit/check-provider-consistency.test.ts`
|
||||
|
||||
- [ ] **Step 0 (VERIFICAÇÃO — obrigatório antes de codar):** descobrir os nomes reais de export, para **não inventar**:
|
||||
```bash
|
||||
grep -nE "export (const|function) " src/shared/constants/providers.ts | grep -iE "provider|section" | head
|
||||
grep -nE "getOrCreateAiProviders|_PROVIDER_SECTIONS|AI_PROVIDERS" src/shared/constants/providers.ts | head
|
||||
grep -nE "baseUrl|^\s*['\"][a-z0-9-]+['\"]\s*:" open-sse/config/providerRegistry.ts | head
|
||||
grep -nE "case ['\"]|=== ['\"]|SPECIALTY_VALIDATORS" src/lib/providers/validation.ts | head
|
||||
```
|
||||
Anote: como enumerar os ids canônicos em runtime, a forma das chaves do `providerRegistry.ts`, e onde `validation.ts` lista os providers cobertos.
|
||||
|
||||
- [ ] **Step 1: Escrever o teste** com fixtures sintéticas (3 conjuntos de ids), afirmando que o diff detecta um id presente em um e ausente em outro. (Implemente a lógica como função pura `diffProviderSets(canonical, registry, validators)` que retorna `{missingInRegistry, missingInValidators, orphanInRegistry}`.)
|
||||
|
||||
- [ ] **Step 2: Rodar e ver falhar.**
|
||||
|
||||
- [ ] **Step 3: Implementar** importando os ids reais (descobertos no Step 0) e cruzando-os. Reusar o padrão de `scripts/check/check-docs-counts-sync.mjs` (que **já conta** executors/oauth/strategies vs docs — é o template direto). Para ids que legitimamente vivem só num lugar, manter um `KNOWN_EXCEPTIONS` allowlist com comentário por entrada.
|
||||
|
||||
- [ ] **Step 4: Rodar no repo real**, triar as divergências reais (as contagens já divergem — algumas serão bugs de registro pela metade, outras exceções legítimas).
|
||||
|
||||
- [ ] **Step 5: Commit** (`feat(check): provider-id consistency gate across providers.ts/registry/validation`).
|
||||
|
||||
**Critério de aceitação:** o gate falha quando um id existe em `providers.ts` mas não no `providerRegistry.ts` (ou vice-versa), e quando um model no registry referencia um provider id desconhecido.
|
||||
|
||||
### Task 2.3: `check-openapi-routes.mjs` — spec ↔ rotas (bidirecional)
|
||||
|
||||
**Ataca:** docs-hallucination (endpoint inventado no `openapi.yaml`).
|
||||
|
||||
**Files:** Create: `scripts/check/check-openapi-routes.mjs`; Test correspondente.
|
||||
|
||||
- [ ] **Step 0 (VERIFICAÇÃO):** confirmar o caminho e a forma do spec:
|
||||
```bash
|
||||
ls docs/reference/openapi.yaml && grep -nE "^\s{2,4}/[a-z]" docs/reference/openapi.yaml | head
|
||||
```
|
||||
Confirmar como `check-openapi-coverage.mjs` já parseia o YAML (reusar o parser dele).
|
||||
|
||||
- [ ] **Step 1–5 (TDD):** teste com spec sintética → implementar: toda `path` do spec resolve para um `route.ts` (reusando `resolveApiPathToRoute` da Task 2.1) e toda rota não-interna aparece no spec (com allowlist para rotas LOCAL_ONLY/internas). Commit.
|
||||
|
||||
### Task 2.4: `check-deps.mjs` — anti-slopsquatting
|
||||
|
||||
**Ataca:** pacotes alucinados (CSA: 19,7% das amostras IA).
|
||||
|
||||
**Files:** Create: `scripts/check/check-deps.mjs`; Test.
|
||||
|
||||
- [ ] **Step 0 (VERIFICAÇÃO):** decidir política — allowlist = todas as deps atuais do `package.json`/lockfile como baseline; novas deps exigem (a) existir no registry, (b) idade ≥ 72h, (c) entrada explícita.
|
||||
- [ ] **Step 1–5 (TDD):** teste com `package.json` sintético adicionando uma dep nova → gate falha se a dep não está no baseline E (não existe no registry OU foi publicada há <72h). Usar `npm view <pkg> time.created` para idade. Reusar o padrão diff-base...HEAD de `check-pr-test-policy.mjs`. Commit.
|
||||
|
||||
### Task 2.5 (opcional): lints Rule #11/#12 via `no-restricted-syntax`
|
||||
|
||||
- [ ] Estender o `eslint.config.mjs` (bloco `no-restricted-syntax` já usado p/ a regra de busca turca) para sinalizar `NextResponse.json({ error: "<string>" })` cru (exigir `buildErrorBody()`) e literais de `clientIdDefault`/`clientSecretDefault` no `providerRegistry.ts` (exigir `resolvePublicCred()`). Ratchet via contagem (adoção 11% → sobe). TDD com fixtures de ESLint.
|
||||
|
||||
**Plugar tudo da Fase 2 no CI:** adicionar `check:fetch-targets`, `check:provider-consistency`, `check:openapi-routes`, `check:deps` ao job `lint` (ou `docs-sync-strict`) do `ci.yml`, e ao pre-commit barato quando rápidos o suficiente.
|
||||
|
||||
---
|
||||
|
||||
# FASE 3 — Catraca de Duplicação + Tamanho (mata-slop) — *expandir em sub-plano*
|
||||
|
||||
**Justificativa:** GitClear mostra duplicação 4–8× na era IA; é a assinatura nº1 de slop. Nenhum gate hoje (Sonar CPD excluído).
|
||||
|
||||
**Specs (criar sub-plano `writing-plans` a partir daqui):**
|
||||
|
||||
1. **Adicionar `jscpd` v5** como devDependency. Rodar `jscpd --reporters json src open-sse` → `quality-metrics.json` ganha `duplication.pct`. **[verificar no install]** o schema JSON do v5 antes de parsear (ver ressalva no relatório §4.2).
|
||||
2. **Estender `collect-metrics.mjs`** com um coletor de duplicação (lê o JSON do jscpd) e um coletor de **tamanho de arquivo** (conta LOC de cada arquivo em `src`+`open-sse`, emite `fileSize.<path>` para os arquivos já acima de um teto, ex. >700 LOC — congelando os 64 atuais).
|
||||
3. **Adicionar regras ESLint** em `eslint.config.mjs` como `warn`: `max-lines` (700), `max-lines-per-function` (80), `complexity` (15), `sonarjs/cognitive-complexity` (15). Coletor adiciona `eslintWarnings` por categoria (a contagem já está na catraca da Fase 1; opcionalmente segregar `complexityWarnings`).
|
||||
4. **Estender `quality-baseline.json`** com `duplication.pct` (`down`) e os `fileSize.*` dos arquivos grandes (`down` — só podem encolher; arquivos novos têm teto absoluto).
|
||||
5. **Teto absoluto para arquivos novos:** o gate falha se um arquivo **não** presente no baseline nasce acima do teto (ex. 700 LOC) — impede o próximo god-component.
|
||||
|
||||
**Critérios de aceitação:** PR que aumenta a duplicação % falha; PR que cresce qualquer um dos 64 arquivos grandes falha; PR que cria arquivo novo >700 LOC falha; refator que encolhe um arquivo grande ratcheta o baseline para baixo (via `--update`).
|
||||
|
||||
---
|
||||
|
||||
# FASE 4 — Catraca de Cobertura + Anti Test-Masking — *expandir em sub-plano*
|
||||
|
||||
**Specs:**
|
||||
|
||||
1. **`check-coverage-ratchet`** já é coberto pelo motor da Fase 1 (as 4 métricas `coverage.*` com `direction: "up"`). Confirmar que o job `quality-gate` roda **após** o merge dos 8 shards de cobertura no CI (não localmente, onde a cobertura é parcial). Adicionar **epsilon** maior (ex. 0.5) para `coverage.branches` por causa do não-determinismo do v8.
|
||||
2. **Pisos por módulo crítico:** estender `collect-metrics.mjs` para emitir `coverage.<modulo>.lines` para uma lista curta de módulos de alto risco (lendo o `coverage-summary.json` por arquivo): `open-sse/handlers/chatCore.ts`, `open-sse/services/combo.ts`, `open-sse/services/accountFallback.ts`, `src/sse/services/auth.ts`, `src/server/authz/routeGuard.ts`, `open-sse/utils/error.ts`, `open-sse/utils/publicCreds.ts`, `src/shared/utils/circuitBreaker.ts`. Cada um vira métrica `up` no baseline (implementa o "risco, não % bruto" do vídeo).
|
||||
3. **`check-test-masking.mjs`** (anti enfraquecimento de asserts): clonar `check-pr-test-policy.mjs` (diff `base...HEAD`); para cada `*.test.ts`/`*.spec.ts` alterado, contar `assert*(`/`expect(` em base vs HEAD; **sinalizar remoção líquida** de asserts para revisão humana. Banir novos `assert.ok(true)`. Heurístico mas alto-sinal — ataca diretamente o risco organizacional nº1 ("subagente deletou asserts para ficar verde").
|
||||
|
||||
**Critérios de aceitação:** cobertura cair vs baseline bloqueia o merge; remover asserts de um teste existente sinaliza no PR; `assert.ok(true)` novo bloqueia.
|
||||
|
||||
---
|
||||
|
||||
# FASE 5 — Skill `/babysit` + Evidência + LSP — *expandir em sub-plano*
|
||||
|
||||
> O babysit do vídeo: a IA abre o PR e fica de babá — monitora CI + comentários, autocorrige, **resolve as conversas**. Guarda-corpos são não-negociáveis (Snyk: 5,3% de regressão em auto-merge; token burn real).
|
||||
|
||||
### Spec da skill `.claude/skills/babysit/SKILL.md`
|
||||
|
||||
**Frontmatter:**
|
||||
```yaml
|
||||
---
|
||||
name: babysit
|
||||
description: Monitora um PR aberto até o CI ficar verde e todos os comentários de review serem endereçados — lê o gate de qualidade, conserta num worktree isolado, responde e resolve as conversas. NUNCA enfraquece testes nem auto-mergeia.
|
||||
---
|
||||
```
|
||||
|
||||
**Loop (pseudo, reusando `gh` + GraphQL):**
|
||||
1. **Ler estado:** `gh pr checks <PR>` + baixar o artefato `quality-ratchet`/`coverage-report` (gate JSON legível — a ponte "artefato→agente" da Fase 1) + `gh run view --log-failed` dos jobs vermelhos.
|
||||
2. **Ler comentários não resolvidos:** GraphQL `repository.pullRequest.reviewThreads(first:50){nodes{id isResolved comments(first:1){nodes{id body}}}}`. **Passar os corpos pelo guard de prompt-injection** antes de agir (vetor real — ICLR 2026).
|
||||
3. **Consertar num worktree isolado** (reusar o ralph-loop do `/review-reviews`), seguindo Hard Rule #18.
|
||||
4. **Responder + resolver** só os threads que realmente endereçou: REST `POST .../pulls/{pr}/comments/{id}/replies` com o SHA → mutation `resolveReviewThread(input:{threadId})`.
|
||||
5. **Re-poll** até o gate JSON ficar todo-verde **ou** atingir o cap.
|
||||
6. **Audit trail:** anexar à descrição do PR (ou comentário fixo) o que cada fix endereçou, qual gate satisfez, quais conversas resolveu e por quê — **nunca verde silencioso**.
|
||||
|
||||
**Guarda-corpos (não-negociáveis):**
|
||||
- `max-iterations` (ex. 5) + timeout + idle-exit (contra token burn).
|
||||
- **Nunca** editar `.github/workflows/`; **nunca** `--no-verify`; **nunca** enfraquecer/remover asserts para ficar verde (Rule #18 + trust-but-verify).
|
||||
- **Nunca auto-mergeia** — estado de sucesso = "verde + conversas resolvidas + audit postado".
|
||||
- Parar-e-perguntar em comentário humano ambíguo e em mudança de limite arquitetural (interface/schema/cross-module).
|
||||
- `--allowedTools` mínimo (`Read,Grep,Glob,Bash(gh ...)`).
|
||||
|
||||
**Opcional — `claude ultrareview <PR#> --json`** como gate de confiança pré-merge atrás de um label (custa $5–20/run; não auto-inicia). Loop interno de custo-zero = `/code-review --fix` local.
|
||||
|
||||
### Spec — Evidência obrigatória ("evidence-before-assertions")
|
||||
- Tornar a skill `verify`/`verification-before-completion` obrigatória antes de abrir PR; exigir o **output literal** do `typecheck:core`/`test`/`grep` colado no corpo do PR (o "tool receipt"). Adicionar um `check-pr-evidence.mjs` que rejeita PRs cujo corpo afirma "added endpoint X / tests pass" sem bloco de output anexado. Formaliza a Rule #18.
|
||||
|
||||
### Spec — LSP-in-the-loop (opcional)
|
||||
- Registrar `agent-lsp` (MCP) ou o `tsserver` para os agentes terem `blast_radius`/diagnostics e `preview_edit` antes de escrever — vira "símbolo inventado" de catch-de-review para impossibilidade-no-edit. Pareia com `typecheck:core` como gate pré-PR (compile-before-claim).
|
||||
|
||||
**Critérios de aceitação:** a skill `/babysit <PR#>` leva um PR de vermelho a verde sem auto-merge, resolve só as conversas que endereçou, respeita o cap de iterações, e deixa rastro auditável; nenhum assert é enfraquecido.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review (checklist do autor)
|
||||
|
||||
- **Cobertura do spec:** Fases 0–2 mapeiam 1:1 com as recomendações do relatório §5; Fases 3–5 cobrem duplicação/tamanho, cobertura/masking e babysit/evidência. ✓
|
||||
- **Sem placeholders nos passos bite-sized:** Fases 0/1/2.1 têm comandos e código reais. As Fases 2.2–2.4 usam um Step-0 de verificação **deliberado** (não placeholder) para não fabricar nomes de export — coerente com o objetivo anti-alucinação. ✓
|
||||
- **Consistência de tipos:** `resolveApiPathToRoute` (Task 2.1) é reusada na Task 2.3; o comparador usa o mesmo formato `{value, direction}` em todas as fases; `quality-metrics.json` é a interface única coletor↔comparador. ✓
|
||||
- **Ordem de dependência:** Fase 1 (motor) precede 3/4 (que só adicionam métricas ao baseline); Fase 0 destrava o resto. ✓
|
||||
|
||||
## Handoff de Execução
|
||||
|
||||
**Plano salvo em `PLANO-QUALITY-GATES.md`.** Duas opções:
|
||||
|
||||
1. **Subagent-Driven (recomendado)** — um subagente fresco por task, review entre tasks. SUB-SKILL: `superpowers:subagent-driven-development`.
|
||||
2. **Inline** — executar nesta sessão com checkpoints. SUB-SKILL: `superpowers:executing-plans`.
|
||||
|
||||
**Recomendação:** começar pela **Fase 0** (quick wins, baixo risco) e **Fase 1** (motor de catraca) numa branch `feat/quality-ratchet`, validar num PR de teste, e só então abrir as fases anti-alucinação. Fases 3–5 viram sub-planos próprios.
|
||||
219
RELATORIO-QUALITY-GATES.md
Normal file
219
RELATORIO-QUALITY-GATES.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# Relatório — Quality Gates, Catraca & Anti-Alucinação no OmniRoute
|
||||
|
||||
> **Data:** 2026-06-09
|
||||
> **Origem:** Auditoria do projeto (5 subagentes Opus em paralelo mapeando todas as pastas exceto `node_modules`/`_references`/`dist`) + análise da transcrição do vídeo *"Qualidade de código"* (Stupid Button Club, 2026-05-04) + pesquisa web 2026 (4 frentes, últimos ~3 meses).
|
||||
> **Companheiro:** Veja [`PLANO-QUALITY-GATES.md`](./PLANO-QUALITY-GATES.md) para o plano de implementação bite-sized (TDD).
|
||||
|
||||
---
|
||||
|
||||
## 0. TL;DR
|
||||
|
||||
1. **O OmniRoute já é muito mais maduro** que o projeto "Strawberry" do vídeo: tem CI com 20 jobs, gate de cobertura, ESLint 9 flat, SonarQube, 14 scripts `check-*.mjs` e **uma catraca real já funcionando** (`check-t11-any-budget.mjs` — orçamento de `any` por arquivo que só pode encolher). O vídeo descreve onde queremos chegar; nós já estamos a meio caminho.
|
||||
2. **Mas faltam exatamente as catracas que o vídeo prega.** Não há baseline congelado de métricas, nem gate de **duplicação**, nem de **tamanho de arquivo**, e o gate de cobertura é um **piso fixo** — não uma catraca "nunca piorar".
|
||||
3. **Há derivas (drifts) reais que pegamos na auditoria:** o gate de cobertura **no CI é `40/40/40/40`** (ci.yml:377), não os `60/60/60/60` que o CLAUDE.md anuncia (esse é só o script local). O Husky está **100% comentado** (zero gate local). O SonarQube tem `coverage` e `cpd` **excluídos** (`sonar-project.properties:9-10`) — as duas métricas mais úteis contra "slop" estão desligadas. E 3 scripts `check-*` existem mas **não rodam em lugar nenhum**.
|
||||
4. **Os maiores ímãs de alucinação são estruturais:** o split de provider em 3 arquivos gigantes em 2 workspaces (`providers.ts` ↔ `providerRegistry.ts` ↔ `validation.ts`, com contagens que já divergem: 229 ids vs 155 blocos vs N validadores), os 300 paths `fetch("/api/...")` hardcoded sem ligação de compilação com as rotas, e o arquivo de **12.760 linhas** (`providers/[id]/page.tsx`) que nenhum agente consegue segurar em contexto.
|
||||
5. **2026 confirma a tese do vídeo com dados:** GitClear (211M linhas) mostra duplicação crescendo 4–8× na era da IA; o paper SlopCodeBench prova que *instrução de prompt sozinha não impede a degradação* — só gates determinísticos seguram. O ecossistema 2026 tem ferramentas maduras para cada métrica (jscpd v5, knip v6, eslint-plugin-sonarjs v4, osv-scanner, Qlty, Sonar "Clean as You Code"/"AI Code Assurance").
|
||||
6. **A jogada é em camadas:** (a) reativar/reconciliar o que já existe; (b) construir o **motor de catraca** (baseline.json + coletor + comparador, clonando o `any-budget`); (c) adicionar **gates determinísticos anti-alucinação** (provider-consistency, fetch-target, openapi-routes); (d) catraca de **duplicação + tamanho**; (e) catraca de **cobertura** + detecção de test-masking; (f) skill **`/babysit`** com guarda-corpos. Detalhe no plano.
|
||||
|
||||
---
|
||||
|
||||
## 1. O que o vídeo ensina (insights destilados)
|
||||
|
||||
O vídeo é uma fala sem roteiro sobre *qualidade de código no mundo em que a IA escreve ~100% do código*. Pontos centrais:
|
||||
|
||||
| # | Insight | Citação/essência |
|
||||
|---|---------|------------------|
|
||||
| 1 | **O humano virou o gargalo.** | "Eu acabei virando o gargalo da IA. Fazer o babysit das coisas do request básicas é o gargalo. Não consigo entregar 4 tarefas ao mesmo tempo se preciso ler 10.000 linhas/dia." |
|
||||
| 2 | **Quality Gate = portão que a IA tem que passar.** | Todo PR passa por um portão; a IA fica em loop se autocorrigindo até ficar verde, em vez de o humano revisar e pedir refação. |
|
||||
| 3 | **Baseline + Catraca (ratchet).** | "Tu congela o baseline e o repositório só pode melhorar a partir dali ou empatar." A catraca anda num sentido só. |
|
||||
| 4 | **Regra de ouro.** | "Cada PR pode adicionar código, mas não pode aumentar nenhuma das métricas — nem por uma violação, nem por uma linha, nem por 0,1 ponto percentual." |
|
||||
| 5 | **Métricas do baseline.** | Violações de ESLint (483 em 120 arquivos), duplicação de código (2,2% via JSCPD), cobertura (%), arquivos acima do limite de tamanho (19 arquivos; o maior com 4.600 linhas). |
|
||||
| 6 | **Pipeline de CI.** | `npm ci` → `npm audit` (critical=bloqueia / high=avisa) → `npm run lint` → `test:coverage` → **script node de quality gate** que compara métricas atuais vs `baseline.json` e falha em qualquer regressão → comentário no PR + **upload de artefatos** que o agente lê para se autocorrigir. |
|
||||
| 7 | **Artefatos legíveis pelo agente.** | "Não adianta cuspir isso no PR. O agente precisa ter acesso ao que está dando errado." |
|
||||
| 8 | **Babysit skill.** | "Recomendo criar uma skill de babysit": a IA monitora o CI + comentários dos revisores, endereça os comentários e **resolve as conversas** para dar rastreabilidade no GitHub. |
|
||||
| 9 | **Comentários perto do código (legibilidade p/ agente).** | Mudou de ideia: antes era contra comentários ("o código é a documentação"); agora, no mundo de agentes, comentário explicando *o quê* e *por quê* perto do código vale mais que um MD gigante, porque o harness faz `grep` no arquivo e lê o comentário junto. |
|
||||
| 10 | **É "só" colar ferramentas.** | "Não é nada excepcional. Eu só estou colando um monte de ferramentas e chamando de quality gate." Pode-se usar SonarQube ou GitHub Code Quality no lugar do script caseiro. |
|
||||
| 11 | **Por que a IA não faz certo de primeira.** | Modelos top já sabem (foram treinados com os livros), mas são "preguiçosos" porque output imperfeito = mais tokens vendidos. A catraca força o nível. |
|
||||
|
||||
**Tradução para o nosso contexto:** o vídeo descreve um sistema que **já temos em embrião** (o `any-budget` é exatamente a catraca da regra de ouro, só que para uma métrica). O salto é (1) generalizar a catraca para todas as métricas, (2) reconciliar os drifts, e (3) fechar os buracos anti-alucinação que são específicos do nosso tamanho.
|
||||
|
||||
---
|
||||
|
||||
## 2. Onde o OmniRoute está hoje (panorama auditado)
|
||||
|
||||
### 2.1 O que já temos (e o vídeo nem sonha)
|
||||
|
||||
- **CI robusto** (`.github/workflows/ci.yml`, ~25 KB, 20 jobs): lint + audit + cycles + route-validation + any-budget + docs-sync + typecheck (core e noimplicit) + build + package-artifact + electron-smoke + unit (8 shards) + Node 24/26 compat + coverage (8 shards + merge) + SonarQube + e2e (9 shards) + integration + security.
|
||||
- **Catraca real já existente:** `scripts/check/check-t11-any-budget.mjs` — array `{file, maxAny}` (a maioria `0`), strip de comentários, anotações de falso-positivo, `exit 1` em regressão. **É o template exato da catraca do vídeo.**
|
||||
- **14 scripts `check-*.mjs`** (cycles, route-validation, any-budget, docs-sync, docs-counts, env-doc-sync, deprecated-versions, doc-links, cli-i18n, openapi-coverage, openapi-security-tiers, pr-test-policy, node-runtime, test-report-summary) — vários já são *gates de consistência fonte-vs-derivado*, o mesmo padrão que precisamos para anti-alucinação.
|
||||
- **PR test policy:** `check-pr-test-policy.mjs` já força "mudou código de produção ⇒ mudou teste" (diff base...HEAD).
|
||||
- **Cobertura sumarizada + comentada no PR:** `test-report-summary.mjs` + `coverage/coverage-summary.json` + job `coverage-pr-comment` (comentário com marcador `<!-- omniroute-coverage-report -->`). **Isto é exatamente o "artefato legível pelo agente" do vídeo** — já construído.
|
||||
- **Disciplina TDD institucionalizada** (Hard Rule #18: todo fix precisa de teste falha→passa ou validação ao vivo no VPS).
|
||||
- **SonarQube** configurado (job no CI + `sonar-project.properties`).
|
||||
- **Skills agênticas de review** já existem: `/review-prs`, `/review-reviews` (bateria de 8 reviewers + ralph-loop), `/code-review`, `/generate-release` (a única com babysit real de CI, mas de workflows de *release*, não do `ci.yml` do PR).
|
||||
|
||||
### 2.2 O que está DESLIGADO ou inerte ⚠️ (achados da auditoria)
|
||||
|
||||
| Item | Estado | Evidência | Impacto |
|
||||
|------|--------|-----------|---------|
|
||||
| **Husky** | 100% comentado (pre-commit **e** pre-push) | `.husky/pre-commit`, `.husky/pre-push` (todas as linhas com `#`) | Zero enforcement local — lint-staged, docs-sync, any-budget, env-doc-sync, openapi checks e o `test:unit` de pre-push dependem 100% do CI. |
|
||||
| **Gate de cobertura no CI** | **40/40/40/40** (não 60) | `ci.yml:377` `--statements 40 --lines 40 --functions 40 --branches 40` | O comentário do PR renderiza contra 60, o script local gata 60, o RELEASE_CHECKLIST diz 75/70, e o baseline real é ~79–82%. **O único número que bloqueia merge é 40** → gate de cobertura quase banguela. |
|
||||
| **Sonar coverage** | Excluído | `sonar-project.properties:9` `sonar.coverage.exclusions=**/*` | Sonar ignora cobertura de todo arquivo. |
|
||||
| **Sonar CPD (duplicação)** | Excluído | `sonar-project.properties:10` `sonar.cpd.exclusions=**/*` | Sonar não detecta copy-paste — a assinatura nº1 de slop de IA. |
|
||||
| **SonarQube job** | Inerte | `ci.yml` roda scan só se `PR && SONAR_TOKEN != '' && SONAR_HOST_URL != ''`; sem `qualitygate.wait` | Em runs sem secret, escreve "skipped"; mesmo quando roda, nunca falha o build. |
|
||||
| **`npm audit`** | Plano (`moderate`), não escalonado | `package.json:112` `--audit-level=moderate` | O vídeo prega critical=bloqueia / high=avisa. O nosso é um nível único. |
|
||||
| **3 scripts órfãos** | Sem CI nem husky | `check:cli-i18n`, `check:openapi-coverage`, `check:openapi-security-tiers` | Existem, dão `exit 1`, mas não rodam em lugar nenhum (Hard Rules #15/#17 guardadas só por um deles). |
|
||||
| **`typecheck:noimplicit:core`** | `continue-on-error: true` | `ci.yml:45-46` | Warn-only "forward-looking". |
|
||||
|
||||
### 2.3 Hotspots de tamanho (sem gate hoje)
|
||||
|
||||
`64 arquivos > 1000 LOC`, `194 > 500 LOC` (src + open-sse, sem testes). Top:
|
||||
|
||||
| LOC | Arquivo | Risco para edição por IA |
|
||||
|-----|---------|--------------------------|
|
||||
| **12.760** | `src/app/(dashboard)/dashboard/providers/[id]/page.tsx` | God-component: **192 `useState`**, 21 `useEffect`, 87 `fetch()` inline, 34 tipos inline. Nenhuma IA segura em contexto; qualquer edição arrisca apagar estado não relacionado. |
|
||||
| 5.977 | `open-sse/handlers/chatCore.ts` | God-handler: 58 funções, invariantes demais, blast radius alto. |
|
||||
| 4.590 | `open-sse/config/providerRegistry.ts` | Array gigante providers+models+OAuth; mistura `resolvePublicCred()` e literais crus. |
|
||||
| 4.456 | `open-sse/services/combo.ts` | 14 estratégias num `if/else if` sem enum/exhaustiveness — estratégia desconhecida vira no-op silencioso. |
|
||||
| 4.349 | `src/app/(dashboard)/dashboard/combos/page.tsx` | 51 `useState`, mesmo padrão god-component. |
|
||||
| 4.205 | `src/lib/providers/validation.ts` | Mega-função com closures e `SPECIALTY_VALIDATORS` definidos *dentro* da função. |
|
||||
| 3.776 | `open-sse/handlers/imageGeneration.ts` | Branching multi-provider num handler. |
|
||||
| 3.076 | `src/shared/constants/providers.ts` | 229 ids em 27 consts agrupados via `Proxy` — sem lista plana. |
|
||||
| 2.869 | `open-sse/executors/chatgpt-web.ts` | Sessão web reversa; classe só começa na linha 2443. |
|
||||
| 2.278 | `src/app/api/providers/[id]/models/route.ts` | God-route: importa ~30 módulos provider-específicos e ramifica por provider num GET. |
|
||||
|
||||
### 2.4 Ímãs de alucinação (ranqueados, da auditoria)
|
||||
|
||||
1. **Split de provider em 3 arquivos / 2 workspaces (nº1).** Não há lista plana de providers — 229 ids escondidos atrás de 27 consts + merge via `Proxy` (`AI_PROVIDERS`). Uma IA não consegue enumerar "quais providers existem" barato → **inventa ids plausíveis** (variantes `*-web`/`*-cli` inexistentes) ou registra no grupo errado. As três contagens (`providers.ts` 229 ids ↔ `providerRegistry.ts` 155 blocos ↔ `validation.ts` N validadores) **já divergem**, então não há cross-check autoritativo. *(Esse é o tema recorrente das nossas memórias de alucinação — ex.: ids inventados, modelos inexistentes.)*
|
||||
2. **300 paths `fetch("/api/...")` hardcoded** no dashboard (659 call sites), sem client tipado. Refatore uma rota e os call sites apodrecem silenciosamente; uma IA editando a UI inventa rota (`/api/providers/[id]/refresh`) ou assume `res.error.message` numa rota que devolve `{error:"..."}`. Sem ligação de símbolo entre os 659 call sites e os 488 `route.ts`.
|
||||
3. **Dual chat stack (armadilha documentada).** Seleção/fallback de conta vive em `src/sse/` (não `open-sse/`). Uma IA pedida para "consertar fallback de conta" edita `open-sse/handlers/chatCore.ts` (errado) em vez de `src/sse/services/auth.ts`. Nada no código cruza os dois stacks. *(Já erramos um diagnóstico público por isso.)*
|
||||
4. **Estratégias de combo inventadas.** 14 nomes reais soterrados num `if/else` de strings (sem enum exportado) → IA inventa nomes plausíveis-mas-falsos (`"latency-optimized"`, `"failover"`) que passam no typecheck como string e viram no-op.
|
||||
5. **Métodos de executor inventados.** O padrão real é "sobrescreve `execute()` inteiro" (48/50 executors), sem hooks documentados → IA inventa `buildRequest`/`parseChunk`/`mapError` que não existem em `BaseExecutor`.
|
||||
6. **Helpers de erro inventados** + queda para `err.message` cru (viola Rule #12) quando o helper inventado "falha"; 5 web executors hoje **não importam helper nenhum**.
|
||||
7. **AGENTS.md de DB defasado:** documenta 21 migrations / 22 módulos quando o real é **94 / 75** — uma IA lendo isso acredita em conjuntos de tabelas/módulos que não existem mais.
|
||||
8. **Route-guard omitido:** rotas novas spawn-capazes (`/api/services/`, `/api/mcp/`) devem entrar em `LOCAL_ONLY_API_PREFIXES`; a convenção está só no CLAUDE.md, não num teste que a IA veja (parcialmente coberta por 1 script órfão).
|
||||
|
||||
---
|
||||
|
||||
## 3. Gap analysis — modelo do vídeo vs OmniRoute
|
||||
|
||||
| Métrica/peça do vídeo | OmniRoute hoje | Gap |
|
||||
|-----------------------|----------------|-----|
|
||||
| `npm ci` determinístico | ✅ em todos os 14 jobs | — |
|
||||
| `npm audit` critical=bloqueia / high=avisa | ⚠️ `--audit-level=moderate` (nível único) | **Escalonar** em dois invokes |
|
||||
| `lint` | ✅ bloqueante | — |
|
||||
| `test` + cobertura | ✅ mas piso **40** no CI (drift) | **Reconciliar** p/ baseline real + catraca |
|
||||
| **Contagem de ESLint congelada** | ❌ (lint é 0-erros, mas warnings livres) | **Construir** (ratchet de violações) |
|
||||
| **Duplicação % (JSCPD)** | ❌ (Sonar CPD excluído, sem jscpd) | **Construir** (jscpd + catraca) |
|
||||
| **Limite de tamanho de arquivo** | ❌ (sem `max-lines`, sem script) | **Construir** (ESLint max-lines + catraca, freeze dos 64) |
|
||||
| **`baseline.json` congelado** | ❌ (nenhum baseline de métricas no repo) | **Construir** (o coração da catraca) |
|
||||
| **Script comparador (regra de ouro)** | 🟡 existe **para `any`** (`any-budget`) | **Generalizar** p/ todas as métricas |
|
||||
| **Sumário markdown + artefatos p/ o agente** | ✅ (coverage summary + PR comment + artifact) | **Reusar** wholesale |
|
||||
| **Babysit skill (monitora CI + resolve conversas)** | 🟡 `review-prs`/`review-reviews`/`generate-release` parciais; nenhuma resolve threads do PR nem loopa no `ci.yml` | **Construir** `/babysit` |
|
||||
| **Comentários perto do código p/ legibilidade de agente** | 🟡 `routeGuard.ts` é exemplar; resto irregular | **Padrão cultural** (Karpathy/guidelines) |
|
||||
|
||||
---
|
||||
|
||||
## 4. O que o mundo faz em 2026 (pesquisa, últimos ~3 meses)
|
||||
|
||||
> Todas as fontes abaixo vêm com URL + data nas seções de origem (ver §7). Onde a pesquisa **não conseguiu confirmar** algo de fonte primária, está marcado **[não-verificado]** — honestidade de engenharia.
|
||||
|
||||
### 4.1 Catraca / baseline-freeze (a "catraca" do vídeo)
|
||||
|
||||
- **betterer** — o tool canônico de ratchet (snapshot de métrica → `.betterer.results`; CI falha se piora, auto-atualiza se melhora). **[caveat]** Baixa velocidade: último commit no `master` em **ago/2025**, releases vazias no GitHub. Viável, mas **não** apostar como peça load-bearing de longo prazo.
|
||||
- **eslint-formatter-ratchet** — formatter que congela contagem de violações de ESLint. **Ativamente mantido** (commit 2026-03-17). Mais estreito (só ESLint) mas é a trajetória oposta ao betterer.
|
||||
- **SonarQube "Clean as You Code" (new-code conditions)** — o padrão baseline-freeze mais maduro: o quality gate aplica condições **só ao código novo** (branch de referência), grandfathering do legado. Atual.
|
||||
- **SonarQube "AI Code Assurance" (2026.1.0)** — gate específico para código gerado por IA (tag o projeto → workflow de assurance + "Sonar way for AI Code" mais estrito). **[não-verificado]** se *bloqueia* o PR (docs canônicas deram 404; descrito como "enforced quality gate" mas mecânica de bloqueio não confirmada em fonte única).
|
||||
- **Qlty CLI (qlty.sh)** — o produto 2026 mais aderente: CLI Rust **OSS e grátis** (v0.630.0, 2026-05-08) que agrega 70+ analisadores; tem **Baseline analysis** (= a catraca), **Quality Gates** com veredito go/no-go e coverage gates. **[caveat]** `qlty metrics` (a tabela LOC/complexidade) **não tem flag JSON** — só `qlty check --sarif`/`qlty smells --sarif`; o ratchet de tamanho/complexidade por arquivo ainda precisa do JSON do ESLint.
|
||||
- **Code Climate Quality → Qlty** — a marca clássica de ratchet virou empresa separada (Qlty, nov/2024). Write-ups antigos de "Code Climate" = Qlty hoje.
|
||||
|
||||
### 4.2 Ferramentas de métrica por tipo (todas com JSON p/ alimentar a catraca)
|
||||
|
||||
| Métrica | Tool 2026 | Comando JSON | Status |
|
||||
|---------|-----------|--------------|--------|
|
||||
| Duplicação | **jscpd v5** (reescrita Rust) | `jscpd --reporters json` (ou `sarif`) | Muito ativo (v5.0.4, 2026-06-08). **[caveat]** schema JSON v4→v5 não confirmado — verificar no install. |
|
||||
| Tamanho/fn-length/ciclomática | **ESLint core** (`max-lines`, `max-lines-per-function`, `complexity`) | `eslint --format json` | Built-in ESLint 9 |
|
||||
| Complexidade cognitiva | **eslint-plugin-sonarjs** (`sonarjs/cognitive-complexity`) | `eslint --format json` | Mantido (v4.0.3, 2026-04-16; agora no monorepo SonarJS — o repo standalone foi arquivado, mas o pacote está vivo). **[caveat]** README das rules deu 404; presença de S3776 em v4 é alta-confiança mas confirmar no install. |
|
||||
| Dead code / unused exports / unused deps | **knip** (vence ts-prune **arquivado** + depcheck **arquivado**) | `knip --reporter json` | Muito ativo (v6.16.1, 2026-06-06) |
|
||||
| Ciclos | **check-cycles.mjs** (já temos) + **dpdm** opcional | `dpdm --circular --output deps.json` | dpdm ativo (v4.2.0, 2026-05-09); madge estagnado |
|
||||
| Vulnerabilidades | **osv-scanner** (Google/OSV) | `osv-scanner --format json` | Muito ativo (push 2026-06-08) |
|
||||
| Política de lockfile (gate, não métrica) | **lockfile-lint** | `lockfile-lint --validate-https --validate-integrity` | Mantido (v5.0.0, 2026-01-25) |
|
||||
|
||||
> **Realidade do ratchet:** não existe tool único 2026 que emita *todas* as métricas como um JSON limpo. O padrão robusto é **N tools que emitem JSON + um reducer Node** que monta `metrics-summary.json` + o comparador que falha só em regressão (exatamente o que o `any-budget` já faz para uma métrica).
|
||||
|
||||
### 4.3 Anti-alucinação (2026)
|
||||
|
||||
- **LSP-in-the-loop / `agent-lsp` (MCP)** — servidor MCP que dá ao agente fatos verificáveis do language server (definições, referências, tipos, diagnostics, `blast_radius`) e `preview_edit` antes de escrever. Funciona com Claude Code. **Fit alto:** vira "símbolo inventado" de catch-de-review para *impossibilidade-no-edit*. (v0.13.0, 2026-06-04 — pequeno mas ativo.)
|
||||
- **Slopsquatting / pacotes alucinados** — **CSA Research Note (2026-04-19):** **19,7%** de 2,23M amostras de código IA continham nomes de pacote alucinados; 205k nomes fabricados únicos; **43%** reaparecem em re-runs (registráveis por atacantes). Defesas: **allowlist** de deps para agentes, **registry existence check** antes de instalar, **age-cooldown** (24–72h), lockfile-exact, scripts de install desabilitados. **Fit alto:** novo `check-deps.mjs`.
|
||||
- **Semcheck** (v1.2.1, fev/2026) — CLI que usa LLM para verificar que a implementação bate com o spec/doc, via `semcheck.yaml` ligando doc↔código; roda em pre-commit e Actions com `fail-on-issues`. Feito para pegar **"docs que descrevem features não implementadas"**. **Fit muito alto** para nossos incidentes recorrentes de docs alucinadas — porém é fuzzy (LLM); pareie com checks determinísticos.
|
||||
- **OpenAPI drift determinístico** — check que toda `path` do `openapi.yaml` resolve para um `route.ts` real (e vice-versa). Rápido, sem LLM, pega "endpoint inventado". **Fit alto** para `docs/reference/openapi.yaml`.
|
||||
- **Skill `verify` / `verification-before-completion`** (já no nosso ambiente) — "evidence before assertions": o veredito PASS/FAIL repousa **só** no que o app rodando demonstrou; rejeita "rodei os testes" como prova. **Fit altíssimo:** é a formalização da nossa Hard Rule #18 — exigir o *output literal* do comando colado no PR ("tool receipt").
|
||||
- **Adversarial review (críticos de sessão fresca)** — agentes Skeptic/Architect/Minimalist leem o diff *contra o spec* ("o autor está comprometido — vai racionalizar"); símbolos/APIs inventados viram violação de spec. Mapeia no nosso `/review-reviews`.
|
||||
- **SlopCodeBench (arXiv 2603.24755, ~mai/2026)** — sem mitigação, erosão estrutural aumentou em **77%** das trajetórias; o código de agente acumula verbosidade ~7× e erosão ~5× mais rápido que repos humanos. **Mitigações só-de-prompt ("anti-slop", "plan-first") melhoram o início mas NÃO param a degradação iterativa.** → **justificativa empírica** de que precisamos de gates determinísticos, não instrução.
|
||||
- **GPT-5.5 System Card (2026-04-23)** — figuras oficiais são modestas (23% mais provável de acerto factual; 3% menos erros num set propenso). O headline de **"queda de 60% em alucinação / 88,7% SWE-bench" é imprensa secundária [não-verificado]**, não a seção de factualidade do system card. Upgrade de modelo ajuda na margem, não substitui gate.
|
||||
|
||||
### 4.4 Babysit loops (2026)
|
||||
|
||||
- **Claude Code "auto-fix in the cloud"** (Anthropic, lançado 2026-03-27): "observa seus PRs na nuvem, resolvendo falhas de CI e comentários de review automaticamente; empurra fixes quando claro, pergunta quando ambíguo." Não auto-mergeia.
|
||||
- **Devin Autofix** (2026-02-10): auto-conserta comentários de review + lint/CI; endereça comentários de bots, mas deixa julgamento humano nas conversas humanas.
|
||||
- **CodeRabbit Autofix** (early access abr/2026): coleta o bloco **"Prompt for AI Agents"** de cada comentário, aplica fix, roda build-verification; **nada mergeia automaticamente**.
|
||||
- **Greptile `greploop` + skill `check-pr`** (MIT) — "dispara review → conserta comentários → re-review até 5/5 de confiança e zero comentários". **Template quase-exato** para a nossa `/babysit`.
|
||||
- **Claude `claude ultrareview <PR#> --json`** (subcomando não-interativo, research preview): bloqueia até terminar, `exit 0/1`, payload de bugs verificados parseável. **Não auto-inicia** e custa $5–20/run → usar atrás de label, não em todo push. (O `/code-review ultra` local com `--fix` é o loop interno de custo-zero.)
|
||||
- **Resolver threads de review:** não há comando `gh` nativo (cli/cli#12419). Padrão de 2 passos GraphQL: `reviewThreads(first:50){nodes{id isResolved...}}` → `mutation { resolveReviewThread(input:{threadId}) }`, respondendo antes com o SHA do commit via REST.
|
||||
- **Guarda-corpos (críticos):**
|
||||
- **Snyk Agent Fix field test (2026): ~5,3% de regressão** ("1 em 19 fixes auto-mergeados introduz problema novo") → **forte argumento contra auto-merge**.
|
||||
- **Token burn:** loops ingênuos realimentam a conversa crescente → prompt incha → alucina do próprio histórico. Uber capou gasto em **$1.500/mês/dev/tool** (abr/2026). Mitigação: **max-iterations**, time limit, idle-exit.
|
||||
- **Test-masking:** o babysit **NÃO** pode enfraquecer/remover asserts para ficar verde (= nossa Rule #18 + memória "trust but verify"). Revisão humana fica nos limites arquiteturais (interface/schema/cross-service).
|
||||
- **Audit trail:** deixar rastro humano-legível (qual fix endereçou o quê, qual gate satisfez, quais conversas resolveu) — nunca um verde silencioso. Reforça o guard de prompt-injection sobre os *corpos de comentário* que o agente ingere (21% dos reviews do ICLR 2026 eram IA; injeção embutida em código é vetor real).
|
||||
|
||||
---
|
||||
|
||||
## 5. Recomendações (ranqueadas) → ver o PLANO
|
||||
|
||||
> Build-vs-buy: **construir in-repo** os gates determinísticos (zero SaaS, dados não saem da box, reusa o harness `check-*.mjs`). **Avaliar Qlty CLI** depois, se quisermos consolidar N scripts num tool. **Não** depender de CodeRabbit/Greptile/Diamond como *o* gate de "não-piorar-métrica" — são opiniões de LLM, não contadores determinísticos.
|
||||
|
||||
**Fase 0 — Reativar & reconciliar (quick wins, sem tooling novo):**
|
||||
1. Reativar pre-commit barato do Husky (lint-staged + docs-sync + any-budget).
|
||||
2. Reconciliar o gate de cobertura: subir o CI de 40 → baseline real (com headroom) e alinhar os 4 lugares que divergem.
|
||||
3. Escalonar `npm audit` (critical=bloqueia / high=avisa).
|
||||
4. Plugar os 3 scripts órfãos (`cli-i18n`, `openapi-coverage`, `openapi-security-tiers`) no CI.
|
||||
|
||||
**Fase 1 — Motor de catraca (o coração):**
|
||||
5. `quality-baseline.json` commitado + `collect-metrics.mjs` (coletor) + `check-quality-ratchet.mjs` (comparador, clone do `any-budget`) + job de CI + artefato + comentário no PR (clone do `coverage-pr-comment`).
|
||||
|
||||
**Fase 2 — Gates determinísticos anti-alucinação:**
|
||||
6. `check-provider-consistency.mjs` (o ímã nº1), `check-fetch-targets.mjs`, `check-openapi-routes.mjs`, allow-list de estratégias/translators/executors, lint Rule #11/#12, `check-deps.mjs` (slopsquatting).
|
||||
|
||||
**Fase 3 — Catraca de duplicação + tamanho (mata-slop):**
|
||||
7. jscpd + ESLint `max-lines`/`max-lines-per-function`/`complexity` + `sonarjs/cognitive-complexity`, congelando os 64 arquivos grandes (catraca só-pode-encolher).
|
||||
|
||||
**Fase 4 — Catraca de cobertura + anti test-masking:**
|
||||
8. `check-coverage-ratchet.mjs` (cobertura não cai vs baseline) + pisos por módulo crítico + `check-test-masking.mjs` (delta de contagem de asserts em testes alterados).
|
||||
|
||||
**Fase 5 — Skill `/babysit` + evidência + LSP:**
|
||||
9. Skill `/babysit` (gh pr checks + reviewThreads + worktree de fix + resolveReviewThread + loop-até-verde, com guarda-corpos), "evidence-before-assertions" obrigatório no corpo do PR, e (opcional) `agent-lsp` MCP.
|
||||
|
||||
---
|
||||
|
||||
## 6. Riscos & ressalvas (honestidade de engenharia)
|
||||
|
||||
- **Flag-day risk:** ligar qualquer gate num projeto que nunca o teve deixa tudo vermelho. **Toda** catraca aqui é *só-regressão* (baseline congelado), nunca um piso absoluto que exige limpeza imediata — exatamente o ponto do vídeo.
|
||||
- **Custo de IA:** o babysit pode queimar tokens. Guarda-corpos (max-iterations, sem auto-merge, sem editar `.github/workflows/`) são não-negociáveis.
|
||||
- **Ressalvas de pesquisa não-verificadas:** betterer baixa-velocidade; Sonar "AI Code Assurance" bloqueio-de-PR não confirmado; "GPT-5.5 −60% alucinação" é imprensa, não system card; schema JSON do jscpd v5 e S3776 do sonarjs v4 a confirmar no install; `qlty metrics` sem JSON. Nenhuma decisão do plano depende criticamente de um item não-verificado.
|
||||
- **Trust-but-verify:** estes números internos (CI=40, husky off, sonar exclusions, 12.760 LOC, any-budget como catraca) foram **conferidos manualmente** contra os arquivos, não só relatados pelos subagentes.
|
||||
|
||||
---
|
||||
|
||||
## 7. Fontes (consolidadas)
|
||||
|
||||
**Catraca / ratchet:** betterer `github.com/phenomnomnominal/betterer` (último master ago/2025); eslint-formatter-ratchet `github.com/Jmsa/eslint-formatter-ratchet` (commit 2026-03-17); SonarQube Clean as You Code `docs.sonarsource.com/.../clean-as-you-code/about-new-code/`; Sonar AI Code Assurance `sonarsource.com/solutions/ai/ai-code-assurance/` + community thread 2026.1.0; Qlty `github.com/qltysh/qlty` (v0.630.0, 2026-05-08), `docs.qlty.sh`; Code Climate→Qlty `codeclimate.com/legacy/...` (2024-11-11).
|
||||
|
||||
**Métricas:** jscpd `github.com/kucherenko/jscpd` (v5.0.4, 2026-06-08); ESLint v10 `eslint.org/blog/2026/02/eslint-v10.0.0-released/` (2026-02-06); eslint-plugin-sonarjs `npm` (v4.0.3, 2026-04-16) + `github.com/SonarSource/SonarJS`; knip `knip.dev` (v6.16.1, 2026-06-06); dpdm `github.com/acrazing/dpdm` (v4.2.0, 2026-05-09); osv-scanner `google.github.io/osv-scanner` (push 2026-06-08); lockfile-lint `github.com/lirantal/lockfile-lint` (v5.0.0, 2026-01-25); GitClear `gitclear.com/ai_assistant_code_quality_2025_research`.
|
||||
|
||||
**Anti-alucinação:** agent-lsp `github.com/blackwell-systems/agent-lsp` (v0.13.0, 2026-06-04); CSA Slopsquatting `labs.cloudsecurityalliance.org/research/...slopsquatting...20260419...` (2026-04-19); Nesbitt package defenses `nesbitt.io/2026/04/09/...` (2026-04-09); Semcheck `github.com/rejot-dev/semcheck` (v1.2.1, fev/2026); verify skill `github.com/Piebald-AI/claude-code-system-prompts/.../skill-verify-skill.md`; Claude best practices `code.claude.com/docs/en/best-practices`; SlopCodeBench `arxiv.org/pdf/2603.24755`; GPT-5.5 system card `deploymentsafety.openai.com/gpt-5-5` (2026-04-23); adversarial review `asdlc.io/patterns/adversarial-code-review/`; OpenAPI drift `speakeasy.com/blog/openapi-spec-drift-detection`.
|
||||
|
||||
**Babysit:** Claude auto-fix cloud `producthunt.com/products/claude-code-auto-fix-in-the-cloud` (2026-03-27); Devin Autofix `cognition.ai/blog/closing-the-agent-loop-...` (2026-02-10); CodeRabbit Autofix `coderabbit.ai/blog/fix-all-issues-with-ai-agents` (2026-02-19); Greptile skills `github.com/greptileai/skills`; Claude GitHub Actions/Code Review/ultrareview `code.claude.com/docs/en/{github-actions,code-review,ultrareview}`; Nx self-healing `nx.dev/blog/autonomous-ai-workflows-with-nx` (2026-02-03); Snyk Agent Fix 5,3% `safeguard.sh/resources/blog/snyk-agent-fix-autofix-field-test-2026`; resolveReviewThread `nakamasato.medium.com/...` + `github.com/cli/cli/issues/12419`; ICLR 2026 AI review `blog.pebblous.ai/report/iclr-2026-ai-peer-review-crisis`.
|
||||
|
||||
---
|
||||
|
||||
*Relatório gerado a partir de auditoria paralela do código + transcrição do vídeo + pesquisa web 2026. Próximo passo: aprovar o [`PLANO-QUALITY-GATES.md`](./PLANO-QUALITY-GATES.md) e escolher por onde começar (recomendação: Fase 0 → Fase 1).*
|
||||
116
SECURITY.md
116
SECURITY.md
@@ -20,9 +20,9 @@ If you discover a security vulnerability in OmniRoute, please report it responsi
|
||||
|
||||
| Version | Support Status |
|
||||
| ------- | -------------- |
|
||||
| 1.0.x | ✅ Active |
|
||||
| 0.8.x | ✅ Security |
|
||||
| < 0.8.0 | ❌ Unsupported |
|
||||
| 3.8.x | ✅ Active |
|
||||
| 3.7.x | ✅ Security |
|
||||
| < 3.7.0 | ❌ Unsupported |
|
||||
|
||||
---
|
||||
|
||||
@@ -31,18 +31,24 @@ If you discover a security vulnerability in OmniRoute, please report it responsi
|
||||
OmniRoute implements a multi-layered security model:
|
||||
|
||||
```
|
||||
Request → CORS → API Key Auth → Prompt Injection Guard → Input Sanitizer → Rate Limiter → Circuit Breaker → Provider
|
||||
Request → CORS → Authz pipeline (classify → policies → enforce)
|
||||
→ Guardrails (PII masker, prompt injection, vision bridge)
|
||||
→ Rate Limiter → Circuit Breaker → Cooldown → Model Lockout → Provider
|
||||
```
|
||||
|
||||
### 🔐 Authentication & Authorization
|
||||
|
||||
| Feature | Implementation |
|
||||
| -------------------- | ---------------------------------------------------------- |
|
||||
| **Dashboard Login** | Password-based auth with JWT tokens (HttpOnly cookies) |
|
||||
| **API Key Auth** | HMAC-signed keys with CRC validation |
|
||||
| **OAuth 2.0 + PKCE** | Secure provider auth (Claude, Codex, Gemini, Cursor, etc.) |
|
||||
| **Token Refresh** | Automatic OAuth token refresh before expiry |
|
||||
| **Secure Cookies** | `AUTH_COOKIE_SECURE=true` for HTTPS environments |
|
||||
| Feature | Implementation |
|
||||
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Dashboard Login** | Password-based auth with JWT tokens (HttpOnly cookies) |
|
||||
| **API Key Auth** | HMAC-signed keys with CRC validation |
|
||||
| **OAuth 2.0 + PKCE** | 14 providers (Claude, Codex, GitHub, Cursor, Antigravity, Gemini, Kimi Coding, Kilo Code, Cline, Qwen, Kiro, Qoder, Windsurf, GitLab Duo) |
|
||||
| **Token Refresh** | Automatic OAuth token refresh before expiry |
|
||||
| **Secure Cookies** | `AUTH_COOKIE_SECURE=true` for HTTPS environments |
|
||||
| **Authz Pipeline** | Route classification (PUBLIC / CLIENT_API / MANAGEMENT) — see `docs/architecture/AUTHZ_GUIDE.md` |
|
||||
| **Route Guard Tiers** | 3-tier model for management routes (LOCAL_ONLY / ALWAYS_PROTECTED / MANAGEMENT) — see `docs/security/ROUTE_GUARD_TIERS.md` |
|
||||
| **Manage-Scope MCP** | Remote `/api/mcp/*` access gated by API keys with `manage` scope; `/api/cli-tools/runtime/*` stays strict-loopback. See ROUTE_GUARD_TIERS |
|
||||
| **MCP Scopes** | ~13 granular scopes (read:health, write:combos, execute:completions, etc.) — see `docs/frameworks/MCP-SERVER.md` |
|
||||
|
||||
### 🛡️ Encryption at Rest
|
||||
|
||||
@@ -57,6 +63,18 @@ All sensitive data stored in SQLite is encrypted using **AES-256-GCM** with scry
|
||||
STORAGE_ENCRYPTION_KEY=$(openssl rand -hex 32)
|
||||
```
|
||||
|
||||
### 🛡️ Guardrails Framework
|
||||
|
||||
OmniRoute ships a hot-reloadable **guardrails registry** (`src/lib/guardrails/`) with 3 built-in guardrails ordered by priority:
|
||||
|
||||
| Guardrail | Priority | Purpose |
|
||||
| ------------------ | -------- | --------------------------------------------------------------------------------------- |
|
||||
| `vision-bridge` | 5 | Bridges non-vision models with image-aware descriptions; SSRF protection for image URLs |
|
||||
| `pii-masker` | 10 | Pre+post call PII redaction (emails, phone, CPF, CNPJ, credit cards, SSN) |
|
||||
| `prompt-injection` | 20 | Detects override/role-hijack/jailbreak/leak patterns |
|
||||
|
||||
Custom guardrails register via `registerGuardrail(new MyGuardrail())`. The model is fail-open (exceptions never block traffic). Per-request opt-out via `x-omniroute-disabled-guardrails` header. → See [`docs/security/GUARDRAILS.md`](docs/security/GUARDRAILS.md).
|
||||
|
||||
### 🧠 Prompt Injection Guard
|
||||
|
||||
Middleware that detects and blocks prompt injection attacks in LLM requests:
|
||||
@@ -98,9 +116,11 @@ PII_REDACTION_ENABLED=true
|
||||
| Feature | Description |
|
||||
| ------------------------ | ---------------------------------------------------------------- |
|
||||
| **CORS** | Configurable origin control (`CORS_ORIGIN` env var, default `*`) |
|
||||
| **IP Filtering** | Whitelist/blacklist IP ranges in dashboard |
|
||||
| **IP Filtering** | Allowlist/blocklist IP ranges in dashboard |
|
||||
| **Rate Limiting** | Per-provider rate limits with automatic backoff |
|
||||
| **Anti-Thundering Herd** | Mutex + per-connection locking prevents cascading 502s |
|
||||
| **TLS Fingerprint** | Browser-like TLS fingerprint spoofing to reduce bot detection |
|
||||
| **CLI Fingerprint** | Per-provider header/body ordering to match native CLI signatures |
|
||||
|
||||
### 🔌 Resilience & Availability
|
||||
|
||||
@@ -113,11 +133,13 @@ PII_REDACTION_ENABLED=true
|
||||
|
||||
### 📋 Compliance
|
||||
|
||||
| Feature | Description |
|
||||
| ------------------ | --------------------------------------------------- |
|
||||
| **Log Retention** | Automatic cleanup after `LOG_RETENTION_DAYS` |
|
||||
| **No-Log Opt-out** | Per API key `noLog` flag disables request logging |
|
||||
| **Audit Log** | Administrative actions tracked in `audit_log` table |
|
||||
| Feature | Description |
|
||||
| ------------------ | ----------------------------------------------------------- |
|
||||
| **Log Retention** | Automatic cleanup after `CALL_LOG_RETENTION_DAYS` |
|
||||
| **No-Log Opt-out** | Per API key `noLog` flag disables request logging |
|
||||
| **Audit Log** | Administrative actions tracked in `audit_log` table |
|
||||
| **MCP Audit** | SQLite-backed audit logging for all MCP tool calls |
|
||||
| **Zod Validation** | All API inputs validated with Zod v4 schemas at module load |
|
||||
|
||||
---
|
||||
|
||||
@@ -163,7 +185,61 @@ docker run -d \
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Run `npm audit` regularly
|
||||
- Run `npm audit` regularly (`npm run audit:deps` covers main + electron)
|
||||
- Keep dependencies updated
|
||||
- The project uses `husky` + `lint-staged` for pre-commit checks
|
||||
- CI pipeline runs ESLint security rules on every push
|
||||
- The project uses `husky` + `lint-staged` for pre-commit checks (lint-staged + check-docs-sync + check:any-budget:t11)
|
||||
- CI pipeline runs ESLint security rules on every push (`no-eval`, `no-implied-eval`, `no-new-func` = error)
|
||||
- Provider constants validated at module load via Zod (`src/shared/validation/schemas.ts`)
|
||||
- Secure-by-default libraries used: `dompurify` / `isomorphic-dompurify` (XSS), `jose` (JWT), `better-sqlite3` (no SQLi risk via parameterized queries), `bcryptjs` (password hashing)
|
||||
|
||||
## Hard Security Rules
|
||||
|
||||
These rules are enforced by tooling and reviewers:
|
||||
|
||||
1. **Never commit secrets** — `.env` is gitignored; `.env.example` is the template (no literals, comments only — see PUBLIC_CREDS.md below)
|
||||
2. **Never use `eval()`, `new Function()`, or implied eval** — ESLint enforces
|
||||
3. **Never bypass Husky hooks** (`--no-verify`, `--no-gpg-sign`) without explicit operator approval
|
||||
4. **Never write raw SQL in routes** — always go through `src/lib/db/` (parameterized)
|
||||
5. **Always validate inputs with Zod** — `src/shared/validation/schemas.ts`
|
||||
6. **Always sanitize upstream headers** — denylist in `src/shared/constants/upstreamHeaders.ts`
|
||||
7. **Encrypt credentials at rest** — AES-256-GCM via `src/lib/db/encryption.ts`
|
||||
8. **Public upstream OAuth identifiers via `resolvePublicCred()`** — never embed `AIza…` / `GOCSPX-…` / `…apps.googleusercontent.com` literals in source. See [`docs/security/PUBLIC_CREDS.md`](docs/security/PUBLIC_CREDS.md).
|
||||
9. **Error responses through `buildErrorBody()` / `sanitizeErrorMessage()`** — never put raw `err.stack` / `err.message` in HTTP / SSE / executor / MCP response bodies. See [`docs/security/ERROR_SANITIZATION.md`](docs/security/ERROR_SANITIZATION.md).
|
||||
10. **`exec()` / `spawn()` runtime values via the `env` option** — never string-interpolate external paths or untrusted values into shell-passed scripts. Reference: `src/mitm/cert/install.ts::updateNssDatabases`.
|
||||
11. **Prefer secure-by-default libraries** — see [tldrsec/awesome-secure-defaults](https://github.com/tldrsec/awesome-secure-defaults) (Helmet.js, DOMPurify, ssrf-req-filter, safe-regex, Google Tink). Reach for them before rolling your own.
|
||||
|
||||
## Supply-chain scanner findings (Socket.dev / Snyk / similar)
|
||||
|
||||
The published `omniroute` npm artifact bundles the Next.js `output: "standalone"`
|
||||
build, which means every route handler — including documented privileged
|
||||
features (MITM, Zed import, Cloud Sync, embedded service supervisor) — ends
|
||||
up in `.next/server/*.js` minified chunks. Heuristic supply-chain scanners
|
||||
frequently pattern-match those chunks against malware signatures.
|
||||
|
||||
For each finding category we maintain a per-finding maintainer attestation:
|
||||
|
||||
- **[`docs/security/SOCKET_DEV_FINDINGS.md`](docs/security/SOCKET_DEV_FINDINGS.md)** —
|
||||
per-finding map: source file ↔ flagged chunk ↔ behaviour ↔ mitigation
|
||||
applied in v3.8.6.
|
||||
- In-source `SECURITY-AUDITOR-NOTE:` blocks at each flagged function point
|
||||
back to the same document.
|
||||
|
||||
For users whose pipeline cannot relax the alert: build with
|
||||
`OMNIROUTE_BUILD_PROFILE=minimal npm run build`. That replaces the four
|
||||
sensitive modules with stubs that return HTTP 503 `feature-disabled` at
|
||||
runtime, so the privileged code paths are physically absent from the bundle.
|
||||
See [`docs/security/SOCKET_DEV_FINDINGS.md`](docs/security/SOCKET_DEV_FINDINGS.md)
|
||||
for the publishing recipe.
|
||||
|
||||
## References
|
||||
|
||||
- [`docs/architecture/AUTHZ_GUIDE.md`](docs/architecture/AUTHZ_GUIDE.md) — authorization pipeline
|
||||
- [`docs/security/GUARDRAILS.md`](docs/security/GUARDRAILS.md) — guardrails framework
|
||||
- [`docs/security/COMPLIANCE.md`](docs/security/COMPLIANCE.md) — audit log and retention
|
||||
- [`docs/security/PUBLIC_CREDS.md`](docs/security/PUBLIC_CREDS.md) — **mandatory** pattern for public upstream credentials
|
||||
- [`docs/security/ERROR_SANITIZATION.md`](docs/security/ERROR_SANITIZATION.md) — **mandatory** pattern for error responses
|
||||
- [`docs/security/SOCKET_DEV_FINDINGS.md`](docs/security/SOCKET_DEV_FINDINGS.md) — maintainer attestation for supply-chain scanner findings
|
||||
- [`docs/architecture/RESILIENCE_GUIDE.md`](docs/architecture/RESILIENCE_GUIDE.md) — circuit breaker + cooldown + lockout
|
||||
- [`docs/security/STEALTH_GUIDE.md`](docs/security/STEALTH_GUIDE.md) — TLS fingerprinting (legal/ethical notice)
|
||||
- [`CLAUDE.md`](CLAUDE.md) — hard rules for AI agents
|
||||
- [tldrsec/awesome-secure-defaults](https://github.com/tldrsec/awesome-secure-defaults) — curated secure-by-default libraries
|
||||
|
||||
224
bin/cli/CONVENTIONS.md
Normal file
224
bin/cli/CONVENTIONS.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# OmniRoute CLI — Internal Conventions
|
||||
|
||||
> Status: normative. Source: `_tasks/features-v3.8.0/cli/fase-0-preparacao/0.3-definir-convencoes.md`.
|
||||
> This file is the authoritative reference for every new or migrated CLI command.
|
||||
> If reality diverges from this document, fix the code first; only edit this file
|
||||
> after the discrepancy has been justified in a PR.
|
||||
|
||||
## 1. Subcommand style
|
||||
|
||||
**Standard**: `git`-style nested verbs.
|
||||
|
||||
```
|
||||
omniroute keys add openai sk-xxx
|
||||
omniroute combo switch fastest
|
||||
omniroute memory search "react hooks"
|
||||
```
|
||||
|
||||
**Not allowed**:
|
||||
|
||||
```
|
||||
omniroute --add-key openai sk-xxx # ❌ flag-as-verb
|
||||
omniroute add-key openai sk-xxx # ❌ hyphen at the top level
|
||||
```
|
||||
|
||||
## 2. Flags
|
||||
|
||||
- Only `--long` and `-s` shorts (one-letter shorts reserved for very common
|
||||
flags: `-h`, `-v`, `-o`, `-q`, `--no-open`).
|
||||
- Format: `--api-key sk-xxx` (space). `=` accepted for parity but doc uses space.
|
||||
- Naming: kebab-case (`--api-key`, `--non-interactive`, `--max-tokens`).
|
||||
- Booleans: `--no-foo` (negative) and `--foo` (positive). Default `false` unless
|
||||
documented.
|
||||
- Multi-value: repeat the flag (`--header X-A=1 --header X-B=2`).
|
||||
|
||||
## 3. Output (`--output`)
|
||||
|
||||
| Value | Use case |
|
||||
| ------- | -------------------------------------------- |
|
||||
| `table` | default human-readable |
|
||||
| `json` | single JSON object, pretty-printed |
|
||||
| `jsonl` | streamed objects, one per line (logs, lists) |
|
||||
| `csv` | spreadsheet ingestion |
|
||||
|
||||
Related flags:
|
||||
|
||||
- `--quiet` / `-q` — suppress headers/spinners (pipe-friendly).
|
||||
- `--no-color` — force ANSI off (auto-detected if `!stdout.isTTY`).
|
||||
|
||||
Helper: `emit(rows, opts)` from `bin/cli/output.mjs` handles all four formats.
|
||||
|
||||
## 4. Exit codes
|
||||
|
||||
| Code | Meaning |
|
||||
| ----- | --------------------------------- |
|
||||
| `0` | success |
|
||||
| `1` | generic error (uncaught, runtime) |
|
||||
| `2` | invalid argument / misuse |
|
||||
| `3` | server offline (when required) |
|
||||
| `4` | auth / permission (401/403) |
|
||||
| `5` | rate limit / quota (429) |
|
||||
| `124` | timeout |
|
||||
|
||||
Helper: `exitWith(code, message?)` from `bin/cli/exit.mjs` (added under
|
||||
`output.mjs` if needed) — always uses these constants. **Never** raw
|
||||
`process.exit(N)` in command code.
|
||||
|
||||
## 5. HTTP errors + retry/backoff
|
||||
|
||||
All API calls go through `apiFetch(path, opts)` (`bin/cli/api.mjs`), which:
|
||||
|
||||
- Reads base URL from `OMNIROUTE_BASE_URL` env or `~/.omniroute/config.json`
|
||||
(active profile).
|
||||
- Injects `Authorization: Bearer ${OMNIROUTE_API_KEY}` when available.
|
||||
- Injects `x-omniroute-cli-token` when applicable (see task 8.12).
|
||||
- Applies a per-attempt timeout (`--timeout 30000`, default 30s).
|
||||
- Maps status → exit code (401→4, 429→5, 5xx→1, etc.).
|
||||
- Never exposes `err.stack` (CLAUDE.md hard rule #12).
|
||||
- Applies exponential backoff with jitter on retryable statuses.
|
||||
|
||||
### Retry defaults
|
||||
|
||||
```js
|
||||
export const RETRY_DEFAULTS = {
|
||||
maxAttempts: 3, // 1 initial + 2 retries
|
||||
baseMs: 500,
|
||||
maxMs: 8000, // jitter can slightly exceed
|
||||
jitter: true, // ±25%
|
||||
retryableStatuses: [408, 425, 429, 502, 503, 504],
|
||||
retryableErrorCodes: [
|
||||
"ECONNRESET",
|
||||
"ECONNREFUSED",
|
||||
"ETIMEDOUT",
|
||||
"ENOTFOUND",
|
||||
"EAI_AGAIN",
|
||||
"EPIPE",
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
### Global flags wired
|
||||
|
||||
- `--retry` (default on) / `--no-retry`
|
||||
- `--retry-max <n>` (default 3) — total attempts
|
||||
- `--timeout <ms>` (default 30000) — per attempt
|
||||
- `--retry-on <csv>` — extra retryable statuses (e.g. `--retry-on 500`)
|
||||
|
||||
### Method semantics
|
||||
|
||||
- Mutations (`POST`/`PUT`/`DELETE`) retry **only** on idempotent-ish statuses
|
||||
(`502`/`503`/`504`/`408`/network), never `409`/`422`. This avoids duplicate
|
||||
side-effects.
|
||||
- `GET` retries all `RETRY_DEFAULTS.retryableStatuses`.
|
||||
- SSE / streaming does **not** auto-retry (operator decides).
|
||||
- Optional `--idempotency-key <uuid>` for extra-safe mutations.
|
||||
|
||||
### Status → exit code map
|
||||
|
||||
| Status | Exit | Retry? |
|
||||
| --------------- | ---- | ------------------------------ |
|
||||
| 200–299 | 0 | n/a |
|
||||
| 400 | 2 | no |
|
||||
| 401 | 4 | no |
|
||||
| 403 | 4 | no |
|
||||
| 404 | 2 | no |
|
||||
| 408 | 124 | **yes** |
|
||||
| 409 | 1 | no (mutations) |
|
||||
| 422 | 2 | no |
|
||||
| 425 | 1 | **yes** |
|
||||
| 429 | 5 | **yes** (respects Retry-After) |
|
||||
| 500 | 1 | configurable (default no) |
|
||||
| 502 / 503 / 504 | 1 | **yes** |
|
||||
| Network errors | 1 | **yes** |
|
||||
| Timeout | 124 | **yes** |
|
||||
|
||||
## 6. Internationalization
|
||||
|
||||
- Every user-facing string goes through `t("module.key", vars)`.
|
||||
- Catalogs live in `bin/cli/locales/{locale}.json` (nested objects).
|
||||
42 files ship out-of-the-box: `en`, `pt-BR`, and 40 additional locales.
|
||||
11 locales are scaffold-only (empty `{}`); all keys fall back to `en` automatically.
|
||||
- Detection order: `--lang` flag → `OMNIROUTE_LANG` env → `LC_ALL` → `LC_MESSAGES` → `LANG` → `en`.
|
||||
- Locale persisted via `config lang set <code>` — saves `OMNIROUTE_LANG` to `~/.omniroute/.env`.
|
||||
- Missing keys return the key itself (no crash).
|
||||
- PRs that add new strings **must** update `en.json` and `pt-BR.json`.
|
||||
Other locale files are best-effort; missing keys silently fall back to `en`.
|
||||
- `normalize()` in `i18n.mjs` validates locale codes via `/^[a-zA-Z0-9-]+$/` to
|
||||
prevent path traversal — never pass raw filesystem paths.
|
||||
- Canonical locale list: `config/i18n.json` — source of truth used by both CLI and
|
||||
dashboard i18n pipelines.
|
||||
|
||||
### Adding a new locale file
|
||||
|
||||
1. Add entry to `config/i18n.json` with `code`, `english`, `native`, `flag`.
|
||||
2. Run `node bin/cli/scripts/generate-locales.mjs` — creates `bin/cli/locales/{code}.json`.
|
||||
3. Fill in translations (or leave as `{}` for en-fallback scaffold).
|
||||
4. The pre-commit hook `check-cli-i18n` will verify all `t()` keys exist in `en.json`.
|
||||
|
||||
## 7. Logs / output channels
|
||||
|
||||
- `stdout` — useful output (parseable when `--output json|jsonl|csv`).
|
||||
- `stderr` — progress, warnings, errors, spinners.
|
||||
- `--verbose` / `-V` — extra detail on stderr.
|
||||
- `--debug` — stack traces, request bodies (dev-mode only; redacts secrets).
|
||||
|
||||
## 8. Server-first / DB-fallback
|
||||
|
||||
Single helper:
|
||||
|
||||
```js
|
||||
import { withRuntime } from "./runtime.mjs";
|
||||
|
||||
await withRuntime(async ({ kind, api, db }) => {
|
||||
if (kind === "http")
|
||||
return api("/api/combos", { retry: false, timeout: 5000, acceptNotOk: true });
|
||||
return db.combos.getCombos();
|
||||
});
|
||||
```
|
||||
|
||||
- `kind: "http"` when server is up (preferred). `api` is `apiFetch` bound to
|
||||
the current profile/base-URL.
|
||||
- `kind: "db"` when server is offline. `db` exposes typed module exports:
|
||||
- `db.combos` → `src/lib/db/combos.ts` (getCombos, getComboByName, createCombo,
|
||||
deleteComboByName, setActiveCombo, …)
|
||||
- `db.recovery` → `src/lib/db/recovery.ts` (countEncryptedCredentials,
|
||||
resetEncryptedColumns)
|
||||
- Mutations that require server **must** error with exit code `3` when the
|
||||
server is down, never silently fall back.
|
||||
- **Never** write raw SQL in commands — always go through `src/lib/db/` modules.
|
||||
The Semgrep rule at `.semgrep/rules/cli-no-sqlite.yaml` enforces this at commit time.
|
||||
|
||||
## 9. Audit of destructive actions
|
||||
|
||||
Commands that mutate state (delete, reset, `--force`) **must**:
|
||||
|
||||
- Ask for interactive confirmation (skipped with `--yes`).
|
||||
- POST to `/api/compliance/audit-log` when the server is up.
|
||||
- Support `--dry-run` (preview without effect).
|
||||
|
||||
## 10. Secrets
|
||||
|
||||
- **Never** log secrets. Mask as `sk-***-xxx` via `maskSecret()` from
|
||||
`bin/cli/output.mjs`.
|
||||
- **Never** accept a secret via positional without warning. Prefer:
|
||||
- env (`OMNIROUTE_*_API_KEY`)
|
||||
- stdin (`--api-key-stdin`)
|
||||
- interactive `askSecret()` (echo off — already implemented in `io.mjs`)
|
||||
- Secrets must not appear in `--verbose` / `--debug` output.
|
||||
|
||||
## 11. Testing baseline
|
||||
|
||||
- Every new command ships with at least one smoke test (happy path + one
|
||||
error path).
|
||||
- Use `tests/unit/cli-*.test.ts` naming. Prefer `node:test` for CLI suites
|
||||
(no extra deps).
|
||||
- Coverage target: ≥60% for `bin/cli/commands/`, ≥75% for `bin/cli/` overall
|
||||
after Fase 8.
|
||||
|
||||
## 12. References
|
||||
|
||||
- CLAUDE.md hard rules — especially #11 (publicCreds), #12 (error
|
||||
sanitization), #13 (shell injection).
|
||||
- `docs/security/ERROR_SANITIZATION.md` — the only acceptable error shapes.
|
||||
- `tests/unit/cli-tools-i18n.test.ts` — current i18n infrastructure (pre-`t()`).
|
||||
- Commander.js docs — Options & subcommand patterns.
|
||||
146
bin/cli/README.md
Normal file
146
bin/cli/README.md
Normal file
@@ -0,0 +1,146 @@
|
||||
# bin/cli — OmniRoute CLI internals
|
||||
|
||||
This directory contains the CLI runtime, helpers, and commands for the `omniroute` binary.
|
||||
|
||||
## Structure
|
||||
|
||||
```
|
||||
bin/cli/
|
||||
├── CONVENTIONS.md ← normative design rules (read this first)
|
||||
├── README.md ← this file
|
||||
├── program.mjs ← Commander setup — global flags, registerCommands()
|
||||
├── api.mjs ← apiFetch() — all HTTP calls + retry/backoff
|
||||
├── runtime.mjs ← withRuntime() — server-first / DB-fallback
|
||||
├── i18n.mjs ← t() — i18n helper + locale detection
|
||||
├── output.mjs ← emit() — table/json/jsonl/csv + printSuccess/printError
|
||||
├── io.mjs ← ask() / askSecret() — interactive prompts
|
||||
├── data-dir.mjs ← resolveDataDir() / resolveStoragePath()
|
||||
├── sqlite.mjs ← openOmniRouteDb() — DB bootstrap
|
||||
├── encryption.mjs ← encrypt/decrypt credentials
|
||||
├── provider-catalog.mjs ← static provider catalog
|
||||
├── provider-store.mjs ← DB CRUD for provider_connections
|
||||
├── provider-test.mjs ← testProviderApiKey()
|
||||
├── settings-store.mjs ← DB CRUD for key_value settings
|
||||
├── locales/
|
||||
│ ├── en.json ← English strings (source of truth, 42+ locales)
|
||||
│ ├── pt-BR.json ← Portuguese (Brazil) — fully translated
|
||||
│ └── {locale}.json ← 40 additional locales (ar, az, de, es, fr, ja, zh-CN, …)
|
||||
├── scripts/
|
||||
│ └── generate-locales.mjs ← scaffold new locale files from config/i18n.json
|
||||
└── commands/
|
||||
├── setup.mjs
|
||||
├── doctor.mjs
|
||||
├── providers.mjs
|
||||
├── config.mjs ← includes `config lang get/set/list`
|
||||
├── status.mjs
|
||||
├── logs.mjs
|
||||
└── update.mjs
|
||||
```
|
||||
|
||||
## Key helpers
|
||||
|
||||
### `apiFetch(path, opts)` — `api.mjs`
|
||||
|
||||
All HTTP calls to the OmniRoute server must go through this wrapper.
|
||||
|
||||
```js
|
||||
import { apiFetch } from "./api.mjs";
|
||||
|
||||
const res = await apiFetch("/api/health");
|
||||
if (!res.ok) await res.assertOk(); // throws ApiError with mapped exit code
|
||||
const data = await res.json();
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `baseUrl` — override base URL (default: `OMNIROUTE_BASE_URL` env or `localhost:20128`)
|
||||
- `apiKey` — override API key (default: `OMNIROUTE_API_KEY`)
|
||||
- `method`, `body`, `headers` — standard fetch options
|
||||
- `timeout` — per-attempt ms (default: `30000`)
|
||||
- `retry` — `false` to disable (default: enabled)
|
||||
- `retryMax` — total attempts (default: `3`)
|
||||
- `verbose` — log retry attempts to stderr
|
||||
|
||||
### `withRuntime(fn, opts)` — `runtime.mjs`
|
||||
|
||||
Provides server-first / DB-fallback transparently.
|
||||
|
||||
```js
|
||||
import { withRuntime } from "./runtime.mjs";
|
||||
|
||||
await withRuntime(async (ctx) => {
|
||||
if (ctx.kind === "http") {
|
||||
const res = await ctx.api("/v1/providers");
|
||||
return res.json();
|
||||
}
|
||||
return ctx.db.prepare("SELECT * FROM provider_connections").all();
|
||||
});
|
||||
```
|
||||
|
||||
- `opts.requireServer = true` — throws `ServerOfflineError` (exit 3) if offline
|
||||
- `opts.preferDb = true` — always use DB (skip server check)
|
||||
|
||||
### `t(key, vars)` — `i18n.mjs`
|
||||
|
||||
Internationalized strings. Catalog loaded from `locales/{locale}.json`.
|
||||
|
||||
```js
|
||||
import { t } from "./i18n.mjs";
|
||||
|
||||
console.log(t("common.serverOffline"));
|
||||
console.log(t("setup.testFailed", { error: err.message }));
|
||||
```
|
||||
|
||||
Locale detection order: `OMNIROUTE_LANG` → `LC_ALL` → `LC_MESSAGES` → `LANG` → `en`.
|
||||
|
||||
### `emit(data, opts)` — `output.mjs`
|
||||
|
||||
Format-aware output. Reads `opts.output` to select table/json/jsonl/csv.
|
||||
|
||||
```js
|
||||
import { emit, printError, EXIT_CODES } from "./output.mjs";
|
||||
|
||||
emit(providers, { output: opts.output ?? "table" });
|
||||
printError("Something went wrong");
|
||||
process.exit(EXIT_CODES.SERVER_OFFLINE);
|
||||
```
|
||||
|
||||
## Locale selection
|
||||
|
||||
The CLI displays text in the user's language. Detection order:
|
||||
|
||||
1. `--lang <code>` flag on the command line
|
||||
2. `OMNIROUTE_LANG` environment variable
|
||||
3. System env: `LC_ALL` → `LC_MESSAGES` → `LANG`
|
||||
4. Fallback: `en`
|
||||
|
||||
**Set permanently:**
|
||||
|
||||
```bash
|
||||
omniroute config lang set pt-BR # saves to ~/.omniroute/.env
|
||||
omniroute config lang list # show all 42 available locales
|
||||
omniroute config lang get # show currently active locale
|
||||
```
|
||||
|
||||
**One-time override:**
|
||||
|
||||
```bash
|
||||
omniroute --lang de providers list # run in German, not persisted
|
||||
OMNIROUTE_LANG=ja omniroute status # same effect via env
|
||||
```
|
||||
|
||||
**Adding a new locale**: add entry to `config/i18n.json`, then run:
|
||||
|
||||
```bash
|
||||
node bin/cli/scripts/generate-locales.mjs
|
||||
```
|
||||
|
||||
## Adding a new command
|
||||
|
||||
1. Create `bin/cli/commands/your-command.mjs`
|
||||
2. Export `registerYourCommand(program)` following the Commander pattern
|
||||
3. Register in `bin/cli/commands/registry.mjs`
|
||||
4. Add strings to `locales/en.json` and `locales/pt-BR.json`
|
||||
5. Write test in `tests/unit/cli-your-command.test.ts`
|
||||
|
||||
See `CONVENTIONS.md` for exit codes, flag naming, output format, and destructive-action rules.
|
||||
70
bin/cli/api-commands/agent-skills.mjs
Normal file
70
bin/cli/api-commands/agent-skills.mjs
Normal file
@@ -0,0 +1,70 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_agent_skills(parent) {
|
||||
const tag = parent.command("agent-skills").description("Agent Skills endpoints");
|
||||
tag.command("get-api-agent-skills")
|
||||
.description("List agent skills catalog")
|
||||
.option("--category <category>", "Filter by category (api = REST API skills, cli = CLI skills)")
|
||||
.option("--area <area>", "Filter by area slug (e.g. \"providers\", \"models\", \"cli-serve\")")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/agent-skills";
|
||||
const qs = new URLSearchParams();
|
||||
if (opts.category != null) qs.set("category", String(opts.category));
|
||||
if (opts.area != null) qs.set("area", String(opts.area));
|
||||
if (qs.toString()) url += "?" + qs.toString();
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-agent-skills-id-")
|
||||
.description("Get a single agent skill")
|
||||
.requiredOption("--id <id>", "Canonical skill ID")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/agent-skills/{id}";
|
||||
url = url.replace("{id}", encodeURIComponent(opts.id ?? ""));
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-agent-skills-id-raw")
|
||||
.description("Get raw SKILL.md content")
|
||||
.requiredOption("--id <id>", "Canonical skill ID")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/agent-skills/{id}/raw";
|
||||
url = url.replace("{id}", encodeURIComponent(opts.id ?? ""));
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-agent-skills-coverage")
|
||||
.description("Get SKILL.md coverage stats")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/agent-skills/coverage";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-agent-skills-generate")
|
||||
.description("Trigger SKILL.md generator")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/agent-skills/generate";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
155
bin/cli/api-commands/agentbridge.mjs
Normal file
155
bin/cli/api-commands/agentbridge.mjs
Normal file
@@ -0,0 +1,155 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_agentbridge(parent) {
|
||||
const tag = parent.command("agentbridge").description("AgentBridge endpoints");
|
||||
tag.command("get-api-tools-agent-bridge-agents")
|
||||
.description("List all 9 IDE agents with current state")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/agents";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-tools-agent-bridge-state")
|
||||
.description("Get global AgentBridge server state")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/state";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-tools-agent-bridge-server")
|
||||
.description("Control AgentBridge MITM server")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/server";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-tools-agent-bridge-agents-agent-id-dns")
|
||||
.description("Enable or disable DNS for one agent")
|
||||
.requiredOption("--agent-id <agentId>", "")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/agents/{agentId}/dns";
|
||||
url = url.replace("{agentId}", encodeURIComponent(opts.agentId ?? ""));
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-tools-agent-bridge-agents-agent-id-mappings")
|
||||
.description("Get model mappings for one agent")
|
||||
.requiredOption("--agent-id <agentId>", "")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/agents/{agentId}/mappings";
|
||||
url = url.replace("{agentId}", encodeURIComponent(opts.agentId ?? ""));
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-tools-agent-bridge-agents-agent-id-mappings")
|
||||
.description("Update model mappings for one agent")
|
||||
.requiredOption("--agent-id <agentId>", "")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/agents/{agentId}/mappings";
|
||||
url = url.replace("{agentId}", encodeURIComponent(opts.agentId ?? ""));
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-tools-agent-bridge-bypass")
|
||||
.description("List bypass patterns (hosts never decrypted)")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/bypass";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-tools-agent-bridge-bypass")
|
||||
.description("Update user bypass patterns")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/bypass";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-tools-agent-bridge-cert")
|
||||
.description("Download or regenerate the AgentBridge CA certificate")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/cert";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-tools-agent-bridge-upstream-ca")
|
||||
.description("Get configured upstream CA cert path")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/upstream-ca";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-tools-agent-bridge-upstream-ca")
|
||||
.description("Set upstream CA cert path for corporate TLS environments")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/tools/agent-bridge/upstream-ca";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
42
bin/cli/api-commands/api-keys.mjs
Normal file
42
bin/cli/api-commands/api-keys.mjs
Normal file
@@ -0,0 +1,42 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_api_keys(parent) {
|
||||
const tag = parent.command("api-keys").description("API Keys endpoints");
|
||||
tag.command("get-api-keys")
|
||||
.description("List API keys")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/keys";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-keys")
|
||||
.description("Create API key")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/keys";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-keys-id-")
|
||||
.description("Delete API key")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/keys/{id}";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
40
bin/cli/api-commands/audio.mjs
Normal file
40
bin/cli/api-commands/audio.mjs
Normal file
@@ -0,0 +1,40 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_audio(parent) {
|
||||
const tag = parent.command("audio").description("Audio endpoints");
|
||||
tag.command("post-api-v1-audio-speech")
|
||||
.description("Generate speech audio")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/audio/speech";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-v1-audio-transcriptions")
|
||||
.description("Transcribe audio")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/audio/transcriptions";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
58
bin/cli/api-commands/chat.mjs
Normal file
58
bin/cli/api-commands/chat.mjs
Normal file
@@ -0,0 +1,58 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_chat(parent) {
|
||||
const tag = parent.command("chat").description("Chat endpoints");
|
||||
tag.command("post-api-v1-chat-completions")
|
||||
.description("Create chat completion")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/chat/completions";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-v1-providers-provider-chat-completions")
|
||||
.description("Create chat completion (provider-specific)")
|
||||
.requiredOption("--provider <provider>", "")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/providers/{provider}/chat/completions";
|
||||
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-v1-api-chat")
|
||||
.description("Ollama-compatible chat endpoint")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/api/chat";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
361
bin/cli/api-commands/cli-tools.mjs
Normal file
361
bin/cli/api-commands/cli-tools.mjs
Normal file
@@ -0,0 +1,361 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_cli_tools(parent) {
|
||||
const tag = parent.command("cli-tools").description("CLI Tools endpoints");
|
||||
tag.command("get-api-cli-tools-backups")
|
||||
.description("List CLI tool backups")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/backups";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-backups")
|
||||
.description("Create CLI tool backup")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/backups";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-runtime-tool-id-")
|
||||
.description("Get runtime status for a CLI tool")
|
||||
.requiredOption("--tool-id <toolId>", "")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/runtime/{toolId}";
|
||||
url = url.replace("{toolId}", encodeURIComponent(opts.toolId ?? ""));
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-guide-settings-tool-id-")
|
||||
.description("Get guide settings for a tool")
|
||||
.requiredOption("--tool-id <toolId>", "")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/guide-settings/{toolId}";
|
||||
url = url.replace("{toolId}", encodeURIComponent(opts.toolId ?? ""));
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-antigravity-mitm")
|
||||
.description("Get Antigravity MITM proxy settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/antigravity-mitm";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-antigravity-mitm")
|
||||
.description("Update Antigravity MITM proxy settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/antigravity-mitm";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-antigravity-mitm")
|
||||
.description("Reset Antigravity MITM proxy settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/antigravity-mitm";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-antigravity-mitm-alias")
|
||||
.description("Get Antigravity MITM alias configuration")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/antigravity-mitm/alias";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-cli-tools-antigravity-mitm-alias")
|
||||
.description("Update Antigravity MITM alias configuration")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/antigravity-mitm/alias";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-claude-settings")
|
||||
.description("Get Claude CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/claude-settings";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-claude-settings")
|
||||
.description("Apply Claude CLI settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/claude-settings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-claude-settings")
|
||||
.description("Reset Claude CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/claude-settings";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-cline-settings")
|
||||
.description("Get Cline CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/cline-settings";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-cline-settings")
|
||||
.description("Apply Cline CLI settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/cline-settings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-cline-settings")
|
||||
.description("Reset Cline CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/cline-settings";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-codex-profiles")
|
||||
.description("Get Codex profiles")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-profiles";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-codex-profiles")
|
||||
.description("Create Codex profile")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-profiles";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-cli-tools-codex-profiles")
|
||||
.description("Update Codex profile")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-profiles";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-codex-profiles")
|
||||
.description("Delete Codex profile")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-profiles";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-codex-settings")
|
||||
.description("Get Codex CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-settings";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-codex-settings")
|
||||
.description("Apply Codex CLI settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-settings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-codex-settings")
|
||||
.description("Reset Codex CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/codex-settings";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-droid-settings")
|
||||
.description("Get Droid CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/droid-settings";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-droid-settings")
|
||||
.description("Apply Droid CLI settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/droid-settings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-droid-settings")
|
||||
.description("Reset Droid CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/droid-settings";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-kilo-settings")
|
||||
.description("Get Kilo CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/kilo-settings";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-kilo-settings")
|
||||
.description("Apply Kilo CLI settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/kilo-settings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-kilo-settings")
|
||||
.description("Reset Kilo CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/kilo-settings";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cli-tools-openclaw-settings")
|
||||
.description("Get OpenClaw CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/openclaw-settings";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cli-tools-openclaw-settings")
|
||||
.description("Apply OpenClaw CLI settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/openclaw-settings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-cli-tools-openclaw-settings")
|
||||
.description("Reset OpenClaw CLI settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cli-tools/openclaw-settings";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
81
bin/cli/api-commands/cloud.mjs
Normal file
81
bin/cli/api-commands/cloud.mjs
Normal file
@@ -0,0 +1,81 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_cloud(parent) {
|
||||
const tag = parent.command("cloud").description("Cloud endpoints");
|
||||
tag.command("post-api-cloud-auth")
|
||||
.description("Authenticate with cloud worker")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cloud/auth";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-cloud-credentials-update")
|
||||
.description("Update cloud worker credentials")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cloud/credentials/update";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-cloud-model-resolve")
|
||||
.description("Resolve model via cloud")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cloud/model/resolve";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-cloud-models-alias")
|
||||
.description("Get cloud model aliases")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cloud/models/alias";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-cloud-models-alias")
|
||||
.description("Update cloud model alias")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/cloud/models/alias";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
69
bin/cli/api-commands/combos.mjs
Normal file
69
bin/cli/api-commands/combos.mjs
Normal file
@@ -0,0 +1,69 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_combos(parent) {
|
||||
const tag = parent.command("combos").description("Combos endpoints");
|
||||
tag.command("get-api-combos")
|
||||
.description("List routing combos")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/combos";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-combos")
|
||||
.description("Create routing combo")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/combos";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("patch-api-combos-id-")
|
||||
.description("Update combo")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/combos/{id}";
|
||||
const res = await apiFetch(url, { method: "PATCH", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-combos-id-")
|
||||
.description("Delete combo")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/combos/{id}";
|
||||
const res = await apiFetch(url, { method: "DELETE", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-combos-metrics")
|
||||
.description("Get combo metrics")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/combos/metrics";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-combos-test")
|
||||
.description("Test a combo configuration")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/combos/test";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
128
bin/cli/api-commands/compression.mjs
Normal file
128
bin/cli/api-commands/compression.mjs
Normal file
@@ -0,0 +1,128 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_compression(parent) {
|
||||
const tag = parent.command("compression").description("Compression endpoints");
|
||||
tag.command("get-api-settings-compression")
|
||||
.description("Get global compression settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/settings/compression";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-settings-compression")
|
||||
.description("Update global compression settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/settings/compression";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-compression-preview")
|
||||
.description("Preview compression for a message payload")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/compression/preview";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-compression-language-packs")
|
||||
.description("List Caveman compression language packs")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/compression/language-packs";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-compression-rules")
|
||||
.description("List Caveman compression rule metadata")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/compression/rules";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-context-rtk-config")
|
||||
.description("Get RTK compression settings")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/context/rtk/config";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("put-api-context-rtk-config")
|
||||
.description("Update RTK compression settings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/context/rtk/config";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "PUT", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-context-rtk-filters")
|
||||
.description("List RTK filters and load diagnostics")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/context/rtk/filters";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-context-rtk-test")
|
||||
.description("Run RTK compression preview for text")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/context/rtk/test";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-context-rtk-raw-output-id-")
|
||||
.description("Read retained redacted RTK raw output")
|
||||
.requiredOption("--id <id>", "")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/context/rtk/raw-output/{id}";
|
||||
url = url.replace("{id}", encodeURIComponent(opts.id ?? ""));
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
202
bin/cli/api-commands/embedded-services.mjs
Normal file
202
bin/cli/api-commands/embedded-services.mjs
Normal file
@@ -0,0 +1,202 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_embedded_services(parent) {
|
||||
const tag = parent.command("embedded-services").description("Embedded Services endpoints");
|
||||
tag.command("post-api-services-9router-install")
|
||||
.description("Install 9Router from npm")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/install";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-9router-start")
|
||||
.description("Start 9Router")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/start";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-9router-stop")
|
||||
.description("Stop 9Router")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/stop";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-9router-restart")
|
||||
.description("Restart 9Router")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/restart";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-9router-update")
|
||||
.description("Update 9Router to a newer npm version")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/update";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-9router-rotate-key")
|
||||
.description("Rotate the 9Router API key")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/rotate-key";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-services-9router-status")
|
||||
.description("Get 9Router status")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/status";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-9router-auto-start")
|
||||
.description("Toggle 9Router auto-start")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/9router/auto-start";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-cliproxy-install")
|
||||
.description("Install CLIProxyAPI from npm")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/install";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-cliproxy-start")
|
||||
.description("Start CLIProxyAPI")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/start";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-cliproxy-stop")
|
||||
.description("Stop CLIProxyAPI")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/stop";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-cliproxy-restart")
|
||||
.description("Restart CLIProxyAPI")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/restart";
|
||||
const res = await apiFetch(url, { method: "POST", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-cliproxy-update")
|
||||
.description("Update CLIProxyAPI to a newer npm version")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/update";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-services-cliproxy-status")
|
||||
.description("Get CLIProxyAPI status")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/status";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-services-cliproxy-auto-start")
|
||||
.description("Toggle CLIProxyAPI auto-start")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/cliproxy/auto-start";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("get-api-services-name-logs")
|
||||
.description("Stream service logs via SSE")
|
||||
.requiredOption("--name <name>", "")
|
||||
.option("--tail <tail>", "Number of historical lines to include in the initial snapshot")
|
||||
.option("--filter <filter>", "Case-insensitive substring filter applied to log lines. No regex — ReDoS-safe by design.")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/services/{name}/logs";
|
||||
url = url.replace("{name}", encodeURIComponent(opts.name ?? ""));
|
||||
const qs = new URLSearchParams();
|
||||
if (opts.tail != null) qs.set("tail", String(opts.tail));
|
||||
if (opts.filter != null) qs.set("filter", String(opts.filter));
|
||||
if (qs.toString()) url += "?" + qs.toString();
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
42
bin/cli/api-commands/embeddings.mjs
Normal file
42
bin/cli/api-commands/embeddings.mjs
Normal file
@@ -0,0 +1,42 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_embeddings(parent) {
|
||||
const tag = parent.command("embeddings").description("Embeddings endpoints");
|
||||
tag.command("post-api-v1-embeddings")
|
||||
.description("Create embeddings")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/embeddings";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-v1-providers-provider-embeddings")
|
||||
.description("Create embeddings (provider-specific)")
|
||||
.requiredOption("--provider <provider>", "")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/providers/{provider}/embeddings";
|
||||
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
49
bin/cli/api-commands/fallback.mjs
Normal file
49
bin/cli/api-commands/fallback.mjs
Normal file
@@ -0,0 +1,49 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_fallback(parent) {
|
||||
const tag = parent.command("fallback").description("Fallback endpoints");
|
||||
tag.command("get-api-fallback-chains")
|
||||
.description("List fallback chains")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/fallback/chains";
|
||||
const res = await apiFetch(url, { method: "GET", baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-fallback-chains")
|
||||
.description("Create fallback chain")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/fallback/chains";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("delete-api-fallback-chains")
|
||||
.description("Delete fallback chain")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/fallback/chains";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "DELETE", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
42
bin/cli/api-commands/images.mjs
Normal file
42
bin/cli/api-commands/images.mjs
Normal file
@@ -0,0 +1,42 @@
|
||||
// AUTO-GENERATED from docs/reference/openapi.yaml. Do not edit.
|
||||
import { apiFetch } from "../api.mjs";
|
||||
import { emit } from "../output.mjs";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export function register_images(parent) {
|
||||
const tag = parent.command("images").description("Images endpoints");
|
||||
tag.command("post-api-v1-images-generations")
|
||||
.description("Generate images")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/images/generations";
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
tag.command("post-api-v1-providers-provider-images-generations")
|
||||
.description("Generate images (provider-specific)")
|
||||
.requiredOption("--provider <provider>", "")
|
||||
.option("--body <jsonOrPath>", "JSON body or @path/to/file.json")
|
||||
.action(async (opts, cmd) => {
|
||||
const gOpts = cmd.optsWithGlobals();
|
||||
let url = "/api/v1/providers/{provider}/images/generations";
|
||||
url = url.replace("{provider}", encodeURIComponent(opts.provider ?? ""));
|
||||
let body;
|
||||
if (opts.body) {
|
||||
body = opts.body.startsWith("@")
|
||||
? JSON.parse(readFileSync(opts.body.slice(1), "utf8"))
|
||||
: JSON.parse(opts.body);
|
||||
}
|
||||
const res = await apiFetch(url, { method: "POST", body, baseUrl: gOpts.baseUrl, apiKey: gOpts.apiKey });
|
||||
const data = res.ok ? await res.json() : await res.text();
|
||||
emit(data, gOpts);
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user