mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
Compare commits
908 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3a34aab9f | ||
|
|
b62bea7d0d | ||
|
|
c1d2d2eb62 | ||
|
|
107fa22ac6 | ||
|
|
816d777495 | ||
|
|
d1d46b9068 | ||
|
|
6f46fd53cf | ||
|
|
7f608c965e | ||
|
|
44026ef1b4 | ||
|
|
cedabc4eda | ||
|
|
cabe2aeb7a | ||
|
|
2c365062f5 | ||
|
|
a386d7f6a5 | ||
|
|
2474329a3f | ||
|
|
2d938ac178 | ||
|
|
44d32f6ce0 | ||
|
|
ff756e0316 | ||
|
|
b14fd5221f | ||
|
|
22ab061312 | ||
|
|
cc0677159e | ||
|
|
c7c2881c66 | ||
|
|
3456865d16 | ||
|
|
fdacacb2c5 | ||
|
|
c3fa442b45 | ||
|
|
2204311ec6 | ||
|
|
8870cabc06 | ||
|
|
e1b5c45b96 | ||
|
|
6d1d82e8f0 | ||
|
|
eeeeaa0db3 | ||
|
|
c3eea9045e | ||
|
|
3436a8e928 | ||
|
|
67cef7e6af | ||
|
|
1a7af0f7ab | ||
|
|
b07e33bff4 | ||
|
|
970213080c | ||
|
|
136583cb11 | ||
|
|
c5cc9369c8 | ||
|
|
2a2d46f772 | ||
|
|
f863c00b91 | ||
|
|
f7ac3ac447 | ||
|
|
c4d994d74d | ||
|
|
af9dfecabf | ||
|
|
4eba154a56 | ||
|
|
a2c07baca4 | ||
|
|
86de9febb9 | ||
|
|
59af60fbf4 | ||
|
|
a1e942988d | ||
|
|
5410c21e3e | ||
|
|
f5683d1e69 | ||
|
|
6f1e4d1fc7 | ||
|
|
36bfb85cd1 | ||
|
|
68ea328db1 | ||
|
|
497569c6f2 | ||
|
|
8ff8defb39 | ||
|
|
a152d11d07 | ||
|
|
a766ad0db9 | ||
|
|
a82fac193d | ||
|
|
e445d5238f | ||
|
|
5d1f788444 | ||
|
|
ca43c2f68d | ||
|
|
eb010a1a68 | ||
|
|
d70760947e | ||
|
|
93e3b623db | ||
|
|
999950b2fc | ||
|
|
568ce4871c | ||
|
|
707abbf190 | ||
|
|
b40acc9eb0 | ||
|
|
773f5ea574 | ||
|
|
020d2307d9 | ||
|
|
e29159eed8 | ||
|
|
2be552c4e5 | ||
|
|
df6ccc7202 | ||
|
|
35a7b08cd1 | ||
|
|
c02e6ecc1a | ||
|
|
f2a9ebb462 | ||
|
|
9dff0b8255 | ||
|
|
8815bc9d47 | ||
|
|
138cc9aedb | ||
|
|
98bc686252 | ||
|
|
31a291bd03 | ||
|
|
32e5583491 | ||
|
|
ef0431d44c | ||
|
|
a4f1040b48 | ||
|
|
740bd1d732 | ||
|
|
b7a7135bb9 | ||
|
|
8db8c7f366 | ||
|
|
32f694892e | ||
|
|
0b22cf9195 | ||
|
|
0081ffabb4 | ||
|
|
0a4e0109b5 | ||
|
|
9d4c5a57a8 | ||
|
|
2b8f912c86 | ||
|
|
9b1992045a | ||
|
|
80bd09332b | ||
|
|
5ca42a3e0c | ||
|
|
b64f928fd0 | ||
|
|
30db303dc5 | ||
|
|
2535f4a2b0 | ||
|
|
93e15e2557 | ||
|
|
e702df9e74 | ||
|
|
dd1418bd8d | ||
|
|
08cc1967e2 | ||
|
|
ca9ba8ad9f | ||
|
|
b5bb6baeda | ||
|
|
0b6663a8ea | ||
|
|
23d6540586 | ||
|
|
804b0f2306 | ||
|
|
ace8a5302e | ||
|
|
7bfda96047 | ||
|
|
1e83f843c1 | ||
|
|
3161ddcbfb | ||
|
|
2c97d2de9b | ||
|
|
6d1bcacf9b | ||
|
|
449c128a5b | ||
|
|
9c3f8311a6 | ||
|
|
42542eab45 | ||
|
|
7290a572cc | ||
|
|
18c4f55118 | ||
|
|
1b7cc2e5a7 | ||
|
|
d382c66c6d | ||
|
|
d0ccd5a00a | ||
|
|
3fa1bbac8a | ||
|
|
4ce2ecd5a2 | ||
|
|
bd87e00380 | ||
|
|
355d1e79d9 | ||
|
|
63b7f04555 | ||
|
|
5dfb6dfccd | ||
|
|
377026dd03 | ||
|
|
b15f4e9301 | ||
|
|
82d8fc5bec | ||
|
|
8876471936 | ||
|
|
8ec08f4913 | ||
|
|
fcc2732693 | ||
|
|
3a2e427d0d | ||
|
|
ac2263f34c | ||
|
|
a956150945 | ||
|
|
2ae0ff0008 | ||
|
|
26748986e3 | ||
|
|
9f49f9e37a | ||
|
|
6c26549955 | ||
|
|
93e053ff89 | ||
|
|
104bda5ba3 | ||
|
|
4769a48e5d | ||
|
|
d97b2265ee | ||
|
|
1917f0eb4a | ||
|
|
d580636cd4 | ||
|
|
782125f72a | ||
|
|
c39ad3b75c | ||
|
|
44159132a5 | ||
|
|
3c019e9199 | ||
|
|
586fa9038a | ||
|
|
924b560240 | ||
|
|
b5ae67aecb | ||
|
|
f91949daee | ||
|
|
6e0eda6317 | ||
|
|
70e8a0f6f3 | ||
|
|
dc390b6a04 | ||
|
|
697db19210 | ||
|
|
314842df11 | ||
|
|
6f707fe45f | ||
|
|
bcd1457002 | ||
|
|
44344bd22d | ||
|
|
04eccc3012 | ||
|
|
5e000543a6 | ||
|
|
fb4da63818 | ||
|
|
e927e98f06 | ||
|
|
3331136a63 | ||
|
|
563f732360 | ||
|
|
2820f6a9a5 | ||
|
|
662002c557 | ||
|
|
63261c1c5d | ||
|
|
1f66f5f4ad | ||
|
|
badd3ea1cd | ||
|
|
90dc1b5f94 | ||
|
|
4d9ce85135 | ||
|
|
d09b189ba1 | ||
|
|
2b88b48c3b | ||
|
|
1e16a3177b | ||
|
|
fe187c63e4 | ||
|
|
f3b5e9fa0a | ||
|
|
55b3550c77 | ||
|
|
08918300c2 | ||
|
|
2709f3a554 | ||
|
|
304a0c8064 | ||
|
|
8a05e78d8e | ||
|
|
c914188339 | ||
|
|
458371c5cc | ||
|
|
3b38a77c09 | ||
|
|
c85b83eb08 | ||
|
|
ac1bab2ffc | ||
|
|
73c3b1da2f | ||
|
|
028cd6ce91 | ||
|
|
dfce18305d | ||
|
|
29c4e472d4 | ||
|
|
6e01a86973 | ||
|
|
57551d990d | ||
|
|
35c35d3d80 | ||
|
|
2b296cabc8 | ||
|
|
a021b09474 | ||
|
|
01328b65e9 | ||
|
|
1765c26657 | ||
|
|
b6973f1b7b | ||
|
|
3ac14c053c | ||
|
|
0caad64533 | ||
|
|
45b5bd4694 | ||
|
|
e0bf30832b | ||
|
|
a75fcac14c | ||
|
|
1b297d1a49 | ||
|
|
ad4ed1d41d | ||
|
|
2cd57b2f8b | ||
|
|
7b8a065e29 | ||
|
|
6d2cb07f17 | ||
|
|
68c244f40b | ||
|
|
45277af6cf | ||
|
|
fd3c9c454f | ||
|
|
ea8aa5b05e | ||
|
|
d06f869560 | ||
|
|
c9afad6206 | ||
|
|
e8224c82b9 | ||
|
|
5050225a09 | ||
|
|
f8fc24ea5c | ||
|
|
204d38da8d | ||
|
|
59a7e1cccc | ||
|
|
64324cf3e4 | ||
|
|
fe4535adce | ||
|
|
eec153e79a | ||
|
|
31459a2c9e | ||
|
|
879d7dc893 | ||
|
|
acce96c36e | ||
|
|
b5dba31bf2 | ||
|
|
a73e0db2f3 | ||
|
|
e54fbacb3d | ||
|
|
af4c115588 | ||
|
|
1aee987a60 | ||
|
|
df2f7837e1 | ||
|
|
fb5ba10f4f | ||
|
|
546a44d8fa | ||
|
|
8d7477816f | ||
|
|
1f5856d7a5 | ||
|
|
b19812f0f5 | ||
|
|
ee9f4fd845 | ||
|
|
20e7f000b3 | ||
|
|
6f6c193006 | ||
|
|
e1578f67af | ||
|
|
13d601e31f | ||
|
|
05a8196c1e | ||
|
|
0c30d6578c | ||
|
|
4c2977b82e | ||
|
|
dc3b58beb3 | ||
|
|
ba105b8423 | ||
|
|
aa3b856a80 | ||
|
|
58621ad6cc | ||
|
|
a4bea47aa5 | ||
|
|
f90047ff14 | ||
|
|
02ae2d377e | ||
|
|
7f7fc38aed | ||
|
|
1a6aea85ee | ||
|
|
4aa115738a | ||
|
|
3e858dfc11 | ||
|
|
ede9da4204 | ||
|
|
d12947ec18 | ||
|
|
ba122767ce | ||
|
|
6e852faa94 | ||
|
|
4188b32758 | ||
|
|
92e3e654f2 | ||
|
|
092c1161b7 | ||
|
|
d62d2db9bc | ||
|
|
2545a8720f | ||
|
|
c73a4d4c4d | ||
|
|
4e703db7a1 | ||
|
|
df79010bc6 | ||
|
|
58473c4511 | ||
|
|
244491841d | ||
|
|
f555dfefad | ||
|
|
fb56d1cd91 | ||
|
|
b0cda2010b | ||
|
|
d65b5d24c7 | ||
|
|
63f2ac5309 | ||
|
|
2255b89322 | ||
|
|
22d022cb13 | ||
|
|
3281a5db1b | ||
|
|
9964772701 | ||
|
|
66d53a82d0 | ||
|
|
af54caef70 | ||
|
|
a44675ecee | ||
|
|
4bb997ea44 | ||
|
|
f84258d3b6 | ||
|
|
caacb32ff9 | ||
|
|
71324e2063 | ||
|
|
8d915d49de | ||
|
|
baa7e92876 | ||
|
|
0c2e204eaa | ||
|
|
87dd60cbea | ||
|
|
b47eb4ed2d | ||
|
|
24cf6eb258 | ||
|
|
678621a5df | ||
|
|
adc958a7d7 | ||
|
|
40b6e9cdf8 | ||
|
|
01bf9f0d65 | ||
|
|
883c871683 | ||
|
|
41b6f7dee6 | ||
|
|
e4cd9c2bc5 | ||
|
|
7dd39a70b6 | ||
|
|
57f83d690d | ||
|
|
fe6a9c9013 | ||
|
|
f176d3b0c6 | ||
|
|
6c7e0455ad | ||
|
|
4149d9e5ea | ||
|
|
6eccfc8d45 | ||
|
|
c94ff33f56 | ||
|
|
81045bf4f8 | ||
|
|
f25b09005e | ||
|
|
18c9719c3c | ||
|
|
10b9adbac5 | ||
|
|
1d9a0a0000 | ||
|
|
b5948e5229 | ||
|
|
e85a7bc513 | ||
|
|
c6df401531 | ||
|
|
f824eb3589 | ||
|
|
70ba59b511 | ||
|
|
5b66287cad | ||
|
|
30ef864fe7 | ||
|
|
a5232b2057 | ||
|
|
8c80aff92b | ||
|
|
ee3326b5d1 | ||
|
|
6e2289bc94 | ||
|
|
a9156f58ea | ||
|
|
84e357e025 | ||
|
|
6d04312b71 | ||
|
|
696db0aa81 | ||
|
|
ca9e8f2ce9 | ||
|
|
553c14178e | ||
|
|
e33e872628 | ||
|
|
01daacc688 | ||
|
|
3a6c925bae | ||
|
|
8d9e096e8c | ||
|
|
7599851add | ||
|
|
4d7951bcc9 | ||
|
|
4ef8064939 | ||
|
|
c7d0d38027 | ||
|
|
7d2acece1d | ||
|
|
6230d3bc35 | ||
|
|
18ff0717b3 | ||
|
|
340b42223d | ||
|
|
9a8a656e96 | ||
|
|
2002026a12 | ||
|
|
477919960d | ||
|
|
92e28580f1 | ||
|
|
21d5ab15d7 | ||
|
|
4b0e34747b | ||
|
|
914d5e2b1b | ||
|
|
292cb5a164 | ||
|
|
472d9f8e2e | ||
|
|
e1fb08afc5 | ||
|
|
adce0e6bfd | ||
|
|
c2a6ce7c17 | ||
|
|
a3bf375810 | ||
|
|
91365c8caa | ||
|
|
02ccc5c7cc | ||
|
|
72fbe17715 | ||
|
|
71020126b0 | ||
|
|
4cf9db9574 | ||
|
|
3bae667b6f | ||
|
|
698800f59c | ||
|
|
0089ba9e39 | ||
|
|
b51482f907 | ||
|
|
7268011db4 | ||
|
|
9b03fe1f65 | ||
|
|
d1f98703ab | ||
|
|
16ba706544 | ||
|
|
8f8a9ae88d | ||
|
|
9ae270fe29 | ||
|
|
2bf2468018 | ||
|
|
4551672c80 | ||
|
|
811cdb8c27 | ||
|
|
ad8858de43 | ||
|
|
b8cbd0e43c | ||
|
|
7cfd868443 | ||
|
|
d284e7ce17 | ||
|
|
d6379ff0e1 | ||
|
|
26f4041911 | ||
|
|
7edab789f7 | ||
|
|
1906056539 | ||
|
|
609e4bb6ae | ||
|
|
331010a1ef | ||
|
|
571619bc15 | ||
|
|
d3abc6706c | ||
|
|
45aca07b15 | ||
|
|
b575c1f30f | ||
|
|
3b38f3aadd | ||
|
|
825986a31a | ||
|
|
8c0be712aa | ||
|
|
2720b4b20c | ||
|
|
70c7f452a5 | ||
|
|
8bae58e7b9 | ||
|
|
9b1cdf0167 | ||
|
|
b705c446f0 | ||
|
|
735f272bc6 | ||
|
|
406fd32698 | ||
|
|
18be128acc | ||
|
|
d84e1d7bb3 | ||
|
|
6622d61309 | ||
|
|
f113ec3279 | ||
|
|
512d2f33a8 | ||
|
|
b3f233c64c | ||
|
|
c6df1612c3 | ||
|
|
7b70422787 | ||
|
|
13671da355 | ||
|
|
562e55a048 | ||
|
|
04a10583c8 | ||
|
|
bab0d0413f | ||
|
|
361bed51ef | ||
|
|
f55e2575b1 | ||
|
|
23fd3da786 | ||
|
|
030e8d75d3 | ||
|
|
a946e848e6 | ||
|
|
4332e24fad | ||
|
|
cf2d028d82 | ||
|
|
95d52c4cf1 | ||
|
|
8ba44455a3 | ||
|
|
2ae15f2e36 | ||
|
|
44ef8cec2f | ||
|
|
9aaa33013b | ||
|
|
d9dacaf525 | ||
|
|
13b86ac4a6 | ||
|
|
62d07aa01d | ||
|
|
33d22fe235 | ||
|
|
43d60f42b3 | ||
|
|
d5452df1f9 | ||
|
|
6d978e2ee5 | ||
|
|
43b1015f57 | ||
|
|
f3aef0ba25 | ||
|
|
8a836dd924 | ||
|
|
e1cffae53b | ||
|
|
10144b53c3 | ||
|
|
71cd8c064c | ||
|
|
1a215a4b20 | ||
|
|
ee5fe34e13 | ||
|
|
5310e42203 | ||
|
|
1645a8aa5a | ||
|
|
5756d59a68 | ||
|
|
73a0eae88d | ||
|
|
d02b62de5d | ||
|
|
942af1fb8b | ||
|
|
342839461a | ||
|
|
387140811c | ||
|
|
d03cb4a024 | ||
|
|
4c7ef3e128 | ||
|
|
066336864f | ||
|
|
6b1df0cceb | ||
|
|
9a2f16d165 | ||
|
|
291c51b704 | ||
|
|
6531f17b44 | ||
|
|
cd5752f7fa | ||
|
|
8bf0903016 | ||
|
|
55b127bff4 | ||
|
|
4d4a95a323 | ||
|
|
93a1ed0d1c | ||
|
|
e8b8ebda2c | ||
|
|
375f654e6d | ||
|
|
e31eb1ebc1 | ||
|
|
5a4f3bc5ad | ||
|
|
889ab114b6 | ||
|
|
2ae1910140 | ||
|
|
0bc9ccf55d | ||
|
|
176db8d456 | ||
|
|
b00b733f07 | ||
|
|
204af946ba | ||
|
|
a61f267044 | ||
|
|
ba5bbef82c | ||
|
|
32ae019771 | ||
|
|
3aff591323 | ||
|
|
b310a05b54 | ||
|
|
dcb24c74dc | ||
|
|
edacc8686a | ||
|
|
844a6aa6fe | ||
|
|
f05c0fdc06 | ||
|
|
44593c514e | ||
|
|
5ca87b9dda | ||
|
|
cfb1b4afbc | ||
|
|
f8d34e1116 | ||
|
|
cfbf3f7171 | ||
|
|
b3b30005e4 | ||
|
|
46f56ea2d0 | ||
|
|
7f513b15b7 | ||
|
|
a4b7cc9a25 | ||
|
|
68c0215b74 | ||
|
|
0811b42484 | ||
|
|
1bd37e7903 | ||
|
|
34411562e4 | ||
|
|
656c273638 | ||
|
|
b83ea51365 | ||
|
|
09bfa6041d | ||
|
|
cb82da7cde | ||
|
|
b5424afe62 | ||
|
|
80f41d7852 | ||
|
|
6ab27d6e4b | ||
|
|
db2d889c0e | ||
|
|
58f0af713d | ||
|
|
613ee72fa2 | ||
|
|
bda12b51d7 | ||
|
|
ab0e644838 | ||
|
|
ddb3817e3c | ||
|
|
f670a075f1 | ||
|
|
32330f55b5 | ||
|
|
b9a60d9d07 | ||
|
|
494e8b6154 | ||
|
|
a5fc5fd93d | ||
|
|
f691e443db | ||
|
|
1f926188ac | ||
|
|
e86058a790 | ||
|
|
6f9d6cf575 | ||
|
|
ac548ed8b4 | ||
|
|
3bc82a19b3 | ||
|
|
8a1501ca5e | ||
|
|
504a7b3054 | ||
|
|
4122af0206 | ||
|
|
f502a6e6cc | ||
|
|
fe8def6854 | ||
|
|
0f0d168877 | ||
|
|
07c2502525 | ||
|
|
4cca18d804 | ||
|
|
d9eb208a22 | ||
|
|
4390284d4d | ||
|
|
810afd296f | ||
|
|
7f90d8d201 | ||
|
|
c1a6e6f0ea | ||
|
|
1607d4e624 | ||
|
|
cc74b9ab03 | ||
|
|
ef68b7ef67 | ||
|
|
55c6827566 | ||
|
|
7afef17923 | ||
|
|
6b661050cb | ||
|
|
e47d8feb50 | ||
|
|
bf006b5e4f | ||
|
|
b7f0b90dc0 | ||
|
|
8e1c6a43a2 | ||
|
|
2002222d13 | ||
|
|
b958fc84d7 | ||
|
|
e440d29274 | ||
|
|
22ecda23a9 | ||
|
|
85951cb086 | ||
|
|
80d7c17d8e | ||
|
|
bfee96a859 | ||
|
|
8b36735d51 | ||
|
|
13efefcfd3 | ||
|
|
f0df6070f9 | ||
|
|
10e26d9d6c | ||
|
|
f00f28ded2 | ||
|
|
7aed488e41 | ||
|
|
f8738a13bb | ||
|
|
c18c9236f7 | ||
|
|
c5ba0ee03a | ||
|
|
20f6dda107 | ||
|
|
92d35f8e18 | ||
|
|
5fe4c38b96 | ||
|
|
12c4cfa3e1 | ||
|
|
2c4352b415 | ||
|
|
701eff9e26 | ||
|
|
98b11bc92d | ||
|
|
d6b7756d17 | ||
|
|
a96327d3e8 | ||
|
|
352c3df480 | ||
|
|
bf683129fa | ||
|
|
92aa3b32e6 | ||
|
|
57f5670971 | ||
|
|
8b30f8c7b6 | ||
|
|
906e370146 | ||
|
|
8c08e834c8 | ||
|
|
8e50929d0d | ||
|
|
bf93d0e752 | ||
|
|
2701a89260 | ||
|
|
08c4798423 | ||
|
|
b5e0abd730 | ||
|
|
b8fe9ac67f | ||
|
|
6e924965c6 | ||
|
|
e51247f626 | ||
|
|
6baeebfec0 | ||
|
|
eb2dfb2638 | ||
|
|
aaa9bff2a3 | ||
|
|
2c9060237f | ||
|
|
d643c87587 | ||
|
|
7566048d83 | ||
|
|
c98608c513 | ||
|
|
16bbbe635c | ||
|
|
3f51686f20 | ||
|
|
789f310a4a | ||
|
|
cd0d037d68 | ||
|
|
4288e1dd69 | ||
|
|
908ea3f0e0 | ||
|
|
ec5461ed17 | ||
|
|
c0aeddbef0 | ||
|
|
5db6221502 | ||
|
|
9d754e3e13 | ||
|
|
7b6b2858d9 | ||
|
|
5d429b952d | ||
|
|
88ebea163a | ||
|
|
f898eaeaa1 | ||
|
|
0071deec8c | ||
|
|
b0159407f0 | ||
|
|
d20509de54 | ||
|
|
11883188a6 | ||
|
|
1626bbc54e | ||
|
|
bf00f52937 | ||
|
|
6e6cd0cf5f | ||
|
|
4f98dcbcbf | ||
|
|
a21895aee6 | ||
|
|
277c9a4439 | ||
|
|
7c2fd929fa | ||
|
|
6fbc0af624 | ||
|
|
53212a6125 | ||
|
|
199722963c | ||
|
|
19ee066471 | ||
|
|
36bd410cad | ||
|
|
5051718713 | ||
|
|
1c90a3ea9e | ||
|
|
1e731f7b19 | ||
|
|
2e7eabc592 | ||
|
|
b9a2dc32cb | ||
|
|
a48ff45c50 | ||
|
|
b4d81f04ad | ||
|
|
dfc06f7764 | ||
|
|
9fd74ebdb7 | ||
|
|
b9d82b7eb1 | ||
|
|
ca729da9a5 | ||
|
|
668a4f4487 | ||
|
|
5d4f55d298 | ||
|
|
312d119469 | ||
|
|
83f90214f2 | ||
|
|
a41a53505b | ||
|
|
d99e203f97 | ||
|
|
10e5856f05 | ||
|
|
847de275f8 | ||
|
|
a0ef1e99b9 | ||
|
|
b104f97744 | ||
|
|
da3689ee40 | ||
|
|
edf960b4a6 | ||
|
|
99952796f1 | ||
|
|
de81b817b1 | ||
|
|
1a01c3bbe0 | ||
|
|
011f9043e8 | ||
|
|
bf06224462 | ||
|
|
eb452cd278 | ||
|
|
d3f6559d93 | ||
|
|
5ef7657335 | ||
|
|
f15ed39165 | ||
|
|
bca1def93b | ||
|
|
df313c5209 | ||
|
|
773b9d0ec2 | ||
|
|
40a01f1f63 | ||
|
|
193ced8f5c | ||
|
|
a8dbca1065 | ||
|
|
fb40f64d0c | ||
|
|
e090ace288 | ||
|
|
d9463aaa14 | ||
|
|
c740f6dcb2 | ||
|
|
0a297bf15d | ||
|
|
b8928b9360 | ||
|
|
40f7e4da2b | ||
|
|
354afc493e | ||
|
|
e3ee082167 | ||
|
|
299193f88d | ||
|
|
09cc0c7a59 | ||
|
|
4c5298bce4 | ||
|
|
88c90d08ad | ||
|
|
d33b578333 | ||
|
|
a86ac3f1b9 | ||
|
|
3508a0e31a | ||
|
|
a105f58280 | ||
|
|
c4df872944 | ||
|
|
47fcf735fa | ||
|
|
56dc95bff5 | ||
|
|
88ca792e02 | ||
|
|
9bf497d3e8 | ||
|
|
49cbcd8c0c | ||
|
|
643856d865 | ||
|
|
70fe3b6d0d | ||
|
|
77b322ceae | ||
|
|
007afb1b0c | ||
|
|
6fcf38838b | ||
|
|
3aaac77313 | ||
|
|
3dc66ab6e5 | ||
|
|
789f80b45d | ||
|
|
ef9aab240d | ||
|
|
73215c55eb | ||
|
|
102efff30e | ||
|
|
ae88eb6a7a | ||
|
|
a40c6d7f68 | ||
|
|
9f65852eb3 | ||
|
|
0b87612685 | ||
|
|
910c423e48 | ||
|
|
fc30827099 | ||
|
|
af64830a47 | ||
|
|
ce7b4252d8 | ||
|
|
a61f5ea834 | ||
|
|
723e0a9105 | ||
|
|
bb01d3eecc | ||
|
|
0220248dc1 | ||
|
|
79bd2c6f11 | ||
|
|
d412042beb | ||
|
|
22377659a8 | ||
|
|
521ceac004 | ||
|
|
1862f2ce5c | ||
|
|
a0fdbf9b91 | ||
|
|
7667ec4020 | ||
|
|
db8730ebcd | ||
|
|
a5533f7bdf | ||
|
|
aab2f85c86 | ||
|
|
54b4698a72 | ||
|
|
852d5ed0b3 | ||
|
|
cf9d13072c | ||
|
|
1950fb8fe4 | ||
|
|
63bfe62c91 | ||
|
|
792cf31f7f | ||
|
|
363217b2c4 | ||
|
|
2f20ba65b7 | ||
|
|
de291ab7b1 | ||
|
|
7ca7b3feba | ||
|
|
9cfff5f24d | ||
|
|
d9d0a46d46 | ||
|
|
bd115fdac8 | ||
|
|
b0cecfa496 | ||
|
|
ea79f69bcf | ||
|
|
64630cfd65 | ||
|
|
cb41d3da12 | ||
|
|
7988f65ab8 | ||
|
|
7bec1e6b35 | ||
|
|
abad4fc5bf | ||
|
|
6b18e3c9f2 | ||
|
|
20d049ba33 | ||
|
|
b7340e6415 | ||
|
|
e92fbcfba1 | ||
|
|
3811714fab | ||
|
|
b03809b2d7 | ||
|
|
b24d599d33 | ||
|
|
2b5ea4977f | ||
|
|
e40057ab84 | ||
|
|
1addb95724 | ||
|
|
b9029e64a0 | ||
|
|
9c6b33783c | ||
|
|
133f24a4d3 | ||
|
|
53fb250975 | ||
|
|
0e447fce16 | ||
|
|
18503ee942 | ||
|
|
f0def1f86f | ||
|
|
2aed8226ee | ||
|
|
5db3553efa | ||
|
|
7828491cc9 | ||
|
|
cbfd30e520 | ||
|
|
3f19c92afd | ||
|
|
0e0bc56d2d | ||
|
|
8a30e585a6 | ||
|
|
30654dae6c | ||
|
|
9bc417603d | ||
|
|
db9e9d69ac | ||
|
|
00016308be | ||
|
|
301ab45538 | ||
|
|
9ca3daec38 | ||
|
|
a1fbf98b4e | ||
|
|
b181df309d | ||
|
|
c323ffb786 | ||
|
|
12d299720d | ||
|
|
a60a9d0154 | ||
|
|
b2fda77a4f | ||
|
|
34d93d4cd5 | ||
|
|
09b7b1e726 | ||
|
|
ee5dfa9d41 | ||
|
|
1cb0633c8b | ||
|
|
0d901e2105 | ||
|
|
4048ff9fee | ||
|
|
95b0de8aa3 | ||
|
|
1f01f83797 | ||
|
|
887f6cd44b | ||
|
|
a9a35b4b4c | ||
|
|
1e6bf4c34a | ||
|
|
db1d7b9120 | ||
|
|
7633c30396 | ||
|
|
edd81e580a | ||
|
|
fb67e33a13 | ||
|
|
e78605ac39 | ||
|
|
c658753fdb | ||
|
|
84dcb2fb00 | ||
|
|
f5086ef8a2 | ||
|
|
6c5ad7d907 | ||
|
|
f9da9fcd85 | ||
|
|
bc2591d501 | ||
|
|
bb9d4e3562 | ||
|
|
eaa6075572 | ||
|
|
042badd23f | ||
|
|
2cb1818d01 | ||
|
|
df46f6931d | ||
|
|
32974e0c57 | ||
|
|
5cdf288a8c | ||
|
|
ecd2cf2f6f | ||
|
|
d327a9662b | ||
|
|
d54fe2628d | ||
|
|
a0777f3182 | ||
|
|
a9e910d2d4 | ||
|
|
c6882a15db | ||
|
|
49b94635ff | ||
|
|
18c9da079e | ||
|
|
62d06fab22 | ||
|
|
3d321762ac | ||
|
|
0a72d0dc15 | ||
|
|
ca8a517814 | ||
|
|
3a7aca777c | ||
|
|
222a5abef3 | ||
|
|
e0ab9b0ebc | ||
|
|
86755334b4 | ||
|
|
43406d468d | ||
|
|
9f807c7777 | ||
|
|
fd9137efec | ||
|
|
03d848f7b8 | ||
|
|
c0a7beb6d9 | ||
|
|
73de67fcd2 | ||
|
|
edd88bd3fe | ||
|
|
7745079647 | ||
|
|
d481307bb4 | ||
|
|
0ac0d7ee72 | ||
|
|
6a2300da32 | ||
|
|
96a6c43b34 | ||
|
|
93abead744 | ||
|
|
9e48e80fa5 | ||
|
|
887a78e280 | ||
|
|
07965844a5 | ||
|
|
e4606463e7 | ||
|
|
cdd0585e04 | ||
|
|
8bd9bdf95d | ||
|
|
d8da34d23f | ||
|
|
139e5c2a14 | ||
|
|
56b5947eaa | ||
|
|
e85035a36c | ||
|
|
56625a3e1f | ||
|
|
a4c9642cf9 | ||
|
|
26f2522e60 | ||
|
|
fd95bf0d21 | ||
|
|
c5f18d1616 | ||
|
|
b083c4d510 | ||
|
|
8bb7fab26e | ||
|
|
4c3e17b9d8 | ||
|
|
9b57cc05cb | ||
|
|
f4107529f6 | ||
|
|
0354362b85 | ||
|
|
cf112e73c1 | ||
|
|
b75b158396 | ||
|
|
367d24b70a | ||
|
|
0fad04b3d5 | ||
|
|
d5ea1ee676 | ||
|
|
c5e741e787 | ||
|
|
5d55571d8d | ||
|
|
b1acf7ed5c | ||
|
|
141be750b2 | ||
|
|
aa2960fa26 | ||
|
|
46b7916ab7 | ||
|
|
6c5ef96af4 | ||
|
|
e3ed63c7de | ||
|
|
d432a06b9c | ||
|
|
0cfe2c2610 | ||
|
|
38bd73789a | ||
|
|
46744b6469 | ||
|
|
9f1639c732 | ||
|
|
1fa50dd28c | ||
|
|
b4136f3902 | ||
|
|
b659188ac8 | ||
|
|
f61411af46 | ||
|
|
d759c548aa | ||
|
|
c9957fd508 | ||
|
|
024a1462f5 | ||
|
|
cbe71595e1 | ||
|
|
6205e99cb3 | ||
|
|
f0089856c0 | ||
|
|
83960f8a56 | ||
|
|
f91b88efac | ||
|
|
e6fc58886a | ||
|
|
083e3114a5 | ||
|
|
0b7a1a04e6 | ||
|
|
48de2e315c | ||
|
|
68fd7dd6b3 | ||
|
|
f0f41c0164 | ||
|
|
c523434e36 | ||
|
|
2396f7b972 | ||
|
|
b3c1936a97 | ||
|
|
f6e0c2d083 | ||
|
|
ba77ff90d3 | ||
|
|
152115dea5 | ||
|
|
507c939f41 | ||
|
|
191a69ad45 | ||
|
|
f352f5e875 | ||
|
|
5b131f5995 | ||
|
|
46aefe3da3 | ||
|
|
a660c18c08 | ||
|
|
71d63d4617 | ||
|
|
b3f806c2f6 | ||
|
|
a5170d6e01 | ||
|
|
377b528b05 | ||
|
|
77b26fdebd | ||
|
|
f413b302fb | ||
|
|
5bf661138b | ||
|
|
928bb44255 | ||
|
|
9dab916b16 | ||
|
|
f2156d79c9 | ||
|
|
688b60c078 | ||
|
|
a554d70499 | ||
|
|
f2687cc30a | ||
|
|
de63679df0 | ||
|
|
0a90308df4 | ||
|
|
b80a3891a4 | ||
|
|
3518013b18 |
7688 changed files with 1125300 additions and 118981 deletions
17
.gitattributes
vendored
17
.gitattributes
vendored
|
|
@ -7,7 +7,24 @@ packages/protocol/openapi.json linguist-generated
|
||||||
packages/client/src/promise/generated/** linguist-generated
|
packages/client/src/promise/generated/** linguist-generated
|
||||||
packages/client/src/effect/generated/** linguist-generated
|
packages/client/src/effect/generated/** linguist-generated
|
||||||
packages/client/src/effect/api/** linguist-generated
|
packages/client/src/effect/api/** linguist-generated
|
||||||
|
# cli-rs: parity recordings and the files `script/gen` writes.
|
||||||
|
packages/cli-rs/parity/fixtures/** linguist-generated
|
||||||
|
packages/cli-rs/assets/queries/** linguist-generated
|
||||||
|
packages/cli-rs/crates/acp/src/permission/structured_patch.json linguist-generated
|
||||||
|
packages/cli-rs/crates/api-types/src/types.rs linguist-generated
|
||||||
|
packages/cli-rs/crates/api/src/generated/** linguist-generated
|
||||||
|
packages/cli-rs/crates/cli/src/run/mime.rs linguist-generated
|
||||||
|
packages/cli-rs/crates/cli/tests/fixtures/** linguist-generated
|
||||||
|
packages/cli-rs/crates/local/src/generated/** linguist-generated
|
||||||
|
packages/cli-rs/crates/mermaid/src/core/entities.rs linguist-generated
|
||||||
|
packages/cli-rs/crates/mermaid/src/core/wide.rs linguist-generated
|
||||||
|
packages/cli-rs/crates/ui/src/fuzzy/accents.rs linguist-generated
|
||||||
|
packages/cli-rs/crates/ui/src/keymap/generated.rs linguist-generated
|
||||||
|
packages/cli-rs/crates/ui/src/theme/generated/** linguist-generated
|
||||||
|
packages/cli-rs/crates/util/fixtures/time.tsv linguist-generated
|
||||||
packages/core/src/**/*.txt text eol=lf
|
packages/core/src/**/*.txt text eol=lf
|
||||||
|
# test/opencode-api-skill.test.ts compares the generated API reference byte for byte, so Windows checkouts keep LF.
|
||||||
|
packages/core/src/plugin/skill/opencode/** text eol=lf
|
||||||
packages/httpapi-codegen/test/generated/*.ts text eol=lf
|
packages/httpapi-codegen/test/generated/*.ts text eol=lf
|
||||||
# The site tests compare source text and humans.txt byte for byte, so Windows checkouts keep LF.
|
# The site tests compare source text and humans.txt byte for byte, so Windows checkouts keep LF.
|
||||||
services/site/** text=auto eol=lf
|
services/site/** text=auto eol=lf
|
||||||
|
|
|
||||||
7
.github/TEAM_MEMBERS
vendored
7
.github/TEAM_MEMBERS
vendored
|
|
@ -11,7 +11,6 @@ kommander
|
||||||
ludvigrask
|
ludvigrask
|
||||||
MrMushrooooom
|
MrMushrooooom
|
||||||
neriousy
|
neriousy
|
||||||
nexxeln
|
|
||||||
R44VC0RP
|
R44VC0RP
|
||||||
rekram1-node
|
rekram1-node
|
||||||
thdxr
|
thdxr
|
||||||
|
|
@ -19,4 +18,8 @@ simonklee
|
||||||
Slickstef11
|
Slickstef11
|
||||||
usrnk1
|
usrnk1
|
||||||
vimtor
|
vimtor
|
||||||
StarpTech
|
Tarquinen
|
||||||
|
dc85
|
||||||
|
vaprdev
|
||||||
|
hearnadam
|
||||||
|
heimoshuiyu
|
||||||
|
|
|
||||||
40
.github/actions/prefetch-ghostty/action.yml
vendored
Normal file
40
.github/actions/prefetch-ghostty/action.yml
vendored
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
name: Prefetch Ghostty dependencies
|
||||||
|
description: Prepare the pinned source and Zig packages for process-daemon's native build
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
- name: Check out pinned Ghostty source
|
||||||
|
id: pins
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GHOSTTY_SOURCE_DIR: ${{ runner.temp }}/ghostty
|
||||||
|
ZIG_GLOBAL_CACHE_DIR: ${{ github.workspace }}/.zig-cache
|
||||||
|
run: |
|
||||||
|
revision=$(git show HEAD:packages/process-daemon/ghostty-revision)
|
||||||
|
git init --quiet "$GHOSTTY_SOURCE_DIR"
|
||||||
|
git -C "$GHOSTTY_SOURCE_DIR" fetch --depth=1 https://github.com/ghostty-org/ghostty.git "$revision"
|
||||||
|
git -C "$GHOSTTY_SOURCE_DIR" -c core.longpaths=true checkout --detach "$revision"
|
||||||
|
echo "revision=$revision" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "zig=$(zig version)" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "GHOSTTY_SOURCE_DIR=$GHOSTTY_SOURCE_DIR" >> "$GITHUB_ENV"
|
||||||
|
echo "ZIG_GLOBAL_CACHE_DIR=$ZIG_GLOBAL_CACHE_DIR" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
# Zig 0.16 stores portable, content-addressed source tarballs in p/.
|
||||||
|
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
|
||||||
|
with:
|
||||||
|
path: .zig-cache/p
|
||||||
|
key: ghostty-packages-${{ steps.pins.outputs.zig }}-${{ steps.pins.outputs.revision }}
|
||||||
|
enableCrossOsArchive: true
|
||||||
|
|
||||||
|
- name: Fetch Zig packages
|
||||||
|
shell: bash
|
||||||
|
working-directory: ${{ env.GHOSTTY_SOURCE_DIR }}
|
||||||
|
run: |
|
||||||
|
for attempt in 1 2 3 4; do
|
||||||
|
echo "zig build --fetch=all (attempt $attempt/4)"
|
||||||
|
if zig build --fetch=all; then exit 0; fi
|
||||||
|
if [[ $attempt == 4 ]]; then exit 1; fi
|
||||||
|
delay=$((5 * 2 ** (attempt - 1)))
|
||||||
|
echo "Retrying in ${delay}s"
|
||||||
|
sleep "$delay"
|
||||||
|
done
|
||||||
53
.github/release/backfill-blockmaps.sh
vendored
Normal file
53
.github/release/backfill-blockmaps.sh
vendored
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# backfill-blockmaps.sh <version>...: builds the .blockmap for each published Windows installer and macOS zip of
|
||||||
|
# the given stable versions from the signed files on opencode.ai/files and uploads it next to them. Releases before
|
||||||
|
# publish-desktop.sh built blockmaps shipped without them, so electron-updater could not update differentially
|
||||||
|
# from them. A blockmap that already exists is left alone; a file the version never shipped is skipped.
|
||||||
|
. "$(dirname "$0")/lib.sh"
|
||||||
|
|
||||||
|
actor=${GITHUB_TRIGGERING_ACTOR:-${GITHUB_ACTOR:-}}
|
||||||
|
if ! (shopt -s nocasematch; [[ "$actor" = thdxr || "$actor" = Hona || "$actor" = rekram1-node ]]); then
|
||||||
|
die "${actor:-An unknown actor} is not allowed to backfill release files"
|
||||||
|
fi
|
||||||
|
[ $# -gt 0 ] || die "No versions given"
|
||||||
|
for version in "$@"; do
|
||||||
|
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] && [[ "$version" != 0.0.0-* ]] ||
|
||||||
|
die "Invalid release version: $version"
|
||||||
|
done
|
||||||
|
|
||||||
|
names=(opencode-desktop-win-arm64.exe opencode-desktop-win-x64.exe opencode-desktop-mac-arm64.zip opencode-desktop-mac-x64.zip)
|
||||||
|
status() {
|
||||||
|
curl -sS -o /dev/null -w '%{http_code}' --head "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
credentials=false
|
||||||
|
for version in "$@"; do
|
||||||
|
dir=$(mktemp -d)
|
||||||
|
for name in "${names[@]}"; do
|
||||||
|
url="https://opencode.ai/files/bin/$version/$name"
|
||||||
|
case "$(status "$url.blockmap")" in
|
||||||
|
200) echo "$version/$name.blockmap exists" && continue ;;
|
||||||
|
404) ;;
|
||||||
|
*) die "Could not check $url.blockmap" ;;
|
||||||
|
esac
|
||||||
|
case "$(status "$url")" in
|
||||||
|
200) ;;
|
||||||
|
404) echo "$version/$name was not published" && continue ;;
|
||||||
|
*) die "Could not check $url" ;;
|
||||||
|
esac
|
||||||
|
curl -fsSL --retry 3 -o "$dir/$name" "$url"
|
||||||
|
node "$release_dir/blockmap.mjs" "$dir/$name"
|
||||||
|
if dry_run; then
|
||||||
|
echo "dry-run upload: bin/$version/$name.blockmap ($(size "$dir/$name.blockmap") bytes)"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if [ "$credentials" = false ]; then
|
||||||
|
r2_credentials
|
||||||
|
credentials=true
|
||||||
|
fi
|
||||||
|
OPENCODE_VERSION=$version upload_file "$dir/$name.blockmap" "$name.blockmap" application/octet-stream ||
|
||||||
|
die "Upload failed: $version/$name.blockmap"
|
||||||
|
echo "uploaded bin/$version/$name.blockmap"
|
||||||
|
done
|
||||||
|
rm -rf "$dir"
|
||||||
|
done
|
||||||
179
.github/release/blockmap.mjs
vendored
Normal file
179
.github/release/blockmap.mjs
vendored
Normal file
|
|
@ -0,0 +1,179 @@
|
||||||
|
// blockmap.mjs <file>...: writes <file>.blockmap next to each file, the gzipped block map electron-updater fetches
|
||||||
|
// for a differential download. It matches electron-builder's buildBlockMap (app-builder-lib 26): Rabin
|
||||||
|
// content-defined chunks of 8-32 KB and a 18-byte BLAKE2b checksum per chunk. electron-builder builds it at pack
|
||||||
|
// time, but signing changes the installer, so the release builds it here from the final signed files.
|
||||||
|
//
|
||||||
|
// It runs in publish jobs that hold secrets, so it uses Node's standard library only.
|
||||||
|
import { createReadStream, writeFileSync } from "node:fs"
|
||||||
|
import { gzipSync } from "node:zlib"
|
||||||
|
|
||||||
|
const MIN = 8192
|
||||||
|
const MAX = 32768
|
||||||
|
const MASK = 16384 - 1
|
||||||
|
const WINDOW = 64
|
||||||
|
|
||||||
|
// Rabin fingerprint tables for the degree-63 polynomial 0xbfe6b8a5bf378d83 (github.com/aclements/go-rabin), each
|
||||||
|
// 64-bit entry split into signed 32-bit hi and lo words.
|
||||||
|
const POLY = 0xbfe6b8a5bf378d83n
|
||||||
|
const PUSH_HI = new Int32Array(256)
|
||||||
|
const PUSH_LO = new Int32Array(256)
|
||||||
|
const POP_HI = new Int32Array(256)
|
||||||
|
const POP_LO = new Int32Array(256)
|
||||||
|
{
|
||||||
|
const mod = (a) => {
|
||||||
|
for (let d = a.toString(2).length - 1; a !== 0n && d >= 63; d = a.toString(2).length - 1)
|
||||||
|
a ^= POLY << BigInt(d - 63)
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
const set = (hi, lo, i, x) => {
|
||||||
|
hi[i] = Number(BigInt.asIntN(32, x >> 32n))
|
||||||
|
lo[i] = Number(BigInt.asIntN(32, x))
|
||||||
|
}
|
||||||
|
for (let i = 0; i < 256; i++) {
|
||||||
|
const b = BigInt(i)
|
||||||
|
set(PUSH_HI, PUSH_LO, i, BigInt.asUintN(64, (b << 63n) ^ mod(b << 63n)))
|
||||||
|
set(POP_HI, POP_LO, i, mod(b << BigInt((WINDOW - 1) * 8)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BLAKE2b (RFC 7693) with an 18-byte digest and no key, on 32-bit word pairs. Node's crypto offers only BLAKE2b-512,
|
||||||
|
// whose digest length is part of the parameter block, so truncating it gives a different hash.
|
||||||
|
const IV = new Uint32Array([
|
||||||
|
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, 0xade682d1,
|
||||||
|
0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19,
|
||||||
|
])
|
||||||
|
const SIGMA = [
|
||||||
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
|
||||||
|
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
|
||||||
|
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
|
||||||
|
[7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
|
||||||
|
[9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
|
||||||
|
[2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
|
||||||
|
[12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
|
||||||
|
[13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
|
||||||
|
[6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
|
||||||
|
[10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
|
||||||
|
].map((row) => row.map((i) => i * 2))
|
||||||
|
const ROUNDS = [...SIGMA, SIGMA[0], SIGMA[1]]
|
||||||
|
const DIGEST = 18
|
||||||
|
const v = new Uint32Array(32)
|
||||||
|
const m = new Uint32Array(32)
|
||||||
|
const h = new Uint32Array(16)
|
||||||
|
const block = new Uint8Array(128)
|
||||||
|
const view = new DataView(block.buffer)
|
||||||
|
|
||||||
|
function add(a, b0, b1) {
|
||||||
|
const lo = v[a] + b0
|
||||||
|
v[a + 1] = v[a + 1] + b1 + (lo >= 0x100000000 ? 1 : 0)
|
||||||
|
v[a] = lo
|
||||||
|
}
|
||||||
|
|
||||||
|
function mix(a, b, c, d, x, y) {
|
||||||
|
add(a, v[b], v[b + 1])
|
||||||
|
add(a, m[x], m[x + 1])
|
||||||
|
let lo = v[d] ^ v[a]
|
||||||
|
let hi = v[d + 1] ^ v[a + 1]
|
||||||
|
v[d] = hi
|
||||||
|
v[d + 1] = lo
|
||||||
|
add(c, v[d], v[d + 1])
|
||||||
|
lo = v[b] ^ v[c]
|
||||||
|
hi = v[b + 1] ^ v[c + 1]
|
||||||
|
v[b] = (lo >>> 24) ^ (hi << 8)
|
||||||
|
v[b + 1] = (hi >>> 24) ^ (lo << 8)
|
||||||
|
add(a, v[b], v[b + 1])
|
||||||
|
add(a, m[y], m[y + 1])
|
||||||
|
lo = v[d] ^ v[a]
|
||||||
|
hi = v[d + 1] ^ v[a + 1]
|
||||||
|
v[d] = (lo >>> 16) ^ (hi << 16)
|
||||||
|
v[d + 1] = (hi >>> 16) ^ (lo << 16)
|
||||||
|
add(c, v[d], v[d + 1])
|
||||||
|
lo = v[b] ^ v[c]
|
||||||
|
hi = v[b + 1] ^ v[c + 1]
|
||||||
|
v[b] = (hi >>> 31) ^ (lo << 1)
|
||||||
|
v[b + 1] = (lo >>> 31) ^ (hi << 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function compress(count, last) {
|
||||||
|
for (let i = 0; i < 16; i++) {
|
||||||
|
v[i] = h[i]
|
||||||
|
v[i + 16] = IV[i]
|
||||||
|
}
|
||||||
|
v[24] ^= count
|
||||||
|
v[25] ^= Math.floor(count / 0x100000000)
|
||||||
|
if (last) {
|
||||||
|
v[28] = ~v[28]
|
||||||
|
v[29] = ~v[29]
|
||||||
|
}
|
||||||
|
for (let i = 0; i < 32; i++) m[i] = view.getUint32(i * 4, true)
|
||||||
|
for (const s of ROUNDS) {
|
||||||
|
mix(0, 8, 16, 24, s[0], s[1])
|
||||||
|
mix(2, 10, 18, 26, s[2], s[3])
|
||||||
|
mix(4, 12, 20, 28, s[4], s[5])
|
||||||
|
mix(6, 14, 22, 30, s[6], s[7])
|
||||||
|
mix(0, 10, 20, 30, s[8], s[9])
|
||||||
|
mix(2, 12, 22, 24, s[10], s[11])
|
||||||
|
mix(4, 14, 16, 26, s[12], s[13])
|
||||||
|
mix(6, 8, 18, 28, s[14], s[15])
|
||||||
|
}
|
||||||
|
for (let i = 0; i < 16; i++) h[i] ^= v[i] ^ v[i + 16]
|
||||||
|
}
|
||||||
|
|
||||||
|
function blake2b(data) {
|
||||||
|
h.set(IV)
|
||||||
|
h[0] ^= 0x01010000 ^ DIGEST
|
||||||
|
let offset = 0
|
||||||
|
while (data.length - offset > 128) {
|
||||||
|
block.set(data.subarray(offset, offset + 128))
|
||||||
|
offset += 128
|
||||||
|
compress(offset, false)
|
||||||
|
}
|
||||||
|
block.fill(0)
|
||||||
|
block.set(data.subarray(offset))
|
||||||
|
compress(data.length, true)
|
||||||
|
return Buffer.from(h.buffer, h.byteOffset, DIGEST).toString("base64")
|
||||||
|
}
|
||||||
|
|
||||||
|
async function blockmap(file) {
|
||||||
|
const checksums = []
|
||||||
|
const sizes = []
|
||||||
|
const chunk = Buffer.allocUnsafe(MAX)
|
||||||
|
const win = new Uint8Array(WINDOW)
|
||||||
|
let n = 0
|
||||||
|
let hi = 0
|
||||||
|
let lo = 0
|
||||||
|
let pos = 0
|
||||||
|
|
||||||
|
const emit = () => {
|
||||||
|
checksums.push(blake2b(chunk.subarray(0, n)))
|
||||||
|
sizes.push(n)
|
||||||
|
n = hi = lo = pos = 0
|
||||||
|
win.fill(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
for await (const data of createReadStream(file, { highWaterMark: 256 * 1024 })) {
|
||||||
|
for (let i = 0; i < data.length; i++) {
|
||||||
|
const b = data[i]
|
||||||
|
chunk[n++] = b
|
||||||
|
if (n <= MIN - WINDOW) continue
|
||||||
|
if (n > MIN) {
|
||||||
|
const old = win[pos]
|
||||||
|
hi ^= POP_HI[old]
|
||||||
|
lo ^= POP_LO[old]
|
||||||
|
}
|
||||||
|
win[pos] = b
|
||||||
|
pos = (pos + 1) % WINDOW
|
||||||
|
const top = (hi >>> 23) & 0xff
|
||||||
|
const nhi = ((hi << 8) | (lo >>> 24)) & 0x7fffffff
|
||||||
|
const nlo = (lo << 8) | b
|
||||||
|
hi = nhi ^ PUSH_HI[top]
|
||||||
|
lo = nlo ^ PUSH_LO[top]
|
||||||
|
if (n >= MIN && ((lo & MASK) === MASK || n >= MAX)) emit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (n > 0) emit()
|
||||||
|
|
||||||
|
const map = { version: "2", files: [{ name: "file", offset: 0, checksums, sizes }] }
|
||||||
|
writeFileSync(`${file}.blockmap`, gzipSync(Buffer.from(JSON.stringify(map)), { level: 9 }))
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const file of process.argv.slice(2)) await blockmap(file)
|
||||||
2
.github/release/entitlements/desktop.plist
vendored
2
.github/release/entitlements/desktop.plist
vendored
|
|
@ -6,5 +6,7 @@
|
||||||
<true/>
|
<true/>
|
||||||
<key>com.apple.security.device.audio-input</key>
|
<key>com.apple.security.device.audio-input</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>com.apple.security.device.camera</key>
|
||||||
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|
|
||||||
8
.github/release/publish-desktop.sh
vendored
8
.github/release/publish-desktop.sh
vendored
|
|
@ -24,7 +24,13 @@ feed() {
|
||||||
done | jq -s --arg date "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" '{files: ., releaseDate: $date}'
|
done | jq -s --arg date "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" '{files: ., releaseDate: $date}'
|
||||||
}
|
}
|
||||||
|
|
||||||
files=$(upload_files "${win[@]}" "${mac[@]}" "${linux[@]}" "${linux_arm[@]}" "${bundles[@]}")
|
# electron-updater fetches <file>.blockmap next to the Windows installer and the macOS zip for a differential
|
||||||
|
# download. Signing changes these files, so the blockmaps electron-builder made at pack time no longer match.
|
||||||
|
differential=("${win[@]}" "$macos/opencode-desktop-mac-arm64.zip" "$macos/opencode-desktop-mac-x64.zip")
|
||||||
|
node "$release_dir/blockmap.mjs" "${differential[@]}"
|
||||||
|
blockmaps=("${differential[@]/%/.blockmap}")
|
||||||
|
|
||||||
|
files=$(upload_files "${win[@]}" "${mac[@]}" "${linux[@]}" "${linux_arm[@]}" "${bundles[@]}" "${blockmaps[@]}")
|
||||||
manifests=$(jq -n --argjson win "$(feed "${win[@]}")" --argjson mac "$(feed "${mac[@]}")" \
|
manifests=$(jq -n --argjson win "$(feed "${win[@]}")" --argjson mac "$(feed "${mac[@]}")" \
|
||||||
--argjson linux "$(feed "${linux[@]}")" --argjson linux_arm64 "$(feed "${linux_arm[@]}")" \
|
--argjson linux "$(feed "${linux[@]}")" --argjson linux_arm64 "$(feed "${linux_arm[@]}")" \
|
||||||
'{"desktop.yml": $win, "desktop-mac.yml": $mac, "desktop-linux.yml": $linux, "desktop-linux-arm64.yml": $linux_arm64}')
|
'{"desktop.yml": $win, "desktop-mac.yml": $mac, "desktop-linux.yml": $linux, "desktop-linux-arm64.yml": $linux_arm64}')
|
||||||
|
|
|
||||||
3
.github/release/publish-discord.sh
vendored
3
.github/release/publish-discord.sh
vendored
|
|
@ -6,7 +6,8 @@
|
||||||
tag="v$OPENCODE_VERSION"
|
tag="v$OPENCODE_VERSION"
|
||||||
payload=$(jq -n --arg tag "$tag" --arg notes "${OPENCODE_RELEASE_NOTES:-}" \
|
payload=$(jq -n --arg tag "$tag" --arg notes "${OPENCODE_RELEASE_NOTES:-}" \
|
||||||
--arg url "https://github.com/$GITHUB_REPOSITORY/releases/tag/$tag" '
|
--arg url "https://github.com/$GITHUB_REPOSITORY/releases/tag/$tag" '
|
||||||
($notes | if length > 4000 then .[:4000] + "\n\n[Full release notes](\($url))" else . end) as $description |
|
($notes | gsub("(?m)^#{4,6}[ \\t]+(?<heading>[^\\r\\n]+)"; "**\(.heading)**") |
|
||||||
|
if length > 4000 then .[:4000] + "\n\n[Full release notes](\($url))" else . end) as $description |
|
||||||
{
|
{
|
||||||
allowed_mentions: {parse: []},
|
allowed_mentions: {parse: []},
|
||||||
embeds: [{title: "OpenCode V2 \($tag)", url: $url, description: $description, color: 2829099}]
|
embeds: [{title: "OpenCode V2 \($tag)", url: $url, description: $description, color: 2829099}]
|
||||||
|
|
|
||||||
8
.github/release/targets/data/dev/og.json
vendored
8
.github/release/targets/data/dev/og.json
vendored
|
|
@ -11,10 +11,10 @@
|
||||||
"harfbuzz.wasm": { "type": "wasm" },
|
"harfbuzz.wasm": { "type": "wasm" },
|
||||||
"satori-layout.wasm": { "type": "wasm" },
|
"satori-layout.wasm": { "type": "wasm" },
|
||||||
"resvg.wasm": { "type": "wasm" },
|
"resvg.wasm": { "type": "wasm" },
|
||||||
"opentui-mono-regular-rest.bin": { "type": "data" },
|
"openmono-regular-rest.bin": { "type": "data" },
|
||||||
"opentui-mono-regular-latin.bin": { "type": "data" },
|
"openmono-regular-latin.bin": { "type": "data" },
|
||||||
"opentui-mono-bold-rest.bin": { "type": "data" },
|
"openmono-bold-rest.bin": { "type": "data" },
|
||||||
"opentui-mono-bold-latin.bin": { "type": "data" }
|
"openmono-bold-latin.bin": { "type": "data" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,10 +11,10 @@
|
||||||
"harfbuzz.wasm": { "type": "wasm" },
|
"harfbuzz.wasm": { "type": "wasm" },
|
||||||
"satori-layout.wasm": { "type": "wasm" },
|
"satori-layout.wasm": { "type": "wasm" },
|
||||||
"resvg.wasm": { "type": "wasm" },
|
"resvg.wasm": { "type": "wasm" },
|
||||||
"opentui-mono-regular-rest.bin": { "type": "data" },
|
"openmono-regular-rest.bin": { "type": "data" },
|
||||||
"opentui-mono-regular-latin.bin": { "type": "data" },
|
"openmono-regular-latin.bin": { "type": "data" },
|
||||||
"opentui-mono-bold-rest.bin": { "type": "data" },
|
"openmono-bold-rest.bin": { "type": "data" },
|
||||||
"opentui-mono-bold-latin.bin": { "type": "data" }
|
"openmono-bold-latin.bin": { "type": "data" }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
53
.github/release/targets/site/dev/worker.json
vendored
53
.github/release/targets/site/dev/worker.json
vendored
|
|
@ -19,7 +19,58 @@
|
||||||
"!/v1/docs/assets/*",
|
"!/v1/docs/assets/*",
|
||||||
"!/v1/docs/pagefind/*",
|
"!/v1/docs/pagefind/*",
|
||||||
"!/v1/docs/llms.txt",
|
"!/v1/docs/llms.txt",
|
||||||
"!/v1/docs/theme.json"
|
"!/v1/docs/theme.json",
|
||||||
|
"/zh/docs",
|
||||||
|
"/zh/docs/*",
|
||||||
|
"!/zh/docs/pagefind/*",
|
||||||
|
"/zht/docs",
|
||||||
|
"/zht/docs/*",
|
||||||
|
"!/zht/docs/pagefind/*",
|
||||||
|
"/ko/docs",
|
||||||
|
"/ko/docs/*",
|
||||||
|
"!/ko/docs/pagefind/*",
|
||||||
|
"/de/docs",
|
||||||
|
"/de/docs/*",
|
||||||
|
"!/de/docs/pagefind/*",
|
||||||
|
"/es/docs",
|
||||||
|
"/es/docs/*",
|
||||||
|
"!/es/docs/pagefind/*",
|
||||||
|
"/fr/docs",
|
||||||
|
"/fr/docs/*",
|
||||||
|
"!/fr/docs/pagefind/*",
|
||||||
|
"/it/docs",
|
||||||
|
"/it/docs/*",
|
||||||
|
"!/it/docs/pagefind/*",
|
||||||
|
"/da/docs",
|
||||||
|
"/da/docs/*",
|
||||||
|
"!/da/docs/pagefind/*",
|
||||||
|
"/ja/docs",
|
||||||
|
"/ja/docs/*",
|
||||||
|
"!/ja/docs/pagefind/*",
|
||||||
|
"/pl/docs",
|
||||||
|
"/pl/docs/*",
|
||||||
|
"!/pl/docs/pagefind/*",
|
||||||
|
"/ru/docs",
|
||||||
|
"/ru/docs/*",
|
||||||
|
"!/ru/docs/pagefind/*",
|
||||||
|
"/uk/docs",
|
||||||
|
"/uk/docs/*",
|
||||||
|
"!/uk/docs/pagefind/*",
|
||||||
|
"/ar/docs",
|
||||||
|
"/ar/docs/*",
|
||||||
|
"!/ar/docs/pagefind/*",
|
||||||
|
"/no/docs",
|
||||||
|
"/no/docs/*",
|
||||||
|
"!/no/docs/pagefind/*",
|
||||||
|
"/br/docs",
|
||||||
|
"/br/docs/*",
|
||||||
|
"!/br/docs/pagefind/*",
|
||||||
|
"/th/docs",
|
||||||
|
"/th/docs/*",
|
||||||
|
"!/th/docs/pagefind/*",
|
||||||
|
"/tr/docs",
|
||||||
|
"/tr/docs/*",
|
||||||
|
"!/tr/docs/pagefind/*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"domains": ["dev.opencode.ai", "docs.dev.opencode.ai"],
|
"domains": ["dev.opencode.ai", "docs.dev.opencode.ai"],
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,58 @@
|
||||||
"!/v1/docs/assets/*",
|
"!/v1/docs/assets/*",
|
||||||
"!/v1/docs/pagefind/*",
|
"!/v1/docs/pagefind/*",
|
||||||
"!/v1/docs/llms.txt",
|
"!/v1/docs/llms.txt",
|
||||||
"!/v1/docs/theme.json"
|
"!/v1/docs/theme.json",
|
||||||
|
"/zh/docs",
|
||||||
|
"/zh/docs/*",
|
||||||
|
"!/zh/docs/pagefind/*",
|
||||||
|
"/zht/docs",
|
||||||
|
"/zht/docs/*",
|
||||||
|
"!/zht/docs/pagefind/*",
|
||||||
|
"/ko/docs",
|
||||||
|
"/ko/docs/*",
|
||||||
|
"!/ko/docs/pagefind/*",
|
||||||
|
"/de/docs",
|
||||||
|
"/de/docs/*",
|
||||||
|
"!/de/docs/pagefind/*",
|
||||||
|
"/es/docs",
|
||||||
|
"/es/docs/*",
|
||||||
|
"!/es/docs/pagefind/*",
|
||||||
|
"/fr/docs",
|
||||||
|
"/fr/docs/*",
|
||||||
|
"!/fr/docs/pagefind/*",
|
||||||
|
"/it/docs",
|
||||||
|
"/it/docs/*",
|
||||||
|
"!/it/docs/pagefind/*",
|
||||||
|
"/da/docs",
|
||||||
|
"/da/docs/*",
|
||||||
|
"!/da/docs/pagefind/*",
|
||||||
|
"/ja/docs",
|
||||||
|
"/ja/docs/*",
|
||||||
|
"!/ja/docs/pagefind/*",
|
||||||
|
"/pl/docs",
|
||||||
|
"/pl/docs/*",
|
||||||
|
"!/pl/docs/pagefind/*",
|
||||||
|
"/ru/docs",
|
||||||
|
"/ru/docs/*",
|
||||||
|
"!/ru/docs/pagefind/*",
|
||||||
|
"/uk/docs",
|
||||||
|
"/uk/docs/*",
|
||||||
|
"!/uk/docs/pagefind/*",
|
||||||
|
"/ar/docs",
|
||||||
|
"/ar/docs/*",
|
||||||
|
"!/ar/docs/pagefind/*",
|
||||||
|
"/no/docs",
|
||||||
|
"/no/docs/*",
|
||||||
|
"!/no/docs/pagefind/*",
|
||||||
|
"/br/docs",
|
||||||
|
"/br/docs/*",
|
||||||
|
"!/br/docs/pagefind/*",
|
||||||
|
"/th/docs",
|
||||||
|
"/th/docs/*",
|
||||||
|
"!/th/docs/pagefind/*",
|
||||||
|
"/tr/docs",
|
||||||
|
"/tr/docs/*",
|
||||||
|
"!/tr/docs/pagefind/*"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"domains": ["opencode.ai", "docs.opencode.ai"],
|
"domains": ["opencode.ai", "docs.opencode.ai"],
|
||||||
|
|
|
||||||
70
.github/workflows/backfill-blockmaps.yml
vendored
Normal file
70
.github/workflows/backfill-blockmaps.yml
vendored
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
name: backfill-blockmaps
|
||||||
|
|
||||||
|
# Uploads the .blockmap files electron-updater needs for a differential update next to desktop releases that
|
||||||
|
# shipped without them (2.2.0 through 2.4.1). Like release.yml's publish jobs, it runs in the release environment,
|
||||||
|
# checks out only .github/release/ and treats the published files as data; releasers only.
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
versions:
|
||||||
|
description: "Space-separated stable versions, such as 2.4.0 2.4.1"
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
dry_run:
|
||||||
|
description: "Build the blockmaps without uploading them"
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: true
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
backfill:
|
||||||
|
if: github.repository == 'anomalyco/opencode' && github.ref == 'refs/heads/dev'
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
environment: release
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
id-token: write
|
||||||
|
env:
|
||||||
|
OPENCODE_DRY_RUN: ${{ inputs.dry_run }}
|
||||||
|
steps:
|
||||||
|
- name: Check out release scripts
|
||||||
|
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
||||||
|
with:
|
||||||
|
ref: ${{ github.sha }}
|
||||||
|
sparse-checkout: /.github/release/
|
||||||
|
sparse-checkout-cone-mode: false
|
||||||
|
persist-credentials: false
|
||||||
|
- id: aws
|
||||||
|
name: Configure AWS credentials
|
||||||
|
if: inputs.dry_run != true
|
||||||
|
uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
|
||||||
|
with:
|
||||||
|
output-env-credentials: false
|
||||||
|
output-credentials: true
|
||||||
|
role-to-assume: arn:aws:iam::604439173067:role/github/opencode-release
|
||||||
|
role-session-name: opencode-${{ github.run_id }}
|
||||||
|
aws-region: us-east-1
|
||||||
|
- name: Cloudflare token
|
||||||
|
id: cloudflare-token
|
||||||
|
if: inputs.dry_run != true
|
||||||
|
run: bash .github/release/cloudflare-token.sh
|
||||||
|
env:
|
||||||
|
AWS_ACCESS_KEY_ID: ${{ steps.aws.outputs.aws-access-key-id }}
|
||||||
|
AWS_SECRET_ACCESS_KEY: ${{ steps.aws.outputs.aws-secret-access-key }}
|
||||||
|
AWS_SESSION_TOKEN: ${{ steps.aws.outputs.aws-session-token }}
|
||||||
|
CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }}
|
||||||
|
- name: Backfill
|
||||||
|
run: |
|
||||||
|
read -ra versions <<< "$VERSIONS"
|
||||||
|
bash .github/release/backfill-blockmaps.sh "${versions[@]}"
|
||||||
|
env:
|
||||||
|
VERSIONS: ${{ inputs.versions }}
|
||||||
|
CLOUDFLARE_ACCOUNT_ID: 15d29c8639fd3733b1b5486a2acfd968
|
||||||
|
CLOUDFLARE_API_TOKEN: ${{ steps.cloudflare-token.outputs.token }}
|
||||||
51
.github/workflows/check-cli-rs.yml
vendored
Normal file
51
.github/workflows/check-cli-rs.yml
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
name: check-cli-rs
|
||||||
|
|
||||||
|
# Checks packages/cli-rs, the Rust client, which check-test.yml leaves out. Pull requests run it only when they change
|
||||||
|
# the client. Its tests and check:drift also compare it with the TypeScript packages below, so a dev push that changes
|
||||||
|
# one runs it too: a TypeScript change that breaks the client shows on dev, not on other teams' pull requests.
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- packages/cli-rs/**
|
||||||
|
- .github/workflows/check-cli-rs.yml
|
||||||
|
push:
|
||||||
|
branches: [dev]
|
||||||
|
paths:
|
||||||
|
- packages/cli-rs/**
|
||||||
|
- packages/cli/src/**
|
||||||
|
- packages/client/**
|
||||||
|
- packages/plugin/**
|
||||||
|
- packages/protocol/**
|
||||||
|
- packages/schema/**
|
||||||
|
- packages/theme/**
|
||||||
|
- packages/tui/**
|
||||||
|
- packages/util/**
|
||||||
|
- bun.lock
|
||||||
|
- .github/workflows/check-cli-rs.yml
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check:
|
||||||
|
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||||
|
timeout-minutes: 45
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: packages/cli-rs
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
||||||
|
# Bun and node_modules: the tests and check:drift run the TypeScript side they compare against.
|
||||||
|
- uses: ./.github/actions/setup-bun
|
||||||
|
# rustup reads rust-toolchain.toml; `bun run cargo` first fetches OpenTUI's native library from its release.
|
||||||
|
- run: rustup toolchain install
|
||||||
|
- run: bun run cargo fmt --check
|
||||||
|
- run: bun run cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||||
|
# Every crate's tests, even after one fails, so one run shows every failure.
|
||||||
|
- run: bun run cargo test --locked --workspace --no-fail-fast
|
||||||
|
- run: bun run check:drift
|
||||||
36
.github/workflows/check-process-daemon.yml
vendored
36
.github/workflows/check-process-daemon.yml
vendored
|
|
@ -4,11 +4,13 @@ on:
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
- packages/process-daemon/**
|
- packages/process-daemon/**
|
||||||
|
- .github/actions/prefetch-ghostty/**
|
||||||
- .github/workflows/check-process-daemon.yml
|
- .github/workflows/check-process-daemon.yml
|
||||||
push:
|
push:
|
||||||
branches: [dev]
|
branches: [dev]
|
||||||
paths:
|
paths:
|
||||||
- packages/process-daemon/**
|
- packages/process-daemon/**
|
||||||
|
- .github/actions/prefetch-ghostty/**
|
||||||
- .github/workflows/check-process-daemon.yml
|
- .github/workflows/check-process-daemon.yml
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
|
@ -59,6 +61,8 @@ jobs:
|
||||||
- uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5
|
- uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5
|
||||||
with:
|
with:
|
||||||
version: 0.16.0
|
version: 0.16.0
|
||||||
|
use-cache: false
|
||||||
|
- uses: ./.github/actions/prefetch-ghostty
|
||||||
- name: Install Rust
|
- name: Install Rust
|
||||||
run: rustup toolchain install 1.90.0 --profile minimal --component rustfmt --component clippy
|
run: rustup toolchain install 1.90.0 --profile minimal --component rustfmt --component clippy
|
||||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||||
|
|
@ -79,7 +83,7 @@ jobs:
|
||||||
windows:
|
windows:
|
||||||
name: Windows (${{ matrix.arch }})
|
name: Windows (${{ matrix.arch }})
|
||||||
runs-on: ${{ matrix.runner }}
|
runs-on: ${{ matrix.runner }}
|
||||||
timeout-minutes: 30
|
timeout-minutes: 45
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
|
|
@ -109,7 +113,7 @@ jobs:
|
||||||
if: matrix.arch == 'x64'
|
if: matrix.arch == 'x64'
|
||||||
with:
|
with:
|
||||||
version: 0.16.0
|
version: 0.16.0
|
||||||
cache-key: ${{ matrix.target }}
|
use-cache: false
|
||||||
# Zig 0.16 crashes when building Ghostty on the native ARM64 host.
|
# Zig 0.16 crashes when building Ghostty on the native ARM64 host.
|
||||||
# Use x64-hosted compilers on this ARM64 runner, but execute ARM64 tests natively.
|
# Use x64-hosted compilers on this ARM64 runner, but execute ARM64 tests natively.
|
||||||
- name: Install x64 Zig for ARM64 cross-compilation
|
- name: Install x64 Zig for ARM64 cross-compilation
|
||||||
|
|
@ -130,6 +134,33 @@ jobs:
|
||||||
$old = '@ptrCast(try si.loadNtdllProc(@tagName(proc)))'
|
$old = '@ptrCast(try si.loadNtdllProc(@tagName(proc)))'
|
||||||
if (!$source.Contains($old)) { throw 'Zig alignment workaround no longer matches; re-evaluate it' }
|
if (!$source.Contains($old)) { throw 'Zig alignment workaround no longer matches; re-evaluate it' }
|
||||||
[System.IO.File]::WriteAllText($file, $source.Replace($old, '@ptrCast(@alignCast(try si.loadNtdllProc(@tagName(proc))))'))
|
[System.IO.File]::WriteAllText($file, $source.Replace($old, '@ptrCast(@alignCast(try si.loadNtdllProc(@tagName(proc))))'))
|
||||||
|
- name: Pin MSVC 14.51 for Zig's Clang 21
|
||||||
|
timeout-minutes: 20
|
||||||
|
run: |
|
||||||
|
$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
|
||||||
|
$vs = & "$installer\vswhere.exe" -latest -products * -property installationPath
|
||||||
|
$tools = "$vs\VC\Tools\MSVC"
|
||||||
|
$arch = '${{ matrix.arch }}'
|
||||||
|
$hasRuntimes = {
|
||||||
|
(Test-Path "$($_.FullName)\lib\x64\vcruntime.lib") -and
|
||||||
|
(Test-Path "$($_.FullName)\lib\$arch\vcruntime.lib")
|
||||||
|
}
|
||||||
|
if (!(Get-ChildItem $tools -Directory -Filter '14.51.*' | Where-Object $hasRuntimes)) {
|
||||||
|
$components = '--add Microsoft.VisualStudio.Component.VC.14.51.x86.x64'
|
||||||
|
if ($arch -eq 'arm64') { $components += ' --add Microsoft.VisualStudio.Component.VC.14.51.ARM64' }
|
||||||
|
$setup = Start-Process "$installer\setup.exe" -ArgumentList "modify --installPath `"$vs`" $components --quiet --norestart" -Wait -PassThru
|
||||||
|
if ($setup.ExitCode -notin 0, 3010) { throw "VS installer exited with $($setup.ExitCode)" }
|
||||||
|
Write-Output "MSVC 14.51 installer exited with $($setup.ExitCode) for $arch"
|
||||||
|
}
|
||||||
|
$toolset = Get-ChildItem $tools -Directory -Filter '14.51.*' |
|
||||||
|
Where-Object $hasRuntimes |
|
||||||
|
Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1
|
||||||
|
if (!$toolset) { throw "Missing MSVC 14.51 for $arch" }
|
||||||
|
# Zig reads this file for both host and target tools on the disposable runner.
|
||||||
|
Set-Content "$vs\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" $toolset.Name -Encoding ascii
|
||||||
|
$libc = zig libc
|
||||||
|
$libc
|
||||||
|
if ($LASTEXITCODE -ne 0 -or $libc -inotcontains "sys_include_dir=$($toolset.FullName)\include") { throw 'Zig selected unexpected MSVC headers' }
|
||||||
- name: Install Rust toolchain and target
|
- name: Install Rust toolchain and target
|
||||||
run: rustup toolchain install $env:RUSTUP_TOOLCHAIN --force-non-host --profile minimal --component rustfmt --component clippy --target $env:CARGO_BUILD_TARGET
|
run: rustup toolchain install $env:RUSTUP_TOOLCHAIN --force-non-host --profile minimal --component rustfmt --component clippy --target $env:CARGO_BUILD_TARGET
|
||||||
- name: Verify runner and compiler architecture
|
- name: Verify runner and compiler architecture
|
||||||
|
|
@ -145,6 +176,7 @@ jobs:
|
||||||
if ($compiler -notcontains 'host: x86_64-pc-windows-msvc') { throw 'Unexpected Rust compiler host' }
|
if ($compiler -notcontains 'host: x86_64-pc-windows-msvc') { throw 'Unexpected Rust compiler host' }
|
||||||
Write-Output "Executable target: $env:CARGO_BUILD_TARGET"
|
Write-Output "Executable target: $env:CARGO_BUILD_TARGET"
|
||||||
zig version
|
zig version
|
||||||
|
- uses: ./.github/actions/prefetch-ghostty
|
||||||
# No cache-on-failure: a timed-out run once saved a partial cache that broke re-runs.
|
# No cache-on-failure: a timed-out run once saved a partial cache that broke re-runs.
|
||||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||||
with:
|
with:
|
||||||
|
|
|
||||||
126
.github/workflows/release-cli-rs.yml
vendored
Normal file
126
.github/workflows/release-cli-rs.yml
vendored
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
name: cli-rs release
|
||||||
|
|
||||||
|
# Builds opencode-native, the Rust client in packages/cli-rs, natively on each runner below and keeps each archive as an
|
||||||
|
# artifact. A cli-rs-v<version> tag also publishes them as a GitHub release. It never becomes Latest: the monorepo's
|
||||||
|
# Latest release drives OpenCode's own update paths.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "cli-rs-v*"
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- .github/workflows/release-cli-rs.yml
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
# Zig links Linux against glibc 2.17, OpenTUI's floor. zig_sha is the archive's, from ziglang.org.
|
||||||
|
- runner: ubuntu-24.04
|
||||||
|
target: x86_64-unknown-linux-gnu
|
||||||
|
zig: x86_64-linux-gnu.2.17
|
||||||
|
zig_sha: 3581863e3cbcfd0fce0efc682ce7e9e93da96668a977791d356a26d2a7e9b17a
|
||||||
|
- runner: ubuntu-24.04-arm
|
||||||
|
target: aarch64-unknown-linux-gnu
|
||||||
|
zig: aarch64-linux-gnu.2.17
|
||||||
|
zig_sha: a1546d5646eb184437918d6635ca6b762a0e889eac09cef720ee7a1ed3fe7795
|
||||||
|
- { runner: macos-15-intel, target: x86_64-apple-darwin }
|
||||||
|
- { runner: macos-15, target: aarch64-apple-darwin }
|
||||||
|
- { runner: windows-2025, target: x86_64-pc-windows-msvc, exe: .exe }
|
||||||
|
runs-on: ${{ matrix.runner }}
|
||||||
|
timeout-minutes: 60
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
working-directory: packages/cli-rs
|
||||||
|
env:
|
||||||
|
OPENCODE_NATIVE_COMMIT: ${{ github.sha }}
|
||||||
|
CARGO_PROFILE_DIST_STRIP: symbols
|
||||||
|
MACOSX_DEPLOYMENT_TARGET: "13.0"
|
||||||
|
# No Visual C++ runtime to install beside the .exe.
|
||||||
|
CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS: -C target-feature=+crt-static
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||||
|
with:
|
||||||
|
bun-version-file: package.json
|
||||||
|
# The version opencode-native --version prints: the tag's, or 0.0.0-<commit> for any other run.
|
||||||
|
- name: Version
|
||||||
|
run: |
|
||||||
|
version=0.0.0-$GITHUB_SHA
|
||||||
|
if [[ $GITHUB_REF == refs/tags/cli-rs-v* ]]; then version=${GITHUB_REF_NAME#cli-rs-v}; fi
|
||||||
|
echo "OPENCODE_VERSION=$version" >> "$GITHUB_ENV"
|
||||||
|
# Zig 0.17.1 as the C and C++ compiler and the linker. The wrapper drops flags zig rejects: cc's --target, and
|
||||||
|
# rustc's Cortex-A53 erratum fix on aarch64.
|
||||||
|
- if: matrix.zig
|
||||||
|
working-directory: ${{ runner.temp }}
|
||||||
|
run: |
|
||||||
|
file=zig-$(uname -m)-linux-0.17.1
|
||||||
|
curl -fsSL --retry 3 -o zig.tar.xz "https://ziglang.org/download/0.17.1/$file.tar.xz"
|
||||||
|
echo "${{ matrix.zig_sha }} zig.tar.xz" | sha256sum -c
|
||||||
|
tar -xJf zig.tar.xz
|
||||||
|
for tool in cc c++; do
|
||||||
|
cat > "zig-$tool" <<EOF
|
||||||
|
#!/bin/sh
|
||||||
|
for a; do shift; case \$a in --target=*|-Wl,--fix-cortex-a53-843419) ;; *) set -- "\$@" "\$a" ;; esac; done
|
||||||
|
exec "$PWD/$file/zig" $tool -target ${{ matrix.zig }} "\$@"
|
||||||
|
EOF
|
||||||
|
chmod +x "zig-$tool"
|
||||||
|
done
|
||||||
|
triple=$(tr a-z- A-Z_ <<< "${{ matrix.target }}")
|
||||||
|
{ echo "CARGO_TARGET_${triple}_LINKER=$PWD/zig-cc"; echo "CC_${triple,,}=$PWD/zig-cc"
|
||||||
|
echo "CXX_${triple,,}=$PWD/zig-c++"; echo "CXXSTDLIB_${triple,,}=c++"; } >> "$GITHUB_ENV"
|
||||||
|
# rustup reads rust-toolchain.toml; `bun run cargo` first fetches OpenTUI's native library from its release.
|
||||||
|
- run: rustup toolchain install
|
||||||
|
- run: bun run cargo build --locked --profile dist --bin opencode-native
|
||||||
|
- name: Check glibc 2.17 and no libstdc++
|
||||||
|
if: matrix.zig
|
||||||
|
run: "! readelf -dV target/dist/opencode-native | grep -E 'GLIBC_2\\.(1[89]|[2-9][0-9])|libstdc\\+\\+'"
|
||||||
|
- name: Package
|
||||||
|
run: |
|
||||||
|
name=opencode-native-$OPENCODE_VERSION-${{ matrix.target }}
|
||||||
|
mkdir -p "dist/$name"
|
||||||
|
cp "target/dist/opencode-native${{ matrix.exe }}" "dist/$name/"
|
||||||
|
# Our licence, and OpenTUI's licences (FFmpeg's among them) from its native release zip.
|
||||||
|
cp ../../LICENSE "dist/$name/"
|
||||||
|
cp -r .opentui/*/host/licenses "dist/$name/"
|
||||||
|
tar -C dist -czf "dist/$name.tar.gz" "$name"
|
||||||
|
ls -l "dist/$name" "dist/$name.tar.gz"
|
||||||
|
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||||
|
with:
|
||||||
|
name: opencode-native-${{ matrix.target }}
|
||||||
|
path: packages/cli-rs/dist/*.tar.gz
|
||||||
|
if-no-files-found: error
|
||||||
|
compression-level: 0
|
||||||
|
|
||||||
|
release:
|
||||||
|
needs: build
|
||||||
|
if: startsWith(github.ref, 'refs/tags/cli-rs-v')
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||||
|
with:
|
||||||
|
pattern: opencode-native-*
|
||||||
|
merge-multiple: true
|
||||||
|
- name: Publish
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
sha256sum ./*.tar.gz > SHA256SUMS
|
||||||
|
gh release create "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" --verify-tag --latest=false \
|
||||||
|
--title "opencode-native ${GITHUB_REF_NAME#cli-rs-v}" --notes "The Rust client (packages/cli-rs) at $GITHUB_SHA." \
|
||||||
|
./*.tar.gz SHA256SUMS
|
||||||
37
.github/workflows/release-process-daemon.yml
vendored
37
.github/workflows/release-process-daemon.yml
vendored
|
|
@ -10,8 +10,10 @@ on:
|
||||||
- "process-daemon-v*"
|
- "process-daemon-v*"
|
||||||
pull_request:
|
pull_request:
|
||||||
paths:
|
paths:
|
||||||
|
- .github/actions/prefetch-ghostty/**
|
||||||
- .github/workflows/release-process-daemon.yml
|
- .github/workflows/release-process-daemon.yml
|
||||||
- packages/process-daemon/build.rs
|
- packages/process-daemon/build.rs
|
||||||
|
- packages/process-daemon/ghostty-revision
|
||||||
- packages/process-daemon/npm/**
|
- packages/process-daemon/npm/**
|
||||||
- packages/process-daemon/script/npm-packages.mjs
|
- packages/process-daemon/script/npm-packages.mjs
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
@ -39,6 +41,8 @@ jobs:
|
||||||
- uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5
|
- uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5
|
||||||
with:
|
with:
|
||||||
version: ${{ env.ZIG_VERSION }}
|
version: ${{ env.ZIG_VERSION }}
|
||||||
|
use-cache: false
|
||||||
|
- uses: ./.github/actions/prefetch-ghostty
|
||||||
- name: Configure baseline Zig builds
|
- name: Configure baseline Zig builds
|
||||||
run: |
|
run: |
|
||||||
chmod +x "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin/zig"
|
chmod +x "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin/zig"
|
||||||
|
|
@ -94,7 +98,8 @@ jobs:
|
||||||
- uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5
|
- uses: mlugg/setup-zig@8d6198c65fb0feaa111df26e6b467fea8345e46f # v2.0.5
|
||||||
with:
|
with:
|
||||||
version: ${{ env.ZIG_VERSION }}
|
version: ${{ env.ZIG_VERSION }}
|
||||||
cache-key: ${{ matrix.target }}
|
use-cache: false
|
||||||
|
- uses: ./.github/actions/prefetch-ghostty
|
||||||
- name: Configure baseline Zig builds
|
- name: Configure baseline Zig builds
|
||||||
run: |
|
run: |
|
||||||
chmod +x "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin/zig"
|
chmod +x "$GITHUB_WORKSPACE/packages/process-daemon/script/release-bin/zig"
|
||||||
|
|
@ -187,7 +192,7 @@ jobs:
|
||||||
if: matrix.arch == 'x64'
|
if: matrix.arch == 'x64'
|
||||||
with:
|
with:
|
||||||
version: ${{ env.ZIG_VERSION }}
|
version: ${{ env.ZIG_VERSION }}
|
||||||
cache-key: release-${{ matrix.target }}
|
use-cache: false
|
||||||
# Zig 0.16 crashes when building Ghostty on the native ARM64 host, so use
|
# Zig 0.16 crashes when building Ghostty on the native ARM64 host, so use
|
||||||
# the x64-hosted compiler there (matching check-process-daemon.yml).
|
# the x64-hosted compiler there (matching check-process-daemon.yml).
|
||||||
- name: Install x64 Zig for ARM64 cross-compilation
|
- name: Install x64 Zig for ARM64 cross-compilation
|
||||||
|
|
@ -206,8 +211,36 @@ jobs:
|
||||||
$old = '@ptrCast(try si.loadNtdllProc(@tagName(proc)))'
|
$old = '@ptrCast(try si.loadNtdllProc(@tagName(proc)))'
|
||||||
if (!$source.Contains($old)) { throw 'Zig alignment workaround no longer matches; re-evaluate it' }
|
if (!$source.Contains($old)) { throw 'Zig alignment workaround no longer matches; re-evaluate it' }
|
||||||
[System.IO.File]::WriteAllText($file, $source.Replace($old, '@ptrCast(@alignCast(try si.loadNtdllProc(@tagName(proc))))'))
|
[System.IO.File]::WriteAllText($file, $source.Replace($old, '@ptrCast(@alignCast(try si.loadNtdllProc(@tagName(proc))))'))
|
||||||
|
- name: Pin MSVC 14.51 for Zig's Clang 21
|
||||||
|
timeout-minutes: 20
|
||||||
|
run: |
|
||||||
|
$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer"
|
||||||
|
$vs = & "$installer\vswhere.exe" -latest -products * -property installationPath
|
||||||
|
$tools = "$vs\VC\Tools\MSVC"
|
||||||
|
$arch = '${{ matrix.arch }}'
|
||||||
|
$hasRuntimes = {
|
||||||
|
(Test-Path "$($_.FullName)\lib\x64\vcruntime.lib") -and
|
||||||
|
(Test-Path "$($_.FullName)\lib\$arch\vcruntime.lib")
|
||||||
|
}
|
||||||
|
if (!(Get-ChildItem $tools -Directory -Filter '14.51.*' | Where-Object $hasRuntimes)) {
|
||||||
|
$components = '--add Microsoft.VisualStudio.Component.VC.14.51.x86.x64'
|
||||||
|
if ($arch -eq 'arm64') { $components += ' --add Microsoft.VisualStudio.Component.VC.14.51.ARM64' }
|
||||||
|
$setup = Start-Process "$installer\setup.exe" -ArgumentList "modify --installPath `"$vs`" $components --quiet --norestart" -Wait -PassThru
|
||||||
|
if ($setup.ExitCode -notin 0, 3010) { throw "VS installer exited with $($setup.ExitCode)" }
|
||||||
|
Write-Output "MSVC 14.51 installer exited with $($setup.ExitCode) for $arch"
|
||||||
|
}
|
||||||
|
$toolset = Get-ChildItem $tools -Directory -Filter '14.51.*' |
|
||||||
|
Where-Object $hasRuntimes |
|
||||||
|
Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1
|
||||||
|
if (!$toolset) { throw "Missing MSVC 14.51 for $arch" }
|
||||||
|
# Zig reads this file for both host and target tools on the disposable runner.
|
||||||
|
Set-Content "$vs\VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt" $toolset.Name -Encoding ascii
|
||||||
|
$libc = zig libc
|
||||||
|
$libc
|
||||||
|
if ($LASTEXITCODE -ne 0 -or $libc -inotcontains "sys_include_dir=$($toolset.FullName)\include") { throw 'Zig selected unexpected MSVC headers' }
|
||||||
- name: Install Rust toolchain and target
|
- name: Install Rust toolchain and target
|
||||||
run: rustup toolchain install $env:RUSTUP_TOOLCHAIN --force-non-host --profile minimal --target $env:CARGO_BUILD_TARGET
|
run: rustup toolchain install $env:RUSTUP_TOOLCHAIN --force-non-host --profile minimal --target $env:CARGO_BUILD_TARGET
|
||||||
|
- uses: ./.github/actions/prefetch-ghostty
|
||||||
- name: Build
|
- name: Build
|
||||||
run: cargo build --locked --release
|
run: cargo build --locked --release
|
||||||
- name: Smoke test
|
- name: Smoke test
|
||||||
|
|
|
||||||
20
.github/workflows/triage-close-issues.yml
vendored
20
.github/workflows/triage-close-issues.yml
vendored
|
|
@ -2,8 +2,17 @@ name: triage-close-issues
|
||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: "0 2 * * *" # Daily at 2:00 AM
|
- cron: "0 2 * * *" # Daily at 2:00 AM UTC
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
dry-run:
|
||||||
|
description: "Log matching issues without closing them"
|
||||||
|
type: boolean
|
||||||
|
default: true
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: triage-close-issues
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
close:
|
close:
|
||||||
|
|
@ -18,7 +27,12 @@ jobs:
|
||||||
with:
|
with:
|
||||||
bun-version: latest
|
bun-version: latest
|
||||||
|
|
||||||
- name: Close stale issues
|
- name: Close stale waiting-for-info issues
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ github.token }}
|
GITHUB_TOKEN: ${{ github.token }}
|
||||||
run: bun script/github/close-issues.ts
|
run: |
|
||||||
|
args=()
|
||||||
|
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ "${{ inputs['dry-run'] }}" != "false" ]; then
|
||||||
|
args+=("--dry-run")
|
||||||
|
fi
|
||||||
|
bun script/github/close-issues.ts "${args[@]}"
|
||||||
|
|
|
||||||
397
.github/workflows/triage-close-linked.yml
vendored
Normal file
397
.github/workflows/triage-close-linked.yml
vendored
Normal file
|
|
@ -0,0 +1,397 @@
|
||||||
|
name: triage-close-linked
|
||||||
|
|
||||||
|
# Closes what GitHub native auto-close misses on merge into the default branch:
|
||||||
|
# - additional issues in lists ("Fixes #1, #2 and #3" -> closes #2 and #3; GitHub closes #1)
|
||||||
|
# - superseded pull requests ("Supersedes #4", "Replaces #5")
|
||||||
|
#
|
||||||
|
# Runs entirely against the GitHub API with no checkout, so pull_request_target is safe.
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [closed]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
pr_number:
|
||||||
|
description: "Merged PR whose description to read"
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
dry_run:
|
||||||
|
description: "Log targets without closing them"
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
close-linked:
|
||||||
|
if: >
|
||||||
|
github.repository == 'anomalyco/opencode' &&
|
||||||
|
(github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 10
|
||||||
|
permissions:
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
|
steps:
|
||||||
|
- name: Close linked issues and superseded PRs
|
||||||
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const ISSUE_KEYWORDS = new Set([
|
||||||
|
"close", "closes", "closed",
|
||||||
|
"fix", "fixes", "fixed",
|
||||||
|
"resolve", "resolves", "resolved",
|
||||||
|
]);
|
||||||
|
const PR_KEYWORDS = new Set([
|
||||||
|
"supersede", "supersedes", "superseded",
|
||||||
|
"replace", "replaces", "replaced",
|
||||||
|
]);
|
||||||
|
const KEYWORDS = new Set([...ISSUE_KEYWORDS, ...PR_KEYWORDS]);
|
||||||
|
const HEDGES = new Set([
|
||||||
|
"may", "might", "could", "would", "possibly", "probably", "potentially",
|
||||||
|
"maybe", "perhaps", "hopefully", "likely", "unlikely", "partially", "partly", "partial",
|
||||||
|
]);
|
||||||
|
const SUBORDINATORS = new Set(["if", "whether", "when", "whenever", "once", "until", "unless", "before", "after"]);
|
||||||
|
const DISQUALIFIERS = new Set([
|
||||||
|
"not", "never", "neither", "nor", "without", "cannot", "can't", "doesn't", "don't",
|
||||||
|
"won't", "didn't", "isn't", "wasn't", "hasn't", "haven't", "hadn't", "wouldn't",
|
||||||
|
"couldn't", "shouldn't", "mightn't", "mustn't",
|
||||||
|
...HEDGES,
|
||||||
|
...SUBORDINATORS,
|
||||||
|
"the", "a", "an", "of", "on", "in", "by", "from", "with", "for", "than",
|
||||||
|
]);
|
||||||
|
const BASE_FORMS = new Set(["close", "fix", "resolve", "supersede", "replace"]);
|
||||||
|
const VERB_MARKERS = new Set(["does", "do", "did", "and"]);
|
||||||
|
const DETERMINERS = new Set(["this", "that", "the", "a", "an"]);
|
||||||
|
const INTERVENING = new Set([
|
||||||
|
"also", "fully", "completely", "entirely", "actually", "really", "yet", "directly", "properly",
|
||||||
|
"have", "has", "had",
|
||||||
|
]);
|
||||||
|
const MAX_TARGETS = 10;
|
||||||
|
|
||||||
|
function stripNonProse(body) {
|
||||||
|
const lines = body.replaceAll("\r\n", "\n").split("\n");
|
||||||
|
const kept = [];
|
||||||
|
let fence = null;
|
||||||
|
let inComment = false;
|
||||||
|
let paragraph = false;
|
||||||
|
for (const line of lines) {
|
||||||
|
if (inComment) {
|
||||||
|
const end = line.indexOf("-->");
|
||||||
|
if (end === -1) { kept.push(""); continue; }
|
||||||
|
inComment = false;
|
||||||
|
kept.push(line.slice(end + 3));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (fence !== null) {
|
||||||
|
if (trimmed.startsWith(fence) && [...trimmed].every(c => c === fence[0])) fence = null;
|
||||||
|
paragraph = false;
|
||||||
|
kept.push("");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (trimmed === "") { paragraph = false; kept.push(""); continue; }
|
||||||
|
// Skip 4-space or tab indented code blocks outside a paragraph.
|
||||||
|
if (!paragraph && (/^ {4}/.test(line) || line.startsWith("\t"))) {
|
||||||
|
kept.push("");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fenceMatch = /^(`{3,}|~{3,})/.exec(trimmed);
|
||||||
|
if (fenceMatch && (fenceMatch[1][0] === "~" || !trimmed.slice(fenceMatch[1].length).includes("`"))) {
|
||||||
|
fence = fenceMatch[1];
|
||||||
|
paragraph = false;
|
||||||
|
kept.push("");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (trimmed.startsWith(">")) { paragraph = false; kept.push(""); continue; }
|
||||||
|
// Skip markdown task list items like "- [ ] Fix #99".
|
||||||
|
if (/^[-*+]\s+\[[ xX]\]/.test(trimmed)) { paragraph = false; kept.push(""); continue; }
|
||||||
|
// Strip inline code spans BEFORE HTML comments so `<!--` in backticks is not a comment.
|
||||||
|
let cleaned = line.replace(/`[^`\n]+`/g, " code ");
|
||||||
|
while (cleaned.includes("<!--")) {
|
||||||
|
const start = cleaned.indexOf("<!--");
|
||||||
|
const end = cleaned.indexOf("-->", start + 4);
|
||||||
|
if (end === -1) {
|
||||||
|
cleaned = cleaned.slice(0, start);
|
||||||
|
inComment = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cleaned = cleaned.slice(0, start) + " " + cleaned.slice(end + 3);
|
||||||
|
}
|
||||||
|
paragraph = !/^#{1,6}\s/.test(trimmed);
|
||||||
|
kept.push(cleaned);
|
||||||
|
}
|
||||||
|
let text = kept.join("\n");
|
||||||
|
text = text.replace(/~~[^~\n]+~~/g, " ");
|
||||||
|
text = text.replace(/<(?:s|del|strike)\b[^>]*>[\s\S]*?<\/(?:s|del|strike)>/gi, " ");
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenize(text) {
|
||||||
|
const tokens = [];
|
||||||
|
let i = 0;
|
||||||
|
while (i < text.length) {
|
||||||
|
const c = text[i];
|
||||||
|
if (c === "\n") {
|
||||||
|
if (tokens.at(-1)?.kind === "newline") tokens[tokens.length - 1] = { kind: "break" };
|
||||||
|
else if (tokens.at(-1)?.kind !== "break") tokens.push({ kind: "newline" });
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c.trim() === "") { i++; continue; }
|
||||||
|
const urlMatch = /^https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/(?:issues|pull)\/(\d+)(?![\w])/i.exec(text.slice(i));
|
||||||
|
if (urlMatch) {
|
||||||
|
tokens.push({ kind: "ref", repository: urlMatch[1].toLowerCase(), number: Number(urlMatch[2]) });
|
||||||
|
i += urlMatch[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const repoRefMatch = /^([\w.-]+\/[\w.-]+)#(\d+)(?![\w'\u2019])/.exec(text.slice(i));
|
||||||
|
if (repoRefMatch) {
|
||||||
|
tokens.push({ kind: "ref", repository: repoRefMatch[1].toLowerCase(), number: Number(repoRefMatch[2]) });
|
||||||
|
i += repoRefMatch[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const bareRefMatch = /^#(\d+)(?![\w'\u2019])/.exec(text.slice(i));
|
||||||
|
if (bareRefMatch) {
|
||||||
|
tokens.push({ kind: "ref", repository: null, number: Number(bareRefMatch[1]) });
|
||||||
|
i += bareRefMatch[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const wordMatch = /^[A-Za-z][A-Za-z0-9'\u2019-]*/.exec(text.slice(i));
|
||||||
|
if (wordMatch) {
|
||||||
|
tokens.push({ kind: "word", text: wordMatch[0].toLowerCase().replaceAll("\u2019", "'") });
|
||||||
|
i += wordMatch[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
tokens.push({ kind: "punct", text: c });
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPunct = (t, s) => t?.kind === "punct" && t.text === s;
|
||||||
|
const isWord = (t, s) => t?.kind === "word" && t.text === s;
|
||||||
|
const skipEmph = (tokens, i) => { while (isPunct(tokens[i], "*") || isPunct(tokens[i], "_")) i++; return i; };
|
||||||
|
const skipEmphBack = (tokens, i) => { while (i >= 0 && (isPunct(tokens[i], "*") || isPunct(tokens[i], "_"))) i--; return i; };
|
||||||
|
const skipInterveningBack = (tokens, i) => {
|
||||||
|
for (;;) {
|
||||||
|
i = skipEmphBack(tokens, i);
|
||||||
|
if (i < 0 || tokens[i].kind !== "word" || !INTERVENING.has(tokens[i].text)) return i;
|
||||||
|
i--;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const endsWithRef = (tokens, k) => {
|
||||||
|
const p = skipEmphBack(tokens, k);
|
||||||
|
const t = tokens[p];
|
||||||
|
if (!t) return false;
|
||||||
|
if (t.kind === "ref") return true;
|
||||||
|
if (isPunct(t, ">")) return tokens[p - 1]?.kind === "ref" && isPunct(tokens[p - 2], "<");
|
||||||
|
if (isPunct(t, ")")) {
|
||||||
|
if (tokens[p - 1]?.kind === "ref" && isPunct(tokens[p - 2], "(")) return true;
|
||||||
|
if (isPunct(tokens[p - 2], "(") && isPunct(tokens[p - 3], "]")) return tokens[p - 4]?.kind === "ref" && isPunct(tokens[p - 5], "[");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// A continuation reference must terminate cleanly (end of text/line/clause or list separator),
|
||||||
|
// so "Fixes #12, #13 is tracked separately" does NOT close #13.
|
||||||
|
const endsCleanly = (tokens, j) => {
|
||||||
|
const next = tokens[skipEmph(tokens, j)];
|
||||||
|
if (!next || next.kind === "newline" || next.kind === "break") return true;
|
||||||
|
if (next.kind === "punct" && ".,;:)&".includes(next.text)) return true;
|
||||||
|
if (isWord(next, "and")) return true;
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
function isClosingStatement(tokens, index, keyword) {
|
||||||
|
let k = skipInterveningBack(tokens, index - 1);
|
||||||
|
// Skip parenthetical / dash / colon lead-ins from a reference ("Reverts #100 (fixes #99)", "TODO: fix #99").
|
||||||
|
if (isPunct(tokens[k], ":") && tokens[k - 1]?.kind === "word" && ["todo", "note", "fyi"].includes(tokens[k - 1].text)) return false;
|
||||||
|
if (tokens[k]?.kind === "punct" && "(—–-".includes(tokens[k].text)) {
|
||||||
|
let q = skipInterveningBack(tokens, k - 1);
|
||||||
|
while (tokens[q]?.kind === "punct" && "-—–".includes(tokens[q].text)) q = skipInterveningBack(tokens, q - 1);
|
||||||
|
if (endsWithRef(tokens, q)) return false;
|
||||||
|
}
|
||||||
|
if (endsWithRef(tokens, k)) return false;
|
||||||
|
const lineStart = tokens[k]?.kind === "newline" || tokens[k]?.kind === "break" || k < 0;
|
||||||
|
if (tokens[k]?.kind === "newline") {
|
||||||
|
const e = skipEmphBack(tokens, k - 1);
|
||||||
|
const w = skipInterveningBack(tokens, e);
|
||||||
|
if (w < e && endsWithRef(tokens, w)) return false;
|
||||||
|
k = w;
|
||||||
|
}
|
||||||
|
const before = tokens[k];
|
||||||
|
if (!before || before.kind !== "word") return true;
|
||||||
|
if (before.text === "which" || before.text === "that") {
|
||||||
|
let p = skipInterveningBack(tokens, k - 1);
|
||||||
|
while (tokens[p]?.kind === "newline" || (tokens[p]?.kind === "punct" && ",(;:-\u2013\u2014".includes(tokens[p].text))) {
|
||||||
|
p = skipInterveningBack(tokens, p - 1);
|
||||||
|
}
|
||||||
|
if (endsWithRef(tokens, p)) return false;
|
||||||
|
}
|
||||||
|
if (DISQUALIFIERS.has(before.text)) return false;
|
||||||
|
let p = skipInterveningBack(tokens, k - 1);
|
||||||
|
if (tokens[p]?.kind === "newline") p = skipInterveningBack(tokens, p - 1);
|
||||||
|
if (tokens[p]?.kind === "word" && DETERMINERS.has(tokens[p].text)) {
|
||||||
|
p = skipInterveningBack(tokens, p - 1);
|
||||||
|
if (tokens[p]?.kind === "newline") p = skipInterveningBack(tokens, p - 1);
|
||||||
|
}
|
||||||
|
if (isPunct(tokens[p], ",")) p = skipInterveningBack(tokens, p - 1);
|
||||||
|
if (tokens[p]?.kind === "word" && (SUBORDINATORS.has(tokens[p].text) || HEDGES.has(tokens[p].text))) return false;
|
||||||
|
if (!BASE_FORMS.has(keyword)) return true;
|
||||||
|
return lineStart ? before.text !== "to" : VERB_MARKERS.has(before.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRef(tokens, index) {
|
||||||
|
index = skipEmph(tokens, index);
|
||||||
|
const t = tokens[index];
|
||||||
|
if (!t) return null;
|
||||||
|
if (t.kind === "ref") return { token: t, end: index + 1 };
|
||||||
|
if (isPunct(t, "<") && tokens[index + 1]?.kind === "ref" && isPunct(tokens[index + 2], ">")) {
|
||||||
|
return { token: tokens[index + 1], end: index + 3 };
|
||||||
|
}
|
||||||
|
if (isPunct(t, "[")) {
|
||||||
|
let close = index + 1;
|
||||||
|
while (close < tokens.length && close < index + 10 && !isPunct(tokens[close], "]")) {
|
||||||
|
if (tokens[close].kind === "newline" || tokens[close].kind === "break") return null;
|
||||||
|
close++;
|
||||||
|
}
|
||||||
|
if (isPunct(tokens[close], "]") && isPunct(tokens[close + 1], "(") && isPunct(tokens[close + 3], ")")) {
|
||||||
|
if (tokens[close + 2]?.kind === "ref") return { token: tokens[close + 2], end: close + 4 };
|
||||||
|
if (close === index + 2 && tokens[index + 1]?.kind === "ref") return { token: tokens[index + 1], end: close + 4 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findLinkedReferences(body, repository) {
|
||||||
|
const self = repository.toLowerCase();
|
||||||
|
const tokens = tokenize(stripNonProse(body));
|
||||||
|
const found = [];
|
||||||
|
let i = 0;
|
||||||
|
while (i < tokens.length) {
|
||||||
|
const token = tokens[i];
|
||||||
|
if (token.kind !== "word" || !KEYWORDS.has(token.text) || !isClosingStatement(tokens, i, token.text)) {
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const targetKind = PR_KEYWORDS.has(token.text) ? "pull" : "issue";
|
||||||
|
let j = i + 1;
|
||||||
|
if (isPunct(tokens[j], ":")) j++;
|
||||||
|
let ref = readRef(tokens, j);
|
||||||
|
if (!ref) { i++; continue; }
|
||||||
|
let pos = 0;
|
||||||
|
for (;;) {
|
||||||
|
// For issue keywords, GitHub natively closes pos === 0 when bare #N/URL/owner/repo#N.
|
||||||
|
// Still emit pos === 0 only for markdown-link/PR keywords, or list continuations (pos > 0),
|
||||||
|
// avoiding racing GitHub native auto-close.
|
||||||
|
const nativeClose = targetKind === "issue" && pos === 0 && tokens[skipEmph(tokens, j)]?.kind === "ref";
|
||||||
|
if (!nativeClose && (pos === 0 || endsCleanly(tokens, ref.end))) {
|
||||||
|
found.push({ repository: ref.token.repository ?? self, number: ref.token.number, keyword: token.text, targetKind });
|
||||||
|
}
|
||||||
|
j = ref.end;
|
||||||
|
pos++;
|
||||||
|
let k = skipEmph(tokens, j);
|
||||||
|
let sep = false;
|
||||||
|
if (isPunct(tokens[k], ",")) { k++; sep = true; }
|
||||||
|
if (isWord(tokens[k], "and") || isPunct(tokens[k], "&")) { k++; sep = true; }
|
||||||
|
if (!sep) break;
|
||||||
|
ref = readRef(tokens, k);
|
||||||
|
if (!ref) break;
|
||||||
|
if (!endsCleanly(tokens, ref.end)) break;
|
||||||
|
}
|
||||||
|
i = j;
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { owner, repo } = context.repo;
|
||||||
|
const repository = `${owner}/${repo}`;
|
||||||
|
const expectedRepoUrl = `https://api.github.com/repos/${repository.toLowerCase()}`;
|
||||||
|
const inputs = context.payload.inputs ?? {};
|
||||||
|
const event = context.payload.pull_request;
|
||||||
|
const prNumber = event?.number ?? Number(inputs.pr_number);
|
||||||
|
const dryRun = String(inputs.dry_run ?? "false") === "true";
|
||||||
|
|
||||||
|
if (!Number.isInteger(prNumber) || prNumber <= 0) {
|
||||||
|
core.setFailed(`Invalid pull request number: ${inputs.pr_number}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });
|
||||||
|
if (!pr.merged) {
|
||||||
|
core.info(`#${prNumber}: not merged, skipping`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const defaultBranch = pr.base.repo.default_branch;
|
||||||
|
if (pr.base.ref !== defaultBranch) {
|
||||||
|
core.info(`#${prNumber}: merged into ${pr.base.ref}, not ${defaultBranch}, skipping`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prAuthor = pr.user?.login?.toLowerCase();
|
||||||
|
const trustedAuthor = ["OWNER", "MEMBER"].includes(pr.author_association);
|
||||||
|
const body = (event ? event.body : pr.body) ?? "";
|
||||||
|
const seen = new Set();
|
||||||
|
const targets = [];
|
||||||
|
for (const ref of findLinkedReferences(body, repository)) {
|
||||||
|
if (ref.repository !== repository.toLowerCase()) continue;
|
||||||
|
if (ref.number === prNumber || seen.has(ref.number)) continue;
|
||||||
|
seen.add(ref.number);
|
||||||
|
targets.push(ref);
|
||||||
|
}
|
||||||
|
if (targets.length === 0) {
|
||||||
|
core.info(`#${prNumber}: no additional linked references to close`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (targets.length > MAX_TARGETS) {
|
||||||
|
core.warning(`#${prNumber}: found ${targets.length} references (cap ${MAX_TARGETS}); refusing bulk close`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
for (const ref of targets) {
|
||||||
|
let item;
|
||||||
|
try {
|
||||||
|
({ data: item } = await github.rest.issues.get({ owner, repo, issue_number: ref.number }));
|
||||||
|
} catch (error) {
|
||||||
|
if (error.status === 404 || error.status === 410) continue;
|
||||||
|
failed++;
|
||||||
|
core.error(`#${ref.number}: ${error.message}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (item.repository_url && item.repository_url.toLowerCase() !== expectedRepoUrl) continue;
|
||||||
|
if (item.state !== "open") continue;
|
||||||
|
const isPull = item.pull_request !== undefined;
|
||||||
|
// Only close issues for close/fix/resolve, and only close PRs for supersede/replace.
|
||||||
|
if (ref.targetKind === "issue" && isPull) continue;
|
||||||
|
if (ref.targetKind === "pull" && !isPull) continue;
|
||||||
|
// Only allow an outside contributor PR to supersede their own PR.
|
||||||
|
if (isPull && !trustedAuthor && item.user?.login?.toLowerCase() !== prAuthor) {
|
||||||
|
core.info(`#${ref.number}: skipping supersede of another contributor PR by non-member`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (dryRun) {
|
||||||
|
core.info(`[dry-run] Would close ${isPull ? "PR" : "issue"} #${ref.number} (${ref.keyword} in #${prNumber})`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (isPull) {
|
||||||
|
await github.rest.pulls.update({ owner, repo, pull_number: ref.number, state: "closed" });
|
||||||
|
} else {
|
||||||
|
await github.rest.issues.update({ owner, repo, issue_number: ref.number, state: "closed", state_reason: "completed" });
|
||||||
|
}
|
||||||
|
await github.rest.issues.createComment({
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
issue_number: ref.number,
|
||||||
|
body: isPull ? `Superseded by #${prNumber}.` : `Closed as completed by #${prNumber}.`,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
failed++;
|
||||||
|
core.error(`#${ref.number}: ${error.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (failed > 0) core.setFailed(`${failed} of ${targets.length} references could not be closed`);
|
||||||
90
.github/workflows/triage-slop.yml
vendored
Normal file
90
.github/workflows/triage-slop.yml
vendored
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
name: triage-slop
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request_target:
|
||||||
|
types: [labeled]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
close-slop:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: >
|
||||||
|
github.event.label.name == 'slop' &&
|
||||||
|
github.repository == 'anomalyco/opencode' &&
|
||||||
|
github.event.pull_request.state == 'open'
|
||||||
|
timeout-minutes: 5
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
|
steps:
|
||||||
|
- name: Close, scrub, and comment on AI slop PR
|
||||||
|
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||||
|
with:
|
||||||
|
script: |
|
||||||
|
const pr = context.payload.pull_request;
|
||||||
|
const pullNumber = pr.number;
|
||||||
|
const login = pr.user?.login?.toLowerCase();
|
||||||
|
|
||||||
|
// Never touch merged/closed PRs, bots, or team members.
|
||||||
|
if (pr.state !== "open" || pr.merged) return;
|
||||||
|
if (pr.user?.type === "Bot" || ["OWNER", "MEMBER"].includes(pr.author_association)) {
|
||||||
|
core.info(`Skipping #${pullNumber}: author ${pr.user?.login} is exempt`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { data: file } = await github.rest.repos.getContent({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
path: ".github/TEAM_MEMBERS",
|
||||||
|
ref: "dev",
|
||||||
|
});
|
||||||
|
const members = new Set(
|
||||||
|
Buffer.from(file.content, "base64").toString("utf8").split("\n").map((l) => l.trim().toLowerCase()).filter(Boolean),
|
||||||
|
);
|
||||||
|
if (login && members.has(login)) {
|
||||||
|
core.info(`Skipping #${pullNumber}: author ${pr.user?.login} is in TEAM_MEMBERS`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
core.warning(`Could not read TEAM_MEMBERS: ${error.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close and scrub first so a failed update never leaves a misleading closed comment.
|
||||||
|
await github.rest.pulls.update({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
pull_number: pullNumber,
|
||||||
|
title: 'ai slop',
|
||||||
|
body: 'This pull request was closed as AI slop and its title/description were cleared to avoid misleading reviewers. If you believe this was closed in error, leave a comment explaining why.',
|
||||||
|
state: 'closed',
|
||||||
|
});
|
||||||
|
|
||||||
|
const marker = "<!-- triage-slop -->";
|
||||||
|
const { data: comments } = await github.rest.issues.listComments({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
issue_number: pullNumber,
|
||||||
|
per_page: 100,
|
||||||
|
});
|
||||||
|
if (comments.some((c) => (c.body || "").includes(marker))) return;
|
||||||
|
|
||||||
|
await github.rest.issues.createComment({
|
||||||
|
owner: context.repo.owner,
|
||||||
|
repo: context.repo.repo,
|
||||||
|
issue_number: pullNumber,
|
||||||
|
body: [
|
||||||
|
marker,
|
||||||
|
'This pull request has been closed because it was flagged as low-quality AI slop.',
|
||||||
|
'',
|
||||||
|
'Common reasons include:',
|
||||||
|
'- Failing to verify the underlying problem exists',
|
||||||
|
'- Failing to test that the change actually fixes it',
|
||||||
|
'- Making unverified assumptions about the codebase or adding speculative/misleading changes',
|
||||||
|
'',
|
||||||
|
'If you believe this was closed in error, leave a comment explaining how you reproduced and verified the change.',
|
||||||
|
].join('\n'),
|
||||||
|
});
|
||||||
|
|
@ -13,12 +13,12 @@ Requirements:
|
||||||
- Preserve meaning, intent, tone, and formatting (including Markdown/MDX structure).
|
- Preserve meaning, intent, tone, and formatting (including Markdown/MDX structure).
|
||||||
- Preserve all technical terms and artifacts exactly: product/company names, API names, identifiers, code, commands/flags, file paths, URLs, versions, error messages, config keys/values, and anything inside inline code or code blocks.
|
- Preserve all technical terms and artifacts exactly: product/company names, API names, identifiers, code, commands/flags, file paths, URLs, versions, error messages, config keys/values, and anything inside inline code or code blocks.
|
||||||
- Also preserve every term listed in the Do-Not-Translate glossary below.
|
- Also preserve every term listed in the Do-Not-Translate glossary below.
|
||||||
- Also apply locale-specific guidance from `.opencode/glossary/<locale>.md` when available (for example, `zh-cn.md`).
|
- Also apply the matching locale file when available: `.opencode/glossary/<locale>.md` for the marketing site, `services/site/src/docs/i18n/glossary/<locale>.md` for the docs (for example, `zh-cn.md` and `zh.md`).
|
||||||
- Do not modify fenced code blocks.
|
- Do not modify fenced code blocks.
|
||||||
- Output ONLY the translation (no commentary).
|
- Output ONLY the translation (no commentary).
|
||||||
|
|
||||||
If the target locale is missing, ask the user to provide it.
|
If the target locale is missing, ask the user to provide it.
|
||||||
If no locale-specific glossary exists, use the global glossary only.
|
If no locale-specific glossary exists, use the shared glossary only.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -35,6 +35,31 @@ When translating the marketing site (`services/site/src/i18n/<locale>.ts` and `s
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
# V2 Docs Pages (opencode.ai/docs)
|
||||||
|
|
||||||
|
When translating a page of the latest docs (`services/site/src/docs/content`):
|
||||||
|
|
||||||
|
- Translate the English page at `src/docs/content/<same path>.mdx` into `src/docs/content/<locale>/<same path>.mdx`, using the site's language folder (`zh`, `zht`, `ko`, `de`, `es`, `fr`, `it`, `da`, `ja`, `pl`, `ru`, `uk`, `ar`, `no`, `br`, `th`, `tr`). English stays at the root.
|
||||||
|
- Translate the frontmatter's `title` and `description`; keep every other key and value as written.
|
||||||
|
- Keep the English heading structure: the same headings, in the same order and depth. Translated pages reuse the English heading ids, so `#anchors` keep working in every language. A translation whose heading depths differ is treated as stale: the build warns, the page shows the English fallback, and `check-translations.ts` lists it. If the English page gains a heading, update the translation's headings in the same place.
|
||||||
|
- Never call OpenCode an "AI coding agent": it is an "open source coding agent" in every language. Do not add "AI" to that phrase; "AI models" and "AI providers" are fine.
|
||||||
|
- Keep every MDX component, prop, code block, inline code span, path, URL, command, flag, config key and product name exactly as written. Translate only prose, table headers and code-block captions.
|
||||||
|
- Keep internal links docs-root-relative (`/config`): the site adds the page's language prefix. Do not write `/docs/...`, `/<locale>/docs/...` or `https://opencode.ai/docs/...`.
|
||||||
|
- A page you do not translate is served in English under that language's chrome, with a notice, so partial translations are safe.
|
||||||
|
- From `services/site`, run `bun src/docs/script/check-translations.ts <locale>` to list missing pages and pages whose English changed since their stamp, then run it with `--stamp` once the language is up to date. Stamps live in `src/docs/i18n/stamps/<locale>.json`.
|
||||||
|
|
||||||
|
## Review before shipping a language
|
||||||
|
|
||||||
|
- Compare every page paragraph by paragraph, list item, table row and code block against the CURRENT English page, not an older translation, and re-read pages whose English changed since their stamp.
|
||||||
|
- Read the result as native prose: remove translationese and literal calques, and keep the tone of the English page.
|
||||||
|
- Check numbers, prices, model IDs and version numbers against the English.
|
||||||
|
- Keep proper nouns, identifiers and code exactly as written, per the shared rules in `src/docs/i18n/glossary.md`.
|
||||||
|
- Keep the English heading order, depth and count; anchors depend on it.
|
||||||
|
- Apply the shared rules in `src/docs/i18n/glossary.md` and the language's terms in `src/docs/i18n/glossary/<locale>.md`.
|
||||||
|
- Spot-check two or three rendered pages in the built site: title, sidebar and code blocks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
# Locale-Specific Glossaries
|
# Locale-Specific Glossaries
|
||||||
|
|
||||||
When a locale glossary exists, use it to:
|
When a locale glossary exists, use it to:
|
||||||
|
|
|
||||||
43
.opencode/glossary/uk.md
Normal file
43
.opencode/glossary/uk.md
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
# uk Glossary
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
- Review of the desktop app's Ukrainian UI copy
|
||||||
|
|
||||||
|
## Do Not Translate (Locale Additions)
|
||||||
|
|
||||||
|
- `OpenCode` (preserve casing in prose; keep `opencode` only in commands, package names, paths, or code)
|
||||||
|
- `OpenCode CLI`
|
||||||
|
- `CLI`, `TUI`, `MCP`, `LSP`, `OAuth` (never transliterate them as `МКП` or `ЛСП`)
|
||||||
|
- Commands, flags, file paths, and code literals (keep exactly as written)
|
||||||
|
|
||||||
|
## Preferred Terms
|
||||||
|
|
||||||
|
| English | Preferred | Notes |
|
||||||
|
| ------------------------------------------------ | ------------------------------ | --------------------------------------------------------------------------- |
|
||||||
|
| session | сесія | Not `сеанс` |
|
||||||
|
| project | проєкт | 2019 orthography, not `проект` |
|
||||||
|
| worktree | робоче дерево | Not `робоча область` or `робоче місце` |
|
||||||
|
| Experimental (settings tab) | Експериментальні функції | Not the bare adjective `Експериментальний` |
|
||||||
|
| shell (tool, activity category, mode) | Термінал | `Використано: Читання, Запис, Термінал`; `режим термінала` |
|
||||||
|
| shell (a running command or process) | команда | `3 команди`, `запущено 2 команди`, `Очікування команди`, `Зупинити команду` |
|
||||||
|
| shell command | команда термінала | `Введіть команду термінала…` |
|
||||||
|
| shell (bash, zsh, PowerShell chosen in settings) | оболонка | Only where the user picks the shell program itself |
|
||||||
|
| terminal (genitive) | термінала | Not `терміналу` |
|
||||||
|
| About (settings tab) | Про OpenCode | Not a bare `Про` |
|
||||||
|
| third-party notices | ліцензії сторонніх компонентів | Not `повідомлення третіх сторін` |
|
||||||
|
| Released under the MIT License | Поширюється за ліцензією MIT | |
|
||||||
|
|
||||||
|
## Guidance
|
||||||
|
|
||||||
|
- Prefer natural Ukrainian phrasing over literal translation
|
||||||
|
- Keep tone clear and direct in UI labels and docs prose
|
||||||
|
- Fill every plural form the locale uses: `.one`, `.few`, `.many`, `.other`
|
||||||
|
- Keep the English punctuation of short taglines when it reads naturally (for example `OpenCode, агент кодування з відкритим кодом`)
|
||||||
|
- Preserve technical artifacts exactly: commands, flags, code, URLs, model IDs, and file paths
|
||||||
|
|
||||||
|
## Avoid
|
||||||
|
|
||||||
|
- Avoid `оболонка` for shell activity, counts, and tool labels; it reads as jargon next to `Читання` and `Запис`
|
||||||
|
- Avoid translating product and protocol names that are fixed identifiers
|
||||||
|
- Avoid mixing multiple Ukrainian terms for the same recurring UI action once a preferred term is established
|
||||||
69
.opencode/glossary/vi.md
Normal file
69
.opencode/glossary/vi.md
Normal file
|
|
@ -0,0 +1,69 @@
|
||||||
|
# vi Glossary
|
||||||
|
|
||||||
|
## Sources
|
||||||
|
|
||||||
|
- PR #55925: https://github.com/anomalyco/opencode/pull/55925 (terminology fixes in this file)
|
||||||
|
- PR #55922: https://github.com/anomalyco/opencode/pull/55922 (Vietnamese Console locale)
|
||||||
|
- Existing Vietnamese copy on dev: `packages/app/src/runtime/i18n/vi.ts`, `packages/ui/src/i18n/vi.ts`, `README.vi.md`
|
||||||
|
|
||||||
|
## Do Not Translate (Locale Additions)
|
||||||
|
|
||||||
|
- `OpenCode` (preserve casing in prose; keep `opencode` only in commands, package names, paths, or code)
|
||||||
|
- `Zen`, `Go`, `Go Plus`, `Black`, `Enterprise`, `Models.dev`
|
||||||
|
- `TUI`, `LSP`, `LLM`, `API`, `CLI`, `MCP`, `SSO`, `SDK`, `IDE`, `SSE`, `ZDR`, `MIT License`
|
||||||
|
- `terminal`, `desktop`, `web`, `shell`
|
||||||
|
- Plan names such as `Black 20`, `Black 100`, `Black 200`
|
||||||
|
- Commands, flags, file paths, and code literals (keep exactly as written)
|
||||||
|
|
||||||
|
## Preferred Terms
|
||||||
|
|
||||||
|
| English | Preferred | Notes |
|
||||||
|
| -------------------------- | --------------------- | -------------------------------------------------------- |
|
||||||
|
| coding agent (the product) | `trợ lý lập trình AI` | Matches the tagline already used in `README.vi.md` |
|
||||||
|
| agent (an instance) | `tác nhân` | Used in app UI copy; keep consistent with `packages/app` |
|
||||||
|
| session | `phiên` | Matches `packages/app/src/runtime/i18n/vi.ts` |
|
||||||
|
| file | `tệp` | `tệp đính kèm` for attachment |
|
||||||
|
| provider | `nhà cung cấp` | |
|
||||||
|
| model | `mô hình` | |
|
||||||
|
| docs | `tài liệu` | |
|
||||||
|
| download | `tải về` | |
|
||||||
|
| sign in / log in | `đăng nhập` | |
|
||||||
|
| sign up | `đăng ký` | |
|
||||||
|
| subscribe | `đăng ký` | Prefer `đăng ký gói ...` for plans |
|
||||||
|
| cancel | `hủy` | |
|
||||||
|
| privacy | `quyền riêng tư` | |
|
||||||
|
| settings | `cài đặt` | |
|
||||||
|
| usage limits | `hạn mức sử dụng` | |
|
||||||
|
| top up (balance/credit) | `nạp thêm` | `nạp thêm số dư` / `nạp thêm tín dụng` |
|
||||||
|
| refund | `hoàn tiền` | |
|
||||||
|
| waitlist | `danh sách chờ` | |
|
||||||
|
| server | `máy chủ` | |
|
||||||
|
| workspace | `không gian làm việc` | |
|
||||||
|
| brand | `thương hiệu` | |
|
||||||
|
| changelog | `nhật ký thay đổi` | |
|
||||||
|
| local models | `mô hình chạy cục bộ` | |
|
||||||
|
| prompt | `lời nhắc` | |
|
||||||
|
| token | `token` | Keep in English; do not use `mã thông báo` |
|
||||||
|
| skill | `kỹ năng` | Matches the app UI label for the skills tab |
|
||||||
|
| plugin | `tiện ích mở rộng` | Matches the app UI label for extensions |
|
||||||
|
| command | `lệnh` | |
|
||||||
|
| theme | `giao diện` | |
|
||||||
|
| formatter | `trình định dạng` | |
|
||||||
|
| compaction | `nén` | |
|
||||||
|
| attachment | `tệp đính kèm` | |
|
||||||
|
| data | `dữ liệu` | |
|
||||||
|
|
||||||
|
## Guidance
|
||||||
|
|
||||||
|
- Prefer natural Vietnamese phrasing over literal translation; short labels stay short
|
||||||
|
- Keep language names static/native in language pickers: always `Tiếng Việt`, never a translated form
|
||||||
|
- Keep `$` amounts in the original currency notation and numbers, e.g. `$10/month`
|
||||||
|
- Vietnamese has no grammatical plural, so `*_one` and `*_other` strings may be identical
|
||||||
|
- Write dates and numbers with the Latin digits used elsewhere in the UI
|
||||||
|
|
||||||
|
## Avoid
|
||||||
|
|
||||||
|
- Avoid translating language names differently per current locale in language lists
|
||||||
|
- Avoid `mã nguồn` for `token` and `token` for `source code`
|
||||||
|
- Avoid Sino-Vietnamese calques such as `chủ đề` for `topic` when `chủ đề` already means theme
|
||||||
|
- Avoid translating `Zen`, `Go`, and `Black` as generic words like `đỉnh cao` or `đi`
|
||||||
|
|
@ -16,7 +16,4 @@
|
||||||
"tools": {
|
"tools": {
|
||||||
"github-pr-search": false,
|
"github-pr-search": false,
|
||||||
},
|
},
|
||||||
"experimental": {
|
|
||||||
"part_rows": true,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,14 +15,14 @@ Read these first rather than repeating them:
|
||||||
|
|
||||||
## Stories and `mount`
|
## Stories and `mount`
|
||||||
|
|
||||||
- **Location.** Put the story next to the production component under `src/` of `ui`, `session-ui`, `app` or `gui-plugins`. The story server indexes `*.stories.tsx` files in those four trees (`packages/stories/vite.config.ts`, `src/index-plugin.ts`), reading each file's `export default { title, id }` and its `export const` stories from source.
|
- **Location.** Put the Lab page next to the production component under `src/` of `ui`, `session-ui`, `app` or `gui-plugins`. The story server indexes `*.lab.tsx` files in those four trees (`packages/stories/vite.config.ts`, `src/index-plugin.ts`), reading each page's `export default { title, id }` and its `export const` states (the stories a test mounts) from source. Name a page that needs the story server's fixture runtime `*.standalone.lab.tsx`: the in-app Lab skips those.
|
||||||
- **Story ID.** It is the meta `id` if one is set (`packages/session-ui/src/components/session-review.stories.tsx:25`). Otherwise it is the kebab-cased `title`, then `--`, then the kebab-cased export. Check it at `http://127.0.0.1:6006/?id=<id>` on a running story server (`bun --cwd packages/stories dev`). A wrong ID renders nothing (the page throws `No story has the id …`), so `mount` waits out its full 30 s root wait (`story.ts:39`) and then fails.
|
- **Story ID.** It is the meta `id` if one is set (`packages/session-ui/src/components/session-review.lab.tsx:25`). Otherwise it is the kebab-cased `title`, then `--`, then the kebab-cased export. Check it at `http://127.0.0.1:6006/?id=<id>` on a running story server (`bun --cwd packages/stories dev`). A wrong ID renders nothing (the page throws `No story has the id …`), so `mount` waits out its full 30 s root wait (`story.ts:39`) and then fails.
|
||||||
- **URL args.** `mount(id, { args, globals })` writes them into the URL as `key:value` pairs (`story.ts:20-36`). The frame reads every one: a value becomes a boolean or number when the story's own default for that key is one, `!true`/`!false`/`!null`/`!undefined` keep Storybook's meaning, and anything else stays text.
|
- **URL args.** `mount(id, { args, globals })` writes them into the URL as `key:value` pairs (`story.ts:20-36`). The frame reads every one: a value becomes a boolean or number when the story's own default for that key is one, `!true`/`!false`/`!null`/`!undefined` keep Storybook's meaning, and anything else stays text.
|
||||||
- Give every arg a typed default. With `args: { split: false }` (`session-review.stories.tsx:129`), `split:false` arrives as a boolean.
|
- Give every arg a typed default. With `args: { split: false }` (`session-review.lab.tsx:129`), `split:false` arrives as a boolean.
|
||||||
- A value containing `;` would split the pair list, so pick such values inside the story, from a `scenario`-style arg.
|
- A value containing `;` would split the pair list, so pick such values inside the story, from a `scenario`-style arg.
|
||||||
- **Globals** are `theme` (default `light`), `direction` and `locale` (`packages/stories/src/frame.tsx`).
|
- **Globals** are `theme` (default `light`), `direction` and `locale` (`packages/stories/src/frame.tsx`).
|
||||||
- **Portaled UI.** `mount` returns `#story-root`. Dialogs, menus and drawers render outside it, so locate them from `page` (`packages/app/component-tests/composer.spec.ts:101-107`).
|
- **Portaled UI.** `mount` returns `#story-root`. Dialogs, menus and drawers render outside it, so locate them from `page` (`packages/app/component-tests/composer.spec.ts:101-107`).
|
||||||
- **Server state** comes from the `resolve.alias` list in `packages/stories/vite.config.ts`, which points app server, SDK and sync modules at `packages/stories/mocks/app/**`. Extend a mock rather than adding a server. The app's components lab renders the same stories inside the real app instead, so a story must not depend on a mock-only export. Tests reset mock state on every mount.
|
- **Server state** comes from the `resolve.alias` list in `packages/stories/vite.config.ts`, which points app server, SDK and sync modules at `packages/stories/mocks/app/**`. Extend a mock rather than adding a server. The app's Lab (`/components`) renders the same pages inside the real app instead, so a story must not depend on a mock-only export. Tests reset mock state on every mount.
|
||||||
- **Requests the mocks do not answer.** Route them with `page.route`. That includes server endpoints such as `/api/fs/read` (`packages/session-ui/component-tests/read-image.spec.ts:20`) and external URLs such as favicons (`packages/session-ui/component-tests/markdown.spec.ts:217`).
|
- **Requests the mocks do not answer.** Route them with `page.route`. That includes server endpoints such as `/api/fs/read` (`packages/session-ui/component-tests/read-image.spec.ts:20`) and external URLs such as favicons (`packages/session-ui/component-tests/markdown.spec.ts:217`).
|
||||||
|
|
||||||
## Fixtures imported by URL
|
## Fixtures imported by URL
|
||||||
|
|
@ -44,10 +44,10 @@ Use these when the contract is not visible in a story, such as construction coun
|
||||||
|
|
||||||
## Vite pre-bundling and reloads
|
## Vite pre-bundling and reloads
|
||||||
|
|
||||||
`packages/stories/vite.config.ts` sets `optimizeDeps.entries`: every `*.stories.tsx` and `*.worker.ts` under the four `src/` trees, every module a component spec names by a `./` or `../` string literal ending in `.ts`/`.tsx` (collected at the top of the file), and the frame's `index.html`. Vite pre-bundles their bare imports before the first page loads. A dependency the scan misses is found on first import instead. If that changes chunks already served, Vite logs `✨ optimized dependencies changed. reloading` and sends `full-reload` with path `*` to every page in every worker, and requests with a stale `?v=` hash get a 504 "Outdated Optimize Dep".
|
`packages/stories/vite.config.ts` sets `optimizeDeps.entries`: every `*.lab.tsx` and `*.worker.ts` under the four `src/` trees, every module a component spec names by a `./` or `../` string literal ending in `.ts`/`.tsx` (collected at the top of the file), and the frame's `index.html`. Vite pre-bundles their bare imports before the first page loads. A dependency the scan misses is found on first import instead. If that changes chunks already served, Vite logs `✨ optimized dependencies changed. reloading` and sends `full-reload` with path `*` to every page in every worker, and requests with a stale `?v=` hash get a 504 "Outdated Optimize Dep".
|
||||||
|
|
||||||
- **The bar is zero reloads.** A cold run of either suite should print neither `new dependencies optimized` nor `optimized dependencies changed`, so these lines are the signal to watch.
|
- **The bar is zero reloads.** A cold run of either suite should print neither `new dependencies optimized` nor `optimized dependencies changed`, so these lines are the signal to watch.
|
||||||
- **Keep new code reachable by the scan.** A module path built at runtime, in a template literal, or without its extension is not collected, and neither is a spec named other than `*.spec.ts`. Name stories `*.stories.tsx`: the story index and the scan read only that extension. Name workers `*.worker.ts`, since the scan does not follow `new Worker(new URL(…))`. Add an `optimizeDeps.include` entry only for a dependency the scan cannot reach. Vite names it in `✨ new dependencies optimized: …`, and `DEBUG=vite:deps` replaces that line with scan and discovery detail.
|
- **Keep new code reachable by the scan.** A module path built at runtime, in a template literal, or without its extension is not collected, and neither is a spec named other than `*.spec.ts`. Name Lab pages `*.lab.tsx`: the story index and the scan read only that extension. Name workers `*.worker.ts`, since the scan does not follow `new Worker(new URL(…))`. Add an `optimizeDeps.include` entry only for a dependency the scan cannot reach. Vite names it in `✨ new dependencies optimized: …`, and `DEBUG=vite:deps` replaces that line with scan and discovery detail.
|
||||||
- **Symptoms.** "page.evaluate: Execution context was destroyed", "Failed to fetch dynamically imported module …/@fs/…", or fixture state that is gone right after `mount` ("Registrations: 1" not found, an empty tab strip).
|
- **Symptoms.** "page.evaluate: Execution context was destroyed", "Failed to fetch dynamically imported module …/@fs/…", or fixture state that is gone right after `mount` ("Registrations: 1" not found, an empty tab strip).
|
||||||
- **Only `mount()` survives a reload,** because it navigates back to the same URL. A reload loses everything set up after it: `page.evaluate` imports, mounted fixtures, state from earlier clicks, and the elements your locators pointed at. Another worker's discovery can trigger it at any moment.
|
- **Only `mount()` survives a reload,** because it navigates back to the same URL. A reload loses everything set up after it: `page.evaluate` imports, mounted fixtures, state from earlier clicks, and the elements your locators pointed at. Another worker's discovery can trigger it at any moment.
|
||||||
- **Fix reloads in the scan, never with retries, timeouts or import order.** The import-everything-before-mount `Promise.all` in `browser-pane-restore.spec.ts:43-58` (comment at `:56`) only narrowed the window. Before the entries existed, that file's `:123` and `:150` were retried in 31 CI jobs each, and failed attempts cost about 39-47 s (Linux) and 34 s (Windows) of worker time per run.
|
- **Fix reloads in the scan, never with retries, timeouts or import order.** The import-everything-before-mount `Promise.all` in `browser-pane-restore.spec.ts:43-58` (comment at `:56`) only narrowed the window. Before the entries existed, that file's `:123` and `:150` were retried in 31 CI jobs each, and failed attempts cost about 39-47 s (Linux) and 34 s (Windows) of worker time per run.
|
||||||
|
|
|
||||||
73
.opencode/skills/focus-states/SKILL.md
Normal file
73
.opencode/skills/focus-states/SKILL.md
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
---
|
||||||
|
name: focus-states
|
||||||
|
description: Focus indicators and focus movement in OpenCode Desktop and the web app. Use when adding or reviewing an interactive component, a :focus/:focus-visible/:focus-within rule, an outline on focus, a list/menu/palette row, a text field, a dialog, menu or popover, a selected state, removing or closing a focused item, or anything that moves focus programmatically.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Focus States
|
||||||
|
|
||||||
|
Use one default ring when someone navigates focus to a control, not when they click or tap it. The exceptions are below. Desktop uses Chromium; on the web, test the browser you’re changing or targeting rather than assuming identical focus behaviour.
|
||||||
|
|
||||||
|
## The ring
|
||||||
|
|
||||||
|
- Use `:focus-visible` for the ring. Don’t use `:focus` to decide whether to show it. `base.css` supplies `outline: 2px solid var(--v2-border-border-focus); outline-offset: 2px` and a 4px radius for links.
|
||||||
|
- Offset: `2px` outward by default. `-2px` inset for full-width rows and for controls flush against an edge that clips or scrolls (segmented items, split buttons, titlebar buttons, clear buttons). No other offsets.
|
||||||
|
- Follow the control’s radius; give a square text action or link 4px where appropriate. Use a wrapper with `:has(> trigger:focus-visible)` when the wrapper owns the visible shape or the trigger’s ring would clip, as with tabs and Settings project cards. End the selector at the wrapper or its pseudo-element (`wrapper:has(…)::after`). A selector that continues after `:has()` (`wrapper:has(…) ~ other`) restyles everything inside the wrapper on each focus change; around the timeline that made scrolling hitch (`packages/app/AGENTS.md`, Timeline stability).
|
||||||
|
- Outline only. Don't draw focus with `box-shadow`: Windows High Contrast removes shadows, so the ring disappears, and shadow rings looked different from every other ring.
|
||||||
|
- Rings appear and disappear instantly. Draw no outline at rest and leave `outline-color` out of `transition`; animating it from the default colour flashes black. Don't use `outline: 2px solid transparent` at rest: High Contrast turns it into a visible outline on every control.
|
||||||
|
- Keep a border that identifies an unfocused control. Where Chromium's forced colours remove the shadow that draws a control's edge, give it a system-colour border in `@media (forced-colors: active)`, separate from the ring, as switches and radios do.
|
||||||
|
- Inline rename inputs rely on the caret and editing state. The timeline's Jump to latest stays in the Tab order with the shared ring, since it's the only quick way back down from the keyboard; its container is `inert` while it's hidden. Loading alone doesn’t add a ring. If a busy button keeps keyboard focus, keep the ring and show the busy state separately with `aria-busy`, a disabled state, or loading text; the ring alone doesn’t say whether the button can be activated.
|
||||||
|
- These ring rules do not replace normal field borders or validation feedback. Those can respond to click focus and have their own inset treatment.
|
||||||
|
|
||||||
|
## Text fields and scroll areas
|
||||||
|
|
||||||
|
Chromium matches `:focus-visible` on every focused text field, and on anything that has focus once a key is pressed. A ring on a large surface then shows after a click, when the app moves focus there, and on returning to the window.
|
||||||
|
|
||||||
|
- A text field never draws the ring, the composer and Home search included. Focus shows as the caret and the field's focused border or background. Don't add ring state or pointer tracking to a field.
|
||||||
|
- A scroll area (the timeline, Home's list) takes focus from a click so the keyboard can scroll it, and draws no ring. It is not a Tab stop: Tab moves between the items inside it, and they show the ring. In a session, PageUp and PageDown in the composer page the timeline.
|
||||||
|
- Moving a screen reader’s reading cursor alone does not move DOM focus.
|
||||||
|
|
||||||
|
## Rows
|
||||||
|
|
||||||
|
- Choose by how focus moves.
|
||||||
|
- Focus stays in a search input while arrow keys move a highlight (`aria-activedescendant`: palettes, search lists): the active option is background-only and should not also be a Tab stop. Independent actions can still be Tab stops.
|
||||||
|
- A full-width row that is its own Tab stop (Home sessions and projects, settings rows) gets a 2px inset ring. Standalone disclosure and tool triggers can use an outset ring if it fits. Hover stays background-only.
|
||||||
|
- With roving focus (tabs and file trees), Tab enters the widget and arrow keys move focus within it. Show a ring on the keyboard-focused item, even though the other items are not separate Tab stops.
|
||||||
|
- The active option’s background highlight can disappear or become too faint in forced colours. Use `Highlight` and `HighlightText` in `@media (forced-colors: active)`. Check that nested labels and icons remain readable.
|
||||||
|
- Selection is not focus. Keep it neutral and distinct from the blue ring. The Settings › General layout cards (`settings/general/interface-mode.css`) are the reference for picker cards: a 2px `--v2-border-border-strong` border, a check badge outside the corner (`--v2-icon-icon-muted` fill, cut out in the surface colour, with a system-colour border in forced colours), and the other options' content faded. Don't use the inverse (black) border.
|
||||||
|
|
||||||
|
## Overlays and menus
|
||||||
|
|
||||||
|
- When an overlay closes and returns focus to its opener:
|
||||||
|
- Pointer dismissals (backdrop click, a close button clicked with the pointer) restore the opener’s ring state from when the overlay opened.
|
||||||
|
- Escape or another keyboard close after a keyboard open shows the ring on the restored control.
|
||||||
|
- Escape after a pointer open restores the no-ring state. Changing that is a deliberate product decision and needs its own test.
|
||||||
|
- Dialogs get this from the dialog context and dropdown menus from the `Menu` wrapper. Select, `Menu.Context`, and raw `@kobalte/core/popover` uses get it from `createOverlayFocus` in `packages/ui/src/context/overlay-focus.tsx`: call `openChanged` from `onOpenChange` and `restore(event, trigger)` from `onCloseAutoFocus`. Without a trigger, `restore(event)` returns to whatever had focus when it opened, such as a context menu's row. Never call a bare `trigger.focus()` on close.
|
||||||
|
- Choose the widget by what's inside, not by how it looks. A menu (`Menu`, `role="menu"`) holds only commands: arrow keys, Home/End and typeahead move, Enter chooses, Esc closes, and Tab does nothing, as in native menus. A popover that holds controls (switches, links, buttons in flyouts, like the Extensions panel) must let Tab move through them; arrow keys may be added on top.
|
||||||
|
|
||||||
|
## Clipping and covering
|
||||||
|
|
||||||
|
- Use `overflow: clip; overflow-clip-margin: 5px` only if the container does not need to scroll, including programmatic scrolling. For scrollers, use an inset ring, padding, or scroll margins as appropriate.
|
||||||
|
- Rows that overlap by a pixel to merge borders (accordions) let the next row paint over the bottom of an inset ring. Raise the header holding focus (`z-index`), as `accordion.css` and `sticky-accordion-header.css` do; with sticky headers, raise the header, not the item, or the item lands under its neighbours' sticky headers.
|
||||||
|
- Keep the whole ring clear of sticky content. Try an inset ring or a targeted `scroll-margin` on the affected items first. Use `scroll-padding` on the scroller only when sticky chrome covers focus across the whole area, since it changes every scroll, not just focus. Account for the header, any fade, and the ring’s reach (4px for the default outset ring). Check Tab and Shift+Tab.
|
||||||
|
|
||||||
|
## Colour and contrast
|
||||||
|
|
||||||
|
- Use `--v2-border-border-focus`, never a raw colour or a per-component override. It is Blue 500 in light and Blue 400 in dark; custom themes can override it.
|
||||||
|
- Light mode has a known contrast gap: Blue 500 is about 2.7:1 on white, below the 3:1 target. It was kept as a documented decision because Blue 600 read too heavy. It is not a pass, and 2.7:1 is not a new threshold.
|
||||||
|
- Measure against the actual adjacent colours in both schemes: the surrounding surface for an outset ring and the control’s fill for an inset ring. If contrast is low, first try a placement that improves it without clipping. If placement can’t fix it, flag the shortfall and revisit the token. Never change the colour per component.
|
||||||
|
|
||||||
|
## Order and movement
|
||||||
|
|
||||||
|
- Follow logical reading and interaction order, including in RTL. Fix DOM order rather than using positive `tabindex`. Use native buttons for actions and links for navigation; use established widget primitives or keyboard patterns for tabs, trees, sliders, and resize handles.
|
||||||
|
- Move focus in response to a user action or to recover focus when its target disappears. Background updates, streamed output, toasts, and incoming prompts must not steal focus.
|
||||||
|
- If a focused item is closed or deleted, move focus to the next place the user can continue the same task: the next or previous item in the same list, or a stable fallback such as the list heading or the control that opened it. Use the visually nearest control only when it serves that task. Don’t leave focus on `<body>`.
|
||||||
|
- Chromium drops focus to `<body>` without an event when the focused element is removed, disabled, or stops being editable. `packages/ui/src/context/focus-rescue.tsx` (installed in `AppBaseProviders`) recovers it inside a `data-focus-scope`: the next item, or the previous after the last, widening to the enclosing scope when the inner one is empty, and back to what had focus before when nothing is left. The control it moves focus to shows its ring only when Tab or an arrow key last moved focus; typing, shortcuts and a key pressed on a clicked control don't count. Mark a new list, strip, chip row or panel with `data-focus-scope` rather than adding per-feature focus code. Rescue never moves focus into a `role="tablist"`, because Kobalte tabs select themselves on focus, so don't mark a tab list as a scope. Items in an overlay leave the return to the overlay; rescue steps in only when the overlay's opener is gone too. Move focus explicitly when the task has a better target than the neighbour, such as the composer after the last chip.
|
||||||
|
- A row that scrolls out of a virtualized list is not a removed item. The list unmounts it with its focused control, and the rescue would then focus a control in another row, which scrolls the list to that row. The list gives focus to its own viewport first, with `preventScroll: true`, as `VirtualRow` does in `packages/app/src/session/timeline/virtualizer.tsx`. Do the same in a new virtualized list.
|
||||||
|
- `focus()` scrolls its target into view. Inside a scroll container, pass `{ preventScroll: true }` unless the reader must see that control next: keyboard navigation to it, or the item that takes the place of a removed one (`packages/app/AGENTS.md`, Timeline stability).
|
||||||
|
|
||||||
|
## Verify
|
||||||
|
|
||||||
|
- A story is optional, for visual checks such as clipping, colour, and forced colours. Use one if the repo has a suitable focus story, or a local one you don't commit; don't add a case for every fix. Test focus order, removal and restoration in the app with real input, not in a story.
|
||||||
|
- Use real keyboard and pointer input for the behaviour you changed. Check Tab and Shift+Tab for order and clipping, and when you replace a control, remove a ring or reuse a picker, run them through the whole changed flow and check both where focus lands and whether you can see it. Check arrow keys for composites, and shortcuts for programmatic focus. For overlay return, check keyboard open with Escape, keyboard open with a pointer dismissal, pointer open with a backdrop click, and pointer open with Escape. Forced focus shows appearance, not whether navigation or restoration works.
|
||||||
|
- After a change to focus in or near the timeline, click a tool header in it, then scroll up and down with the wheel. The timeline must follow the wheel.
|
||||||
|
- Check light, dark, and forced colours when the indicator or its background changes. Report Chromium forced-colours emulation (DevTools → Rendering → `forced-colors: active`) separately from native Windows High Contrast or assistive-technology testing.
|
||||||
|
|
@ -23,6 +23,40 @@
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"overrides": [
|
"overrides": [
|
||||||
|
{
|
||||||
|
"files": ["packages/ai/src/**"],
|
||||||
|
"rules": {
|
||||||
|
"no-restricted-globals": [
|
||||||
|
"error",
|
||||||
|
{
|
||||||
|
"name": "Reflect",
|
||||||
|
"message": "Use typed property access or direct invocation. Suppress this rule only for genuine reflection."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "fetch",
|
||||||
|
"message": "Send HTTP through RequestExecutor, which applies executor-wide and scoped middleware (HTTP hooks). A request sent any other way skips them."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"no-restricted-imports": [
|
||||||
|
"error",
|
||||||
|
{
|
||||||
|
"paths": [
|
||||||
|
{
|
||||||
|
"name": "effect/http",
|
||||||
|
"importNames": ["HttpClient", "FetchHttpClient"],
|
||||||
|
"message": "Send HTTP through RequestExecutor, which applies executor-wide and scoped middleware (HTTP hooks). Only route/executor.ts holds the HTTP client."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"files": ["packages/ai/src/route/executor.ts"],
|
||||||
|
"rules": {
|
||||||
|
"no-restricted-imports": "off"
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"files": [
|
"files": [
|
||||||
"packages/app/**",
|
"packages/app/**",
|
||||||
|
|
@ -145,33 +179,6 @@
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
"files": ["packages/codemode/src/interpreter/**", "packages/codemode/src/stdlib/**"],
|
|
||||||
"rules": {
|
|
||||||
"no-restricted-imports": [
|
|
||||||
"error",
|
|
||||||
{
|
|
||||||
"paths": [
|
|
||||||
{
|
|
||||||
"name": "effect",
|
|
||||||
"allowTypeImports": true,
|
|
||||||
"message": "The evaluator and built-ins are plain generators driven by the job queue in runner.ts. Start host work with runner.host or block on it with runner.blocking; only runner.ts, execute.ts, and extensions.ts run Effects."
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"files": [
|
|
||||||
"packages/codemode/src/interpreter/runner.ts",
|
|
||||||
"packages/codemode/src/interpreter/execute.ts",
|
|
||||||
"packages/codemode/src/interpreter/extensions.ts"
|
|
||||||
],
|
|
||||||
"rules": {
|
|
||||||
"no-restricted-imports": "off"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"ignorePatterns": [
|
"ignorePatterns": [
|
||||||
|
|
@ -181,6 +188,7 @@
|
||||||
"**/.sst",
|
"**/.sst",
|
||||||
"**/*.d.ts",
|
"**/*.d.ts",
|
||||||
"**/sdk.gen.ts",
|
"**/sdk.gen.ts",
|
||||||
|
"packages/cli-rs/**",
|
||||||
"packages/plugins/figma/skills/**",
|
"packages/plugins/figma/skills/**",
|
||||||
".agent/**",
|
".agent/**",
|
||||||
".agents/**",
|
".agents/**",
|
||||||
|
|
|
||||||
|
|
@ -2,4 +2,5 @@ sst-env.d.ts
|
||||||
packages/desktop/src/bindings.ts
|
packages/desktop/src/bindings.ts
|
||||||
packages/client/src/generated/
|
packages/client/src/generated/
|
||||||
packages/client/src/generated-effect/
|
packages/client/src/generated-effect/
|
||||||
|
packages/core/src/plugin/skill/opencode/
|
||||||
packages/plugins/figma/skills/
|
packages/plugins/figma/skills/
|
||||||
|
|
|
||||||
|
|
@ -182,8 +182,8 @@ const table = sqliteTable("session", {
|
||||||
|
|
||||||
- When you open a PR, decide whether the change needs a flag: new user-visible behavior, risky core changes, and anything not ready to release get one; fixes, refactors, docs and tests do not.
|
- When you open a PR, decide whether the change needs a flag: new user-visible behavior, risky core changes, and anything not ready to release get one; fixes, refactors, docs and tests do not.
|
||||||
- Gate risky behavior, or behavior that lands over several PRs, with a key and a description in `packages/schema/src/config/flag.ts`, and read it with `Flag.enabled("<key>")` from `@opencode/core/flag`.
|
- Gate risky behavior, or behavior that lands over several PRs, with a key and a description in `packages/schema/src/config/flag.ts`, and read it with `Flag.enabled("<key>")` from `@opencode/core/flag`.
|
||||||
- Flags are on in local and dev builds and off in releases; `experimental.<key>` in config and `OPENCODE_FLAGS="key,-other"` override that.
|
- Flags default to on in local and dev builds and off in releases, except `optInOnly` flags (such as `todo`), which require an explicit `OPENCODE_FLAGS=<key>` or `experimental.<key>: true` in every build.
|
||||||
- Say in the PR body which flag guards the change. To try every flag at once, use `OPENCODE_FLAGS=all` or `experimental.all_flags: true`; a `-<key>` opt-out or `experimental.<key>: false` still wins, and neither `all` nor `all_flags` is a flag key.
|
- Say in the PR body which flag guards the change. The reserved switches `OPENCODE_FLAGS=all` and `experimental.all_flags: true` skip opt-in-only flags; use `all,-<key>` or `experimental.<key>: false` to opt out within the respective source.
|
||||||
- Ship a feature by deleting its flag and the checks that read it.
|
- Ship a feature by deleting its flag and the checks that read it.
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
@ -202,8 +202,7 @@ const table = sqliteTable("session", {
|
||||||
|
|
||||||
## Plugin Loading
|
## Plugin Loading
|
||||||
|
|
||||||
- Plugins load asynchronously. Server handlers never wait for them (`Plugin.awaitActivation`), never retry until something appears, and never turn slow plugins into a timeout or 503. This applies to reads and to actions such as `rpc.call` and `vcs.init`.
|
- Plugins load asynchronously. Server handlers never wait for them (`Plugin.awaitActivation`), never retry until something appears, and never turn slow plugins into a timeout or 503. This applies to reads and to actions such as `generate.*`, `rpc.call`, `vcs.init` and `websearch.query`.
|
||||||
- Temporary exception: endpoints that list or use providers managed policy can deny (`model.list`, `model.default`, `provider.list`, `generate.*`, `voice.*` and `websearch.query`) wait through `awaitPlugins` in `packages/server/src/location.ts`, because policy is applied by the last plugin to activate and is missing until then. Don't add new waits; this goes away once a plugin batch becomes visible only when it ends.
|
|
||||||
- The server answers with what is loaded now: lists may be empty or partial on a cold Location, and an action whose model, provider or RPC hasn't loaded yet fails with not-found. That is expected, not a bug to fix on the server.
|
- The server answers with what is loaded now: lists may be empty or partial on a cold Location, and an action whose model, provider or RPC hasn't loaded yet fails with not-found. That is expected, not a bug to fix on the server.
|
||||||
- Clients are responsible for making sure what they need is loaded before they call. Long-lived clients refresh on the matching `*.updated` event (`model.updated`, `agent.updated`, `skill.updated`, `integration.updated`, `plugin.updated`, ...). One-shot clients (CLI commands, ACP, SDK callers) wait on their side, for example by polling `plugin.list` or the entry they need. See `packages/cli/src/services/plugin-startup.ts`.
|
- Clients are responsible for making sure what they need is loaded before they call. Long-lived clients refresh on the matching `*.updated` event (`model.updated`, `agent.updated`, `skill.updated`, `integration.updated`, `plugin.updated`, ...). One-shot clients (CLI commands, ACP, SDK callers) wait on their side, for example by polling `plugin.list` or the entry they need. See `packages/cli/src/services/plugin-startup.ts`.
|
||||||
- Running the hooks that are registered and waiting for their result is fine (for example `hooks.trigger("session", "http.request", ...)`). What is not allowed is waiting for plugins to load first: if the plugin that adds a hook hasn't loaded yet, the call runs without that hook.
|
- Running the hooks that are registered and waiting for their result is fine (for example `hooks.trigger("session", "http.request", ...)`). What is not allowed is waiting for plugins to load first: if the plugin that adds a hook hasn't loaded yet, the call runs without that hook.
|
||||||
|
|
|
||||||
483
CHANGELOG.md
483
CHANGELOG.md
|
|
@ -2,6 +2,489 @@
|
||||||
|
|
||||||
Release notes for OpenCode V2, newest first.
|
Release notes for OpenCode V2, newest first.
|
||||||
|
|
||||||
|
## v2.4.1 — 2026-11-23
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **macOS 12 Session Fix**: OpenCode can save assistant messages again on the older SQLite version included with macOS 12. ([#65771](https://github.com/anomalyco/opencode/pull/65771))
|
||||||
|
- **Config-Only Providers Show Their Models**: Providers you set up only in your config, such as Ollama, now show their models in `/models` without a `/connect` login. ([#65793](https://github.com/anomalyco/opencode/pull/65793))
|
||||||
|
- **Unread `/btw` Answers**: When a side question finishes behind another side-panel tab, its tab shows an unread dot until you open it. ([#65821](https://github.com/anomalyco/opencode/pull/65821))
|
||||||
|
|
||||||
|
### Core
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- With `experimental.model_speeds` enabled, model service tiers are exposed as remembered speeds instead of separate model-picker entries. ([#65749](https://github.com/anomalyco/opencode/pull/65749))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed assistant messages failing to save on macOS 12 because its system SQLite does not support the JSON operator used in v2.4.0. ([#65771](https://github.com/anomalyco/opencode/pull/65771))
|
||||||
|
- Fixed compaction retaining more recent history than `keep.tokens`, including when a single newest message already exceeds the allowance. ([#65768](https://github.com/anomalyco/opencode/pull/65768))
|
||||||
|
- Fixed occasional extra cache cost in long goal sessions after a compaction. ([#65788](https://github.com/anomalyco/opencode/pull/65788))
|
||||||
|
|
||||||
|
### TUI
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- With `experimental.model_speeds` enabled, `/speed` and `/fast` list the current model’s service tiers and relative prices. The `speed.list` and `speed.cycle` keybinds are available without default bindings. ([#65749](https://github.com/anomalyco/opencode/pull/65749))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed `/models` hiding models from config-only providers such as Ollama when no `/connect` login exists. ([#65793](https://github.com/anomalyco/opencode/pull/65793))
|
||||||
|
|
||||||
|
### Desktop
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- With `experimental.model_speeds` enabled, models with service tiers have a speed dropdown beside the variant selector; `/speed` cycles through the available speeds. ([#65749](https://github.com/anomalyco/opencode/pull/65749))
|
||||||
|
- Layout choices in Settings now use consistent navigation-card previews and accent styling. ([#65757](https://github.com/anomalyco/opencode/pull/65757), [#65800](https://github.com/anomalyco/opencode/pull/65800))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed `/btw` answers completed behind another side-panel tab providing no unread indication. The tab now shows a dot until viewed. ([#65821](https://github.com/anomalyco/opencode/pull/65821))
|
||||||
|
- Fixed the timeline, Home list, file viewers and tool output adding invisible or oversized stops to keyboard Tab navigation. They remain focusable by clicking for keyboard scrolling. ([#65758](https://github.com/anomalyco/opencode/pull/65758), [#65785](https://github.com/anomalyco/opencode/pull/65785))
|
||||||
|
- Fixed unwanted focus rings around clicked Settings pages, error details, What’s New and the terminal, and corrected the split button’s focus-ring corners. ([#65783](https://github.com/anomalyco/opencode/pull/65783), [#65785](https://github.com/anomalyco/opencode/pull/65785))
|
||||||
|
- Fixed folder paths showing middle-truncation markers unnecessarily at fractional UI zoom levels. ([#65225](https://github.com/anomalyco/opencode/pull/65225))
|
||||||
|
|
||||||
|
### SDK
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- An aborted shared event subscription now stops immediately even when the source has already completed or failed with buffered events remaining. Thanks @chirag127. ([#65441](https://github.com/anomalyco/opencode/pull/65441))
|
||||||
|
|
||||||
|
### Extensions
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Effect and Promise plugins can create, list and delete automations through `ctx.experimental.automation.{create,list,delete}`. ([#65747](https://github.com/anomalyco/opencode/pull/65747))
|
||||||
|
- `@opencode/plugin` now supports `@opentui/core` and `@opentui/solid` from version 0.8.0, allowing plugins capped below OpenTUI 0.9 to install again. ([#65819](https://github.com/anomalyco/opencode/pull/65819))
|
||||||
|
|
||||||
|
## v2.4.0 — 2026-11-23
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Built-In Desktop Browser**: Import your sign-ins and browsing history from Chrome, Edge, Firefox or Safari, and add extensions from Chromium browsers or the Chrome and Edge stores. Everything stays in one persistent desktop profile: chat links open signed in, your tabs survive restarts and the agent can read and drive the same pages without you switching apps. ([#63002](https://github.com/anomalyco/opencode/pull/63002), [#65073](https://github.com/anomalyco/opencode/pull/65073))
|
||||||
|
- **Automations**: Ask the agent to run a prompt, a script or a shell command on a timer, on a cron schedule or when an MCP server sends an event, and manage them with `/automation`. Set `"automations": false` in your config if you don't want them. ([#65296](https://github.com/anomalyco/opencode/pull/65296), [#65186](https://github.com/anomalyco/opencode/pull/65186))
|
||||||
|
- **Generate Videos**: When a connected provider has a video model, the agent can make videos with `generate_video`. It keeps working while the video renders and saves the files into your workspace when they're ready. ([#63666](https://github.com/anomalyco/opencode/pull/63666), [#65664](https://github.com/anomalyco/opencode/pull/65664))
|
||||||
|
- **New TUI Look**: The TUI's new designs are on by default, and the `opencode` theme is the new one. Pick `opencode-classic` in **Theme** to keep the previous colors. ([#64988](https://github.com/anomalyco/opencode/pull/64988))
|
||||||
|
- **Windows Taskbar Status**: On Windows, the taskbar button shows session progress, counts sessions that need you and flashes when a permission or question is waiting. ([#65317](https://github.com/anomalyco/opencode/pull/65317), [#65318](https://github.com/anomalyco/opencode/pull/65318), [#65319](https://github.com/anomalyco/opencode/pull/65319))
|
||||||
|
|
||||||
|
### Upgrade notes
|
||||||
|
|
||||||
|
- **Image tool renamed.** `experimental_image_generate` is now `generate_image`. Permission rules with the old name are mapped automatically, but saved "always allow" approvals are not, so it asks again once. ([#65682](https://github.com/anomalyco/opencode/pull/65682))
|
||||||
|
- **Plugins that follow a version now update on their own.** A plugin written as `name@latest`, a version range (such as `name@^1.2.0`), a Git branch or a Git `semver:` range is checked on startup and every 24 hours, and a newer match is installed and reloaded. Ranges never leave their range, and if a new version fails to load the previous one keeps running. A bare `name`, an exact version, another tag such as `@next`, a Git tag or a commit hash doesn't update itself; `opencode plugin update` still updates those by hand. ([#64764](https://github.com/anomalyco/opencode/pull/64764), [#65052](https://github.com/anomalyco/opencode/pull/65052), [#65056](https://github.com/anomalyco/opencode/pull/65056))
|
||||||
|
- **GitHub Copilot no longer reads `GITHUB_TOKEN`.** Set `COPILOT_GITHUB_TOKEN` or sign in with OAuth. ([#64697](https://github.com/anomalyco/opencode/pull/64697))
|
||||||
|
- **MCP servers are tried on the newest protocol first.** A server without a `protocol` setting is probed before falling back to the legacy handshake. Set `protocol: "legacy"` on a server that misbehaves. ([#65282](https://github.com/anomalyco/opencode/pull/65282))
|
||||||
|
- **The TUI `opencode` theme changed.** It now means the new theme; set `opencode-classic` for the previous look, and `experimental["new-designs"]: false` in your TUI config for the previous designs. ([#64988](https://github.com/anomalyco/opencode/pull/64988))
|
||||||
|
- **Chat links open in the browser pane.** In the desktop app, web links from the chat open beside the conversation. Modifier-click a link to open it in your system browser. A `browser` deny in your permission rules refuses every agent browser call. ([#63002](https://github.com/anomalyco/opencode/pull/63002))
|
||||||
|
- **OpenCode Go connects through OpenCode.** The connect dialogs and `opencode auth login` list one **OpenCode** option that includes Go models. **OpenCode Go** is only listed when a Go key is already saved, and saved keys keep working. ([#65466](https://github.com/anomalyco/opencode/pull/65466))
|
||||||
|
- **New desktop shortcut.** `Cmd+Shift+S` (`Ctrl+Shift+S` on Windows and Linux) now archives the open session. The composer's `Cmd+U` and `Escape`/`Ctrl+G` now follow the **Attach file** and **Stop session** shortcuts. ([#65428](https://github.com/anomalyco/opencode/pull/65428), [#64394](https://github.com/anomalyco/opencode/pull/64394))
|
||||||
|
- **Code Mode session tool paths moved.** `tools.opencode.session_rename` and `session_move` are now `tools.opencode.session.rename` and `.move`. Direct tool names and permission actions are unchanged. ([#65080](https://github.com/anomalyco/opencode/pull/65080))
|
||||||
|
- **TUI plugins need OpenTUI 0.9.4.** `@opencode/plugin` requires `@opentui/core` and `@opentui/solid` 0.9.4 or later. Renderers passed to `registerCodeBlockRenderer` now receive an OpenTUI block (`block.text`) instead of a Markdown token; `codeBlockStyle` and `escaped` are gone. ([#63989](https://github.com/anomalyco/opencode/pull/63989))
|
||||||
|
- **SDK: plugins load in the background again.** Plugins are meant to load asynchronously, and the server never waits for them. In v2.2.7 the model, provider, `generate.*`, `voice.*` and `websearch.query` endpoints started waiting up to 5 seconds for plugins and returning 503 after that ([#63040](https://github.com/anomalyco/opencode/pull/63040)); this release removes that wait. Right after startup these endpoints answer with whatever has loaded, so a list can be empty or partial. Long-lived clients should refresh on the matching `*.updated` event, such as `model.updated`. One-shot scripts should wait on their side, for example by polling `plugin.list` until it returns plugins, or the endpoint until the entry they need appears. ([#63814](https://github.com/anomalyco/opencode/pull/63814))
|
||||||
|
- **Desktop voice needs a matching server.** The app reads each voice model's engine, which older servers don't report, so voice shows as unavailable against a server from before this release. ([#65506](https://github.com/anomalyco/opencode/pull/65506))
|
||||||
|
- **Storage write path.** Assistant parts are now saved as their own rows. `experimental.part_rows: false` restores the old path for this release. ([#65039](https://github.com/anomalyco/opencode/pull/65039))
|
||||||
|
|
||||||
|
### Core
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Added automations. Agents can schedule prompts, Code Mode scripts or fixed shell commands to run once, on an interval, on a cron schedule or when a connected MCP server pushes an event. Use the `/automation` command or the `automation` tools. A shell action asks for approval once, when it's created, and records each run's exit code and output. Set `"automations": false` to turn them off. ([#65296](https://github.com/anomalyco/opencode/pull/65296), [#65186](https://github.com/anomalyco/opencode/pull/65186), [#65217](https://github.com/anomalyco/opencode/pull/65217), [#65236](https://github.com/anomalyco/opencode/pull/65236), [#65001](https://github.com/anomalyco/opencode/pull/65001), [#65699](https://github.com/anomalyco/opencode/pull/65699))
|
||||||
|
- MCP Events shipped: OpenCode follows the MCP Events beta for push delivery, with argument checks, heartbeats and automatic reconnects. An event too large for its prompt is skipped and its automation keeps running. ([#65271](https://github.com/anomalyco/opencode/pull/65271), [#65673](https://github.com/anomalyco/opencode/pull/65673))
|
||||||
|
- MCP servers without a `protocol` setting now negotiate the newest MCP protocol and fall back to the legacy handshake. ([#65282](https://github.com/anomalyco/opencode/pull/65282))
|
||||||
|
- Agents can generate videos with `generate_video` whenever a connected provider has a video model. The job runs in the background, survives a server restart, saves the finished videos into the workspace and wakes the agent with their paths. Set a default model with `experimental.video_generate.model`. The image tool is now called `generate_image`. ([#63666](https://github.com/anomalyco/opencode/pull/63666), [#64546](https://github.com/anomalyco/opencode/pull/64546), [#65664](https://github.com/anomalyco/opencode/pull/65664), [#65682](https://github.com/anomalyco/opencode/pull/65682))
|
||||||
|
- Plugins that follow a version (`name@latest`, a version range, a Git branch or a Git `semver:` range) are checked on startup and every 24 hours, and a newer match is installed and reloaded without a restart. A range stays within its range, and if a new version fails to load, the previous one keeps running. Other plugins still only report updates. ([#64764](https://github.com/anomalyco/opencode/pull/64764), [#65052](https://github.com/anomalyco/opencode/pull/65052), [#65056](https://github.com/anomalyco/opencode/pull/65056))
|
||||||
|
- The Claude Agent provider has a `configDir` setting for a Claude config folder other than the default. Given a list of folders, a chat moves to the next account when one hits its usage limit. Claude Agent sessions also show up in Claude Code as coming from `opencode`. ([#62514](https://github.com/anomalyco/opencode/pull/62514), [#65035](https://github.com/anomalyco/opencode/pull/65035), [#65016](https://github.com/anomalyco/opencode/pull/65016))
|
||||||
|
- Removing a Sign in with ChatGPT account, with `opencode auth logout` or the remove button in the app, now also revokes it with OpenAI. ([#64947](https://github.com/anomalyco/opencode/pull/64947))
|
||||||
|
- The ChatGPT plan model lists now come from models.dev, so new models show up without an OpenCode update. ([#65579](https://github.com/anomalyco/opencode/pull/65579))
|
||||||
|
- Voice models are now listed from models.dev, adding newer OpenAI models such as `gpt-live-1.1`. ([#65491](https://github.com/anomalyco/opencode/pull/65491))
|
||||||
|
- Reading far into a large file with `read`, or reading its tail, takes far fewer reads, which is much faster on remote workspaces. ([#65611](https://github.com/anomalyco/opencode/pull/65611))
|
||||||
|
- The shell tool's result says why a command ended without an exit code, and lists its output after the smaller fields so they survive truncation. ([#65365](https://github.com/anomalyco/opencode/pull/65365), [#65513](https://github.com/anomalyco/opencode/pull/65513))
|
||||||
|
- Code Mode scripts can define getters and setters, errors have a `stack` showing where they were thrown, and a failed import says why. ([#64908](https://github.com/anomalyco/opencode/pull/64908), [#64939](https://github.com/anomalyco/opencode/pull/64939), [#64587](https://github.com/anomalyco/opencode/pull/64587))
|
||||||
|
- A `timeout` set on a provider now applies to every request, including image, video, speech, transcription, embedding and compaction requests, which previously could hang forever on a stalled provider. ([#64692](https://github.com/anomalyco/opencode/pull/64692))
|
||||||
|
- Gemma 4 models on Google's Interactions API offer the `none` and `thinking` variants, and the provider's `safetySettings` are sent to Interactions. ([#65038](https://github.com/anomalyco/opencode/pull/65038), [#65036](https://github.com/anomalyco/opencode/pull/65036))
|
||||||
|
- Added `claude-agent` as a web search provider. With Claude Agent connected, set `"websearch": { "provider": "claude-agent" }` to run `websearch` through Claude Code's WebSearch, which Claude plans include, so any model can search without a search API key. ([#65704](https://github.com/anomalyco/opencode/pull/65704))
|
||||||
|
- With `full_codemode` on, agents can call `tools.opencode.session.interrupt` to stop another session, its background jobs and its subagents. ([#65718](https://github.com/anomalyco/opencode/pull/65718))
|
||||||
|
- Stored blobs, such as generated videos, are deleted a week after they were written, so the data folder no longer grows without limit. Copies saved into your project are untouched; `GET /api/experimental/blob/:id` returns 404 for a deleted blob. ([#65671](https://github.com/anomalyco/opencode/pull/65671))
|
||||||
|
- Config now reloads only when a file that feeds it changes, not on every write under `.opencode` such as editing a skill. ([#62158](https://github.com/anomalyco/opencode/pull/62158))
|
||||||
|
- Each streamed assistant part is saved as its own row instead of rewriting the whole message on every update, so long steps with many tool calls save reliably. ([#65039](https://github.com/anomalyco/opencode/pull/65039))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed GitHub Copilot picking up `GITHUB_TOKEN`, which git tooling and GitHub Actions often set without Copilot access. It now reads `COPILOT_GITHUB_TOKEN`. ([#64697](https://github.com/anomalyco/opencode/pull/64697))
|
||||||
|
- Fixed shell commands the scanner can't analyze, such as dynamic execution, failing outright. They now ask for permission, and a matching `shell` deny rule still blocks them. ([#65269](https://github.com/anomalyco/opencode/pull/65269))
|
||||||
|
- Fixed sessions getting stuck on provider 400 errors after a model called a tool by a dotted name such as a Code Mode path. A Code Mode tool called at the top level now runs as that tool, with a note telling the model to use `execute`. ([#65292](https://github.com/anomalyco/opencode/pull/65292), [#65193](https://github.com/anomalyco/opencode/pull/65193), [#65494](https://github.com/anomalyco/opencode/pull/65494))
|
||||||
|
- Fixed a forced tool choice for a namespaced tool naming a tool the request never declared on every provider except native OpenAI Responses. ([#65621](https://github.com/anomalyco/opencode/pull/65621), [#65726](https://github.com/anomalyco/opencode/pull/65726))
|
||||||
|
- Fixed the shell tool's description not saying which OS and shell commands run in when `full_codemode` is on. ([#65712](https://github.com/anomalyco/opencode/pull/65712))
|
||||||
|
- Fixed a revoked or expired ChatGPT sign-in failing every prompt with "Request failed: 400". It now asks you to connect again. ([#65289](https://github.com/anomalyco/opencode/pull/65289))
|
||||||
|
- Fixed `edit` and `patch` replacing every non-UTF-8 character (Latin-1, cp1252, GBK…) with `<60>` across the whole file. They now refuse to rewrite such files. ([#64868](https://github.com/anomalyco/opencode/pull/64868))
|
||||||
|
- Fixed the review pane showing every line as changed in repositories with `core.autocrlf=true`, and symlinks as modified with `core.symlinks=false`. ([#64884](https://github.com/anomalyco/opencode/pull/64884))
|
||||||
|
- Fixed file permission rules not matching other capitalizations of the same path on macOS. Thanks @knp-sap. ([#64626](https://github.com/anomalyco/opencode/pull/64626))
|
||||||
|
- Fixed the model picker staying empty while a slow project was still loading. ([#63814](https://github.com/anomalyco/opencode/pull/63814))
|
||||||
|
- Fixed Claude Agent processes staying alive after their session was deleted. Thanks @WTLAIB. ([#62649](https://github.com/anomalyco/opencode/pull/62649))
|
||||||
|
- Fixed Claude Agent models becoming unavailable after Claude Code renamed them, and Claude Agent now waits up to 60 seconds for its process to start. ([#65032](https://github.com/anomalyco/opencode/pull/65032), [#65064](https://github.com/anomalyco/opencode/pull/65064))
|
||||||
|
- Fixed shell commands failing with "failed to open output file" after OpenCode's shell output directory was removed. ([#64889](https://github.com/anomalyco/opencode/pull/64889))
|
||||||
|
- Fixed concurrent shell commands failing on Windows with PowerShell 7 from the Microsoft Store, and stopping one such command killing the others. ([#64901](https://github.com/anomalyco/opencode/pull/64901))
|
||||||
|
- Fixed `opencode service set password` writing the password to the CLI log. ([#64911](https://github.com/anomalyco/opencode/pull/64911))
|
||||||
|
- Fixed `opencode run` hanging when a FIFO is passed as an attachment; it's now rejected right away. Thanks @yang0228. ([#64696](https://github.com/anomalyco/opencode/pull/64696))
|
||||||
|
- Fixed `opencode <name>` crashing with a stack trace when `<name>` is neither a command nor a directory. It now prints help and the error. ([#65262](https://github.com/anomalyco/opencode/pull/65262))
|
||||||
|
- Fixed the background service becoming unresponsive at startup with a large database write-ahead log on a slow disk. ([#64532](https://github.com/anomalyco/opencode/pull/64532))
|
||||||
|
- Fixed a client that opens a session during a running tool call not seeing that tool's progress, such as a running subagent's session. ([#64929](https://github.com/anomalyco/opencode/pull/64929))
|
||||||
|
- Fixed Markdown commands dropping a separate `variant` next to `model`, and agents being skipped when frontmatter repair turned inline lists or objects into strings. ([#65118](https://github.com/anomalyco/opencode/pull/65118), [#65119](https://github.com/anomalyco/opencode/pull/65119))
|
||||||
|
- Fixed Google Interactions responses stopping early when Google splits a response across requests. ([#65006](https://github.com/anomalyco/opencode/pull/65006))
|
||||||
|
- Fixed GPT models over OpenAI's WebSocket transport resending the whole conversation after a freeform tool call such as `execute` or `patch`. ([#64706](https://github.com/anomalyco/opencode/pull/64706))
|
||||||
|
- Fixed `gpt-6.2-astra` and later Astra models getting a 500k context window with ChatGPT sign-in; they stay at 272k. ([#64725](https://github.com/anomalyco/opencode/pull/64725))
|
||||||
|
- OpenAI `cyber_policy` and Gemini "terms of use" refusals are now reported as content policy errors. Thanks @lu-zero. ([#64844](https://github.com/anomalyco/opencode/pull/64844), [#64910](https://github.com/anomalyco/opencode/pull/64910))
|
||||||
|
- Fixed MiniMax text-to-video requests without an aspect ratio being rejected; they now default to `16:9`. ([#64822](https://github.com/anomalyco/opencode/pull/64822))
|
||||||
|
- Fixed several Code Mode built-ins to match Bun: `localeCompare` and `Date` `toLocale*` honor their locale and options, `toBase64`/`fromBase64` honor their options, `Buffer` `map`, `filter`, `slice` and `subarray` return a Buffer, and `Uint8Array.BYTES_PER_ELEMENT` is defined. ([#64935](https://github.com/anomalyco/opencode/pull/64935), [#64938](https://github.com/anomalyco/opencode/pull/64938), [#64931](https://github.com/anomalyco/opencode/pull/64931), [#64933](https://github.com/anomalyco/opencode/pull/64933), [#64930](https://github.com/anomalyco/opencode/pull/64930), [#64965](https://github.com/anomalyco/opencode/pull/64965))
|
||||||
|
- Fixed large file views not refreshing when only the end of the file changed. ([#65114](https://github.com/anomalyco/opencode/pull/65114))
|
||||||
|
- Fixed the install script failing with a disk-space error when `curl` is installed through Snap. ([#65132](https://github.com/anomalyco/opencode/pull/65132))
|
||||||
|
|
||||||
|
### TUI
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- The new TUI designs are on by default, and the theme named `opencode` is the new theme. The previous default is available as `opencode-classic`, and `opencode2` keeps working as an alias of `opencode`. To go back to the previous designs, turn off **New designs** in the Experiments dialog. ([#64988](https://github.com/anomalyco/opencode/pull/64988))
|
||||||
|
- `/login` and `/auth` open the same dialog as `/connect`, which now lists a single **OpenCode** entry that includes OpenCode Go models. ([#65265](https://github.com/anomalyco/opencode/pull/65265), [#65466](https://github.com/anomalyco/opencode/pull/65466))
|
||||||
|
- Pressing `↓` opens the picker on the first tab with something running, the same tab that clicking the footer opens. ([#64972](https://github.com/anomalyco/opencode/pull/64972))
|
||||||
|
- Text prompt dialogs such as rename session, `/btw`, worktree names and connect forms end with a **Submit** button, and prompt and export dialogs have tighter spacing. ([#64944](https://github.com/anomalyco/opencode/pull/64944))
|
||||||
|
- The `opencode` theme's light mode uses lighter grays for the prompt box, selected tabs and hovered rows. ([#64962](https://github.com/anomalyco/opencode/pull/64962))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed connect forms built from integration fields, such as the Azure resource name, showing an empty row between the title and the input. ([#64944](https://github.com/anomalyco/opencode/pull/64944))
|
||||||
|
- Fixed list dialogs ending with two blank rows, and the **Manage workspaces** footer not staying at the bottom. ([#64983](https://github.com/anomalyco/opencode/pull/64983))
|
||||||
|
- Fixed long dialog lists replacing their last visible row with a stray `…`. ([#64934](https://github.com/anomalyco/opencode/pull/64934))
|
||||||
|
- Fixed the selection bar of a delete-confirmation row staying blue instead of red. ([#64936](https://github.com/anomalyco/opencode/pull/64936))
|
||||||
|
- Fixed file, agent and skill mentions landing on the wrong text when you restore a prompt sent from the desktop or web app that contains tabs or wide characters. ([#63989](https://github.com/anomalyco/opencode/pull/63989))
|
||||||
|
|
||||||
|
### Desktop
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- The browser pane keeps you signed in. Links from the chat open beside the conversation in one saved profile, you can import sign-ins and browsing history from Chrome, Edge, Firefox, Safari and other browsers, and you can install store extensions after reviewing what they can access. The pane gains a right-click menu, find in page, page dialogs, permission prompts, pop-up blocking and readable error pages, and the address bar completes from your history. The agent can read and drive the same signed-in tabs. ([#63002](https://github.com/anomalyco/opencode/pull/63002), [#65073](https://github.com/anomalyco/opencode/pull/65073))
|
||||||
|
- New tabs that a page opens in the browser pane appear beside the tab they came from, and middle-clicking a link opens it in a new tab. ([#65126](https://github.com/anomalyco/opencode/pull/65126), [#65091](https://github.com/anomalyco/opencode/pull/65091))
|
||||||
|
- Comments in the browser pane, file viewer and review diff can be sent to the session right away with `Mod+Enter`. Depending on your follow-up setting, they send, steer or queue. ([#65264](https://github.com/anomalyco/opencode/pull/65264))
|
||||||
|
- Added **Wrap code blocks** under Settings › General › Timeline, plus a **Wrap lines** button on timeline code blocks with lines too long to fit. ([#64545](https://github.com/anomalyco/opencode/pull/64545), [#64576](https://github.com/anomalyco/opencode/pull/64576))
|
||||||
|
- Added **Keep side panel open across sessions** in Settings › General. ([#64950](https://github.com/anomalyco/opencode/pull/64950))
|
||||||
|
- Added an **Archive session** command, bound to `Cmd+Shift+S` (`Ctrl+Shift+S` on Windows and Linux). ([#65428](https://github.com/anomalyco/opencode/pull/65428))
|
||||||
|
- The Home session menu has **Open** and **Open in background**, and Home shows the provider connect hint when nothing is connected. ([#65209](https://github.com/anomalyco/opencode/pull/65209), [#65212](https://github.com/anomalyco/opencode/pull/65212), [#64885](https://github.com/anomalyco/opencode/pull/64885))
|
||||||
|
- The Inbox layout's sidebar has a **Drafts** group for unsent new-session drafts. ([#65525](https://github.com/anomalyco/opencode/pull/65525))
|
||||||
|
- Conversation search (`Cmd+F` / `Ctrl+F`) has previous and next match buttons. ([#64865](https://github.com/anomalyco/opencode/pull/64865))
|
||||||
|
- The connect dialog lists one **OpenCode** option that includes OpenCode Go models, Settings › Providers follows the same rule, and the free model picker has a tighter layout. ([#65466](https://github.com/anomalyco/opencode/pull/65466), [#65740](https://github.com/anomalyco/opencode/pull/65740), [#64927](https://github.com/anomalyco/opencode/pull/64927))
|
||||||
|
- When you reach your ChatGPT Business workspace's usage limit, a dialog explains it and offers **Copy request for admin**. ([#64926](https://github.com/anomalyco/opencode/pull/64926))
|
||||||
|
- Voice uses the newest GPT-Live model the server lists. ([#65506](https://github.com/anomalyco/opencode/pull/65506))
|
||||||
|
- Shortcuts go through the same keymap engine as the TUI, and the new **Stop session** command can be changed in Settings › Shortcuts. ([#64394](https://github.com/anomalyco/opencode/pull/64394))
|
||||||
|
- Shortcuts can be key chords, such as `Mod+K Mod+C` or `G I`. In Settings › Shortcuts, click **+** on a shortcut you just recorded to add another key, up to 4. While a chord is pending, a panel lists the keys that continue it. ([#64395](https://github.com/anomalyco/opencode/pull/64395))
|
||||||
|
- The activity pill keeps a subagent listed while work it started is still running. ([#64790](https://github.com/anomalyco/opencode/pull/64790))
|
||||||
|
- The goal pill has a new design with the labels Following goal, Goal paused and Goal reached. ([#60001](https://github.com/anomalyco/opencode/pull/60001))
|
||||||
|
- Keyboard focus shows as one consistent ring across the app, no longer appears after a mouse click, and moves to the next item when the focused one is removed. The timeline and the composer no longer draw a ring around their whole frame. ([#64909](https://github.com/anomalyco/opencode/pull/64909), [#64976](https://github.com/anomalyco/opencode/pull/64976), [#65082](https://github.com/anomalyco/opencode/pull/65082), [#65084](https://github.com/anomalyco/opencode/pull/65084), [#65100](https://github.com/anomalyco/opencode/pull/65100), [#65690](https://github.com/anomalyco/opencode/pull/65690))
|
||||||
|
- Only the latest response shows its Copy button all the time; older ones show it on hover or focus. ([#64640](https://github.com/anomalyco/opencode/pull/64640))
|
||||||
|
- Added experimental tab groups for side tabs under Settings › Experimental. ([#64407](https://github.com/anomalyco/opencode/pull/64407))
|
||||||
|
- On Windows, the taskbar button shows session status as a progress bar, a count badge for sessions that need you, and flashes when a permission or question is waiting. Notifications say what is being asked and disappear once you answer. ([#65317](https://github.com/anomalyco/opencode/pull/65317), [#65318](https://github.com/anomalyco/opencode/pull/65318), [#65319](https://github.com/anomalyco/opencode/pull/65319), [#65325](https://github.com/anomalyco/opencode/pull/65325), [#65421](https://github.com/anomalyco/opencode/pull/65421))
|
||||||
|
- On Windows, the jump list has **New Session** and **New Window**, you can drag files from the file tree into other apps, and **Open in** includes Windows Terminal and lists only installed apps. ([#65327](https://github.com/anomalyco/opencode/pull/65327), [#65330](https://github.com/anomalyco/opencode/pull/65330), [#65320](https://github.com/anomalyco/opencode/pull/65320))
|
||||||
|
- The web app can be built to run under a path prefix, for example behind a reverse proxy, with `bun --cwd packages/app build --base=/opencode/`. ([#64597](https://github.com/anomalyco/opencode/pull/64597))
|
||||||
|
- The background activity menu stays smooth with many subagents, and the model picker stays responsive with catalogs of thousands of models. ([#65634](https://github.com/anomalyco/opencode/pull/65634), [#65189](https://github.com/anomalyco/opencode/pull/65189), [#65635](https://github.com/anomalyco/opencode/pull/65635))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed `opencode://open-project` and `opencode://new-session` links doing nothing. ([#65332](https://github.com/anomalyco/opencode/pull/65332))
|
||||||
|
- Fixed file links like `~/Downloads/clip.mp4` showing "File not found". `~` now opens in the server's home folder. ([#65689](https://github.com/anomalyco/opencode/pull/65689))
|
||||||
|
- Fixed an open session's side panel tabs disappearing after you had used many other sessions. ([#65328](https://github.com/anomalyco/opencode/pull/65328), [#65322](https://github.com/anomalyco/opencode/pull/65322))
|
||||||
|
- Fixed the app freezing when opening a session on a remote server with **Share sign-ins with remote servers** on. ([#65339](https://github.com/anomalyco/opencode/pull/65339))
|
||||||
|
- Fixed the app freezing for several seconds when you open a group of long Code Mode scripts. An Execute row now lists its latest 10 calls, with **+N more** for the earlier ones. ([#65696](https://github.com/anomalyco/opencode/pull/65696))
|
||||||
|
- Fixed the browser pane showing "The browser couldn't open" in a project whose server had only just started. ([#65720](https://github.com/anomalyco/opencode/pull/65720))
|
||||||
|
- Fixed **Clear browsing data** clearing everything on the first click; it now asks first. ([#65124](https://github.com/anomalyco/opencode/pull/65124))
|
||||||
|
- Fixed browser tabs showing a generic globe instead of the site's icon, saved tabs appearing late after the app reopens, and the page going blank while a panel is resized on Windows. ([#65094](https://github.com/anomalyco/opencode/pull/65094), [#65067](https://github.com/anomalyco/opencode/pull/65067), [#65083](https://github.com/anomalyco/opencode/pull/65083))
|
||||||
|
- Fixed sites in the browser pane replacing the app's badge on the taskbar or Dock. ([#65646](https://github.com/anomalyco/opencode/pull/65646))
|
||||||
|
- Fixed the mouse Back and Forward buttons doing nothing. ([#65129](https://github.com/anomalyco/opencode/pull/65129))
|
||||||
|
- Fixed a subagent's pending permission request not reappearing after a reload or reconnect. ([#65120](https://github.com/anomalyco/opencode/pull/65120))
|
||||||
|
- Fixed background jobs that changed while the job list was loading showing the wrong state, and rows in the activity menu jumping around. ([#64966](https://github.com/anomalyco/opencode/pull/64966), [#65312](https://github.com/anomalyco/opencode/pull/65312))
|
||||||
|
- Fixed the session view crashing when a timeline row disappeared mid-update. ([#64565](https://github.com/anomalyco/opencode/pull/64565))
|
||||||
|
- Fixed earlier replies being folded into the "Used N tools" group when a session was woken without a new message. ([#64917](https://github.com/anomalyco/opencode/pull/64917))
|
||||||
|
- Fixed the Context tab showing the latest instruction update as the "System Prompt". ([#64991](https://github.com/anomalyco/opencode/pull/64991))
|
||||||
|
- Fixed the session header briefly showing the wrong worktree while a new session starts. ([#65190](https://github.com/anomalyco/opencode/pull/65190))
|
||||||
|
- Fixed Grep, Glob and List rows showing the parent of the folder they searched, and Windows paths not showing relative to the project. ([#65460](https://github.com/anomalyco/opencode/pull/65460), [#65639](https://github.com/anomalyco/opencode/pull/65639))
|
||||||
|
- Fixed server event streams going stale after Windows wakes from sleep, and windows reopening in the wrong place after being snapped or minimized. ([#65321](https://github.com/anomalyco/opencode/pull/65321), [#65323](https://github.com/anomalyco/opencode/pull/65323))
|
||||||
|
- Fixed the Windows caption buttons being hard to see with a contrast theme. ([#65324](https://github.com/anomalyco/opencode/pull/65324))
|
||||||
|
- Fixed **Open in PowerShell** on Windows opening Windows PowerShell instead of PowerShell 7 when it's installed. ([#64873](https://github.com/anomalyco/opencode/pull/64873))
|
||||||
|
- Fixed builds packaged without `app-update.yml`, such as AUR packages, showing update-check errors. Settings now shows **Updates unavailable**. ([#64681](https://github.com/anomalyco/opencode/pull/64681))
|
||||||
|
- Fixed the message menu's "Today" and "Yesterday" labels, and Home's date headers staying invisible while scrolling. ([#65081](https://github.com/anomalyco/opencode/pull/65081), [#64665](https://github.com/anomalyco/opencode/pull/64665))
|
||||||
|
- Fixed clipped or misleading focus rings, the side panel's add button being skipped by `Tab`, and the **Compacted** label only partly highlighting on hover. ([#65215](https://github.com/anomalyco/opencode/pull/65215), [#65192](https://github.com/anomalyco/opencode/pull/65192), [#65176](https://github.com/anomalyco/opencode/pull/65176), [#65177](https://github.com/anomalyco/opencode/pull/65177), [#65211](https://github.com/anomalyco/opencode/pull/65211), [#65213](https://github.com/anomalyco/opencode/pull/65213), [#65644](https://github.com/anomalyco/opencode/pull/65644))
|
||||||
|
- Fixed the Hex voice tip showing on phones and tablets, and a fringe on project icon corners. ([#64583](https://github.com/anomalyco/opencode/pull/64583), [#64582](https://github.com/anomalyco/opencode/pull/64582))
|
||||||
|
|
||||||
|
### SDK
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Added `experimental.job.cancel` to cancel a running background job, and an `experimental.job.updated` event when a job starts, moves to the background or ends. `@opencode/client/solid`'s `createData` has a `job` slice. ([#64790](https://github.com/anomalyco/opencode/pull/64790), [#65266](https://github.com/anomalyco/opencode/pull/65266), [#64956](https://github.com/anomalyco/opencode/pull/64956))
|
||||||
|
- The video endpoints (`experimental.generate.video.create` and `.get`) no longer need a flag. Video jobs survive a server restart, can return more than one video, and stay readable for 24 hours after they finish. ([#65664](https://github.com/anomalyco/opencode/pull/65664), [#64546](https://github.com/anomalyco/opencode/pull/64546))
|
||||||
|
- The automation endpoints work without a flag, and an automation can run a shell command as its action. ([#65296](https://github.com/anomalyco/opencode/pull/65296), [#65186](https://github.com/anomalyco/opencode/pull/65186))
|
||||||
|
|
||||||
|
### Extensions
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- A plugin tool can set `options.codemode` to an object (`{ pinned?, description?, input?, output? }`) to give its Code Mode form its own description and schemas. Top-level `options.pinned` still works but is deprecated. ([#64515](https://github.com/anomalyco/opencode/pull/64515))
|
||||||
|
- The `execute.before` and `execute.after` tool hooks receive `info`, the tool's definition, and `codemode`, which is true when a Code Mode script made the call. ([#64515](https://github.com/anomalyco/opencode/pull/64515))
|
||||||
|
- An integration's OAuth method can define `revoke` to sign a credential out remotely before it's removed. ([#64947](https://github.com/anomalyco/opencode/pull/64947))
|
||||||
|
- TUI plugins can read a session's running background jobs with `api.data.job.list(sessionID)` (experimental). ([#64956](https://github.com/anomalyco/opencode/pull/64956))
|
||||||
|
- `experimental.idle` background entries can have the kind `video`. ([#63666](https://github.com/anomalyco/opencode/pull/63666))
|
||||||
|
- GUI plugins can declare their own SVG icons with `Plugin.define({ icons })` and use them through `ctx.icons`. The built-in `outline-pair` and `outline-steer` icons were removed. ([#64577](https://github.com/anomalyco/opencode/pull/64577))
|
||||||
|
- The GUI composer API adds `composer.send(commentID)` and `composer.delivery()`, and the `Browser` contract adds `experimental.open` and `experimental.close`. ([#65264](https://github.com/anomalyco/opencode/pull/65264), [#63002](https://github.com/anomalyco/opencode/pull/63002))
|
||||||
|
- GUI `System.open` only launches HTTP, HTTPS and mail URLs, and `Browser.open` refuses `file://` URLs outside the built-in preview. ([#63002](https://github.com/anomalyco/opencode/pull/63002))
|
||||||
|
|
||||||
|
## v2.3.2 — 2026-11-18
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **GPT-6.2 Prompt Caching**: GPT-6.2 models don't cache a system prompt sent in the Responses `instructions` field, so every step re-billed it as uncached input. OpenCode now sends it as a leading developer message on every Responses route, including OpenAI (API key and ChatGPT sign-in), GitHub Copilot, Zen, Azure and OpenRouter, so it is cached from the second step on. ([#64542](https://github.com/anomalyco/opencode/pull/64542), [#64544](https://github.com/anomalyco/opencode/pull/64544))
|
||||||
|
|
||||||
|
### Core
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed GPT-6.2 models re-billing the system prompt as uncached input on every step. On GitHub Copilot `gpt-6.2-sol`, uncached input per step dropped from about 14,000 tokens to 3. Compaction through `/responses/compact` now reads the same cached prefix. ([#64542](https://github.com/anomalyco/opencode/pull/64542), [#64544](https://github.com/anomalyco/opencode/pull/64544))
|
||||||
|
- `webfetch` structured output no longer repeats the `url` and `format` it was called with. ([#64534](https://github.com/anomalyco/opencode/pull/64534))
|
||||||
|
|
||||||
|
## v2.3.1 — 2026-11-17
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Timed-Out Shell Commands Keep Running**: A shell command still running when its timeout expires now moves to the background instead of being killed, so long builds and test runs finish and report back. A foreground `timeout: 0` now means the default 120 seconds. ([#63699](https://github.com/anomalyco/opencode/pull/63699))
|
||||||
|
- **Compaction Without the Wait**: As a session nears automatic compaction, the summary is now written in the background, so your next prompt doesn't pause for it. Set `compaction.background: false` to turn it off; a background summary that ends up unused still costs tokens. ([#64290](https://github.com/anomalyco/opencode/pull/64290))
|
||||||
|
- **GPT 6.2 with ChatGPT Sign-In**: GPT 6.2 Sol and GPT 6.2 Astra, plus their fast variants, now show up in the model picker when you sign in with ChatGPT. ([#64508](https://github.com/anomalyco/opencode/pull/64508))
|
||||||
|
- **Update Plugins from Settings**: Open **Settings › Extensions**, click **Check for updates**, then **Update** on any plugin with a new version. ([#64511](https://github.com/anomalyco/opencode/pull/64511))
|
||||||
|
- **Comment on Selected Code**: Selecting code in diff and file viewers now just selects it, so you can copy it, and an **Add comment** toolbar appears beside the selection. ([#64410](https://github.com/anomalyco/opencode/pull/64410))
|
||||||
|
|
||||||
|
### Core
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Shell commands still running when their timeout expires now move to the background instead of being killed, in every build. The `shell_timeout_background` flag is gone; configs that still set it keep loading. A foreground `timeout: 0` now uses the default 120 second timeout instead of waiting until the command exits. ([#63699](https://github.com/anomalyco/opencode/pull/63699))
|
||||||
|
- Background compaction is now on by default: as a session nears automatic compaction, the summary is written in the background so the next prompt doesn't wait for it. Turn it off with `compaction.background: false`; a background summary that is never used still costs tokens. The `experimental.background_compaction` setting is removed. ([#64290](https://github.com/anomalyco/opencode/pull/64290))
|
||||||
|
- OpenCode again reads `CLAUDE.md` in any directory that has no `AGENTS.md`, and falls back to `~/.claude/CLAUDE.md` when the global `AGENTS.md` is missing. This also applies to instructions found when the agent reads nested files. Set `OPENCODE_DISABLE_CLAUDE_CODE` or `OPENCODE_DISABLE_CLAUDE_CODE_PROMPT` to skip every `CLAUDE.md`. ([#64474](https://github.com/anomalyco/opencode/pull/64474), [#64533](https://github.com/anomalyco/opencode/pull/64533))
|
||||||
|
- Added GPT 6.2 Sol and GPT 6.2 Astra, plus their fast variants, to the ChatGPT model list. ([#64508](https://github.com/anomalyco/opencode/pull/64508))
|
||||||
|
- `websearch` now returns a flat list of results, each with its `url`, `title`, `content` and `published` date. ([#64471](https://github.com/anomalyco/opencode/pull/64471))
|
||||||
|
- Code Mode and plugins get a simpler structured result from `read`: `text` (with `offset`, `lineCount` and `next`), `directory` (entry names) or `media` (a URI instead of base64). What the model sees is unchanged. ([#64361](https://github.com/anomalyco/opencode/pull/64361))
|
||||||
|
- Code Mode programs can use Node's `Buffer` for encoding and decoding bytes. ([#64365](https://github.com/anomalyco/opencode/pull/64365))
|
||||||
|
- In Code Mode, `search("issues")` now works as shorthand for `search({ query: "issues" })`. ([#64347](https://github.com/anomalyco/opencode/pull/64347))
|
||||||
|
- Code Mode tool summaries in the catalog can now be up to 500 characters instead of 120, so the model sees more of each tool's description. ([#64341](https://github.com/anomalyco/opencode/pull/64341))
|
||||||
|
- The `glob` and `grep` tools now report a malformed filename glob (for example `[`) as an error that names the parameter to fix, instead of returning no results. ([#63960](https://github.com/anomalyco/opencode/pull/63960))
|
||||||
|
- Server requests that crash now return a 500 with a readable JSON `UnknownError` body instead of an empty one. Storage problems name the cause (for example "Storage is full" or "Storage is read-only"); other crashes include a `ref` you can find in the server log. ([#64022](https://github.com/anomalyco/opencode/pull/64022))
|
||||||
|
- The shell tool description now tells the model that its session ID is in the `OPENCODE_SESSION_ID` environment variable. ([#63718](https://github.com/anomalyco/opencode/pull/63718))
|
||||||
|
- Experimental schedules are now automations, behind the `automations` flag (the old `schedules` flag still works). An automation runs on a time, an interval, a cron or a pushed MCP event, and either sends a prompt (to the creating session, another session or a new subagent) or runs a Code Mode program that decides whether to send one. Use `/automation` or the `automation_*` tools. Active or paused plain prompt schedules carry over; schedules with a condition or run limit, and finished ones, are dropped. ([#64160](https://github.com/anomalyco/opencode/pull/64160))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed finished shell commands leaving zombie processes under `opencode-pty`. The process daemon now cleans each command up when it exits. Background processes started by a successful command (`cmd &`) keep running, and a failed command's leftovers are stopped. ([#64266](https://github.com/anomalyco/opencode/pull/64266), [#64251](https://github.com/anomalyco/opencode/pull/64251))
|
||||||
|
- Fixed ChatGPT and OpenAI subscription logins losing their sharing-limit safeguards and context caps when a token refresh failed. ([#64470](https://github.com/anomalyco/opencode/pull/64470))
|
||||||
|
- Fixed Claude Agent models falling back to a 200K context window when Claude Code adds or renames a model. Thanks @Tarquinen. ([#64107](https://github.com/anomalyco/opencode/pull/64107))
|
||||||
|
- Fixed requests being rejected after switching models mid-session on OpenAI-compatible providers. Models that declare a different reasoning field (such as `reasoning_content`) no longer receive `reasoning_details` from earlier turns. ([#64243](https://github.com/anomalyco/opencode/pull/64243))
|
||||||
|
- Rejecting a permission request now rejects only the other pending requests from the same step, not every pending request in the session. ([#64343](https://github.com/anomalyco/opencode/pull/64343))
|
||||||
|
- Fixed a finished subagent being reported to its parent as still running when its answer quoted the "Background work still running" heading. ([#64026](https://github.com/anomalyco/opencode/pull/64026))
|
||||||
|
- Fixed ACP clients missing turns that a background shell woke after the original turn ended. ([#64262](https://github.com/anomalyco/opencode/pull/64262))
|
||||||
|
- Reading a small text file now applies the default line and byte limits, so a short file with very many lines is paged instead of returned whole. ([#63810](https://github.com/anomalyco/opencode/pull/63810))
|
||||||
|
- Paged reads that select a single blank line now return that line instead of an empty result. ([#63809](https://github.com/anomalyco/opencode/pull/63809))
|
||||||
|
- `read` now rejects `limit: 0` with "Limit must be a positive integer". ([#63808](https://github.com/anomalyco/opencode/pull/63808))
|
||||||
|
- Text files that start with `BM` are no longer mistaken for BMP images, and only real `GIF87a`/`GIF89a` headers count as GIFs, so these files read as text again. ([#63822](https://github.com/anomalyco/opencode/pull/63822), [#63811](https://github.com/anomalyco/opencode/pull/63811))
|
||||||
|
- Fixed shell output pages, grep previews, generated titles, read lines and shell output tails splitting emoji and other multi-byte characters, which showed up as `<60>`. ([#63984](https://github.com/anomalyco/opencode/pull/63984), [#63967](https://github.com/anomalyco/opencode/pull/63967))
|
||||||
|
- Shell commands using unknown ANSI-C escapes such as `$'\q'` are now read the same way Bash and Zsh read them, so permission rules can match them. ([#64263](https://github.com/anomalyco/opencode/pull/64263))
|
||||||
|
- Session title search is now case-insensitive for non-ASCII letters, such as Cyrillic and accented text. ([#64259](https://github.com/anomalyco/opencode/pull/64259))
|
||||||
|
- Fixed `grep` results being dropped when a matching line or path is not valid UTF-8. Thanks @Tarquinen. ([#62249](https://github.com/anomalyco/opencode/pull/62249))
|
||||||
|
- The `@` file picker now finds files in hidden folders such as `.github/` and dotfiles such as `.env.example` when file search uses ripgrep (the default on Windows and outside git repos). `.git` and gitignored files stay excluded. Thanks @Tarquinen. ([#62577](https://github.com/anomalyco/opencode/pull/62577))
|
||||||
|
- An unreachable well-known integration source is now skipped instead of dropping every well-known source. Thanks @Tarquinen. ([#62578](https://github.com/anomalyco/opencode/pull/62578))
|
||||||
|
- A corrupt cached project ID is now ignored instead of being used. Thanks @Tarquinen. ([#62576](https://github.com/anomalyco/opencode/pull/62576))
|
||||||
|
- Plugin tool renames from `tool.execute.before` now apply to calls inside Code Mode programs, and a renamed call returns the new tool's structured result. ([#63633](https://github.com/anomalyco/opencode/pull/63633), [#64333](https://github.com/anomalyco/opencode/pull/64333))
|
||||||
|
- In Code Mode, calling a tool that doesn't exist now returns a rejected promise, so `.catch` and `Promise.allSettled` can handle it instead of the whole script failing. ([#64510](https://github.com/anomalyco/opencode/pull/64510))
|
||||||
|
- A Code Mode program that only logs no longer shows a stray `null` line before its logs. ([#64344](https://github.com/anomalyco/opencode/pull/64344))
|
||||||
|
|
||||||
|
### TUI
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Permission prompts from a subagent, and from that subagent's own subagents, now appear while you view the subagent's session. Prompts also show in front of an open composer. ([#64343](https://github.com/anomalyco/opencode/pull/64343))
|
||||||
|
- The export dialog under the new designs can save to the system temp directory as well as the project folder. Thanks @Tarquinen. ([#62490](https://github.com/anomalyco/opencode/pull/62490))
|
||||||
|
- Removed time to first token (ttft) from the assistant message footer. Tokens per second still shows when `session.tps` is on. ([#63759](https://github.com/anomalyco/opencode/pull/63759))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- When another TUI sharing your tabs closes the session you're viewing, closing it here now moves to the neighbouring tab. ([#64261](https://github.com/anomalyco/opencode/pull/64261))
|
||||||
|
- Fixed broken characters at the edges of the shell output viewer and the inline shell display when output is long. ([#63967](https://github.com/anomalyco/opencode/pull/63967), [#63984](https://github.com/anomalyco/opencode/pull/63984))
|
||||||
|
|
||||||
|
### Desktop
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- You can check for and install plugin package updates from **Settings › Extensions**. Use **Check for updates** to look for new versions, then click **Update** on any plugin that has one. ([#64511](https://github.com/anomalyco/opencode/pull/64511), [#64525](https://github.com/anomalyco/opencode/pull/64525))
|
||||||
|
- Selecting code in diff and file viewers now just selects text, so you can copy it. An **Add comment** toolbar appears next to the selection to comment on those lines; line numbers and the gutter `+` still start a comment directly. ([#64410](https://github.com/anomalyco/opencode/pull/64410))
|
||||||
|
- Cmd+F (Ctrl+F) now finds text in Markdown, Mermaid, CSV and HTML previews in the side panel, using the same find bar as the code view. ([#63663](https://github.com/anomalyco/opencode/pull/63663))
|
||||||
|
- Disconnecting a provider or removing an account in **Settings → Providers** now asks for confirmation first. Disconnecting OpenCode Console says how many providers will stop working. ([#64212](https://github.com/anomalyco/opencode/pull/64212))
|
||||||
|
- The model picker's variant flyout now follows the keyboard: it opens beside the highlighted row, `→` enters it to pick a variant or toggle Favorite, and `←` or `Escape` goes back. A model's Console budget and reset time now show in the flyout. ([#64409](https://github.com/anomalyco/opencode/pull/64409), [#64423](https://github.com/anomalyco/opencode/pull/64423))
|
||||||
|
- When **New worktree** is selected for a new session, the composer shows the base branch (`from dev ▾`). Click it to pick another base; the choice applies immediately, and **Use main checkout** switches back. ([#64228](https://github.com/anomalyco/opencode/pull/64228))
|
||||||
|
- Redesigned the folder picker for remote servers, with a path bar, up to three recent-project pills plus a **More projects** menu, and a search box that shows the selected folder. ([#64241](https://github.com/anomalyco/opencode/pull/64241))
|
||||||
|
- ` ```latex ` and ` ```math ` code fences now render as display math once complete. ([#64380](https://github.com/anomalyco/opencode/pull/64380))
|
||||||
|
- The new icon set is now the default, and the **New icons** experiment has been removed. ([#64466](https://github.com/anomalyco/opencode/pull/64466), [#64451](https://github.com/anomalyco/opencode/pull/64451))
|
||||||
|
- The copy button under assistant messages is now always visible. Message metadata still appears on hover. ([#64478](https://github.com/anomalyco/opencode/pull/64478))
|
||||||
|
- Text files opened in side-panel tabs now have the same copy and download actions as other files. ([#64463](https://github.com/anomalyco/opencode/pull/64463))
|
||||||
|
- **Manage models** now shows every provider as a card with a `⋯` menu, whether or not you're signed in to OpenCode Console. ([#64235](https://github.com/anomalyco/opencode/pull/64235))
|
||||||
|
- The connect provider dialog has a cleaner layout for every sign-in step: breadcrumbs, method icons, full-width device codes, and a "Signing in from another device?" row for pasting a redirect URL. ([#63829](https://github.com/anomalyco/opencode/pull/63829))
|
||||||
|
- **Collapse long messages** is no longer experimental. It is now a setting under **Timeline** preferences. ([#64441](https://github.com/anomalyco/opencode/pull/64441))
|
||||||
|
- Settings now opens on your client preferences, which are listed first, pairing is grouped with Servers, and there's a **Help & feedback** link. ([#64440](https://github.com/anomalyco/opencode/pull/64440), [#64220](https://github.com/anomalyco/opencode/pull/64220))
|
||||||
|
- Automatic compactions now always show as a single quiet divider; manual and failed compactions still show the full record. ([#64290](https://github.com/anomalyco/opencode/pull/64290))
|
||||||
|
- Pairing QR codes can carry a server name, which becomes the paired server's default name. ([#64139](https://github.com/anomalyco/opencode/pull/64139))
|
||||||
|
- Image attachment thumbnails are larger, with a 3:2 crop, and a failed image no longer moves the message below it when retried. ([#64215](https://github.com/anomalyco/opencode/pull/64215))
|
||||||
|
- The Hex voice tip no longer appears when Hex is already installed, its copy now says what Hex is, and tips wait an hour after first launch before the first one shows. ([#64130](https://github.com/anomalyco/opencode/pull/64130), [#64131](https://github.com/anomalyco/opencode/pull/64131), [#63974](https://github.com/anomalyco/opencode/pull/63974), [#63760](https://github.com/anomalyco/opencode/pull/63760))
|
||||||
|
- Added missing translations for every non-English language, about 920 strings each. ([#64205](https://github.com/anomalyco/opencode/pull/64205))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed the desktop app failing to start when `drafts.sqlite` was a symlink to or copy of the CLI's `opencode.db`. The desktop now moves that file aside and creates its own, leaving the CLI database untouched. ([#64203](https://github.com/anomalyco/opencode/pull/64203))
|
||||||
|
- Switching session tabs with a keyboard shortcut now focuses the composer. ([#64418](https://github.com/anomalyco/opencode/pull/64418))
|
||||||
|
- Long prompts now stay folded while a new session is being created. ([#64452](https://github.com/anomalyco/opencode/pull/64452))
|
||||||
|
- On macOS, the browser pane stays live while you resize panels instead of showing a still image. ([#64443](https://github.com/anomalyco/opencode/pull/64443))
|
||||||
|
- Submenus now open one at a time and swap without blinking, and stay open while you move the pointer across other items to reach them. ([#63739](https://github.com/anomalyco/opencode/pull/63739))
|
||||||
|
- Pressing a button now dismisses its tooltip until you hover it again, and copy buttons show "Copied" for two seconds, including in the `/btw` panel. ([#63834](https://github.com/anomalyco/opencode/pull/63834))
|
||||||
|
- Dialogs now use consistent sizes, corner radius and row styles across the command palette, session search, model picker, location picker and other lists. ([#63432](https://github.com/anomalyco/opencode/pull/63432), [#64216](https://github.com/anomalyco/opencode/pull/64216), [#64206](https://github.com/anomalyco/opencode/pull/64206))
|
||||||
|
- Sessions on OpenCode Go no longer show a $0.00 cost. ([#63744](https://github.com/anomalyco/opencode/pull/63744))
|
||||||
|
- **Use main checkout** now stays on one line in the branch picker, and wrapped question descriptions have better spacing. ([#64450](https://github.com/anomalyco/opencode/pull/64450), [#64446](https://github.com/anomalyco/opencode/pull/64446))
|
||||||
|
- Restyled the **Timeline detail** slider and visibility buttons in settings so they read as clickable. ([#64186](https://github.com/anomalyco/opencode/pull/64186))
|
||||||
|
- Polished small details: animated counts no longer look faded at rest, the sidebar resize pill is hidden, the sidebar peek insets match, subagent breadcrumbs show a hover background, and screen readers name the redirect URL field after its label only. ([#64155](https://github.com/anomalyco/opencode/pull/64155), [#64219](https://github.com/anomalyco/opencode/pull/64219), [#64192](https://github.com/anomalyco/opencode/pull/64192), [#63742](https://github.com/anomalyco/opencode/pull/63742), [#63885](https://github.com/anomalyco/opencode/pull/63885))
|
||||||
|
|
||||||
|
### SDK
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Unhandled server errors now return a JSON `UnknownError` body (`message` and `ref`) with status 500 instead of an empty body. ([#64022](https://github.com/anomalyco/opencode/pull/64022))
|
||||||
|
- Experimental automation endpoints replace the schedule endpoints: `/api/experimental/automation` and `client.experimental.automation.*` (`create`, `list`, `get`, `pause`, `resume`, `delete`). `/api/experimental/schedule` and `client.experimental.schedule.*` are removed. ([#64160](https://github.com/anomalyco/opencode/pull/64160))
|
||||||
|
- Config adds `compaction.background`; `experimental.background_compaction` and the `shell_timeout_background` flag are removed. ([#64290](https://github.com/anomalyco/opencode/pull/64290), [#63699](https://github.com/anomalyco/opencode/pull/63699))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Apps embedding the SDK with an in-memory database no longer import the user's legacy `auth.json` credentials. Only a database file opened by path imports them. ([#63716](https://github.com/anomalyco/opencode/pull/63716))
|
||||||
|
|
||||||
|
### Extensions
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Each tool call inside a Code Mode program now has its own call ID in plugin hooks and traces. Its permission requests still show on the `execute` call's row. ([#64324](https://github.com/anomalyco/opencode/pull/64324))
|
||||||
|
- Plugin `SessionIdleBackground` items can now be `{ kind: "codemode", sessionID, jobID }`, and GUI plugin `BridgeLayout` accepts an optional `clip` rectangle. ([#64343](https://github.com/anomalyco/opencode/pull/64343), [#63819](https://github.com/anomalyco/opencode/pull/63819))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- The browser extension's URL bar action buttons are now spaced 6px apart. ([#64214](https://github.com/anomalyco/opencode/pull/64214))
|
||||||
|
|
||||||
|
## v2.3.0 — 2026-11-13
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- **Background Subagents by Default**: Subagents now return immediately, continue in the background, and report back whenever they become idle. You can keep working in the parent session while multiple subagents run concurrently. ([#63382](https://github.com/anomalyco/opencode/pull/63382))
|
||||||
|
- **Quieter Transcripts by Default**: The TUI now summarizes each run of tool calls and thoughts into one collapsible activity row, so the answer is easier to follow. To see every step again, set **Verbosity** to `medium` or `high` in settings, or set `session.verbosity` in your TUI config; an existing setting is kept. ([#63207](https://github.com/anomalyco/opencode/pull/63207))
|
||||||
|
- **Jump to an Earlier Prompt**: In the desktop app, open **Jump to message** from the command palette or press `Cmd+Alt+G` (`Ctrl+Alt+G` on Windows and Linux) to search prompts across the current session and jump directly to one. ([#63585](https://github.com/anomalyco/opencode/pull/63585))
|
||||||
|
|
||||||
|
### Core
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Subagents now always run in the background, return their session ID immediately, and report results to their parent whenever they become idle. ([#63382](https://github.com/anomalyco/opencode/pull/63382))
|
||||||
|
- Added experimental support for MCP events, behind the `mcp_events` flag. ([#63254](https://github.com/anomalyco/opencode/pull/63254), [#63261](https://github.com/anomalyco/opencode/pull/63261), [#63269](https://github.com/anomalyco/opencode/pull/63269))
|
||||||
|
- Shell commands now survive server handoffs and keep their output when interrupted.
|
||||||
|
- Added experimental support for moving a shell command to the background when its timeout expires, behind the `shell_timeout_background` flag. With the flag on, an explicit timeout on a background command stops it. ([#63024](https://github.com/anomalyco/opencode/pull/63024), [#63703](https://github.com/anomalyco/opencode/pull/63703))
|
||||||
|
- Local Windows shell commands now run through the process daemon.
|
||||||
|
- Added support for freeform tool input on compatible models.
|
||||||
|
- Added LM Studio decision-model support.
|
||||||
|
- Agents are now told when their session is a fork. Thanks @hasta84. ([#63235](https://github.com/anomalyco/opencode/pull/63235))
|
||||||
|
- Tool output truncation now keeps the beginning of the output and preserves a usable preview if the full output cannot be saved.
|
||||||
|
- Tail reads no longer load the entire file into memory.
|
||||||
|
- Providers can present a client certificate for gateways that require mutual TLS. Set `settings.tls` with `cert`, `key` and an optional `passphrase` on the provider; values accept `{file:}` and `{env:}` like `apiKey`. ([#61832](https://github.com/anomalyco/opencode/pull/61832))
|
||||||
|
- When a subagent goes idle while its own background work is still running, its report to the parent now says it is still running, so the parent waits for the final report instead of treating the partial answer as done. ([#63675](https://github.com/anomalyco/opencode/pull/63675))
|
||||||
|
- Code Mode gets simpler structured results from file and skill tools: `write` and `edit` return their confirmation as a string, `patch` returns an empty result, and `skill` returns the skill's directory and content. ([#63616](https://github.com/anomalyco/opencode/pull/63616), [#63635](https://github.com/anomalyco/opencode/pull/63635), [#63618](https://github.com/anomalyco/opencode/pull/63618), [#63623](https://github.com/anomalyco/opencode/pull/63623))
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Fixed case-only file renames in patches on case-insensitive filesystems.
|
||||||
|
- Fixed stale thinking being retained after Claude Agent prompts or tools change.
|
||||||
|
- Fixed directly driven child sessions not resuming after a restart.
|
||||||
|
- Fixed plugin replacement stopping when cleanup of an earlier plugin fails.
|
||||||
|
- Fixed MCP OAuth refreshes and localhost redirects when a server rewrites `127.0.0.1`.
|
||||||
|
- Fixed saved API keys being omitted from local-model discovery.
|
||||||
|
- Local model discovery (Ollama, LM Studio, vLLM) waits up to 15 seconds per request instead of 1, so remote or tunnelled endpoints list their models, and a slow endpoint no longer delays other endpoints or config reloads. ([#63700](https://github.com/anomalyco/opencode/pull/63700))
|
||||||
|
- In Code Mode, calling a namespace as if it were a tool now suggests up to three real tools under it. ([#63697](https://github.com/anomalyco/opencode/pull/63697))
|
||||||
|
- Fixed retryable provider streams losing completed work when interrupted.
|
||||||
|
- Fixed GitHub Copilot requests using the wrong endpoint before models finish loading.
|
||||||
|
- Fixed exhausted request rate limits being treated as terminal. Thanks @Kyle-j-bush. ([#59816](https://github.com/anomalyco/opencode/pull/59816))
|
||||||
|
- Fixed LM Studio models with a null context length and accepted decision-type models. Thanks @tomzhu1024. ([#56214](https://github.com/anomalyco/opencode/pull/56214))
|
||||||
|
|
||||||
|
### TUI
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Transcript verbosity now defaults to `low`, which summarizes each run of tools and thoughts into one activity row. A `session.verbosity` you already set is kept. ([#63207](https://github.com/anomalyco/opencode/pull/63207))
|
||||||
|
- Session IDs found in messages can now be opened directly.
|
||||||
|
- Activity tabs are clickable and open the correct view.
|
||||||
|
- Shell mode has its own prompt color under the new designs.
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Restored pasted text when undo brings back its placeholder.
|
||||||
|
- Restored the live draft after browsing prompt history.
|
||||||
|
- Fixed copying a paste from within the prompt selection.
|
||||||
|
- Preserved the Mini composer caret when closing the command palette.
|
||||||
|
- Prevented image bytes from being retained in transcript storage when image previews are disabled.
|
||||||
|
- Fixed paste-chip contrast across light and dark themes.
|
||||||
|
- Fixed plugin-provided themes updating live.
|
||||||
|
- Session lists now open at the top rather than at the current session.
|
||||||
|
- Mini scrollback now shows the subagent card instead of obsolete launch instructions.
|
||||||
|
|
||||||
|
### Desktop
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Added **Jump to message** to the command palette with `Cmd+Alt+G` / `Ctrl+Alt+G`, including prompts not yet loaded in the timeline. Thanks @usrnk1. ([#63585](https://github.com/anomalyco/opencode/pull/63585))
|
||||||
|
- Added the experimental **Recent** sessions sidebar, with cross-server recency, local pins, reordering, and standard session-row actions.
|
||||||
|
- Recent sessions are limited to the last seven days and 30 rows, and can be hidden or muted.
|
||||||
|
- Added an experimental customizable sessions sidebar.
|
||||||
|
- Mermaid diagrams can now be maximized for zooming and panning. ([#59250](https://github.com/anomalyco/opencode/pull/59250))
|
||||||
|
- Added `Alt+Enter` to place a follow-up first in the queue and `Mod+Enter` to steer the next queued prompt.
|
||||||
|
- Holding the modifier key now shows tab shortcut numbers.
|
||||||
|
- Each server’s terminal shell can be selected from its menu.
|
||||||
|
- Added a free-limit panel in place of the composer when applicable.
|
||||||
|
- Session IDs are easier to find and copy.
|
||||||
|
|
||||||
|
#### Bug fixes
|
||||||
|
|
||||||
|
- Recent sessions now keep stable recency ordering through list reloads, renames, and completed runs.
|
||||||
|
- Fixed browser panes not retrying after server plugins finish loading.
|
||||||
|
- Fixed mention suggestions being recreated while typing.
|
||||||
|
- Fixed SSH prompts failing to advance or close after connection.
|
||||||
|
- Fixed pasted provider-auth redirect URLs being rejected.
|
||||||
|
- Restored message footers in the New timeline.
|
||||||
|
- Fixed links whose labels contain inline code.
|
||||||
|
- Fixed the desktop main process freezing while probing the login-shell environment.
|
||||||
|
- Fixed the drag region after changing layout direction.
|
||||||
|
- Fixed vertical-tab previews snapping to the wrong tab.
|
||||||
|
- Fixed the file-tree sidebar opening animation.
|
||||||
|
- Fixed pairing QR-code contrast in light themes. Thanks @ssskay. ([#63220](https://github.com/anomalyco/opencode/pull/63220))
|
||||||
|
- Fixed activity-tab navigation and click handling. Thanks @OpeOginni. ([#60168](https://github.com/anomalyco/opencode/pull/60168))
|
||||||
|
|
||||||
|
### SDK
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Event subscriptions can now receive `experimental.mcp.event` events from MCP event subscriptions.
|
||||||
|
- Model capability schemas now advertise supported freeform tool-input formats.
|
||||||
|
- Session throughput is now measured from the first streamed token.
|
||||||
|
- Session creation documentation now clarifies the `parentID` field.
|
||||||
|
|
||||||
|
### Extensions
|
||||||
|
|
||||||
|
#### Improvements
|
||||||
|
|
||||||
|
- Promise-based tools can cooperatively stop through `ToolContext.signal`.
|
||||||
|
- Added the experimental `session.fork` hook.
|
||||||
|
- Promise plugin cleanup failures no longer prevent subsequent plugin replacements.
|
||||||
|
- `@opencode/plugin/effect` now exports `Tool`, so an `execute.before` hook can reject a call with `Tool.Error` without importing `@opencode/schema/tool`. ([#63698](https://github.com/anomalyco/opencode/pull/63698))
|
||||||
|
|
||||||
## v2.2.7 — 2026-11-10
|
## v2.2.7 — 2026-11-10
|
||||||
|
|
||||||
### Highlights
|
### Highlights
|
||||||
|
|
|
||||||
|
|
@ -110,4 +110,4 @@ OpenCode 内置两种 Agent,可用 `Tab` 键快速切换:
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=52ao9352-5623-4fa0-b7dd-3407c392c1af&qr_code=true) | [X.com](https://x.com/opencode)
|
**加入我们的社区** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=a53kb082-3aff-41fb-b412-b3e669334f16&qr_code=true) | [X.com](https://x.com/opencode)
|
||||||
|
|
|
||||||
|
|
@ -110,4 +110,4 @@ OpenCode 內建了兩種 Agent,您可以使用 `Tab` 鍵快速切換。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=52ao9352-5623-4fa0-b7dd-3407c392c1af&qr_code=true) | [X.com](https://x.com/opencode)
|
**加入我們的社群** [飞书](https://applink.feishu.cn/client/chat/chatter/add_by_link?link_token=a53kb082-3aff-41fb-b412-b3e669334f16&qr_code=true) | [X.com](https://x.com/opencode)
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
exact = true
|
exact = true
|
||||||
# Only install newly resolved package versions published at least 3 days ago.
|
# Only install newly resolved package versions published at least 3 days ago.
|
||||||
minimumReleaseAge = 259200
|
minimumReleaseAge = 259200
|
||||||
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-arm64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta", "@textjs/app", "@textjs/core", "@textjs/opencode", "@textjs/react"]
|
minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-arm64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta", "@textjs/app", "@textjs/core", "@textjs/opencode", "@textjs/react", "psychoscript"]
|
||||||
|
|
||||||
[test]
|
[test]
|
||||||
root = "./do-not-run-tests-from-root"
|
root = "./do-not-run-tests-from-root"
|
||||||
|
|
|
||||||
6
flake.lock
generated
6
flake.lock
generated
|
|
@ -2,11 +2,11 @@
|
||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1790510107,
|
"lastModified": 1794840529,
|
||||||
"narHash": "sha256-EVMNYv7hYDDD9TGVT/hIyTYgpiXA8y3m5xIEIxuGNU0=",
|
"narHash": "sha256-ySrWnmZB5UsZTYGHHnBjllT05O5iFjElCRS+mabtfP0=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "3181085bfd08663b6b9e60bc7a8395c2aaa741bd",
|
"rev": "e21fec321d73511849707a7585e4ea155ee4bf40",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
|
||||||
47
install
47
install
|
|
@ -262,6 +262,26 @@ print_progress() {
|
||||||
printf "\r${ORANGE}%s%s %3d%%${NC}" "$filled" "$empty" "$percent" >&4
|
printf "\r${ORANGE}%s%s %3d%%${NC}" "$filled" "$empty" "$percent" >&4
|
||||||
}
|
}
|
||||||
|
|
||||||
|
install_tmp_dir=""
|
||||||
|
download_curl_pid=""
|
||||||
|
cursor_hidden=false
|
||||||
|
|
||||||
|
cleanup_download() {
|
||||||
|
if [ -n "${download_curl_pid:-}" ]; then
|
||||||
|
kill "$download_curl_pid" 2>/dev/null || true
|
||||||
|
wait "$download_curl_pid" 2>/dev/null || true
|
||||||
|
download_curl_pid=""
|
||||||
|
fi
|
||||||
|
if [ "$cursor_hidden" = "true" ]; then
|
||||||
|
{ printf '\033[?25h' >&4; exec 4>&-; } 2>/dev/null || true
|
||||||
|
cursor_hidden=false
|
||||||
|
fi
|
||||||
|
if [ -n "${install_tmp_dir:-}" ]; then
|
||||||
|
rm -rf "$install_tmp_dir"
|
||||||
|
install_tmp_dir=""
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
download_with_progress() {
|
download_with_progress() {
|
||||||
local url="$1"
|
local url="$1"
|
||||||
local output="$2"
|
local output="$2"
|
||||||
|
|
@ -272,20 +292,23 @@ download_with_progress() {
|
||||||
exec 4>/dev/null
|
exec 4>/dev/null
|
||||||
fi
|
fi
|
||||||
|
|
||||||
local headers="${output}.headers"
|
|
||||||
|
|
||||||
# Hide cursor
|
# Hide cursor
|
||||||
printf "\033[?25l" >&4
|
printf "\033[?25l" >&4
|
||||||
|
cursor_hidden=true
|
||||||
|
|
||||||
trap "trap - RETURN; rm -f \"$headers\"; printf '\033[?25h' >&4; exec 4>&-" RETURN
|
trap 'trap - RETURN; if [ "$cursor_hidden" = "true" ]; then printf "\033[?25h" >&4; exec 4>&-; cursor_hidden=false; fi' RETURN
|
||||||
|
|
||||||
|
local headers="${output}.headers"
|
||||||
|
|
||||||
# Poll the file size on a timer so rendering cost stays fixed no matter how many bytes arrive.
|
# Poll the file size on a timer so rendering cost stays fixed no matter how many bytes arrive.
|
||||||
# Read the size with ls because busybox wc -c reads the whole file.
|
# Read the size with ls because busybox wc -c reads the whole file.
|
||||||
curl -fsL -D "$headers" -o "$output" "$url" &
|
# Bash opens both files so a confined curl (e.g. snap) with a private /tmp can still write them.
|
||||||
local curl_pid=$!
|
# npm's CDN omits content-length on HEAD, so read it from this request's headers.
|
||||||
|
curl -fsL -D /dev/stderr "$url" > "$output" 2> "$headers" &
|
||||||
|
download_curl_pid=$!
|
||||||
|
|
||||||
local length bytes
|
local length bytes
|
||||||
while kill -0 "$curl_pid" 2>/dev/null; do
|
while kill -0 "$download_curl_pid" 2>/dev/null; do
|
||||||
if [ -f "$output" ]; then
|
if [ -f "$output" ]; then
|
||||||
length=$(grep -i '^content-length:' "$headers" 2>/dev/null | tail -n 1 | tr -dc '0-9' || true)
|
length=$(grep -i '^content-length:' "$headers" 2>/dev/null | tail -n 1 | tr -dc '0-9' || true)
|
||||||
bytes=$(ls -ln "$output" | awk '{print $5}')
|
bytes=$(ls -ln "$output" | awk '{print $5}')
|
||||||
|
|
@ -295,7 +318,8 @@ download_with_progress() {
|
||||||
done
|
done
|
||||||
|
|
||||||
local ret=0
|
local ret=0
|
||||||
wait "$curl_pid" || ret=$?
|
wait "$download_curl_pid" || ret=$?
|
||||||
|
download_curl_pid=""
|
||||||
if [ "$ret" -eq 0 ]; then
|
if [ "$ret" -eq 0 ]; then
|
||||||
bytes=$(ls -ln "$output" | awk '{print $5}')
|
bytes=$(ls -ln "$output" | awk '{print $5}')
|
||||||
print_progress "$bytes" "$bytes"
|
print_progress "$bytes" "$bytes"
|
||||||
|
|
@ -308,11 +332,16 @@ download_and_install() {
|
||||||
print_message info "\n${MUTED}Installing ${NC}$APP ${MUTED}version: ${NC}$specific_version"
|
print_message info "\n${MUTED}Installing ${NC}$APP ${MUTED}version: ${NC}$specific_version"
|
||||||
local tmp_dir="${TMPDIR:-/tmp}/opencode_install_$$"
|
local tmp_dir="${TMPDIR:-/tmp}/opencode_install_$$"
|
||||||
mkdir -p "$tmp_dir"
|
mkdir -p "$tmp_dir"
|
||||||
|
install_tmp_dir="$tmp_dir"
|
||||||
|
trap cleanup_download EXIT
|
||||||
|
trap 'exit 130' INT
|
||||||
|
trap 'exit 143' TERM
|
||||||
|
|
||||||
if [[ "$os" == "windows" ]] || ! [ -t 2 ] || ! download_with_progress "$url" "$tmp_dir/$filename"; then
|
if [[ "$os" == "windows" ]] || ! [ -t 2 ] || ! download_with_progress "$url" "$tmp_dir/$filename"; then
|
||||||
# Fallback to standard curl on Windows, non-TTY environments, or if custom progress fails
|
# Fallback to standard curl on Windows, non-TTY environments, or if custom progress fails
|
||||||
local ret=0
|
local ret=0
|
||||||
curl -f -# -L -o "$tmp_dir/$filename" "$url" || ret=$?
|
# Redirect in bash instead of passing -o to curl so confined builds (e.g. snap) don't need host /tmp access.
|
||||||
|
curl -f -# -L "$url" > "$tmp_dir/$filename" || ret=$?
|
||||||
# curl exits 23 when it cannot write the file, usually because the temporary directory is full.
|
# curl exits 23 when it cannot write the file, usually because the temporary directory is full.
|
||||||
if [ "$ret" -eq 23 ]; then
|
if [ "$ret" -eq 23 ]; then
|
||||||
print_message error "Could not write the download to $tmp_dir. Make sure it has enough free space, or set TMPDIR to another directory, then try again." >&2
|
print_message error "Could not write the download to $tmp_dir. Make sure it has enough free space, or set TMPDIR to another directory, then try again." >&2
|
||||||
|
|
@ -329,7 +358,7 @@ download_and_install() {
|
||||||
fi
|
fi
|
||||||
mv "$tmp_dir/package/bin/$binary_name" "$INSTALL_DIR/$installed_binary"
|
mv "$tmp_dir/package/bin/$binary_name" "$INSTALL_DIR/$installed_binary"
|
||||||
chmod 755 "$INSTALL_DIR/$installed_binary"
|
chmod 755 "$INSTALL_DIR/$installed_binary"
|
||||||
rm -rf "$tmp_dir"
|
cleanup_download
|
||||||
}
|
}
|
||||||
|
|
||||||
install_from_binary() {
|
install_from_binary() {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"nodeModules": {
|
"nodeModules": {
|
||||||
"x86_64-linux": "sha256-UOVs48Z4yO4TJv859cg89lsul54KB9StTSl/VSQJXmc=",
|
"x86_64-linux": "sha256-LhAICCt8oDBwcwwxDf11PBxJPgKx9gz0TcLcWEoSxp4=",
|
||||||
"aarch64-linux": "sha256-INQvojH68t0J1Hc61N1dJvTJzl89afkQNrUcahxOs9g=",
|
"aarch64-linux": "sha256-lDEEZsLHGVvMgI7dsQqURo+Fo/dUyMisoOy2bb9qUGA=",
|
||||||
"aarch64-darwin": "sha256-AU2AUkdlL1g+hBkMZX93gQeQy6u8F0Gyzuk48yoN8as="
|
"aarch64-darwin": "sha256-ktDDSk98gLUiafmmuWhsIO/1zqi06QeMzp1QvPoaWFE="
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
20
package.json
20
package.json
|
|
@ -2,7 +2,7 @@
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"name": "opencode",
|
"name": "opencode",
|
||||||
"description": "AI-powered development tool",
|
"description": "AI-powered development tool",
|
||||||
"version": "2.2.7",
|
"version": "2.4.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "bun@1.4.4",
|
"packageManager": "bun@1.4.4",
|
||||||
|
|
@ -14,7 +14,7 @@
|
||||||
"dev:desktop": "bun --cwd packages/desktop dev",
|
"dev:desktop": "bun --cwd packages/desktop dev",
|
||||||
"dev:web": "bun --cwd packages/app dev",
|
"dev:web": "bun --cwd packages/app dev",
|
||||||
"dev:site": "bun run --cwd services/site dev",
|
"dev:site": "bun run --cwd services/site dev",
|
||||||
"lint": "oxlint && ast-grep scan -c script/ast-grep/gui-plugins/sgconfig.yml && bun script/sdk-docs.ts && bun script/check-greys.ts",
|
"lint": "oxlint && ast-grep scan -c script/ast-grep/gui-plugins/sgconfig.yml && ast-grep scan --rule script/ast-grep/dialog-size.yml packages && bun script/sdk-docs.ts && bun script/check-greys.ts",
|
||||||
"lint:changed": "bun script/lint-changed.ts",
|
"lint:changed": "bun script/lint-changed.ts",
|
||||||
"lint:effect-patterns": "ast-grep scan -c script/ast-grep/sgconfig.yml packages/util/src packages/core/src packages/server/src packages/protocol/src packages/cli/src",
|
"lint:effect-patterns": "ast-grep scan -c script/ast-grep/sgconfig.yml packages/util/src packages/core/src packages/server/src packages/protocol/src packages/cli/src",
|
||||||
"lint:effect-simplifications": "ast-grep scan -c script/ast-grep/effect-simplifications/sgconfig.yml --off=unused-suppression packages",
|
"lint:effect-simplifications": "ast-grep scan -c script/ast-grep/effect-simplifications/sgconfig.yml --off=unused-suppression packages",
|
||||||
|
|
@ -48,12 +48,12 @@
|
||||||
"@effect/sql-sqlite-node": "4.1.0",
|
"@effect/sql-sqlite-node": "4.1.0",
|
||||||
"@npmcli/arborist": "9.4.0",
|
"@npmcli/arborist": "9.4.0",
|
||||||
"@types/bun": "1.4.3",
|
"@types/bun": "1.4.3",
|
||||||
"@hona/strobe": "0.34.0",
|
"@hona/strobe": "0.44.1",
|
||||||
"@types/cross-spawn": "6.0.6",
|
"@types/cross-spawn": "6.0.6",
|
||||||
"@octokit/rest": "22.0.0",
|
"@octokit/rest": "22.0.0",
|
||||||
"@opentui/core": "0.8.4",
|
"@opentui/core": "0.9.9",
|
||||||
"@opentui/keymap": "0.8.4",
|
"@opentui/keymap": "0.9.9",
|
||||||
"@opentui/solid": "0.8.4",
|
"@opentui/solid": "0.9.9",
|
||||||
"@tanstack/solid-virtual": "3.13.37",
|
"@tanstack/solid-virtual": "3.13.37",
|
||||||
"@standard-schema/spec": "1.1.0",
|
"@standard-schema/spec": "1.1.0",
|
||||||
"@kobalte/core": "0.13.13",
|
"@kobalte/core": "0.13.13",
|
||||||
|
|
@ -110,7 +110,7 @@
|
||||||
"@ast-grep/cli": "0.44.0",
|
"@ast-grep/cli": "0.44.0",
|
||||||
"@hona/strobe": "catalog:",
|
"@hona/strobe": "catalog:",
|
||||||
"@opencode/client": "workspace:*",
|
"@opencode/client": "workspace:*",
|
||||||
"@oxlint/plugins": "1.60.0",
|
"@oxlint/plugins": "1.93.0",
|
||||||
"@tsconfig/bun": "catalog:",
|
"@tsconfig/bun": "catalog:",
|
||||||
"@types/bun": "catalog:",
|
"@types/bun": "catalog:",
|
||||||
"@types/mime-types": "3.0.1",
|
"@types/mime-types": "3.0.1",
|
||||||
|
|
@ -118,7 +118,7 @@
|
||||||
"@typescript/native": "catalog:",
|
"@typescript/native": "catalog:",
|
||||||
"glob": "13.0.5",
|
"glob": "13.0.5",
|
||||||
"husky": "9.1.7",
|
"husky": "9.1.7",
|
||||||
"oxlint": "1.60.0",
|
"oxlint": "1.93.0",
|
||||||
"prettier": "3.6.2",
|
"prettier": "3.6.2",
|
||||||
"semver": "^7.6.0",
|
"semver": "^7.6.0",
|
||||||
"turbo": "2.10.2"
|
"turbo": "2.10.2"
|
||||||
|
|
@ -174,6 +174,8 @@
|
||||||
"electron-updater@6.8.9": "patches/electron-updater@6.8.9.patch",
|
"electron-updater@6.8.9": "patches/electron-updater@6.8.9.patch",
|
||||||
"@pierre/trees@1.0.0-beta.6": "patches/@pierre%2Ftrees@1.0.0-beta.6.patch",
|
"@pierre/trees@1.0.0-beta.6": "patches/@pierre%2Ftrees@1.0.0-beta.6.patch",
|
||||||
"@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch",
|
"@brendonovich/vite-plugin-opencode@0.1.3": "patches/@brendonovich%2Fvite-plugin-opencode@0.1.3.patch",
|
||||||
"@modelcontextprotocol/client@2.4.0": "patches/@modelcontextprotocol%2Fclient@2.4.0.patch"
|
"@modelcontextprotocol/client@2.4.0": "patches/@modelcontextprotocol%2Fclient@2.4.0.patch",
|
||||||
|
"@kobalte/core@0.13.13": "patches/@kobalte%2Fcore@0.13.13.patch",
|
||||||
|
"bun-pty@0.4.11": "patches/bun-pty@0.4.11.patch"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,8 @@
|
||||||
- **One canonical model.** The Schema classes in `src/schema/` are the data model. Do not add a parallel shape or a second construction path.
|
- **One canonical model.** The Schema classes in `src/schema/` are the data model. Do not add a parallel shape or a second construction path.
|
||||||
- **Independent of Session.** Auth, permissions, plugins, and orchestration belong in Core. `ai.stream`/`ai.generate` run exactly one model call.
|
- **Independent of Session.** Auth, permissions, plugins, and orchestration belong in Core. `ai.stream`/`ai.generate` run exactly one model call.
|
||||||
- **Reuse protocols.** Providers compose existing protocols with `Route.make(...)` instead of cloning them.
|
- **Reuse protocols.** Providers compose existing protocols with `Route.make(...)` instead of cloning them.
|
||||||
- **One API, two runtimes.** `ai` from `@opencode/ai` and `ai` from `@opencode/ai/effect` have the same namespaces and operations, with the same names, overloads, input and options (plus `signal` on the Promise side); keep `test/promise-parity.types.ts` passing.
|
- **One API, two runtimes.** `ai` from `@opencode/ai` and `ai` from `@opencode/ai/effect` have the same namespaces and operations, with the same names, overloads, input and options (plus `RunOptions`, `signal` and `http`, on the Promise side); keep `test/promise-parity.types.ts` passing.
|
||||||
|
- **One way to hook HTTP.** Every request goes through `RequestExecutor`, which applies executor-wide middleware (`RequestExecutor.middleware`) and the caller's scoped middleware (`RequestExecutor.withMiddleware`, Promise `{ http }`). Don't add a per-method hook option or send HTTP any other way. A `url` asset downloads with its own `middleware`, which a route sets only for URLs on the provider's origin. Types already require every route to send through the executor it is given, and lint rejects `fetch` and the `HttpClient` import outside `route/executor.ts`. Keep `test/http-hooks.test.ts` passing; it lists every Promise method.
|
||||||
|
|
||||||
## Code style
|
## Code style
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -249,6 +249,29 @@ const logged = RequestExecutor.middleware((request, next) =>
|
||||||
const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged })
|
const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged })
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To hook only some calls, such as adding a per-user header, scope middleware to them. It runs on every provider request
|
||||||
|
they make, whatever the modality: submits, polls, results and cancels. Executor-wide middleware wraps it.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const signed: HttpMiddleware = (request, next) => next(HttpClientRequest.setHeader(request, "x-user", "user-1"))
|
||||||
|
|
||||||
|
// Effect: an Effect or a Stream
|
||||||
|
const video =
|
||||||
|
yield *
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const job = yield* ai.video.start({ model, prompt: "A red balloon floats up" })
|
||||||
|
return yield* ai.video.result(model, job.id)
|
||||||
|
}).pipe(RequestExecutor.withMiddleware(signed))
|
||||||
|
|
||||||
|
// Promise: `http` on any call's options; a handle it returns keeps it
|
||||||
|
await AI.ai.video.start({ model, prompt: "A red balloon floats up" }, { http: signed })
|
||||||
|
```
|
||||||
|
|
||||||
|
Downloading a `url` asset never uses the caller's scoped middleware, so hooks that add credentials can't reach another
|
||||||
|
host such as a CDN or a presigned storage URL. A result URL on the provider's own origin carries the middleware of the
|
||||||
|
call that returned it (`asset.middleware`), so it downloads the same way later. Set `middleware` yourself with
|
||||||
|
`Media.url(url, { middleware })`.
|
||||||
|
|
||||||
## Venice AI
|
## Venice AI
|
||||||
|
|
||||||
`Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat`
|
`Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat`
|
||||||
|
|
@ -1031,12 +1054,29 @@ const program = Effect.gen(function* () {
|
||||||
|
|
||||||
The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes.
|
The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes.
|
||||||
|
|
||||||
|
### Image jobs
|
||||||
|
|
||||||
|
`ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same
|
||||||
|
calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and
|
||||||
|
read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read;
|
||||||
|
`result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an
|
||||||
|
`UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on
|
||||||
|
every image model today all four fail with an `UnsupportedOperation` reason before sending anything.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const program = Effect.gen(function* () {
|
||||||
|
const job = yield* ai.image.start({ model, prompt: "A lighthouse" })
|
||||||
|
const status = yield* ai.image.status(model, job.id) // { status, progress? }
|
||||||
|
if (status.status === "completed") return yield* ai.image.result(model, job.id)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
## Video generation
|
## Video generation
|
||||||
|
|
||||||
Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
|
Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
|
||||||
fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
|
fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
|
||||||
`token`, plain JSON you can store and read back from another process, so recovering after a restart is the same call
|
`id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart
|
||||||
as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
|
is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
|
||||||
`BytePlus`, `MiniMax` and `Google` facades.
|
`BytePlus`, `MiniMax` and `Google` facades.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
|
|
@ -1057,22 +1097,29 @@ const program = Effect.gen(function* () {
|
||||||
resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
|
resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
|
||||||
sound: false,
|
sound: false,
|
||||||
})
|
})
|
||||||
job.token // `{ requestID }` for xAI: store it with the provider and model ID
|
job.id // the provider's job ID: store it with the provider and model ID
|
||||||
|
|
||||||
const status = yield* ai.video.status(model, job.token)
|
const status = yield* ai.video.status(model, job.id)
|
||||||
status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
|
status.status // "running" | "completed" | "error"
|
||||||
|
status.reason // "failed" | "cancelled" | "expired", only when status is "error"
|
||||||
status.progress // 0..1, only when the provider reports it
|
status.progress // 0..1, only when the provider reports it
|
||||||
|
|
||||||
const response = yield* ai.video.result(model, job.token)
|
const response = yield* ai.video.result(model, job.id)
|
||||||
yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
|
yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
|
The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
|
||||||
everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
|
everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
|
||||||
fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider
|
fails before sending when its protocol has no way to express it, such as a reference video on xAI. `sound` is the
|
||||||
|
exception: on models whose sound can't be switched (MiniMax H3 and Gemini Omni always have it, Hailuo never does) it
|
||||||
|
isn't sent, and the model's own behavior applies. Values the provider
|
||||||
may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
|
may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
|
||||||
|
|
||||||
|
`start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with
|
||||||
|
`Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references
|
||||||
|
whose type isn't stated are sent and checked by the provider. `references` take any kind.
|
||||||
|
|
||||||
`status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
|
`status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
|
||||||
provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
|
provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
|
||||||
outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
|
outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
|
||||||
|
|
@ -1110,11 +1157,11 @@ Provider notes:
|
||||||
`/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` /
|
`/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` /
|
||||||
`reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
|
`reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
|
||||||
`ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
|
`ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
|
||||||
`ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound,
|
`ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound
|
||||||
so `sound: false` fails before sending. On Hailuo, `start` and `end` map to `first_frame_image` and
|
and has no field for it, so `sound` isn't sent. On Hailuo, `start` and `end` map to `first_frame_image` and
|
||||||
`last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
|
`last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
|
||||||
expires after one hour. Hailuo is silent and has no aspect field, so `sound: true`, an explicit `aspect`, and video
|
expires after one hour. Hailuo is always silent, so `sound` isn't sent; it has no aspect field, so an explicit
|
||||||
or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
|
`aspect` and video or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
|
||||||
such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
|
such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
|
||||||
- **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
|
- **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
|
||||||
role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
|
role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
|
||||||
|
|
@ -1122,7 +1169,7 @@ Provider notes:
|
||||||
`reference_to_video` for references only; with both, the prompt decides. `duration` becomes
|
`reference_to_video` for references only; with both, the prompt decides. `duration` becomes
|
||||||
`response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
|
`response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
|
||||||
lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
|
lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
|
||||||
first frame) and `sound: false` (Omni always generates audio). Videos come back as inline bytes. `cancel` posts to
|
first frame). Omni always generates audio and has no field for it, so `sound` isn't sent. Videos come back as inline bytes. `cancel` posts to
|
||||||
`/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
|
`/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
|
||||||
to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
|
to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
|
||||||
|
|
||||||
|
|
@ -1132,8 +1179,8 @@ The promise client has the same calls, each accepting `{ signal }`:
|
||||||
import { ai } from "@opencode/ai"
|
import { ai } from "@opencode/ai"
|
||||||
|
|
||||||
const job = await ai.video.start({ model, prompt })
|
const job = await ai.video.start({ model, prompt })
|
||||||
const status = await ai.video.status(model, job.token)
|
const status = await ai.video.status(model, job.id)
|
||||||
if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4")
|
if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).video, "./kite.mp4")
|
||||||
```
|
```
|
||||||
|
|
||||||
## Public API
|
## Public API
|
||||||
|
|
@ -1147,9 +1194,9 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
|
||||||
- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
|
- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
|
||||||
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
||||||
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
||||||
- **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model.
|
- **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs).
|
||||||
- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
|
- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
|
||||||
- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by a stored token; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer.
|
- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer.
|
||||||
- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
|
- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
|
||||||
- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
|
- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
|
||||||
- **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
|
- **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
|
||||||
|
|
@ -1305,8 +1352,8 @@ const program = Effect.gen(function* () {
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
Inline routes emit only `finish` from `stream` (no faked deltas); queued routes emit `generation-queued` /
|
Inline routes emit only `finish` from `stream` (no faked deltas); queued routes emit `generation-progress`
|
||||||
`generation-progress` before it.
|
before it.
|
||||||
|
|
||||||
Provider notes:
|
Provider notes:
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"version": "2.2.7",
|
"version": "2.4.1",
|
||||||
"name": "@opencode/ai",
|
"name": "@opencode/ai",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|
@ -136,6 +136,7 @@
|
||||||
"./providers/vercel-ai-gateway/responses": "./src/providers/vercel-ai-gateway/responses.ts",
|
"./providers/vercel-ai-gateway/responses": "./src/providers/vercel-ai-gateway/responses.ts",
|
||||||
"./providers/xai": "./src/providers/xai.ts",
|
"./providers/xai": "./src/providers/xai.ts",
|
||||||
"./providers/xai/images": "./src/providers/xai/images.ts",
|
"./providers/xai/images": "./src/providers/xai/images.ts",
|
||||||
|
"./providers/xai/videos": "./src/providers/xai/videos.ts",
|
||||||
"./providers/zai": "./src/providers/zai.ts",
|
"./providers/zai": "./src/providers/zai.ts",
|
||||||
"./providers/zai-coding-plan": "./src/providers/zai-coding-plan.ts",
|
"./providers/zai-coding-plan": "./src/providers/zai-coding-plan.ts",
|
||||||
"./providers/zai-coding-plan/chat": "./src/providers/zai-coding-plan/chat.ts",
|
"./providers/zai-coding-plan/chat": "./src/providers/zai-coding-plan/chat.ts",
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ import {
|
||||||
type ToolEntry,
|
type ToolEntry,
|
||||||
} from "./schema/messages.js"
|
} from "./schema/messages.js"
|
||||||
import { effortUpdate } from "./effort-updates.js"
|
import { effortUpdate } from "./effort-updates.js"
|
||||||
|
import { toolsUpdate } from "./tool-updates.js"
|
||||||
|
|
||||||
const AUTO: CachePolicyObject = {
|
const AUTO: CachePolicyObject = {
|
||||||
tools: true,
|
tools: true,
|
||||||
|
|
@ -191,14 +192,15 @@ const markMessages = (
|
||||||
let remaining = strategy.tail
|
let remaining = strategy.tail
|
||||||
while (remaining > 0 && start > 0) {
|
while (remaining > 0 && start > 0) {
|
||||||
start -= 1
|
start -= 1
|
||||||
if (effortUpdate(messages[start]!) === undefined) remaining -= 1
|
if (!isMarker(messages[start]!)) remaining -= 1
|
||||||
}
|
}
|
||||||
let next = messages
|
let next = messages
|
||||||
for (let i = start; i < messages.length; i++)
|
for (let i = start; i < messages.length; i++) if (!isMarker(messages[i]!)) next = markMessageAt(next, i, hint, budget)
|
||||||
if (effortUpdate(messages[i]!) === undefined) next = markMessageAt(next, i, hint, budget)
|
|
||||||
return next
|
return next
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isMarker = (message: Message) => effortUpdate(message) !== undefined || toolsUpdate(message) !== undefined
|
||||||
|
|
||||||
const countHints = (request: LLMRequest) =>
|
const countHints = (request: LLMRequest) =>
|
||||||
countToolHints(request.tools) +
|
countToolHints(request.tools) +
|
||||||
request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) +
|
request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) +
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { tryRequest } from "./media-model.js"
|
||||||
import {
|
import {
|
||||||
AIError,
|
AIError,
|
||||||
type BaseRequest,
|
type BaseRequest,
|
||||||
type HttpOptions,
|
type TransportOptions,
|
||||||
ModelID,
|
ModelID,
|
||||||
ProviderID,
|
ProviderID,
|
||||||
ProviderMetadata,
|
ProviderMetadata,
|
||||||
|
|
@ -200,7 +200,8 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
|
||||||
readonly id: ModelID
|
readonly id: ModelID
|
||||||
readonly provider: ProviderID
|
readonly provider: ProviderID
|
||||||
readonly route: DecisionModelRoute<Options>
|
readonly route: DecisionModelRoute<Options>
|
||||||
readonly http?: HttpOptions
|
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
|
||||||
|
readonly transport?: TransportOptions
|
||||||
readonly compatibility?: DecisionModelCompatibility
|
readonly compatibility?: DecisionModelCompatibility
|
||||||
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
||||||
readonly providerOptions?: ProviderOptions
|
readonly providerOptions?: ProviderOptions
|
||||||
|
|
@ -209,7 +210,7 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
|
||||||
this.id = input.id
|
this.id = input.id
|
||||||
this.provider = input.provider
|
this.provider = input.provider
|
||||||
this.route = input.route
|
this.route = input.route
|
||||||
this.http = input.http
|
this.transport = input.transport
|
||||||
this.compatibility = input.compatibility
|
this.compatibility = input.compatibility
|
||||||
this.providerOptions = input.providerOptions
|
this.providerOptions = input.providerOptions
|
||||||
}
|
}
|
||||||
|
|
@ -228,7 +229,7 @@ export namespace DecisionModel {
|
||||||
readonly id: ModelID
|
readonly id: ModelID
|
||||||
readonly provider: ProviderID
|
readonly provider: ProviderID
|
||||||
readonly route: DecisionModelRoute<Options>
|
readonly route: DecisionModelRoute<Options>
|
||||||
readonly http?: HttpOptions
|
readonly transport?: TransportOptions
|
||||||
readonly compatibility?: DecisionModelCompatibility
|
readonly compatibility?: DecisionModelCompatibility
|
||||||
readonly providerOptions?: ProviderOptions
|
readonly providerOptions?: ProviderOptions
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { tryRequest } from "./media-model.js"
|
||||||
import {
|
import {
|
||||||
type AIError,
|
type AIError,
|
||||||
type BaseRequest,
|
type BaseRequest,
|
||||||
type HttpOptions,
|
type TransportOptions,
|
||||||
ModelID,
|
ModelID,
|
||||||
ProviderID,
|
ProviderID,
|
||||||
ProviderMetadata,
|
ProviderMetadata,
|
||||||
|
|
@ -38,7 +38,10 @@ export type EmbeddingOptions = Record<string, unknown>
|
||||||
/** What an embedding model's route does; `EmbeddingRoute.make(...).model(...)` builds one from a protocol. */
|
/** What an embedding model's route does; `EmbeddingRoute.make(...).model(...)` builds one from a protocol. */
|
||||||
export interface EmbeddingModelRoute<Options extends EmbeddingOptions = EmbeddingOptions> {
|
export interface EmbeddingModelRoute<Options extends EmbeddingOptions = EmbeddingOptions> {
|
||||||
readonly id: string
|
readonly id: string
|
||||||
generate(request: EmbeddingRequest<EmbeddingModel<Options>>, execute: Execute): Effect.Effect<EmbeddingResponse, AIError>
|
generate(
|
||||||
|
request: EmbeddingRequest<EmbeddingModel<Options>>,
|
||||||
|
execute: Execute,
|
||||||
|
): Effect.Effect<EmbeddingResponse, AIError>
|
||||||
}
|
}
|
||||||
|
|
||||||
export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions> {
|
export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions> {
|
||||||
|
|
@ -46,7 +49,8 @@ export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions>
|
||||||
readonly id: ModelID
|
readonly id: ModelID
|
||||||
readonly provider: ProviderID
|
readonly provider: ProviderID
|
||||||
readonly route: EmbeddingModelRoute<Options>
|
readonly route: EmbeddingModelRoute<Options>
|
||||||
readonly http?: HttpOptions
|
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
|
||||||
|
readonly transport?: TransportOptions
|
||||||
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
||||||
readonly providerOptions?: ProviderOptions
|
readonly providerOptions?: ProviderOptions
|
||||||
|
|
||||||
|
|
@ -54,7 +58,7 @@ export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions>
|
||||||
this.id = input.id
|
this.id = input.id
|
||||||
this.provider = input.provider
|
this.provider = input.provider
|
||||||
this.route = input.route
|
this.route = input.route
|
||||||
this.http = input.http
|
this.transport = input.transport
|
||||||
this.providerOptions = input.providerOptions
|
this.providerOptions = input.providerOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -72,7 +76,7 @@ export namespace EmbeddingModel {
|
||||||
readonly id: ModelID
|
readonly id: ModelID
|
||||||
readonly provider: ProviderID
|
readonly provider: ProviderID
|
||||||
readonly route: EmbeddingModelRoute<Options>
|
readonly route: EmbeddingModelRoute<Options>
|
||||||
readonly http?: HttpOptions
|
readonly transport?: TransportOptions
|
||||||
readonly providerOptions?: ProviderOptions
|
readonly providerOptions?: ProviderOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -43,6 +43,7 @@ export type {
|
||||||
export { Realtime } from "./experimental/realtime.js"
|
export { Realtime } from "./experimental/realtime.js"
|
||||||
export type {
|
export type {
|
||||||
RealtimeConnectInput,
|
RealtimeConnectInput,
|
||||||
|
RealtimeEngine,
|
||||||
RealtimeSession,
|
RealtimeSession,
|
||||||
RealtimeTransport,
|
RealtimeTransport,
|
||||||
RealtimeTransportInput,
|
RealtimeTransportInput,
|
||||||
|
|
|
||||||
|
|
@ -99,14 +99,13 @@ export const model = (input: MediaRoute.ModelInput) =>
|
||||||
new ExtractionModel({
|
new ExtractionModel({
|
||||||
id: input.id,
|
id: input.id,
|
||||||
provider: route.provider,
|
provider: route.provider,
|
||||||
http: input.http,
|
transport: input.transport,
|
||||||
route: MediaRoute.inline({
|
route: MediaRoute.inline({
|
||||||
protocol,
|
protocol,
|
||||||
endpoint: Endpoint.path<MediaProtocol.Body, ExtractionRequest>(({ request }) => `/${request.model.id}`, {
|
endpoint: Endpoint.path<MediaProtocol.Body, ExtractionRequest>(({ request }) => `/${request.model.id}`, {
|
||||||
baseURL: input.baseURL,
|
baseURL: input.baseURL,
|
||||||
}),
|
}),
|
||||||
auth: input.auth,
|
auth: input.auth,
|
||||||
headers: input.headers,
|
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Clock, Effect, Redacted, Schema } from "effect"
|
import { Clock, Effect, Redacted, Schema } from "effect"
|
||||||
import { HttpClientRequest } from "effect/http"
|
import { HttpClientRequest } from "effect/http"
|
||||||
import { RequestExecutor } from "../route/executor.js"
|
import { RequestExecutor } from "../route/executor.js"
|
||||||
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "../schema/index.js"
|
import { AIError, InvalidProviderOutputError, InvalidRequestError, type RequestTimeout } from "../schema/index.js"
|
||||||
import { encodeJson } from "../utils/json.js"
|
import { encodeJson } from "../utils/json.js"
|
||||||
|
|
||||||
const OPENAI_BASE_URL = "https://api.openai.com/v1"
|
const OPENAI_BASE_URL = "https://api.openai.com/v1"
|
||||||
|
|
@ -21,42 +21,30 @@ export type RealtimeTransport =
|
||||||
export type RealtimeSession = Readonly<Record<string, unknown>>
|
export type RealtimeSession = Readonly<Record<string, unknown>>
|
||||||
|
|
||||||
export interface RealtimeConnectInput {
|
export interface RealtimeConnectInput {
|
||||||
|
readonly engine: RealtimeEngine
|
||||||
readonly model: string
|
readonly model: string
|
||||||
readonly apiKey: Redacted.Redacted
|
readonly apiKey: Redacted.Redacted
|
||||||
/** Where a GPT-Live session starts, OpenAI by default: another host of its API, such as OpenCode's. */
|
/** Where a GPT-Live session starts, OpenAI by default: another host of its API, such as OpenCode's. */
|
||||||
readonly baseURL?: string
|
readonly baseURL?: string
|
||||||
/** Headers that host needs besides the API key, such as OpenCode's workspace. */
|
/** Headers that host needs besides the API key, such as OpenCode's workspace. */
|
||||||
readonly headers?: Readonly<Record<string, string>>
|
readonly headers?: Readonly<Record<string, string>>
|
||||||
|
readonly timeout?: RequestTimeout
|
||||||
readonly session?: RealtimeSession
|
readonly session?: RealtimeSession
|
||||||
readonly transport: RealtimeTransportInput
|
readonly transport: RealtimeTransportInput
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The voice APIs this package speaks, by provider and models.dev API. Which models they start comes from models.dev.
|
||||||
export const engines = [
|
export const engines = [
|
||||||
{ family: "gpt-live", model: "gpt-live-1", id: "openai-live", provider: "openai", transports: ["webrtc"] },
|
{ id: "openai-live", provider: "openai", api: "live", transports: ["webrtc"] },
|
||||||
{
|
{ id: "openai-realtime", provider: "openai", api: "realtime", transports: ["webrtc", "websocket"] },
|
||||||
family: "gpt-realtime",
|
{ id: "xai-realtime", provider: "xai", api: "realtime", transports: ["websocket"] },
|
||||||
model: "gpt-realtime-2.1",
|
{ id: "gemini-live", provider: "google", api: "bidi-generate-content", transports: ["websocket"] },
|
||||||
id: "openai-realtime",
|
|
||||||
provider: "openai",
|
|
||||||
transports: ["webrtc", "websocket"],
|
|
||||||
},
|
|
||||||
{ family: "grok-voice", model: "grok-voice-3.0", id: "xai-realtime", provider: "xai", transports: ["websocket"] },
|
|
||||||
{
|
|
||||||
family: "gemini-3.8-live",
|
|
||||||
model: "gemini-3.8-live",
|
|
||||||
id: "gemini-live",
|
|
||||||
provider: "google",
|
|
||||||
transports: ["websocket"],
|
|
||||||
},
|
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
// Matches the bare family name (`gpt-realtime`) and its versions (`gpt-realtime-2.1`, `gpt-realtime-mini`).
|
export type RealtimeEngine = (typeof engines)[number]
|
||||||
export const engine = (model: string) =>
|
|
||||||
engines.find((item) => model === item.family || model.startsWith(`${item.family}-`))
|
|
||||||
|
|
||||||
export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeConnectInput) {
|
export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeConnectInput) {
|
||||||
const resolved = engine(input.model)
|
const resolved = input.engine
|
||||||
if (!resolved) return yield* invalidRequest(`Unsupported voice model: ${input.model}`)
|
|
||||||
if (!resolved.transports.some((type) => type === input.transport.type))
|
if (!resolved.transports.some((type) => type === input.transport.type))
|
||||||
return yield* invalidRequest(`${input.model} only supports ${resolved.transports.join(", ")} transport`)
|
return yield* invalidRequest(`${input.model} only supports ${resolved.transports.join(", ")} transport`)
|
||||||
const session = { ...input.session, model: input.model }
|
const session = { ...input.session, model: input.model }
|
||||||
|
|
@ -69,16 +57,23 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
||||||
input.apiKey,
|
input.apiKey,
|
||||||
{ session, transport: input.transport },
|
{ session, transport: input.transport },
|
||||||
LiveSessionResponse,
|
LiveSessionResponse,
|
||||||
{ headers: input.headers },
|
{ headers: input.headers, timeout: input.timeout },
|
||||||
)
|
)
|
||||||
return { type: "webrtc" as const, sdp: data.transport.sdp }
|
return { type: "webrtc" as const, sdp: data.transport.sdp }
|
||||||
}
|
}
|
||||||
case "openai-realtime": {
|
case "openai-realtime": {
|
||||||
if (input.transport.type === "websocket")
|
if (input.transport.type === "websocket")
|
||||||
return yield* clientSecret(resolved.id, OPENAI_BASE_URL, input.model, input.apiKey, {
|
return yield* clientSecret(
|
||||||
expires_after: { anchor: "created_at", seconds: 60 },
|
resolved.id,
|
||||||
session,
|
OPENAI_BASE_URL,
|
||||||
})
|
input.model,
|
||||||
|
input.apiKey,
|
||||||
|
{
|
||||||
|
expires_after: { anchor: "created_at", seconds: 60 },
|
||||||
|
session,
|
||||||
|
},
|
||||||
|
input.timeout,
|
||||||
|
)
|
||||||
const form = new FormData()
|
const form = new FormData()
|
||||||
form.append("sdp", input.transport.sdp)
|
form.append("sdp", input.transport.sdp)
|
||||||
form.append("session", encodeJson(session))
|
form.append("session", encodeJson(session))
|
||||||
|
|
@ -89,13 +84,21 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
||||||
input.apiKey,
|
input.apiKey,
|
||||||
form,
|
form,
|
||||||
Schema.String,
|
Schema.String,
|
||||||
|
{ timeout: input.timeout },
|
||||||
)
|
)
|
||||||
return { type: "webrtc" as const, sdp }
|
return { type: "webrtc" as const, sdp }
|
||||||
}
|
}
|
||||||
case "xai-realtime":
|
case "xai-realtime":
|
||||||
return yield* clientSecret(resolved.id, XAI_BASE_URL, input.model, input.apiKey, {
|
return yield* clientSecret(
|
||||||
expires_after: { seconds: 60 },
|
resolved.id,
|
||||||
})
|
XAI_BASE_URL,
|
||||||
|
input.model,
|
||||||
|
input.apiKey,
|
||||||
|
{
|
||||||
|
expires_after: { seconds: 60 },
|
||||||
|
},
|
||||||
|
input.timeout,
|
||||||
|
)
|
||||||
case "gemini-live": {
|
case "gemini-live": {
|
||||||
const now = yield* Clock.currentTimeMillis
|
const now = yield* Clock.currentTimeMillis
|
||||||
const expiresAt = now + 60_000
|
const expiresAt = now + 60_000
|
||||||
|
|
@ -110,7 +113,7 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
||||||
bidiGenerateContentSetup: { ...input.session, model: `models/${input.model}` },
|
bidiGenerateContentSetup: { ...input.session, model: `models/${input.model}` },
|
||||||
},
|
},
|
||||||
AuthTokenResponse,
|
AuthTokenResponse,
|
||||||
{ authHeader: "x-goog-api-key" },
|
{ authHeader: "x-goog-api-key", timeout: input.timeout },
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
type: "websocket" as const,
|
type: "websocket" as const,
|
||||||
|
|
@ -124,7 +127,6 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
||||||
|
|
||||||
export const Realtime = {
|
export const Realtime = {
|
||||||
engines,
|
engines,
|
||||||
engine,
|
|
||||||
connect,
|
connect,
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
|
|
@ -158,11 +160,18 @@ const post = <A>(
|
||||||
apiKey: Redacted.Redacted,
|
apiKey: Redacted.Redacted,
|
||||||
body: Record<string, unknown> | FormData,
|
body: Record<string, unknown> | FormData,
|
||||||
response: Schema.Codec<A, string>,
|
response: Schema.Codec<A, string>,
|
||||||
options: { readonly authHeader?: string; readonly headers?: Readonly<Record<string, string>> } = {},
|
options: {
|
||||||
|
readonly authHeader?: string
|
||||||
|
readonly headers?: Readonly<Record<string, string>>
|
||||||
|
readonly timeout?: RequestTimeout
|
||||||
|
} = {},
|
||||||
) =>
|
) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const executor = yield* RequestExecutor.Service
|
const executor = yield* RequestExecutor.Service
|
||||||
const res = yield* executor.execute(
|
const res = yield* RequestExecutor.withTimeout(
|
||||||
|
executor.execute,
|
||||||
|
options.timeout,
|
||||||
|
)(
|
||||||
HttpClientRequest.post(url).pipe(
|
HttpClientRequest.post(url).pipe(
|
||||||
HttpClientRequest.setHeaders(options.headers ?? {}),
|
HttpClientRequest.setHeaders(options.headers ?? {}),
|
||||||
options.authHeader
|
options.authHeader
|
||||||
|
|
@ -176,7 +185,7 @@ const post = <A>(
|
||||||
const http = RequestExecutor.responseHttp(res)
|
const http = RequestExecutor.responseHttp(res)
|
||||||
const fail = (message: string, cause?: unknown, raw?: string) =>
|
const fail = (message: string, cause?: unknown, raw?: string) =>
|
||||||
new AIError({ reason: new InvalidProviderOutputError({ route, message, body: raw, http, cause }) })
|
new AIError({ reason: new InvalidProviderOutputError({ route, message, body: raw, http, cause }) })
|
||||||
const text = yield* res.text.pipe(Effect.mapError((cause) => fail(`Failed to read ${route} response`, cause)))
|
const text = yield* RequestExecutor.responseText(res)
|
||||||
return yield* Schema.decodeEffect(response)(text).pipe(
|
return yield* Schema.decodeEffect(response)(text).pipe(
|
||||||
Effect.mapError((cause) => fail(`${route} returned an invalid response`, cause, text)),
|
Effect.mapError((cause) => fail(`${route} returned an invalid response`, cause, text)),
|
||||||
)
|
)
|
||||||
|
|
@ -188,8 +197,9 @@ const clientSecret = (
|
||||||
model: string,
|
model: string,
|
||||||
apiKey: Redacted.Redacted,
|
apiKey: Redacted.Redacted,
|
||||||
body: Record<string, unknown>,
|
body: Record<string, unknown>,
|
||||||
|
timeout?: RequestTimeout,
|
||||||
) =>
|
) =>
|
||||||
post(route, `${baseURL}/realtime/client_secrets`, apiKey, body, ClientSecretResponse).pipe(
|
post(route, `${baseURL}/realtime/client_secrets`, apiKey, body, ClientSecretResponse, { timeout }).pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(data): RealtimeTransport => ({
|
(data): RealtimeTransport => ({
|
||||||
type: "websocket",
|
type: "websocket",
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,21 @@
|
||||||
import { Clock, Duration, Effect, Schedule, Schema, Stream } from "effect"
|
import { Clock, Duration, Effect, Schedule, Schema, Stream } from "effect"
|
||||||
import { AIError, TimeoutError } from "./schema/errors.js"
|
import { AIError, TimeoutError } from "./schema/errors.js"
|
||||||
|
|
||||||
export const Status = Schema.Literals(["queued", "running", "completed", "failed", "cancelled", "expired"])
|
export const Status = Schema.Literals(["running", "completed", "error"])
|
||||||
export type Status = Schema.Schema.Type<typeof Status>
|
export type Status = Schema.Schema.Type<typeof Status>
|
||||||
|
|
||||||
|
/** Why a generation ended in `error`. */
|
||||||
|
export const Reason = Schema.Literals(["failed", "cancelled", "expired"])
|
||||||
|
export type Reason = Schema.Schema.Type<typeof Reason>
|
||||||
|
|
||||||
/** Provider-neutral view of one generation observation. */
|
/** Provider-neutral view of one generation observation. */
|
||||||
export interface Snapshot {
|
export interface Snapshot {
|
||||||
readonly id: string
|
readonly id: string
|
||||||
readonly status: Status
|
readonly status: Status
|
||||||
|
/** Set when `status` is `error`. */
|
||||||
|
readonly reason?: Reason
|
||||||
/** Normalized 0..1 when the provider reports progress. */
|
/** Normalized 0..1 when the provider reports progress. */
|
||||||
readonly progress?: number
|
readonly progress?: number
|
||||||
readonly position?: number
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -35,31 +40,30 @@ export interface AwaitOptions {
|
||||||
const DEFAULT_POLL_INTERVAL = Duration.seconds(5)
|
const DEFAULT_POLL_INTERVAL = Duration.seconds(5)
|
||||||
const DEFAULT_POLL_TIMEOUT = Duration.minutes(10)
|
const DEFAULT_POLL_TIMEOUT = Duration.minutes(10)
|
||||||
|
|
||||||
export const QueuedEvent = Schema.Struct({
|
|
||||||
type: Schema.tag("generation-queued"),
|
|
||||||
id: Schema.String,
|
|
||||||
position: Schema.optional(Schema.Number),
|
|
||||||
}).annotate({ identifier: "Generation.Event.Queued" })
|
|
||||||
|
|
||||||
export const ProgressEvent = Schema.Struct({
|
export const ProgressEvent = Schema.Struct({
|
||||||
type: Schema.tag("generation-progress"),
|
type: Schema.tag("generation-progress"),
|
||||||
id: Schema.String,
|
id: Schema.String,
|
||||||
progress: Schema.optional(Schema.Number),
|
progress: Schema.optional(Schema.Number),
|
||||||
}).annotate({ identifier: "Generation.Event.Progress" })
|
}).annotate({ identifier: "Generation.Event.Progress" })
|
||||||
|
|
||||||
export type Observation = Schema.Schema.Type<typeof QueuedEvent> | Schema.Schema.Type<typeof ProgressEvent>
|
export type Observation = Schema.Schema.Type<typeof ProgressEvent>
|
||||||
|
|
||||||
export type Event = Observation | { readonly type: "generation-finished"; readonly id: string; readonly status: Status }
|
export type Event =
|
||||||
|
| Observation
|
||||||
|
| {
|
||||||
|
readonly type: "generation-finished"
|
||||||
|
readonly id: string
|
||||||
|
readonly status: Status
|
||||||
|
readonly reason?: Reason
|
||||||
|
}
|
||||||
|
|
||||||
const TERMINAL: ReadonlySet<Status> = new Set(["completed", "failed", "cancelled", "expired"])
|
export const isTerminal = (status: Status) => status !== "running"
|
||||||
|
|
||||||
export const isTerminal = (status: Status) => TERMINAL.has(status)
|
|
||||||
|
|
||||||
export class Generation<Response> {
|
export class Generation<Response> {
|
||||||
readonly id: string
|
readonly id: string
|
||||||
readonly status: Status
|
readonly status: Status
|
||||||
|
readonly reason?: Reason
|
||||||
readonly progress?: number
|
readonly progress?: number
|
||||||
readonly position?: number
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
readonly route: Route<Response>,
|
readonly route: Route<Response>,
|
||||||
|
|
@ -69,16 +73,16 @@ export class Generation<Response> {
|
||||||
) {
|
) {
|
||||||
this.id = snapshot.id
|
this.id = snapshot.id
|
||||||
this.status = snapshot.status
|
this.status = snapshot.status
|
||||||
|
this.reason = snapshot.reason
|
||||||
this.progress = snapshot.progress
|
this.progress = snapshot.progress
|
||||||
this.position = snapshot.position
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get snapshot(): Snapshot {
|
get snapshot(): Snapshot {
|
||||||
return {
|
return {
|
||||||
id: this.id,
|
id: this.id,
|
||||||
status: this.status,
|
status: this.status,
|
||||||
|
reason: this.reason,
|
||||||
progress: this.progress,
|
progress: this.progress,
|
||||||
position: this.position,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -139,8 +143,7 @@ export class Generation<Response> {
|
||||||
}
|
}
|
||||||
|
|
||||||
private event(): Event {
|
private event(): Event {
|
||||||
if (this.terminal) return { type: "generation-finished", id: this.id, status: this.status }
|
if (this.terminal) return { type: "generation-finished", id: this.id, status: this.status, reason: this.reason }
|
||||||
if (this.status === "queued") return { type: "generation-queued", id: this.id, position: this.position }
|
|
||||||
return { type: "generation-progress", id: this.id, progress: this.progress }
|
return { type: "generation-progress", id: this.id, progress: this.progress }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,89 @@
|
||||||
import { Context } from "effect"
|
import { Context, Effect, Layer, Schema, Stream } from "effect"
|
||||||
|
import type { AwaitOptions } from "./generation.js"
|
||||||
import { MediaClient } from "./media-client.js"
|
import { MediaClient } from "./media-client.js"
|
||||||
import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js"
|
import { RequestExecutor } from "./route/executor.js"
|
||||||
|
import { AIError, UnsupportedOperationError } from "./schema/index.js"
|
||||||
|
import type { ImageEvent, ImageJob, ImageModel, ImageRequest, ImageResponse, ImageStatus } from "./image.js"
|
||||||
|
|
||||||
export type Interface = MediaClient.Interface<ImageRequest, ImageEvent, ImageResponse>
|
/** `start`, `status`, `result` and `cancel` fail with `UnsupportedOperation` on inline and stream routes. */
|
||||||
|
export interface Interface
|
||||||
|
extends Pick<MediaClient.Interface<ImageRequest, ImageEvent, ImageResponse>, "generate" | "stream"> {
|
||||||
|
readonly start: (request: ImageRequest) => Effect.Effect<ImageJob, AIError>
|
||||||
|
readonly status: (model: ImageModel, id: string) => Effect.Effect<ImageStatus, AIError>
|
||||||
|
readonly result: (model: ImageModel, id: string) => Effect.Effect<ImageResponse, AIError>
|
||||||
|
readonly cancel: (model: ImageModel, id: string) => Effect.Effect<void, AIError>
|
||||||
|
}
|
||||||
|
|
||||||
export class ImageClientService extends Context.Service<ImageClientService, Interface>()("@opencode/ImageClient") {}
|
export class ImageClientService extends Context.Service<ImageClientService, Interface>()("@opencode/ImageClient") {}
|
||||||
export const Service = ImageClientService
|
export const Service = ImageClientService
|
||||||
export type Service = ImageClientService
|
export type Service = ImageClientService
|
||||||
|
|
||||||
|
const responseEvents = (response: ImageResponse) => [
|
||||||
|
...response.images.map((image, index) => ({ type: "image" as const, index, image })),
|
||||||
|
{ type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata },
|
||||||
|
]
|
||||||
|
|
||||||
|
// A queued image route whose token isn't a string is a programmer defect, not a provider error.
|
||||||
|
const decodeID = (token: unknown) => Schema.decodeUnknownEffect(Schema.String)(token).pipe(Effect.orDie)
|
||||||
|
|
||||||
|
export const layer = Layer.effect(
|
||||||
|
Service,
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const executor = yield* RequestExecutor.Service
|
||||||
|
const media = MediaClient.operations<ImageRequest, ImageEvent, ImageResponse>(executor.execute, {
|
||||||
|
modality: "image",
|
||||||
|
responseEvents,
|
||||||
|
})
|
||||||
|
const attach = (model: ImageModel, id: string, operation: string) => {
|
||||||
|
if (model.route.kind !== "queued") return Effect.fail(MediaClient.notQueued("image", model.route, operation))
|
||||||
|
return model.route.attach(model, id, executor.execute)
|
||||||
|
}
|
||||||
|
return Service.of({
|
||||||
|
generate: media.generate,
|
||||||
|
stream: media.stream,
|
||||||
|
start: (request) =>
|
||||||
|
media.start(request).pipe(
|
||||||
|
// The token, not the snapshot id, is what `status` and `result` decode; `ImageModel.fromRoute` makes it a string.
|
||||||
|
Effect.flatMap((generation) => decodeID(generation.token)),
|
||||||
|
Effect.map((id) => ({ id })),
|
||||||
|
),
|
||||||
|
status: (model, id) =>
|
||||||
|
attach(model, id, "status").pipe(
|
||||||
|
Effect.flatMap((route) => route.status),
|
||||||
|
Effect.map((snapshot) => ({ status: snapshot.status, reason: snapshot.reason, progress: snapshot.progress })),
|
||||||
|
),
|
||||||
|
result: (model, id) => attach(model, id, "result").pipe(Effect.flatMap((route) => route.result)),
|
||||||
|
cancel: (model, id) =>
|
||||||
|
attach(model, id, "cancel").pipe(
|
||||||
|
Effect.flatMap(
|
||||||
|
(route) =>
|
||||||
|
route.cancel ??
|
||||||
|
Effect.fail(
|
||||||
|
new AIError({
|
||||||
|
reason: new UnsupportedOperationError({
|
||||||
|
operation: "image.cancel",
|
||||||
|
provider: model.provider,
|
||||||
|
route: model.route.id,
|
||||||
|
message: `${model.provider}/${model.route.id} has no way to cancel an image generation`,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
export const ImageClient = {
|
export const ImageClient = {
|
||||||
Service,
|
Service,
|
||||||
...MediaClient.make(Service, {
|
layer,
|
||||||
modality: "image",
|
responseEvents,
|
||||||
responseEvents: (response: ImageResponse) => [
|
generate: (request: ImageRequest, options?: AwaitOptions) =>
|
||||||
...response.images.map((image, index) => ({ type: "image" as const, index, image })),
|
Service.use((client) => client.generate(request, options)),
|
||||||
{ type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata },
|
stream: (request: ImageRequest, options?: AwaitOptions) =>
|
||||||
],
|
Stream.unwrap(Service.useSync((client) => client.stream(request, options))),
|
||||||
}),
|
start: (request: ImageRequest) => Service.use((client) => client.start(request)),
|
||||||
|
status: (model: ImageModel, id: string) => Service.use((client) => client.status(model, id)),
|
||||||
|
result: (model: ImageModel, id: string) => Service.use((client) => client.result(model, id)),
|
||||||
|
cancel: (model: ImageModel, id: string) => Service.use((client) => client.cancel(model, id)),
|
||||||
} as const
|
} as const
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
import { Effect, Schema, Stream } from "effect"
|
import { Effect, Schema, Stream } from "effect"
|
||||||
import { Generation, ProgressEvent, QueuedEvent, type AwaitOptions } from "./generation.js"
|
import { ProgressEvent, type AwaitOptions, type Reason, type Status } from "./generation.js"
|
||||||
import { Media } from "./media.js"
|
import { Media } from "./media.js"
|
||||||
import { MediaModel, composeRoute, tryRequest } from "./media-model.js"
|
import { MediaModel, composeRoute, tryRequest } from "./media-model.js"
|
||||||
import { MediaRoute } from "./route/media.js"
|
import { MediaRoute } from "./route/media.js"
|
||||||
|
|
@ -24,7 +24,10 @@ export type ImageRoute = MediaRoute.AnyRoute<ImageRequest, ImageEvent, ImageResp
|
||||||
export class ImageModel<Options extends ImageOptions = ImageOptions> extends MediaModel<ImageRoute, Options> {
|
export class ImageModel<Options extends ImageOptions = ImageOptions> extends MediaModel<ImageRoute, Options> {
|
||||||
declare protected readonly _ImageModel: void
|
declare protected readonly _ImageModel: void
|
||||||
|
|
||||||
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
|
/**
|
||||||
|
* The number of type arguments selects the kind: `<Options>` for inline or queued, `<Options, Frame, State>` for
|
||||||
|
* stream. A queued route's token is the provider's job ID, so `ImageJob.id` is exactly what `status` and `result` take.
|
||||||
|
*/
|
||||||
static fromRoute<Options extends ImageOptions>(
|
static fromRoute<Options extends ImageOptions>(
|
||||||
route: MediaModel.InlineRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse>,
|
route: MediaModel.InlineRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse>,
|
||||||
input: MediaRoute.ModelInput,
|
input: MediaRoute.ModelInput,
|
||||||
|
|
@ -33,18 +36,18 @@ export class ImageModel<Options extends ImageOptions = ImageOptions> extends Med
|
||||||
route: MediaModel.StreamRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, Frame, State>,
|
route: MediaModel.StreamRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, Frame, State>,
|
||||||
input: MediaRoute.ModelInput,
|
input: MediaRoute.ModelInput,
|
||||||
): ImageModel<Options>
|
): ImageModel<Options>
|
||||||
static fromRoute<Options extends ImageOptions, Token>(
|
static fromRoute<Options extends ImageOptions>(
|
||||||
route: MediaModel.QueuedRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse, Token>,
|
route: MediaModel.QueuedRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse, string>,
|
||||||
input: MediaRoute.ModelInput,
|
input: MediaRoute.ModelInput,
|
||||||
): ImageModel<Options>
|
): ImageModel<Options>
|
||||||
static fromRoute<Options extends ImageOptions, Frame, State, Token>(
|
static fromRoute<Options extends ImageOptions, Frame, State>(
|
||||||
route: MediaModel.AnyRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, ImageResponse, Frame, State, Token>,
|
route: MediaModel.AnyRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, ImageResponse, Frame, State, string>,
|
||||||
input: MediaRoute.ModelInput,
|
input: MediaRoute.ModelInput,
|
||||||
) {
|
) {
|
||||||
return new ImageModel<Options>({
|
return new ImageModel<Options>({
|
||||||
id: input.id,
|
id: input.id,
|
||||||
provider: route.protocol.provider,
|
provider: route.protocol.provider,
|
||||||
http: input.http,
|
transport: input.transport,
|
||||||
providerOptions: input.providerOptions,
|
providerOptions: input.providerOptions,
|
||||||
route: composeRoute(route, input, collectResponse) as ImageRoute,
|
route: composeRoute(route, input, collectResponse) as ImageRoute,
|
||||||
})
|
})
|
||||||
|
|
@ -99,9 +102,23 @@ export type ImageRequestInput<Model extends ImageModel = ImageModel> = Omit<
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Response and events
|
// Job, status, response and events
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** A submitted generation on a queued route. Store `id` with the model to read the job later, from any process. */
|
||||||
|
export interface ImageJob {
|
||||||
|
/** The provider's job ID. */
|
||||||
|
readonly id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ImageStatus {
|
||||||
|
readonly status: Status
|
||||||
|
/** Set when `status` is `error`. */
|
||||||
|
readonly reason?: Reason
|
||||||
|
/** 0..1, only when the provider reports progress. */
|
||||||
|
readonly progress?: number
|
||||||
|
}
|
||||||
|
|
||||||
export class ImageResponse extends Schema.Class<ImageResponse>("Image.Response")({
|
export class ImageResponse extends Schema.Class<ImageResponse>("Image.Response")({
|
||||||
images: Schema.Array(Media.AssetSchema),
|
images: Schema.Array(Media.AssetSchema),
|
||||||
usage: Schema.optional(MediaUsage),
|
usage: Schema.optional(MediaUsage),
|
||||||
|
|
@ -127,16 +144,11 @@ export const ImageFinishEvent = Schema.Struct({
|
||||||
providerMetadata: Schema.optional(ProviderMetadata),
|
providerMetadata: Schema.optional(ProviderMetadata),
|
||||||
}).annotate({ identifier: "Image.Event.Finish" })
|
}).annotate({ identifier: "Image.Event.Finish" })
|
||||||
|
|
||||||
const imageEventTagged = Schema.Union([
|
const imageEventTagged = Schema.Union([ProgressEvent, ImagePartialEvent, ImageOutputEvent, ImageFinishEvent]).pipe(
|
||||||
QueuedEvent,
|
Schema.toTaggedUnion("type"),
|
||||||
ProgressEvent,
|
)
|
||||||
ImagePartialEvent,
|
|
||||||
ImageOutputEvent,
|
|
||||||
ImageFinishEvent,
|
|
||||||
]).pipe(Schema.toTaggedUnion("type"))
|
|
||||||
export const ImageEvent = Object.assign(imageEventTagged, {
|
export const ImageEvent = Object.assign(imageEventTagged, {
|
||||||
is: {
|
is: {
|
||||||
generationQueued: imageEventTagged.guards["generation-queued"],
|
|
||||||
generationProgress: imageEventTagged.guards["generation-progress"],
|
generationProgress: imageEventTagged.guards["generation-progress"],
|
||||||
imagePartial: imageEventTagged.guards["image-partial"],
|
imagePartial: imageEventTagged.guards["image-partial"],
|
||||||
image: imageEventTagged.guards.image,
|
image: imageEventTagged.guards.image,
|
||||||
|
|
@ -193,21 +205,32 @@ export function stream(input: ImageRequestInput, options?: AwaitOptions) {
|
||||||
return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => ImageClient.stream(request, options))))
|
return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => ImageClient.stream(request, options))))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Inline and streaming routes fail with `UnsupportedOperation`. */
|
/** Submit a generation and return at once; nothing polls. Inline and stream routes fail with `UnsupportedOperation`. */
|
||||||
export function start<const Model extends ImageModel>(
|
export function start<const Model extends ImageModel>(
|
||||||
input: ImageRequestInput<Model>,
|
input: ImageRequestInput<Model>,
|
||||||
): Effect.Effect<Generation<ImageResponse>, AIError, Service>
|
): Effect.Effect<ImageJob, AIError, Service>
|
||||||
export function start(input: ImageRequestInput) {
|
export function start(input: ImageRequestInput) {
|
||||||
return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.start(request)))
|
return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.start(request)))
|
||||||
}
|
}
|
||||||
|
|
||||||
export const resume = (model: ImageModel, token: unknown): Effect.Effect<Generation<ImageResponse>, AIError, Service> =>
|
/** One status read for a job ID. */
|
||||||
ImageClient.resume(model, token)
|
export const status = (model: ImageModel, id: string): Effect.Effect<ImageStatus, AIError, Service> =>
|
||||||
|
ImageClient.status(model, id)
|
||||||
|
|
||||||
|
/** The finished images; fails while the job is still running, or with the provider's reason when it failed. */
|
||||||
|
export const result = (model: ImageModel, id: string): Effect.Effect<ImageResponse, AIError, Service> =>
|
||||||
|
ImageClient.result(model, id)
|
||||||
|
|
||||||
|
/** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */
|
||||||
|
export const cancel = (model: ImageModel, id: string): Effect.Effect<void, AIError, Service> =>
|
||||||
|
ImageClient.cancel(model, id)
|
||||||
|
|
||||||
export const Image = {
|
export const Image = {
|
||||||
request,
|
request,
|
||||||
generate,
|
generate,
|
||||||
stream,
|
stream,
|
||||||
start,
|
start,
|
||||||
resume,
|
status,
|
||||||
|
result,
|
||||||
|
cancel,
|
||||||
} as const
|
} as const
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import {
|
||||||
type StreamOptions,
|
type StreamOptions,
|
||||||
type TriggerCompactOptions,
|
type TriggerCompactOptions,
|
||||||
} from "./route/client.js"
|
} from "./route/client.js"
|
||||||
import { RequestExecutor } from "./route/executor.js"
|
import { RequestExecutor, type HttpMiddleware } from "./route/executor.js"
|
||||||
import {
|
import {
|
||||||
AIError,
|
AIError,
|
||||||
InvalidRequestError,
|
InvalidRequestError,
|
||||||
|
|
@ -56,8 +56,16 @@ export interface Options {
|
||||||
|
|
||||||
export interface RunOptions {
|
export interface RunOptions {
|
||||||
readonly signal?: AbortSignal
|
readonly signal?: AbortSignal
|
||||||
|
/**
|
||||||
|
* Runs on every provider request the call makes, like `RequestExecutor.withMiddleware`: submits, polls, results and
|
||||||
|
* cancels included. A handle the call returns keeps it for its own calls.
|
||||||
|
*/
|
||||||
|
readonly http?: HttpMiddleware
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Options for reading or writing an asset. Downloads use the asset's own `middleware`, never a caller's `http`. */
|
||||||
|
export type AssetRunOptions = Omit<RunOptions, "http">
|
||||||
|
|
||||||
export type Services = AIClient.Services
|
export type Services = AIClient.Services
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -97,7 +105,7 @@ export const make = (options: Options = {}) => {
|
||||||
|
|
||||||
/** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
|
/** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
|
||||||
const run = <A, E>(effect: Effect.Effect<A, E, Services>, options?: RunOptions) =>
|
const run = <A, E>(effect: Effect.Effect<A, E, Services>, options?: RunOptions) =>
|
||||||
runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)))
|
runtime.runPromise(Effect.raceFirst(scoped(effect, options?.http), abortEffect(options?.signal)))
|
||||||
|
|
||||||
const iterate = <A, E>(stream: Stream.Stream<A, E, Services>, options?: RunOptions): AsyncIterable<A> =>
|
const iterate = <A, E>(stream: Stream.Stream<A, E, Services>, options?: RunOptions): AsyncIterable<A> =>
|
||||||
Stream.toAsyncIterable(
|
Stream.toAsyncIterable(
|
||||||
|
|
@ -105,7 +113,10 @@ export const make = (options: Options = {}) => {
|
||||||
runtime.contextEffect.pipe(
|
runtime.contextEffect.pipe(
|
||||||
Effect.map(
|
Effect.map(
|
||||||
(context): Stream.Stream<A, unknown> =>
|
(context): Stream.Stream<A, unknown> =>
|
||||||
stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context)),
|
scoped(stream, options?.http).pipe(
|
||||||
|
Stream.interruptWhen(abortEffect(options?.signal)),
|
||||||
|
Stream.provideContext(context),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
@ -119,8 +130,9 @@ export const make = (options: Options = {}) => {
|
||||||
input: LLMRequestInput<Model>,
|
input: LLMRequestInput<Model>,
|
||||||
options?: StreamOptions & RunOptions,
|
options?: StreamOptions & RunOptions,
|
||||||
): Promise<LLMResponse>
|
): Promise<LLMResponse>
|
||||||
|
// `run` and `iterate` apply `http` around the whole call, so the LLM call gets none of its own.
|
||||||
function generate(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
|
function generate(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
|
||||||
return run(LLM.generate(input, options), options)
|
return run(LLM.generate(input, { ...options, http: undefined }), options)
|
||||||
}
|
}
|
||||||
|
|
||||||
function stream<const Model extends LanguageModel, S extends OutputSchema>(
|
function stream<const Model extends LanguageModel, S extends OutputSchema>(
|
||||||
|
|
@ -132,7 +144,7 @@ export const make = (options: Options = {}) => {
|
||||||
options?: StreamOptions & RunOptions,
|
options?: StreamOptions & RunOptions,
|
||||||
): AsyncIterable<LLMEvent>
|
): AsyncIterable<LLMEvent>
|
||||||
function stream(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
|
function stream(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
|
||||||
return iterate(LLM.stream(input, options), options)
|
return iterate(LLM.stream(input, { ...options, http: undefined }), options)
|
||||||
}
|
}
|
||||||
|
|
||||||
function loop<const Model extends LanguageModel, S extends OutputSchema>(
|
function loop<const Model extends LanguageModel, S extends OutputSchema>(
|
||||||
|
|
@ -144,7 +156,7 @@ export const make = (options: Options = {}) => {
|
||||||
options?: StreamOptions & RunOptions,
|
options?: StreamOptions & RunOptions,
|
||||||
): AsyncIterable<LLMEvent>
|
): AsyncIterable<LLMEvent>
|
||||||
function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
|
function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
|
||||||
return iterate(LLM.loop(input, options), options)
|
return iterate(LLM.loop(input, { ...options, http: undefined }), options)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Read `events` from `stream` or `loop` to the end and fold them into the final result. */
|
/** Read `events` from `stream` or `loop` to the end and fold them into the final result. */
|
||||||
|
|
@ -165,31 +177,33 @@ export const make = (options: Options = {}) => {
|
||||||
options?: (TriggerCompactOptions | EndpointCompactOptions) & RunOptions,
|
options?: (TriggerCompactOptions | EndpointCompactOptions) & RunOptions,
|
||||||
) {
|
) {
|
||||||
return options?.mechanism === "trigger"
|
return options?.mechanism === "trigger"
|
||||||
? run(LLM.compact(request as CheckpointRequest, options), options)
|
? run(LLM.compact(request as CheckpointRequest, { ...options, http: undefined }), options)
|
||||||
: run(LLM.compact(request as CompactionRequest, options), options)
|
: run(LLM.compact(request as CompactionRequest, { ...options, http: undefined }), options)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handle = <Response>(generation: Generation<Response>): GenerationHandle<Response> => ({
|
const handle =
|
||||||
...generation.snapshot,
|
(http: HttpMiddleware | undefined) =>
|
||||||
snapshot: generation.snapshot,
|
<Response>(generation: Generation<Response>): GenerationHandle<Response> => ({
|
||||||
terminal: generation.terminal,
|
...generation.snapshot,
|
||||||
token: generation.token,
|
snapshot: generation.snapshot,
|
||||||
await: (options) => run(generation.await(options), options),
|
terminal: generation.terminal,
|
||||||
events: (options) => iterate(generation.events(options), options),
|
token: generation.token,
|
||||||
result: (options) => run(generation.result(), options),
|
await: (options) => run(generation.await(options), { http, ...options }),
|
||||||
refresh: (options) => run(generation.refresh(), options).then(handle),
|
events: (options) => iterate(generation.events(options), { http, ...options }),
|
||||||
cancel: (options) => run(generation.cancel(), options),
|
result: (options) => run(generation.result(), { http, ...options }),
|
||||||
})
|
refresh: (options) => run(generation.refresh(), { http, ...options }).then(handle(options?.http ?? http)),
|
||||||
|
cancel: (options) => run(generation.cancel(), { http, ...options }),
|
||||||
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
run,
|
run,
|
||||||
/** Decoded asset bytes, downloading `url` sources through the executor. */
|
/** Decoded asset bytes, downloading `url` sources through the executor. */
|
||||||
bytes: (asset: Media.Asset, options?: RunOptions) => run(asset.bytes(), options),
|
bytes: (asset: Media.Asset, options?: AssetRunOptions) => run(asset.bytes(), options),
|
||||||
base64: (asset: Media.Asset, options?: RunOptions) => run(asset.base64(), options),
|
base64: (asset: Media.Asset, options?: AssetRunOptions) => run(asset.base64(), options),
|
||||||
/** Pull a `url` asset into owned bytes before the provider URL expires. */
|
/** Pull a `url` asset into owned bytes before the provider URL expires. */
|
||||||
materialize: (asset: Media.Asset, options?: RunOptions) => run(asset.materialize(), options),
|
materialize: (asset: Media.Asset, options?: AssetRunOptions) => run(asset.materialize(), options),
|
||||||
/** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */
|
/** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */
|
||||||
file: async (path: string, options?: Media.AssetOptions & RunOptions) => {
|
file: async (path: string, options?: Media.AssetOptions & AssetRunOptions) => {
|
||||||
const { readFile } = await import("node:fs/promises")
|
const { readFile } = await import("node:fs/promises")
|
||||||
return run(
|
return run(
|
||||||
Effect.tryPromise({
|
Effect.tryPromise({
|
||||||
|
|
@ -205,7 +219,7 @@ export const make = (options: Options = {}) => {
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
/** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
|
/** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
|
||||||
write: async (asset: Media.Asset, path: string, options?: RunOptions) => {
|
write: async (asset: Media.Asset, path: string, options?: AssetRunOptions) => {
|
||||||
const { open, rename, rm } = await import("node:fs/promises")
|
const { open, rename, rm } = await import("node:fs/promises")
|
||||||
const temporary = `${path}.${crypto.randomUUID()}.tmp`
|
const temporary = `${path}.${crypto.randomUUID()}.tmp`
|
||||||
try {
|
try {
|
||||||
|
|
@ -241,10 +255,14 @@ export const make = (options: Options = {}) => {
|
||||||
input: ImageRequestInput<Model> | ImageRequest,
|
input: ImageRequestInput<Model> | ImageRequest,
|
||||||
options?: AwaitOptions & RunOptions,
|
options?: AwaitOptions & RunOptions,
|
||||||
) => iterate(Image.stream(input, options), options),
|
) => iterate(Image.stream(input, options), options),
|
||||||
|
/** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */
|
||||||
start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) =>
|
start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) =>
|
||||||
run(Image.start(input), options).then(handle),
|
run(Image.start(input), options),
|
||||||
resume: (model: ImageModel, token: unknown, options?: RunOptions) =>
|
/** One status read for a job ID. */
|
||||||
run(Image.resume(model, token), options).then(handle),
|
status: (model: ImageModel, id: string, options?: RunOptions) => run(Image.status(model, id), options),
|
||||||
|
/** The finished images; fails while the job is still running. */
|
||||||
|
result: (model: ImageModel, id: string, options?: RunOptions) => run(Image.result(model, id), options),
|
||||||
|
cancel: (model: ImageModel, id: string, options?: RunOptions) => run(Image.cancel(model, id), options),
|
||||||
},
|
},
|
||||||
decision: {
|
decision: {
|
||||||
request: Decision.request,
|
request: Decision.request,
|
||||||
|
|
@ -260,14 +278,14 @@ export const make = (options: Options = {}) => {
|
||||||
},
|
},
|
||||||
video: {
|
video: {
|
||||||
request: Video.request,
|
request: Video.request,
|
||||||
/** Submit a generation and return its `{ id, token }` at once; nothing polls. */
|
/** Submit a generation and return its `{ id }` at once; nothing polls. */
|
||||||
start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) =>
|
start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) =>
|
||||||
run(Video.start(input), options),
|
run(Video.start(input), options),
|
||||||
/** One status read for a stored token. */
|
/** One status read for a job ID. */
|
||||||
status: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.status(model, token), options),
|
status: (model: VideoModel, id: string, options?: RunOptions) => run(Video.status(model, id), options),
|
||||||
/** The finished videos; fails while the job is still running. */
|
/** The finished videos; fails while the job is still running. */
|
||||||
result: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.result(model, token), options),
|
result: (model: VideoModel, id: string, options?: RunOptions) => run(Video.result(model, id), options),
|
||||||
cancel: (model: VideoModel, token: unknown, options?: RunOptions) => run(Video.cancel(model, token), options),
|
cancel: (model: VideoModel, id: string, options?: RunOptions) => run(Video.cancel(model, id), options),
|
||||||
},
|
},
|
||||||
/** Experimental: may change without compatibility guarantees. */
|
/** Experimental: may change without compatibility guarantees. */
|
||||||
experimental: {
|
experimental: {
|
||||||
|
|
@ -295,9 +313,9 @@ export const make = (options: Options = {}) => {
|
||||||
start: <const Model extends TranscriptionModel>(
|
start: <const Model extends TranscriptionModel>(
|
||||||
input: TranscriptionRequestInput<Model> | TranscriptionRequest,
|
input: TranscriptionRequestInput<Model> | TranscriptionRequest,
|
||||||
options?: RunOptions,
|
options?: RunOptions,
|
||||||
) => run(Transcription.start(input), options).then(handle),
|
) => run(Transcription.start(input), options).then(handle(options?.http)),
|
||||||
resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) =>
|
resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) =>
|
||||||
run(Transcription.resume(model, token), options).then(handle),
|
run(Transcription.resume(model, token), options).then(handle(options?.http)),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
dispose: () => runtime.dispose(),
|
dispose: () => runtime.dispose(),
|
||||||
|
|
@ -306,6 +324,11 @@ export const make = (options: Options = {}) => {
|
||||||
|
|
||||||
export type Client = ReturnType<typeof make>
|
export type Client = ReturnType<typeof make>
|
||||||
|
|
||||||
|
const scoped = <Self extends Effect.Effect<unknown, unknown, unknown> | Stream.Stream<unknown, unknown, unknown>>(
|
||||||
|
self: Self,
|
||||||
|
http: HttpMiddleware | undefined,
|
||||||
|
) => (http === undefined ? self : RequestExecutor.withMiddleware(http)(self))
|
||||||
|
|
||||||
const fileError = (message: string, cause: unknown) =>
|
const fileError = (message: string, cause: unknown) =>
|
||||||
new AIError({ reason: new InvalidRequestError({ message, cause }) })
|
new AIError({ reason: new InvalidRequestError({ message, cause }) })
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,7 @@ import {
|
||||||
import { tool, type ExecutableTool, type Tool, type ToolSchema } from "./tool.js"
|
import { tool, type ExecutableTool, type Tool, type ToolSchema } from "./tool.js"
|
||||||
import { runTools } from "./tool-runtime.js"
|
import { runTools } from "./tool-runtime.js"
|
||||||
import { addUsage, nextRequest, pendingCalls } from "./loop.js"
|
import { addUsage, nextRequest, pendingCalls } from "./loop.js"
|
||||||
|
import { foldTools } from "./tool-updates.js"
|
||||||
|
|
||||||
/** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */
|
/** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */
|
||||||
export type LLMRequestInput<Model extends LanguageModel = LanguageModel> = TextRequestFields<Model> & PromptOrMessages
|
export type LLMRequestInput<Model extends LanguageModel = LanguageModel> = TextRequestFields<Model> & PromptOrMessages
|
||||||
|
|
@ -53,7 +54,10 @@ interface TextRequestFields<Model extends LanguageModel>
|
||||||
GenerationOptionsFields {
|
GenerationOptionsFields {
|
||||||
readonly id?: string
|
readonly id?: string
|
||||||
readonly system?: string | SystemPart | ReadonlyArray<SystemPart>
|
readonly system?: string | SystemPart | ReadonlyArray<SystemPart>
|
||||||
/** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */
|
/**
|
||||||
|
* Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. The same as a
|
||||||
|
* `Message.tools({ add: tools })` leading the history.
|
||||||
|
*/
|
||||||
readonly tools?: ReadonlyArray<Tool | ToolEntryInput>
|
readonly tools?: ReadonlyArray<Tool | ToolEntryInput>
|
||||||
readonly toolChoice?: ToolChoice.Input
|
readonly toolChoice?: ToolChoice.Input
|
||||||
readonly cache?: CachePolicy
|
readonly cache?: CachePolicy
|
||||||
|
|
@ -149,11 +153,35 @@ export function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, o
|
||||||
const { tools, until, ...rest } = input
|
const { tools, until, ...rest } = input
|
||||||
return Stream.unwrap(
|
return Stream.unwrap(
|
||||||
prepare({ ...rest, tools }).pipe(
|
prepare({ ...rest, tools }).pipe(
|
||||||
Effect.map(({ request, output }) => driveLoop({ tools, until, output, options }, request, [], undefined)),
|
// Untyped callers may omit `tools`.
|
||||||
|
Effect.map(({ request, output }) =>
|
||||||
|
driveLoop(
|
||||||
|
{ tools: runnableTools(tools ?? [], input.messages ?? []), until, output, options },
|
||||||
|
request,
|
||||||
|
[],
|
||||||
|
undefined,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Tools that `Message.tools(...)` adds run like top-level ones; a later change with the same name replaces or removes them.
|
||||||
|
const runnableTools = (tools: ReadonlyArray<Tool>, messages: ReadonlyArray<Message | Message.Input>) =>
|
||||||
|
messages
|
||||||
|
.reduce<ReadonlyArray<Tool | ToolEntryInput>>(
|
||||||
|
(current, message) =>
|
||||||
|
message.role === "system" && message.tools !== undefined
|
||||||
|
? foldTools(
|
||||||
|
current,
|
||||||
|
message.tools.add ?? [],
|
||||||
|
(message.tools.remove ?? []).map((item) => (typeof item === "string" ? item : item.name)),
|
||||||
|
)
|
||||||
|
: current,
|
||||||
|
tools,
|
||||||
|
)
|
||||||
|
.filter((item): item is Tool => "_definition" in item)
|
||||||
|
|
||||||
export { collect, type Collected, type CollectResult } from "./loop.js"
|
export { collect, type Collected, type CollectResult } from "./loop.js"
|
||||||
|
|
||||||
interface Step {
|
interface Step {
|
||||||
|
|
@ -209,7 +237,7 @@ const finishStep = (
|
||||||
}
|
}
|
||||||
|
|
||||||
interface LoopContext {
|
interface LoopContext {
|
||||||
readonly tools: ReadonlyArray<ExecutableTool>
|
readonly tools: ReadonlyArray<Tool>
|
||||||
readonly until: LLMLoopInput["until"]
|
readonly until: LLMLoopInput["until"]
|
||||||
readonly output: Tool | undefined
|
readonly output: Tool | undefined
|
||||||
readonly options: StreamOptions | undefined
|
readonly options: StreamOptions | undefined
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { type Context, Effect, Layer, Stream } from "effect"
|
||||||
import { resultEvents, type AwaitOptions, type Generation, type Observation } from "./generation.js"
|
import { resultEvents, type AwaitOptions, type Generation, type Observation } from "./generation.js"
|
||||||
import { RequestExecutor } from "./route/executor.js"
|
import { RequestExecutor } from "./route/executor.js"
|
||||||
import type { MediaRoute } from "./route/media.js"
|
import type { MediaRoute } from "./route/media.js"
|
||||||
import { AIError, UnsupportedOperationError } from "./schema/index.js"
|
import { AIError, UnsupportedOperationError, type ProviderID } from "./schema/index.js"
|
||||||
|
|
||||||
/** A media request whose model carries the route that executes it. */
|
/** A media request whose model carries the route that executes it. */
|
||||||
export interface RoutedRequest<Self extends MediaRoute.MediaRequest, Event, Response> extends MediaRoute.MediaRequest {
|
export interface RoutedRequest<Self extends MediaRoute.MediaRequest, Event, Response> extends MediaRoute.MediaRequest {
|
||||||
|
|
@ -17,55 +17,71 @@ export interface Interface<Req extends RoutedRequest<Req, Event, Response>, Even
|
||||||
readonly resume: (model: Req["model"], token: unknown) => Effect.Effect<Generation<Response>, AIError>
|
readonly resume: (model: Req["model"], token: unknown) => Effect.Effect<Generation<Response>, AIError>
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One modality's layer and service accessors, dispatching each request on its route's `kind`. */
|
export interface Input<Event, Response> {
|
||||||
|
readonly modality: string
|
||||||
|
/** A completed response expanded into the streaming event shape. */
|
||||||
|
readonly responseEvents: (response: Response) => ReadonlyArray<Event>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `${modality}.${operation}` on a route that is not queued. */
|
||||||
|
export const notQueued = (
|
||||||
|
modality: string,
|
||||||
|
route: { readonly provider: ProviderID; readonly id: string },
|
||||||
|
operation: string,
|
||||||
|
) =>
|
||||||
|
new AIError({
|
||||||
|
reason: new UnsupportedOperationError({
|
||||||
|
operation: `${modality}.${operation}`,
|
||||||
|
provider: route.provider,
|
||||||
|
route: route.id,
|
||||||
|
message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
||||||
|
/** One modality's operations over an executor, dispatching each request on its route's `kind`. */
|
||||||
|
export const operations = <Req extends RoutedRequest<Req, Event, Response>, Event, Response>(
|
||||||
|
execute: MediaRoute.Execute,
|
||||||
|
input: Input<Event, Response>,
|
||||||
|
): Interface<Req, Event, Response> => {
|
||||||
|
const start = (request: Req) => {
|
||||||
|
const route = request.model.route
|
||||||
|
if (route.kind !== "queued") return Effect.fail(notQueued(input.modality, route, "start"))
|
||||||
|
return route.start(request, execute)
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
start,
|
||||||
|
resume: (model, token) => {
|
||||||
|
if (model.route.kind !== "queued") return Effect.fail(notQueued(input.modality, model.route, "resume"))
|
||||||
|
return model.route.resume(model, token, execute)
|
||||||
|
},
|
||||||
|
generate: (request, options) => {
|
||||||
|
const route = request.model.route
|
||||||
|
if (route.kind !== "queued") return route.generate(request, execute)
|
||||||
|
return start(request).pipe(Effect.flatMap((generation) => generation.await(options)))
|
||||||
|
},
|
||||||
|
stream: (request, options) => {
|
||||||
|
const route = request.model.route
|
||||||
|
if (route.kind === "stream") return route.stream(request, execute)
|
||||||
|
if (route.kind === "queued")
|
||||||
|
return Stream.unwrap(
|
||||||
|
start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))),
|
||||||
|
)
|
||||||
|
return Stream.fromIterableEffect(Effect.map(route.generate(request, execute), input.responseEvents))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One modality's layer and service accessors over `operations`. */
|
||||||
export const make = <Self, Req extends RoutedRequest<Req, Event, Response>, Event, Response>(
|
export const make = <Self, Req extends RoutedRequest<Req, Event, Response>, Event, Response>(
|
||||||
service: Context.Service<Self, Interface<Req, Event, Response>>,
|
service: Context.Service<Self, Interface<Req, Event, Response>>,
|
||||||
input: {
|
input: Input<Event, Response>,
|
||||||
readonly modality: string
|
|
||||||
/** A completed response expanded into the streaming event shape. */
|
|
||||||
readonly responseEvents: (response: Response) => ReadonlyArray<Event>
|
|
||||||
},
|
|
||||||
) => ({
|
) => ({
|
||||||
responseEvents: input.responseEvents,
|
responseEvents: input.responseEvents,
|
||||||
layer: Layer.effect(
|
layer: Layer.effect(
|
||||||
service,
|
service,
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const executor = yield* RequestExecutor.Service
|
const executor = yield* RequestExecutor.Service
|
||||||
const notQueued = (route: MediaRoute.AnyRoute<Req, Event, Response>, operation: string) =>
|
return service.of(operations<Req, Event, Response>(executor.execute, input))
|
||||||
new AIError({
|
|
||||||
reason: new UnsupportedOperationError({
|
|
||||||
operation: `${input.modality}.${operation}`,
|
|
||||||
provider: route.provider,
|
|
||||||
route: route.id,
|
|
||||||
message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
const start = (request: Req) => {
|
|
||||||
const route = request.model.route
|
|
||||||
if (route.kind !== "queued") return Effect.fail(notQueued(route, "start"))
|
|
||||||
return route.start(request, executor.execute)
|
|
||||||
}
|
|
||||||
return service.of({
|
|
||||||
start,
|
|
||||||
resume: (model, token) => {
|
|
||||||
if (model.route.kind !== "queued") return Effect.fail(notQueued(model.route, "resume"))
|
|
||||||
return model.route.resume(model, token, executor.execute)
|
|
||||||
},
|
|
||||||
generate: (request, options) => {
|
|
||||||
const route = request.model.route
|
|
||||||
if (route.kind !== "queued") return route.generate(request, executor.execute)
|
|
||||||
return start(request).pipe(Effect.flatMap((generation) => generation.await(options)))
|
|
||||||
},
|
|
||||||
stream: (request, options) => {
|
|
||||||
const route = request.model.route
|
|
||||||
if (route.kind === "stream") return route.stream(request, executor.execute)
|
|
||||||
if (route.kind === "queued")
|
|
||||||
return Stream.unwrap(
|
|
||||||
start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))),
|
|
||||||
)
|
|
||||||
return Stream.fromIterableEffect(Effect.map(route.generate(request, executor.execute), input.responseEvents))
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
generate: (request: Req, options?: AwaitOptions) => service.use((client) => client.generate(request, options)),
|
generate: (request: Req, options?: AwaitOptions) => service.use((client) => client.generate(request, options)),
|
||||||
|
|
|
||||||
|
|
@ -7,12 +7,12 @@ import {
|
||||||
InvalidRequestError,
|
InvalidRequestError,
|
||||||
ModelID,
|
ModelID,
|
||||||
ProviderID,
|
ProviderID,
|
||||||
type HttpOptions,
|
|
||||||
type ProviderOptions,
|
type ProviderOptions,
|
||||||
|
type TransportOptions,
|
||||||
} from "./schema/index.js"
|
} from "./schema/index.js"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
|
* What every media model carries: ids, the configured route, and deployment transport overlays. Modality classes
|
||||||
* (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
|
* (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
|
||||||
* marker so one cannot stand in for the other in requests.
|
* marker so one cannot stand in for the other in requests.
|
||||||
*/
|
*/
|
||||||
|
|
@ -23,7 +23,8 @@ export class MediaModel<Route, Options> {
|
||||||
readonly id: ModelID
|
readonly id: ModelID
|
||||||
readonly provider: ProviderID
|
readonly provider: ProviderID
|
||||||
readonly route: Route
|
readonly route: Route
|
||||||
readonly http?: HttpOptions
|
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
|
||||||
|
readonly transport?: TransportOptions
|
||||||
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
||||||
readonly providerOptions?: ProviderOptions
|
readonly providerOptions?: ProviderOptions
|
||||||
|
|
||||||
|
|
@ -31,7 +32,7 @@ export class MediaModel<Route, Options> {
|
||||||
this.id = ModelID.make(input.id)
|
this.id = ModelID.make(input.id)
|
||||||
this.provider = ProviderID.make(input.provider)
|
this.provider = ProviderID.make(input.provider)
|
||||||
this.route = input.route
|
this.route = input.route
|
||||||
this.http = input.http
|
this.transport = input.transport
|
||||||
this.providerOptions = input.providerOptions
|
this.providerOptions = input.providerOptions
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -43,7 +44,7 @@ export namespace MediaModel {
|
||||||
readonly id: string | ModelID
|
readonly id: string | ModelID
|
||||||
readonly provider: string | ProviderID
|
readonly provider: string | ProviderID
|
||||||
readonly route: Route
|
readonly route: Route
|
||||||
readonly http?: HttpOptions
|
readonly transport?: TransportOptions
|
||||||
readonly providerOptions?: ProviderOptions
|
readonly providerOptions?: ProviderOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -101,8 +102,7 @@ const composition = <Request extends MediaRoute.MediaRequest, Protocol>(
|
||||||
protocol: route.protocol,
|
protocol: route.protocol,
|
||||||
endpoint: Endpoint.path(route.path, { baseURL: input.baseURL ?? route.baseURL }),
|
endpoint: Endpoint.path(route.path, { baseURL: input.baseURL ?? route.baseURL }),
|
||||||
auth: input.auth,
|
auth: input.auth,
|
||||||
headers:
|
headers: route.headers,
|
||||||
route.headers === undefined && input.headers === undefined ? undefined : { ...route.headers, ...input.headers },
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const isStreamInput = <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(
|
const isStreamInput = <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,15 @@ import { Effect, FileSystem, Result, Schema, SchemaGetter, Stream } from "effect
|
||||||
import { Base64 } from "effect/encoding"
|
import { Base64 } from "effect/encoding"
|
||||||
import { HttpClientRequest } from "effect/http"
|
import { HttpClientRequest } from "effect/http"
|
||||||
import { ProviderID } from "./schema/ids.js"
|
import { ProviderID } from "./schema/ids.js"
|
||||||
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "./schema/errors.js"
|
import { AIError, InvalidRequestError } from "./schema/errors.js"
|
||||||
import { ProviderMetadata } from "./schema/options.js"
|
import { ProviderMetadata } from "./schema/options.js"
|
||||||
import { responseHttp, Service } from "./route/executor-service.js"
|
import {
|
||||||
|
CurrentMiddleware,
|
||||||
|
type HttpMiddleware,
|
||||||
|
responseBytes,
|
||||||
|
responseStream,
|
||||||
|
Service,
|
||||||
|
} from "./route/executor-service.js"
|
||||||
import { detectMediaType, fileMediaType } from "./utils/media-type.js"
|
import { detectMediaType, fileMediaType } from "./utils/media-type.js"
|
||||||
|
|
||||||
export { detectMediaType } from "./utils/media-type.js"
|
export { detectMediaType } from "./utils/media-type.js"
|
||||||
|
|
@ -109,6 +115,8 @@ export class Asset {
|
||||||
readonly providerMetadata?: ProviderMetadata
|
readonly providerMetadata?: ProviderMetadata
|
||||||
/** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
|
/** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
|
||||||
readonly headers?: Record<string, string>
|
readonly headers?: Record<string, string>
|
||||||
|
/** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */
|
||||||
|
readonly middleware?: HttpMiddleware
|
||||||
|
|
||||||
// Derived payload forms are cached on the instance because every protocol lowering re-reads the same payload. The
|
// Derived payload forms are cached on the instance because every protocol lowering re-reads the same payload. The
|
||||||
// cache is check-then-set (concurrent first reads of a `url` source may both download) and is never observable
|
// cache is check-then-set (concurrent first reads of a `url` source may both download) and is never observable
|
||||||
|
|
@ -127,6 +135,7 @@ export class Asset {
|
||||||
this.expiresAt = input.source.type === "url" ? input.source.expiresAt : undefined
|
this.expiresAt = input.source.type === "url" ? input.source.expiresAt : undefined
|
||||||
this.providerMetadata = input.providerMetadata
|
this.providerMetadata = input.providerMetadata
|
||||||
this.headers = input.source.type === "url" ? input.headers : undefined
|
this.headers = input.source.type === "url" ? input.headers : undefined
|
||||||
|
this.middleware = input.source.type === "url" ? input.middleware : undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
|
/** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
|
||||||
|
|
@ -151,7 +160,7 @@ export class Asset {
|
||||||
? Effect.fromResult(Base64.decode(source.data)).pipe(
|
? Effect.fromResult(Base64.decode(source.data)).pipe(
|
||||||
Effect.mapError((cause) => invalid(`Media asset contains invalid base64 data`, cause)),
|
Effect.mapError((cause) => invalid(`Media asset contains invalid base64 data`, cause)),
|
||||||
)
|
)
|
||||||
: download(source, this.headers)
|
: download(source, this.headers, this.middleware)
|
||||||
return decoded.pipe(Effect.tap((data) => Effect.sync(() => (this.#bytes = data))))
|
return decoded.pipe(Effect.tap((data) => Effect.sync(() => (this.#bytes = data))))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -160,7 +169,7 @@ export class Asset {
|
||||||
stream(): Stream.Stream<Uint8Array, AIError, Service> {
|
stream(): Stream.Stream<Uint8Array, AIError, Service> {
|
||||||
const source = this.source
|
const source = this.source
|
||||||
if (source.type !== "url" || this.#bytes !== undefined) return Stream.fromEffect(this.bytes())
|
if (source.type !== "url" || this.#bytes !== undefined) return Stream.fromEffect(this.bytes())
|
||||||
return Stream.unwrap(downloadStream(source, this.headers))
|
return Stream.unwrap(downloadStream(source, this.headers, this.middleware))
|
||||||
}
|
}
|
||||||
|
|
||||||
base64(): Effect.Effect<string, AIError, Service> {
|
base64(): Effect.Effect<string, AIError, Service> {
|
||||||
|
|
@ -211,6 +220,12 @@ export namespace Asset {
|
||||||
* credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting.
|
* credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting.
|
||||||
*/
|
*/
|
||||||
readonly headers?: Record<string, string>
|
readonly headers?: Record<string, string>
|
||||||
|
/**
|
||||||
|
* Middleware for downloading a `url` source, runtime-only like `headers`. A download never uses the caller's
|
||||||
|
* scoped middleware (`RequestExecutor.withMiddleware`), so hooks that add provider credentials can't reach another
|
||||||
|
* host. Routes set this to that middleware only for result URLs on the provider's origin.
|
||||||
|
*/
|
||||||
|
readonly middleware?: HttpMiddleware
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -239,49 +254,42 @@ export const AssetSchema = AssetEncoded.pipe(
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with
|
||||||
|
* `Media.image`; an asset known to be a video, audio or document is rejected.
|
||||||
|
*/
|
||||||
|
export const ImageAssetSchema = AssetInstance.check(
|
||||||
|
Schema.makeFilter(
|
||||||
|
(asset) =>
|
||||||
|
asset.kind === "image" ||
|
||||||
|
((asset.source.type === "url" || asset.source.type === "ref") && asset.source.mediaType === undefined) ||
|
||||||
|
`expected an image, got ${asset.mediaType}`,
|
||||||
|
),
|
||||||
|
).pipe(Schema.brand("Media.ImageAsset"))
|
||||||
|
export type ImageAsset = typeof ImageAssetSchema.Type
|
||||||
|
|
||||||
const download = Effect.fn("Media.download")(function* (
|
const download = Effect.fn("Media.download")(function* (
|
||||||
source: Extract<Source, { readonly type: "url" }>,
|
source: Extract<Source, { readonly type: "url" }>,
|
||||||
headers: Record<string, string> | undefined,
|
headers: Record<string, string> | undefined,
|
||||||
|
middleware: HttpMiddleware | undefined,
|
||||||
) {
|
) {
|
||||||
const executor = yield* Service
|
const executor = yield* Service
|
||||||
const response = yield* executor.execute(
|
const response = yield* executor
|
||||||
HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})),
|
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
|
||||||
)
|
.pipe(Effect.provideService(CurrentMiddleware, middleware))
|
||||||
const buffer = yield* response.arrayBuffer.pipe(
|
return yield* responseBytes(response)
|
||||||
Effect.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AIError({
|
|
||||||
reason: new InvalidProviderOutputError({
|
|
||||||
message: `Failed to read media from ${source.url}`,
|
|
||||||
http: responseHttp(response),
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
return new Uint8Array(buffer)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const downloadStream = Effect.fn("Media.downloadStream")(function* (
|
const downloadStream = Effect.fn("Media.downloadStream")(function* (
|
||||||
source: Extract<Source, { readonly type: "url" }>,
|
source: Extract<Source, { readonly type: "url" }>,
|
||||||
headers: Record<string, string> | undefined,
|
headers: Record<string, string> | undefined,
|
||||||
|
middleware: HttpMiddleware | undefined,
|
||||||
) {
|
) {
|
||||||
const executor = yield* Service
|
const executor = yield* Service
|
||||||
const response = yield* executor.execute(
|
const response = yield* executor
|
||||||
HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})),
|
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
|
||||||
)
|
.pipe(Effect.provideService(CurrentMiddleware, middleware))
|
||||||
return response.stream.pipe(
|
return responseStream(response)
|
||||||
Stream.mapError(
|
|
||||||
(cause) =>
|
|
||||||
new AIError({
|
|
||||||
reason: new InvalidProviderOutputError({
|
|
||||||
message: `Failed to read media from ${source.url}`,
|
|
||||||
http: responseHttp(response),
|
|
||||||
cause,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
@ -330,6 +338,13 @@ export type Data = Uint8Array | ArrayBuffer | URL | string
|
||||||
/** What file inputs accept: an `Asset` or plain `Data`. */
|
/** What file inputs accept: an `Asset` or plain `Data`. */
|
||||||
export type Input = Asset | Data
|
export type Input = Asset | Data
|
||||||
|
|
||||||
|
/** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */
|
||||||
|
export const image = (input: Input, mediaType?: string): ImageAsset => {
|
||||||
|
const asset = make(input, mediaType)
|
||||||
|
if (!Schema.is(ImageAssetSchema)(asset)) throw invalid(`expected an image, got ${asset.mediaType}`)
|
||||||
|
return asset
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
|
* Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
|
||||||
* bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
|
* bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,8 @@ export const protocol = Protocol.make({
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
stream: AnthropicMessages.protocol.stream,
|
stream: AnthropicMessages.protocol.stream,
|
||||||
|
supportsEffortUpdates: AnthropicMessages.protocol.supportsEffortUpdates,
|
||||||
|
toolUpdates: AnthropicMessages.protocol.toolUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export * as AlibabaMessages from "./alibaba-messages.js"
|
export * as AlibabaMessages from "./alibaba-messages.js"
|
||||||
|
|
|
||||||
|
|
@ -81,6 +81,7 @@ export const protocol = Protocol.make({
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
|
supportsEffortUpdates: OpenResponses.protocol.supportsEffortUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export * as AlibabaResponses from "./alibaba-responses.js"
|
export * as AlibabaResponses from "./alibaba-responses.js"
|
||||||
|
|
|
||||||
|
|
@ -23,11 +23,13 @@ import {
|
||||||
type ProviderOptions,
|
type ProviderOptions,
|
||||||
type ToolCallPart,
|
type ToolCallPart,
|
||||||
type ToolDefinition,
|
type ToolDefinition,
|
||||||
|
type ToolChanges,
|
||||||
type ToolResultPart,
|
type ToolResultPart,
|
||||||
} from "../schema/index.js"
|
} from "../schema/index.js"
|
||||||
import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js"
|
import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js"
|
||||||
import { classifyProviderFailure } from "../provider-error.js"
|
import { classifyProviderFailure } from "../provider-error.js"
|
||||||
import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js"
|
import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js"
|
||||||
|
import { addsTools, toolsUpdate, type ToolUpdateEncoding } from "../tool-updates.js"
|
||||||
import * as Cache from "./utils/cache.js"
|
import * as Cache from "./utils/cache.js"
|
||||||
import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
|
import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
|
||||||
import { Lifecycle } from "./utils/lifecycle.js"
|
import { Lifecycle } from "./utils/lifecycle.js"
|
||||||
|
|
@ -253,17 +255,6 @@ const AnthropicAssistantBlock = Schema.Union([
|
||||||
type AnthropicAssistantBlock = Schema.Schema.Type<typeof AnthropicAssistantBlock>
|
type AnthropicAssistantBlock = Schema.Schema.Type<typeof AnthropicAssistantBlock>
|
||||||
type AnthropicToolResultBlock = Schema.Schema.Type<typeof AnthropicToolResultBlock>
|
type AnthropicToolResultBlock = Schema.Schema.Type<typeof AnthropicToolResultBlock>
|
||||||
|
|
||||||
const AnthropicMessage = Schema.Union([
|
|
||||||
Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }),
|
|
||||||
Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }),
|
|
||||||
Schema.Struct({
|
|
||||||
role: Schema.Literal("system"),
|
|
||||||
content: Schema.Array(AnthropicTextBlock),
|
|
||||||
output_config: Schema.optional(Schema.Struct({ effort: Schema.String })),
|
|
||||||
}),
|
|
||||||
]).pipe(Schema.toTaggedUnion("role"))
|
|
||||||
type AnthropicMessage = Schema.Schema.Type<typeof AnthropicMessage>
|
|
||||||
|
|
||||||
const AnthropicTool = Schema.Struct({
|
const AnthropicTool = Schema.Struct({
|
||||||
name: Schema.String,
|
name: Schema.String,
|
||||||
description: Schema.String,
|
description: Schema.String,
|
||||||
|
|
@ -272,6 +263,26 @@ const AnthropicTool = Schema.Struct({
|
||||||
})
|
})
|
||||||
type AnthropicTool = Schema.Schema.Type<typeof AnthropicTool>
|
type AnthropicTool = Schema.Schema.Type<typeof AnthropicTool>
|
||||||
|
|
||||||
|
const AnthropicToolAdditionBlock = Schema.Struct({
|
||||||
|
type: Schema.tag("tool_addition"),
|
||||||
|
tool: Schema.Struct({ type: Schema.tag("tool_definition"), definition: AnthropicTool }),
|
||||||
|
})
|
||||||
|
const AnthropicToolRemovalBlock = Schema.Struct({
|
||||||
|
type: Schema.tag("tool_removal"),
|
||||||
|
tool: Schema.Struct({ type: Schema.tag("tool_reference"), name: Schema.String }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const AnthropicMessage = Schema.Union([
|
||||||
|
Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }),
|
||||||
|
Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }),
|
||||||
|
Schema.Struct({
|
||||||
|
role: Schema.Literal("system"),
|
||||||
|
content: Schema.Array(Schema.Union([AnthropicTextBlock, AnthropicToolAdditionBlock, AnthropicToolRemovalBlock])),
|
||||||
|
output_config: Schema.optional(Schema.Struct({ effort: Schema.String })),
|
||||||
|
}),
|
||||||
|
]).pipe(Schema.toTaggedUnion("role"))
|
||||||
|
type AnthropicMessage = Schema.Schema.Type<typeof AnthropicMessage>
|
||||||
|
|
||||||
const AnthropicToolChoice = Schema.Union([
|
const AnthropicToolChoice = Schema.Union([
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
type: Schema.Literals(["auto", "any", "none"]),
|
type: Schema.Literals(["auto", "any", "none"]),
|
||||||
|
|
@ -792,6 +803,28 @@ const lowerWrappedSystemUpdate = Effect.fnUntraced(function* (
|
||||||
return { type: "text" as const, text: part.text, cache_control: cacheControl(breakpoints, part.cache) }
|
return { type: "text" as const, text: part.text, cache_control: cacheControl(breakpoints, part.cache) }
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const lowerToolsUpdate = Effect.fnUntraced(function* (
|
||||||
|
message: LLMRequest["messages"][number],
|
||||||
|
update: ToolChanges,
|
||||||
|
breakpoints: Cache.Breakpoints,
|
||||||
|
) {
|
||||||
|
const text = message.content.length === 0 ? [] : (yield* lowerNativeSystemUpdate(message, breakpoints)).content
|
||||||
|
return {
|
||||||
|
role: "system" as const,
|
||||||
|
content: [
|
||||||
|
...ProviderShared.flattenTools(update.add).map((tool) => ({
|
||||||
|
type: "tool_addition" as const,
|
||||||
|
tool: { type: "tool_definition" as const, definition: lowerTool(breakpoints, tool) },
|
||||||
|
})),
|
||||||
|
...update.remove.map((name) => ({
|
||||||
|
type: "tool_removal" as const,
|
||||||
|
tool: { type: "tool_reference" as const, name },
|
||||||
|
})),
|
||||||
|
...text,
|
||||||
|
],
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
const appendToUserTurn = (messages: AnthropicMessage[], block: AnthropicUserBlock) => {
|
const appendToUserTurn = (messages: AnthropicMessage[], block: AnthropicUserBlock) => {
|
||||||
const last = messages.at(-1)
|
const last = messages.at(-1)
|
||||||
if (last?.role === "user") messages[messages.length - 1] = { role: "user", content: [...last.content, block] }
|
if (last?.role === "user") messages[messages.length - 1] = { role: "user", content: [...last.content, block] }
|
||||||
|
|
@ -808,6 +841,13 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
|
||||||
const releaseHeld = Effect.fnUntraced(function* () {
|
const releaseHeld = Effect.fnUntraced(function* () {
|
||||||
const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"))
|
const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"))
|
||||||
for (const update of held.splice(0)) {
|
for (const update of held.splice(0)) {
|
||||||
|
const tools = toolsUpdate(update)
|
||||||
|
if (tools !== undefined) {
|
||||||
|
if (!native) return yield* invalid("Anthropic Messages tool updates must follow a user message or tool result")
|
||||||
|
const lowered = yield* lowerToolsUpdate(update, tools, breakpoints)
|
||||||
|
if (lowered.content.length > 0) messages.push(lowered)
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (native) messages.push(yield* lowerNativeSystemUpdate(update, breakpoints))
|
if (native) messages.push(yield* lowerNativeSystemUpdate(update, breakpoints))
|
||||||
else appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(update, breakpoints))
|
else appendToUserTurn(messages, yield* lowerWrappedSystemUpdate(update, breakpoints))
|
||||||
}
|
}
|
||||||
|
|
@ -821,6 +861,12 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
|
||||||
messages.push({ role: "system", content: [], output_config: { effort: update.effort ?? DEFAULT_EFFORT } })
|
messages.push({ role: "system", content: [], output_config: { effort: update.effort ?? DEFAULT_EFFORT } })
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// Held like text updates, so one between a tool call and its result lands after the result. Planning keeps a
|
||||||
|
// marker in place only on models that take native system messages.
|
||||||
|
if (toolsUpdate(message) !== undefined) {
|
||||||
|
held.push(message)
|
||||||
|
continue
|
||||||
|
}
|
||||||
if (splitsLocalToolResults(request.messages, index))
|
if (splitsLocalToolResults(request.messages, index))
|
||||||
return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result")
|
return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result")
|
||||||
if (holdUpdates) held.push(message)
|
if (holdUpdates) held.push(message)
|
||||||
|
|
@ -930,6 +976,21 @@ const supportsEffortUpdates = (request: LLMRequest) => {
|
||||||
return version.major > 5 || (version.major === 5 && version.minor >= 1)
|
return version.major > 5 || (version.major === 5 && version.minor >= 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `tool_addition` adds a tool, or redefines one with the same name; `tool_removal` removes one. A held marker is
|
||||||
|
// released just before the next assistant message, where Anthropic only accepts a native system message after a
|
||||||
|
// user message or tool result; a marker that would land elsewhere folds.
|
||||||
|
const toolUpdates = {
|
||||||
|
kinds: ["add", "remove", "replace"],
|
||||||
|
placeable: (request, index) => {
|
||||||
|
if (!supportsNativeSystemUpdates(request)) return false
|
||||||
|
const end = request.messages.findIndex((next, at) => at > index && next.role === "assistant")
|
||||||
|
const role = request.messages
|
||||||
|
.slice(0, end === -1 ? undefined : end)
|
||||||
|
.findLast((next) => next.role !== "system")?.role
|
||||||
|
return role === "user" || role === "tool"
|
||||||
|
},
|
||||||
|
} satisfies ToolUpdateEncoding
|
||||||
|
|
||||||
const applyThinkingBindingDefault = (model: LLMRequest["model"], thinking: AnthropicThinking | undefined) => {
|
const applyThinkingBindingDefault = (model: LLMRequest["model"], thinking: AnthropicThinking | undefined) => {
|
||||||
if (isThinkingOff(thinking)) return thinking
|
if (isThinkingOff(thinking)) return thinking
|
||||||
if (!supportsThinkingBlockBinding(model)) return thinking
|
if (!supportsThinkingBlockBinding(model)) return thinking
|
||||||
|
|
@ -961,10 +1022,11 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
|
||||||
// messages. Tools live highest in the cache hierarchy, so when callers
|
// messages. Tools live highest in the cache hierarchy, so when callers
|
||||||
// over-mark we keep their tool hints and shed the message-tail ones first.
|
// over-mark we keep their tool hints and shed the message-tail ones first.
|
||||||
const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)
|
const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP)
|
||||||
const flattened = ProviderShared.flattenToolRequest(updates.request)
|
const definitions = ProviderShared.flattenTools(updates.request.tools)
|
||||||
const tools = flattened.tools.length === 0 ? undefined : flattened.tools.map((tool) => lowerTool(breakpoints, tool))
|
const tools = definitions.length === 0 ? undefined : definitions.map((tool) => lowerTool(breakpoints, tool))
|
||||||
// Anthropic rejects tool_choice when tools are absent; "none" is only meaningful with tools present.
|
// Anthropic rejects tool_choice when no tool is declared; "none" is only meaningful with tools present.
|
||||||
const toolChoice = tools === undefined || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice)
|
const declared = tools !== undefined || addsTools(request)
|
||||||
|
const toolChoice = !declared || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice)
|
||||||
const systemParts = request.system.filter((part) => part.text.length > 0)
|
const systemParts = request.system.filter((part) => part.text.length > 0)
|
||||||
const system =
|
const system =
|
||||||
systemParts.length === 0
|
systemParts.length === 0
|
||||||
|
|
@ -974,7 +1036,7 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
|
||||||
text: part.text,
|
text: part.text,
|
||||||
cache_control: cacheControl(breakpoints, part.cache),
|
cache_control: cacheControl(breakpoints, part.cache),
|
||||||
}))
|
}))
|
||||||
const messages = yield* lowerMessages(flattened.request, breakpoints)
|
const messages = yield* lowerMessages(updates.request, breakpoints)
|
||||||
yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP)
|
yield* Cache.warnDropped(breakpoints, "Anthropic Messages", ANTHROPIC_BREAKPOINT_CAP)
|
||||||
const output_config =
|
const output_config =
|
||||||
updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format }
|
updates.effort === undefined && format === undefined ? undefined : { effort: updates.effort, format }
|
||||||
|
|
@ -1528,6 +1590,7 @@ export const protocol = Protocol.make({
|
||||||
step,
|
step,
|
||||||
},
|
},
|
||||||
supportsEffortUpdates,
|
supportsEffortUpdates,
|
||||||
|
toolUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const transport = <
|
export const transport = <
|
||||||
|
|
@ -1568,6 +1631,14 @@ function requiredBetaHeaders(
|
||||||
|
|
||||||
if (body.messages.some((message) => message.role === "system" && message.output_config !== undefined))
|
if (body.messages.some((message) => message.role === "system" && message.output_config !== undefined))
|
||||||
betas.push("mid-conversation-output-config-2026-07-01")
|
betas.push("mid-conversation-output-config-2026-07-01")
|
||||||
|
if (
|
||||||
|
body.messages.some(
|
||||||
|
(message) =>
|
||||||
|
message.role === "system" &&
|
||||||
|
message.content.some((block) => block.type === "tool_addition" || block.type === "tool_removal"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
betas.push("inline-tools-2026-09-15")
|
||||||
|
|
||||||
// Opus 5.5 accepts `speed` without this header; earlier fast-mode models reject `speed` without it.
|
// Opus 5.5 accepts `speed` without this header; earlier fast-mode models reject `speed` without it.
|
||||||
if (body.speed !== undefined) betas.push("fast-mode-2026-02-01")
|
if (body.speed !== undefined) betas.push("fast-mode-2026-02-01")
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { Effect, Schema } from "effect"
|
import { Effect, Schema } from "effect"
|
||||||
import type { HttpClientResponse } from "effect/http"
|
import type { HttpClientResponse } from "effect/http"
|
||||||
import type { Status } from "../generation.js"
|
|
||||||
import { Media } from "../media.js"
|
import { Media } from "../media.js"
|
||||||
import { MediaProtocol } from "../route/media-protocol.js"
|
import { MediaProtocol } from "../route/media-protocol.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
|
|
@ -78,11 +77,11 @@ const Transcript = Schema.Struct({
|
||||||
})
|
})
|
||||||
|
|
||||||
const STATUS = {
|
const STATUS = {
|
||||||
queued: "queued",
|
queued: "running",
|
||||||
processing: "running",
|
processing: "running",
|
||||||
completed: "completed",
|
completed: "completed",
|
||||||
error: "failed",
|
error: "failed",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 5. Request body construction
|
// 5. Request body construction
|
||||||
|
|
@ -133,8 +132,10 @@ const decodeStart = Effect.fn("AssemblyAITranscription.decodeStart")(function* (
|
||||||
response: HttpClientResponse.HttpClientResponse,
|
response: HttpClientResponse.HttpClientResponse,
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTranscript(response)
|
const output = yield* decodeTranscript(response)
|
||||||
const status = MediaProtocol.status(STATUS, output.value.status)
|
return {
|
||||||
return { token: { transcriptID: output.value.id }, snapshot: { id: output.value.id, status } }
|
token: { transcriptID: output.value.id },
|
||||||
|
snapshot: { id: output.value.id, ...MediaProtocol.status(STATUS, output.value.status) },
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeStatus = Effect.fn("AssemblyAITranscription.decodeStatus")(function* (
|
const decodeStatus = Effect.fn("AssemblyAITranscription.decodeStatus")(function* (
|
||||||
|
|
@ -142,8 +143,7 @@ const decodeStatus = Effect.fn("AssemblyAITranscription.decodeStatus")(function*
|
||||||
context: MediaProtocol.PollContext<Token>,
|
context: MediaProtocol.PollContext<Token>,
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTranscript(response)
|
const output = yield* decodeTranscript(response)
|
||||||
const status = MediaProtocol.status(STATUS, output.value.status)
|
return { id: context.token.transcriptID, ...MediaProtocol.status(STATUS, output.value.status) }
|
||||||
return { id: context.token.transcriptID, status }
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const seconds = (milliseconds: number) => milliseconds / 1000
|
const seconds = (milliseconds: number) => milliseconds / 1000
|
||||||
|
|
@ -154,7 +154,7 @@ const decodeResult = Effect.fn("AssemblyAITranscription.decodeResult")(function*
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTranscript(response)
|
const output = yield* decodeTranscript(response)
|
||||||
const transcript = output.value
|
const transcript = output.value
|
||||||
const status = MediaProtocol.status(STATUS, transcript.status)
|
const status = MediaProtocol.state(STATUS, transcript.status)
|
||||||
const error = transcript.error ?? undefined
|
const error = transcript.error ?? undefined
|
||||||
if (status === "failed")
|
if (status === "failed")
|
||||||
return yield* output.ended("failed", `${route.name} transcription failed${error === undefined ? "" : `: ${error}`}`)
|
return yield* output.ended("failed", `${route.name} transcription failed${error === undefined ? "" : `: ${error}`}`)
|
||||||
|
|
|
||||||
|
|
@ -312,8 +312,8 @@ const removeEmptyToolInputKeys = (input: unknown): unknown => {
|
||||||
const lowerToolCall = (part: ToolCallPart, normalizeID: (id: string) => string): BedrockToolUseBlock => ({
|
const lowerToolCall = (part: ToolCallPart, normalizeID: (id: string) => string): BedrockToolUseBlock => ({
|
||||||
toolUse: {
|
toolUse: {
|
||||||
toolUseId: normalizeID(part.id),
|
toolUseId: normalizeID(part.id),
|
||||||
// Models can emit names that Converse rejects when replayed in history.
|
// Converse rejects replayed names over 64 characters; flattenRequest already fixed invalid characters.
|
||||||
name: part.name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64) || "_",
|
name: part.name.slice(0, 64),
|
||||||
input: removeEmptyToolInputKeys(part.input),
|
input: removeEmptyToolInputKeys(part.input),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
@ -560,7 +560,7 @@ const applyThinkingBindingDefault = (request: LLMRequest, thinking: Readonly<Rec
|
||||||
|
|
||||||
const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: LLMRequest) {
|
const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request: LLMRequest) {
|
||||||
const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined
|
const toolChoice = request.toolChoice ? yield* lowerToolChoice(request.toolChoice) : undefined
|
||||||
const flattened = ProviderShared.flattenToolRequest(request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
const options = yield* decodeOptions(request.providerOptions ?? {})
|
const options = yield* decodeOptions(request.providerOptions ?? {})
|
||||||
const maxTokens =
|
const maxTokens =
|
||||||
isNova2(request.model) && (options.effort === "high" || isHighReasoningEffort(request.http?.body))
|
isNova2(request.model) && (options.effort === "high" || isHighReasoningEffort(request.http?.body))
|
||||||
|
|
@ -593,16 +593,16 @@ const fromRequest = Effect.fn("BedrockConverse.fromRequest")(function* (request:
|
||||||
// tools → system → messages order to favour the highest-impact prefixes.
|
// tools → system → messages order to favour the highest-impact prefixes.
|
||||||
const breakpoints = BedrockCache.breakpoints(request.model)
|
const breakpoints = BedrockCache.breakpoints(request.model)
|
||||||
const toolConfig = (() => {
|
const toolConfig = (() => {
|
||||||
if (flattened.tools.length === 0) return undefined
|
if (definitions.length === 0) return undefined
|
||||||
return {
|
return {
|
||||||
tools: lowerTools(breakpoints, flattened.tools),
|
tools: lowerTools(breakpoints, definitions),
|
||||||
// Converse has no native "none". Keep definitions stable for prompt
|
// Converse has no native "none". Keep definitions stable for prompt
|
||||||
// caching and omit only the unsupported choice.
|
// caching and omit only the unsupported choice.
|
||||||
toolChoice,
|
toolChoice,
|
||||||
}
|
}
|
||||||
})()
|
})()
|
||||||
const system = lowerSystem(breakpoints, request.system)
|
const system = lowerSystem(breakpoints, request.system)
|
||||||
const messages = yield* lowerMessages(flattened.request, breakpoints)
|
const messages = yield* lowerMessages(request, breakpoints)
|
||||||
yield* warnDropped(breakpoints, "Bedrock Converse", BedrockCache.BEDROCK_BREAKPOINT_CAP)
|
yield* warnDropped(breakpoints, "Bedrock Converse", BedrockCache.BEDROCK_BREAKPOINT_CAP)
|
||||||
const inferenceConfig = (() => {
|
const inferenceConfig = (() => {
|
||||||
if (
|
if (
|
||||||
|
|
|
||||||
|
|
@ -145,7 +145,7 @@ const TOOL_CHOICE = { auto: undefined, none: "NONE", required: "REQUIRED", tool:
|
||||||
|
|
||||||
const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMRequest) {
|
const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMRequest) {
|
||||||
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(request.providerOptions ?? {})
|
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(request.providerOptions ?? {})
|
||||||
const flattened = ProviderShared.flattenToolRequest(request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
const messages: (typeof Message.Type)[] = request.system.length
|
const messages: (typeof Message.Type)[] = request.system.length
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
|
|
@ -157,7 +157,7 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMR
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
: []
|
: []
|
||||||
for (const message of flattened.request.messages) {
|
for (const message of request.messages) {
|
||||||
if (message.role === "system") {
|
if (message.role === "system") {
|
||||||
messages.push({ role: "user", content: (yield* ProviderShared.wrappedSystemUpdate("Cohere Chat", message)).text })
|
messages.push({ role: "user", content: (yield* ProviderShared.wrappedSystemUpdate("Cohere Chat", message)).text })
|
||||||
continue
|
continue
|
||||||
|
|
@ -211,7 +211,7 @@ const fromRequest = Effect.fn("CohereChat.fromRequest")(function* (request: LLMR
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const selected = request.toolChoice?.type === "tool" ? request.toolChoice.name : undefined
|
const selected = request.toolChoice?.type === "tool" ? request.toolChoice.name : undefined
|
||||||
const tools = selected === undefined ? flattened.tools : flattened.tools.filter((tool) => tool.name === selected)
|
const tools = selected === undefined ? definitions : definitions.filter((tool) => tool.name === selected)
|
||||||
if (selected !== undefined && tools.length === 0)
|
if (selected !== undefined && tools.length === 0)
|
||||||
return yield* ProviderShared.invalidRequest("Cohere Chat tool choice must name an available tool")
|
return yield* ProviderShared.invalidRequest("Cohere Chat tool choice must name an available tool")
|
||||||
if (tools.some((tool) => tool.native !== undefined))
|
if (tools.some((tool) => tool.native !== undefined))
|
||||||
|
|
|
||||||
|
|
@ -149,25 +149,6 @@ const GeminiThinkingConfig = Schema.Struct({
|
||||||
thinkingLevel: Schema.optional(GeminiThinkingLevel),
|
thinkingLevel: Schema.optional(GeminiThinkingLevel),
|
||||||
})
|
})
|
||||||
|
|
||||||
const GeminiSafetySetting = Schema.Struct({
|
|
||||||
category: knownString<
|
|
||||||
| "HARM_CATEGORY_UNSPECIFIED"
|
|
||||||
| "HARM_CATEGORY_HATE_SPEECH"
|
|
||||||
| "HARM_CATEGORY_DANGEROUS_CONTENT"
|
|
||||||
| "HARM_CATEGORY_HARASSMENT"
|
|
||||||
| "HARM_CATEGORY_SEXUALLY_EXPLICIT"
|
|
||||||
| "HARM_CATEGORY_CIVIC_INTEGRITY"
|
|
||||||
>(),
|
|
||||||
threshold: knownString<
|
|
||||||
| "HARM_BLOCK_THRESHOLD_UNSPECIFIED"
|
|
||||||
| "BLOCK_LOW_AND_ABOVE"
|
|
||||||
| "BLOCK_MEDIUM_AND_ABOVE"
|
|
||||||
| "BLOCK_ONLY_HIGH"
|
|
||||||
| "BLOCK_NONE"
|
|
||||||
| "OFF"
|
|
||||||
>(),
|
|
||||||
})
|
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
// Provider Options
|
// Provider Options
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
@ -180,7 +161,7 @@ const GeminiThinkingConfigInput = Schema.Struct({
|
||||||
})
|
})
|
||||||
const Options = Schema.Struct({
|
const Options = Schema.Struct({
|
||||||
cachedContent: lenient(Schema.String),
|
cachedContent: lenient(Schema.String),
|
||||||
safetySettings: lenient(Schema.Array(GeminiSafetySetting)),
|
safetySettings: lenient(Schema.Array(GeminiGenerateContent.SafetySetting)),
|
||||||
serviceTier: lenient(knownString<"standard" | "flex" | "priority">()),
|
serviceTier: lenient(knownString<"standard" | "flex" | "priority">()),
|
||||||
thinkingConfig: lenient(GeminiThinkingConfigInput),
|
thinkingConfig: lenient(GeminiThinkingConfigInput),
|
||||||
})
|
})
|
||||||
|
|
@ -202,7 +183,7 @@ const GeminiBodyFields = {
|
||||||
cachedContent: Schema.optional(Schema.String),
|
cachedContent: Schema.optional(Schema.String),
|
||||||
contents: Schema.Array(GeminiContent),
|
contents: Schema.Array(GeminiContent),
|
||||||
labels: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
labels: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
||||||
safetySettings: optionalArray(GeminiSafetySetting),
|
safetySettings: optionalArray(GeminiGenerateContent.SafetySetting),
|
||||||
serviceTier: Schema.optional(Schema.String),
|
serviceTier: Schema.optional(Schema.String),
|
||||||
systemInstruction: Schema.optional(GeminiSystemInstruction),
|
systemInstruction: Schema.optional(GeminiSystemInstruction),
|
||||||
tools: optionalArray(GeminiTool),
|
tools: optionalArray(GeminiTool),
|
||||||
|
|
@ -442,8 +423,8 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) {
|
||||||
})
|
})
|
||||||
|
|
||||||
const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMRequest) {
|
const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMRequest) {
|
||||||
const flattened = ProviderShared.flattenToolRequest(request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
const hasTools = flattened.tools.length > 0
|
const hasTools = definitions.length > 0
|
||||||
const options = yield* decodeOptions(request.providerOptions ?? {})
|
const options = yield* decodeOptions(request.providerOptions ?? {})
|
||||||
const generationConfig = {
|
const generationConfig = {
|
||||||
maxOutputTokens: request.maxTokens,
|
maxOutputTokens: request.maxTokens,
|
||||||
|
|
@ -474,7 +455,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cachedContent: options.cachedContent,
|
cachedContent: options.cachedContent,
|
||||||
contents: yield* lowerMessages(flattened.request),
|
contents: yield* lowerMessages(request),
|
||||||
safetySettings: options.safetySettings,
|
safetySettings: options.safetySettings,
|
||||||
serviceTier: options.serviceTier,
|
serviceTier: options.serviceTier,
|
||||||
systemInstruction:
|
systemInstruction:
|
||||||
|
|
@ -482,7 +463,7 @@ const fromRequest = Effect.fn("Gemini.fromRequest")(function* (request: LLMReque
|
||||||
tools: hasTools
|
tools: hasTools
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
functionDeclarations: flattened.tools.map(lowerTool),
|
functionDeclarations: definitions.map(lowerTool),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
: undefined,
|
: undefined,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { Effect, Schema } from "effect"
|
import { Effect, Schema } from "effect"
|
||||||
import type { HttpClientResponse } from "effect/http"
|
import type { HttpClientResponse } from "effect/http"
|
||||||
import type { Status } from "../generation.js"
|
|
||||||
import { Media } from "../media.js"
|
import { Media } from "../media.js"
|
||||||
import { MediaProtocol } from "../route/media-protocol.js"
|
import { MediaProtocol } from "../route/media-protocol.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
|
|
@ -49,7 +48,8 @@ export type Request = VideoRequest<VideoModel<GoogleVideoOptions>>
|
||||||
// 2. Token and response schemas
|
// 2. Token and response schemas
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const Token = Schema.Struct({ interactionID: Schema.String })
|
/** The provider's job ID; it is all a later status, result or cancel call needs. */
|
||||||
|
export const Token = Schema.String
|
||||||
export type Token = Schema.Schema.Type<typeof Token>
|
export type Token = Schema.Schema.Type<typeof Token>
|
||||||
|
|
||||||
const Content = Schema.Struct({
|
const Content = Schema.Struct({
|
||||||
|
|
@ -91,7 +91,7 @@ const STATUS = {
|
||||||
incomplete: "completed",
|
incomplete: "completed",
|
||||||
failed: "failed",
|
failed: "failed",
|
||||||
cancelled: "cancelled",
|
cancelled: "cancelled",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 3. Failures
|
// 3. Failures
|
||||||
|
|
@ -128,11 +128,6 @@ const task = (request: Request) => {
|
||||||
const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* (request: Request) {
|
const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* (request: Request) {
|
||||||
if (request.end !== undefined && request.start === undefined)
|
if (request.end !== undefined && request.start === undefined)
|
||||||
return yield* route.unsupported("video.end", `${route.name} reads a lone image as the start frame; send start too`)
|
return yield* route.unsupported("video.end", `${route.name} reads a lone image as the start frame; send start too`)
|
||||||
if (request.sound === false)
|
|
||||||
return yield* route.unsupported(
|
|
||||||
"video.sound",
|
|
||||||
`${route.name} always generates audio and has no option to turn it off`,
|
|
||||||
)
|
|
||||||
const media = yield* Effect.forEach(
|
const media = yield* Effect.forEach(
|
||||||
[request.start, request.end, ...(request.references ?? [])].filter(
|
[request.start, request.end, ...(request.references ?? [])].filter(
|
||||||
(asset): asset is Media.Asset => asset !== undefined,
|
(asset): asset is Media.Asset => asset !== undefined,
|
||||||
|
|
@ -168,8 +163,8 @@ const fromRequest = Effect.fn("GoogleInteractionsVideo.fromRequest")(function* (
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const decodeStart = route.decodeStarted(Interaction, (value) => ({
|
const decodeStart = route.decodeStarted(Interaction, (value) => ({
|
||||||
token: { interactionID: value.id },
|
token: value.id,
|
||||||
snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status) },
|
snapshot: { id: value.id, ...MediaProtocol.status(STATUS, value.status) },
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const decodeInteraction = route.decodeJson(Interaction)
|
const decodeInteraction = route.decodeJson(Interaction)
|
||||||
|
|
@ -179,7 +174,7 @@ const decodeStatus = Effect.fn("GoogleInteractionsVideo.decodeStatus")(function*
|
||||||
context: MediaProtocol.PollContext<Token>,
|
context: MediaProtocol.PollContext<Token>,
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeInteraction(response)
|
const output = yield* decodeInteraction(response)
|
||||||
return { id: context.token.interactionID, status: MediaProtocol.status(STATUS, output.value.status) }
|
return { id: context.token, ...MediaProtocol.status(STATUS, output.value.status) }
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* (
|
const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function* (
|
||||||
|
|
@ -188,8 +183,8 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function*
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeInteraction(response)
|
const output = yield* decodeInteraction(response)
|
||||||
const decoded = output.value
|
const decoded = output.value
|
||||||
const status = MediaProtocol.status(STATUS, decoded.status)
|
const status = MediaProtocol.state(STATUS, decoded.status)
|
||||||
if (status === "running") return yield* output.pending(context.token.interactionID)
|
if (status === "running") return yield* output.pending(context.token)
|
||||||
const errors = decoded.errors ?? []
|
const errors = decoded.errors ?? []
|
||||||
const codes = errors.flatMap((error) => {
|
const codes = errors.flatMap((error) => {
|
||||||
const code = errorCode(error.code)
|
const code = errorCode(error.code)
|
||||||
|
|
@ -197,7 +192,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function*
|
||||||
})
|
})
|
||||||
const messages = errors.flatMap((error) => (error.message?.trim() ? [error.message.trim()] : []))
|
const messages = errors.flatMap((error) => (error.message?.trim() ? [error.message.trim()] : []))
|
||||||
if (status === "cancelled")
|
if (status === "cancelled")
|
||||||
return yield* output.ended("cancelled", `${route.name} interaction ${context.token.interactionID} was cancelled`)
|
return yield* output.ended("cancelled", `${route.name} interaction ${context.token} was cancelled`)
|
||||||
if (status === "failed") {
|
if (status === "failed") {
|
||||||
const message = `${route.name} generation failed${codes.length === 0 ? "" : ` (${codes.join(", ")})`}${messages.length === 0 ? "" : `: ${messages.join("\n")}`}`
|
const message = `${route.name} generation failed${codes.length === 0 ? "" : ` (${codes.join(", ")})`}${messages.length === 0 ? "" : `: ${messages.join("\n")}`}`
|
||||||
if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code)))
|
if (codes.some((code) => code === "CONTENT_BLOCKED" || GeminiGenerateContent.contentFiltered(code)))
|
||||||
|
|
@ -250,7 +245,7 @@ const decodeResult = Effect.fn("GoogleInteractionsVideo.decodeResult")(function*
|
||||||
// 7. Protocol and route
|
// 7. Protocol and route
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const interactionPath = (token: Token) => `${PATH}/${token.interactionID}`
|
const interactionPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}`
|
||||||
|
|
||||||
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
||||||
token: Token,
|
token: Token,
|
||||||
|
|
@ -261,7 +256,7 @@ export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(rout
|
||||||
})
|
})
|
||||||
|
|
||||||
export const model = (input: MediaRoute.ModelInput) =>
|
export const model = (input: MediaRoute.ModelInput) =>
|
||||||
VideoModel.fromRoute<GoogleVideoOptions, Token>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
|
VideoModel.fromRoute<GoogleVideoOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
|
||||||
|
|
||||||
export const GoogleInteractionsVideo = {
|
export const GoogleInteractionsVideo = {
|
||||||
protocol,
|
protocol,
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,14 @@
|
||||||
import { Effect, Option, Schema, SchemaGetter } from "effect"
|
import { Effect, Option, Schema, SchemaGetter, Stream } from "effect"
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { Auth } from "../route/auth.js"
|
import { Auth } from "../route/auth.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { Framing } from "../route/framing.js"
|
|
||||||
import { Protocol } from "../route/protocol.js"
|
import { Protocol } from "../route/protocol.js"
|
||||||
|
import {
|
||||||
|
HttpTransport,
|
||||||
|
type Transport,
|
||||||
|
type TransportExecution,
|
||||||
|
type TransportPrepareInput,
|
||||||
|
} from "../route/transport/index.js"
|
||||||
import {
|
import {
|
||||||
AIError,
|
AIError,
|
||||||
ContentPolicyError,
|
ContentPolicyError,
|
||||||
|
|
@ -25,6 +30,9 @@ import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
|
||||||
import { ToolStream } from "./utils/tool-stream.js"
|
import { ToolStream } from "./utils/tool-stream.js"
|
||||||
|
|
||||||
const ADAPTER = "google-interactions"
|
const ADAPTER = "google-interactions"
|
||||||
|
const CONTINUATION = "requires_continuation"
|
||||||
|
// Matches Google's GenAI SDKs (Python, JS, and Go).
|
||||||
|
const MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS = 3
|
||||||
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator"
|
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator"
|
||||||
export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
|
export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
|
||||||
|
|
||||||
|
|
@ -38,6 +46,7 @@ const Options = Schema.Struct({
|
||||||
thinkingLevel: lenient(ThinkingLevel),
|
thinkingLevel: lenient(ThinkingLevel),
|
||||||
thinkingSummaries: lenient(knownString<"auto" | "none">()),
|
thinkingSummaries: lenient(knownString<"auto" | "none">()),
|
||||||
serviceTier: lenient(knownString<"standard" | "flex" | "priority" | "deferred">()),
|
serviceTier: lenient(knownString<"standard" | "flex" | "priority" | "deferred">()),
|
||||||
|
safetySettings: lenient(Schema.Array(GeminiGenerateContent.SafetySetting)),
|
||||||
})
|
})
|
||||||
export type OptionsInput = typeof Options.Encoded
|
export type OptionsInput = typeof Options.Encoded
|
||||||
export type ProviderOptionsInput = OptionsInput
|
export type ProviderOptionsInput = OptionsInput
|
||||||
|
|
@ -83,12 +92,14 @@ const ToolChoice = Schema.Union([
|
||||||
])
|
])
|
||||||
const Body = Schema.Struct({
|
const Body = Schema.Struct({
|
||||||
model: Schema.String,
|
model: Schema.String,
|
||||||
input: Schema.Array(InputStep),
|
input: Schema.optional(Schema.Array(InputStep)),
|
||||||
stream: Schema.Literal(true),
|
stream: Schema.Literal(true),
|
||||||
store: Schema.Boolean,
|
store: Schema.Boolean,
|
||||||
previous_interaction_id: Schema.optional(Schema.String),
|
previous_interaction_id: Schema.optional(Schema.String),
|
||||||
|
continuation_token: Schema.optional(Schema.String),
|
||||||
system_instruction: Schema.optional(Schema.String),
|
system_instruction: Schema.optional(Schema.String),
|
||||||
service_tier: Schema.optional(Schema.String),
|
service_tier: Schema.optional(Schema.String),
|
||||||
|
safety_settings: Schema.optional(Schema.Array(Schema.Struct({ type: Schema.String, threshold: Schema.String }))),
|
||||||
tools: Schema.optional(
|
tools: Schema.optional(
|
||||||
Schema.Array(
|
Schema.Array(
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
|
|
@ -157,6 +168,7 @@ const Interaction = Schema.StructWithRest(
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
id: Schema.optional(Schema.String),
|
id: Schema.optional(Schema.String),
|
||||||
status: Schema.String,
|
status: Schema.String,
|
||||||
|
continuation_token: optionalNull(Schema.String),
|
||||||
usage: Schema.optional(RawUsage),
|
usage: Schema.optional(RawUsage),
|
||||||
errors: Schema.optional(
|
errors: Schema.optional(
|
||||||
Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String), message: Schema.optional(Schema.String) })),
|
Schema.Array(Schema.Struct({ code: Schema.optional(Schema.String), message: Schema.optional(Schema.String) })),
|
||||||
|
|
@ -202,6 +214,8 @@ const Event = Schema.Union([
|
||||||
event_type: Schema.Literal("interaction.status_update"),
|
event_type: Schema.Literal("interaction.status_update"),
|
||||||
interaction_id: Schema.optional(Schema.String),
|
interaction_id: Schema.optional(Schema.String),
|
||||||
status: Schema.String,
|
status: Schema.String,
|
||||||
|
continuation_token: optionalNull(Schema.String),
|
||||||
|
usage: Schema.optional(RawUsage),
|
||||||
}),
|
}),
|
||||||
Schema.Struct({ event_type: Schema.Literal("interaction.completed"), interaction: Interaction }),
|
Schema.Struct({ event_type: Schema.Literal("interaction.completed"), interaction: Interaction }),
|
||||||
Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.optionalKey(Schema.Unknown) }),
|
Schema.Struct({ event_type: Schema.Literal("error"), error: Schema.optionalKey(Schema.Unknown) }),
|
||||||
|
|
@ -216,6 +230,10 @@ interface ParserState {
|
||||||
readonly route: string
|
readonly route: string
|
||||||
readonly metadataKey: string
|
readonly metadataKey: string
|
||||||
readonly lifecycle: Lifecycle.State
|
readonly lifecycle: Lifecycle.State
|
||||||
|
readonly hop: number
|
||||||
|
readonly hasToolCalls: boolean
|
||||||
|
readonly usage?: RawUsage
|
||||||
|
readonly continuedUsage: ReadonlyArray<RawUsage | undefined>
|
||||||
readonly steps: Partial<Record<number, OutputStep>>
|
readonly steps: Partial<Record<number, OutputStep>>
|
||||||
readonly tools: ToolStream.State<number>
|
readonly tools: ToolStream.State<number>
|
||||||
}
|
}
|
||||||
|
|
@ -224,13 +242,28 @@ type StepResult = readonly [ParserState, ReadonlyArray<LLMEvent>]
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
// Request Body Construction
|
// Request Body Construction
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
// https://aistudio.google.com/docs/document-processing#office-documents
|
||||||
|
const OFFICE_DOCUMENT_MIME_TYPES = new Set([
|
||||||
|
"application/msword",
|
||||||
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.template",
|
||||||
|
"application/vnd.oasis.opendocument.text",
|
||||||
|
"application/vnd.ms-powerpoint",
|
||||||
|
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||||
|
"application/vnd.oasis.opendocument.presentation",
|
||||||
|
"application/vnd.ms-excel",
|
||||||
|
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
"application/vnd.oasis.opendocument.spreadsheet",
|
||||||
|
])
|
||||||
|
|
||||||
export const mediaContent = Effect.fnUntraced(function* (asset: Media.Asset) {
|
export const mediaContent = Effect.fnUntraced(function* (asset: Media.Asset) {
|
||||||
if (
|
if (
|
||||||
asset.kind !== "image" &&
|
asset.kind !== "image" &&
|
||||||
asset.kind !== "audio" &&
|
asset.kind !== "audio" &&
|
||||||
asset.kind !== "video" &&
|
asset.kind !== "video" &&
|
||||||
asset.mediaType !== "application/pdf" &&
|
asset.mediaType !== "application/pdf" &&
|
||||||
asset.mediaType !== "text/csv"
|
asset.mediaType !== "text/csv" &&
|
||||||
|
!OFFICE_DOCUMENT_MIME_TYPES.has(asset.mediaType)
|
||||||
)
|
)
|
||||||
return yield* ProviderShared.invalidRequest(
|
return yield* ProviderShared.invalidRequest(
|
||||||
`Google Interactions does not support ${asset.mediaType} document input`,
|
`Google Interactions does not support ${asset.mediaType} document input`,
|
||||||
|
|
@ -335,8 +368,8 @@ const lowerToolResult = Effect.fnUntraced(function* (part: ToolResultPart) {
|
||||||
|
|
||||||
const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (request: LLMRequest) {
|
const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (request: LLMRequest) {
|
||||||
const options = yield* decodeOptions(request.providerOptions ?? {})
|
const options = yield* decodeOptions(request.providerOptions ?? {})
|
||||||
const flattened = ProviderShared.flattenToolRequest(request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
if (flattened.tools.some((tool) => tool.native !== undefined))
|
if (definitions.some((tool) => tool.native !== undefined))
|
||||||
return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported")
|
return yield* ProviderShared.invalidRequest("Google Interactions hosted tools are not supported")
|
||||||
if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined)
|
if (request.topK !== undefined || request.frequencyPenalty !== undefined || request.presencePenalty !== undefined)
|
||||||
return yield* ProviderShared.invalidRequest(
|
return yield* ProviderShared.invalidRequest(
|
||||||
|
|
@ -353,15 +386,19 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
model: request.model.id,
|
model: request.model.id,
|
||||||
input: yield* lowerMessages(flattened.request),
|
input: yield* lowerMessages(request),
|
||||||
stream: true as const,
|
stream: true as const,
|
||||||
// Full-history replay need not create retained provider resources. Continuation callers opt in to storage.
|
// Full-history replay need not create retained provider resources. Continuation callers opt in to storage.
|
||||||
store: options.store ?? false,
|
store: options.store ?? false,
|
||||||
previous_interaction_id: options.previousInteractionId,
|
previous_interaction_id: options.previousInteractionId,
|
||||||
system_instruction: request.system.length ? ProviderShared.joinText(request.system) : undefined,
|
system_instruction: request.system.length ? ProviderShared.joinText(request.system) : undefined,
|
||||||
service_tier: options.serviceTier,
|
service_tier: options.serviceTier,
|
||||||
tools: flattened.tools.length
|
safety_settings: options.safetySettings?.map((setting) => ({
|
||||||
? flattened.tools.map((tool) => ({
|
type: setting.category.replace(/^HARM_CATEGORY_/, "").toLowerCase(),
|
||||||
|
threshold: setting.threshold.toLowerCase(),
|
||||||
|
})),
|
||||||
|
tools: definitions.length
|
||||||
|
? definitions.map((tool) => ({
|
||||||
type: "function" as const,
|
type: "function" as const,
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
description: tool.description,
|
description: tool.description,
|
||||||
|
|
@ -387,32 +424,54 @@ const fromRequest = Effect.fn("GoogleInteractions.fromRequest")(function* (reque
|
||||||
const metadata = (state: ParserState, step: OutputStep): ProviderMetadata => ({
|
const metadata = (state: ParserState, step: OutputStep): ProviderMetadata => ({
|
||||||
[state.metadataKey]: { interactionSignature: step.signature },
|
[state.metadataKey]: { interactionSignature: step.signature },
|
||||||
})
|
})
|
||||||
const mapUsage = (usage: RawUsage | undefined, key: string) => {
|
const mapUsage = (usage: RawUsage | undefined, key: string, continued: ParserState["continuedUsage"]) => {
|
||||||
if (!usage) return undefined
|
if (!usage && continued.every((hop) => !hop)) return undefined
|
||||||
const input = usage.total_input_tokens ?? undefined
|
const first = continued.length ? continued[0] : usage
|
||||||
const cached = usage.total_cached_tokens ?? undefined
|
const hops = [...continued, usage]
|
||||||
const reasoning = usage.total_thought_tokens ?? undefined
|
const sum = (field: (hop: RawUsage) => number | null | undefined) =>
|
||||||
const output =
|
ProviderShared.sumTokens(...hops.map((hop) => (hop ? (field(hop) ?? undefined) : undefined)))
|
||||||
usage.total_output_tokens === undefined || usage.total_output_tokens === null
|
const input = first?.total_input_tokens ?? undefined
|
||||||
|
const cached = first?.total_cached_tokens ?? undefined
|
||||||
|
const reasoning = sum((hop) => hop.total_thought_tokens)
|
||||||
|
const text = sum((hop) => hop.total_output_tokens)
|
||||||
|
const output = continued.length
|
||||||
|
? ProviderShared.sumTokens(text, reasoning)
|
||||||
|
: text === undefined
|
||||||
? undefined
|
? undefined
|
||||||
: usage.total_output_tokens + (reasoning ?? 0)
|
: text + (reasoning ?? 0)
|
||||||
return new Usage({
|
return new Usage({
|
||||||
contextTokens: usage.raw_prompt_token ?? input,
|
contextTokens: first?.raw_prompt_token ?? input,
|
||||||
inputTokens: input,
|
inputTokens: input,
|
||||||
outputTokens: output,
|
outputTokens: output,
|
||||||
nonCachedInputTokens: ProviderShared.subtractTokens(input, cached),
|
nonCachedInputTokens: ProviderShared.subtractTokens(input, cached),
|
||||||
cacheReadInputTokens: cached,
|
cacheReadInputTokens: cached,
|
||||||
reasoningTokens: reasoning,
|
reasoningTokens: reasoning,
|
||||||
totalTokens: usage.total_tokens ?? undefined,
|
totalTokens: continued.length
|
||||||
providerMetadata: { [key]: usage },
|
? ProviderShared.totalTokens(input, output, undefined)
|
||||||
|
: (usage?.total_tokens ?? undefined),
|
||||||
|
// Keep re-billed input in provider metadata, separate from the logical call's input.
|
||||||
|
providerMetadata: {
|
||||||
|
[key]: continued.length
|
||||||
|
? {
|
||||||
|
total_input_tokens: sum((hop) => hop.total_input_tokens),
|
||||||
|
total_cached_tokens: sum((hop) => hop.total_cached_tokens),
|
||||||
|
total_output_tokens: text,
|
||||||
|
total_thought_tokens: reasoning,
|
||||||
|
total_tokens: sum((hop) => hop.total_tokens),
|
||||||
|
requests: hops.length,
|
||||||
|
}
|
||||||
|
: (usage ?? {}),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const blockID = (state: ParserState, index: number) => (state.hop === 0 ? String(index) : `${state.hop}:${index}`)
|
||||||
|
|
||||||
const onStart = Effect.fnUntraced(function* (state: ParserState, index: number, step: OutputStep) {
|
const onStart = Effect.fnUntraced(function* (state: ParserState, index: number, step: OutputStep) {
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
let lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
let lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||||
let tools = state.tools
|
let tools = state.tools
|
||||||
const id = String(index)
|
const id = blockID(state, index)
|
||||||
if (step.type === "thought") {
|
if (step.type === "thought") {
|
||||||
lifecycle = Lifecycle.reasoningStart(lifecycle, events, id, metadata(state, step))
|
lifecycle = Lifecycle.reasoningStart(lifecycle, events, id, metadata(state, step))
|
||||||
for (const part of step.summary ?? []) lifecycle = Lifecycle.reasoningDelta(lifecycle, events, id, part.text)
|
for (const part of step.summary ?? []) lifecycle = Lifecycle.reasoningDelta(lifecycle, events, id, part.text)
|
||||||
|
|
@ -439,7 +498,16 @@ const onStart = Effect.fnUntraced(function* (state: ParserState, index: number,
|
||||||
events.push(LLMEvent.toolInputStart({ id: step.id, name: step.name, providerMetadata: metadata(state, step) }))
|
events.push(LLMEvent.toolInputStart({ id: step.id, name: step.name, providerMetadata: metadata(state, step) }))
|
||||||
} else
|
} else
|
||||||
return yield* ProviderShared.eventError(ADAPTER, `Unsupported Interactions step: ${step.type}`, encodeJson(step))
|
return yield* ProviderShared.eventError(ADAPTER, `Unsupported Interactions step: ${step.type}`, encodeJson(step))
|
||||||
return [{ ...state, lifecycle, tools, steps: { ...state.steps, [index]: step } }, events] satisfies StepResult
|
return [
|
||||||
|
{
|
||||||
|
...state,
|
||||||
|
lifecycle,
|
||||||
|
tools,
|
||||||
|
hasToolCalls: state.hasToolCalls || step.type === "function_call",
|
||||||
|
steps: { ...state.steps, [index]: step },
|
||||||
|
},
|
||||||
|
events,
|
||||||
|
] satisfies StepResult
|
||||||
})
|
})
|
||||||
|
|
||||||
const onDelta = Effect.fnUntraced(function* (state: ParserState, index: number, delta: typeof Delta.Type) {
|
const onDelta = Effect.fnUntraced(function* (state: ParserState, index: number, delta: typeof Delta.Type) {
|
||||||
|
|
@ -449,12 +517,15 @@ const onDelta = Effect.fnUntraced(function* (state: ParserState, index: number,
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
if (delta.type === "text" && step.type === "model_output")
|
if (delta.type === "text" && step.type === "model_output")
|
||||||
return [
|
return [
|
||||||
{ ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, String(index), delta.text) },
|
{ ...state, lifecycle: Lifecycle.textDelta(state.lifecycle, events, blockID(state, index), delta.text) },
|
||||||
events,
|
events,
|
||||||
] satisfies StepResult
|
] satisfies StepResult
|
||||||
if (delta.type === "thought_summary" && step.type === "thought")
|
if (delta.type === "thought_summary" && step.type === "thought")
|
||||||
return [
|
return [
|
||||||
{ ...state, lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, String(index), delta.content.text) },
|
{
|
||||||
|
...state,
|
||||||
|
lifecycle: Lifecycle.reasoningDelta(state.lifecycle, events, blockID(state, index), delta.content.text),
|
||||||
|
},
|
||||||
events,
|
events,
|
||||||
] satisfies StepResult
|
] satisfies StepResult
|
||||||
if (delta.type === "thought_signature") {
|
if (delta.type === "thought_signature") {
|
||||||
|
|
@ -493,12 +564,15 @@ const onStop = Effect.fnUntraced(function* (state: ParserState, index: number) {
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
if (step.type === "thought")
|
if (step.type === "thought")
|
||||||
return [
|
return [
|
||||||
{ ...state, lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, String(index), metadata(state, step)) },
|
{
|
||||||
|
...state,
|
||||||
|
lifecycle: Lifecycle.reasoningEnd(state.lifecycle, events, blockID(state, index), metadata(state, step)),
|
||||||
|
},
|
||||||
events,
|
events,
|
||||||
] satisfies StepResult
|
] satisfies StepResult
|
||||||
if (step.type === "model_output")
|
if (step.type === "model_output")
|
||||||
return [
|
return [
|
||||||
{ ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, String(index)) },
|
{ ...state, lifecycle: Lifecycle.textEnd(state.lifecycle, events, blockID(state, index)) },
|
||||||
events,
|
events,
|
||||||
] satisfies StepResult
|
] satisfies StepResult
|
||||||
const result = yield* ToolStream.finish(ADAPTER, state.tools, index)
|
const result = yield* ToolStream.finish(ADAPTER, state.tools, index)
|
||||||
|
|
@ -524,7 +598,32 @@ const failureReason = (route: string, code: string | undefined, message: string,
|
||||||
return classifyProviderFailure({ message, data, rawBody })
|
return classifyProviderFailure({ message, data, rawBody })
|
||||||
}
|
}
|
||||||
|
|
||||||
const step = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
// Marks a request boundary without adding another logical LLM step or finish.
|
||||||
|
class NextRequest {}
|
||||||
|
|
||||||
|
const step = Effect.fnUntraced(function* (state: ParserState, event: Event | NextRequest) {
|
||||||
|
if (event instanceof NextRequest) {
|
||||||
|
const pending = yield* ToolStream.finishAll(ADAPTER, state.tools)
|
||||||
|
const events = [...pending.events]
|
||||||
|
let lifecycle = state.lifecycle
|
||||||
|
for (const [index, step] of Object.entries(state.steps)) {
|
||||||
|
const id = blockID(state, Number(index))
|
||||||
|
if (step?.type === "thought") lifecycle = Lifecycle.reasoningEnd(lifecycle, events, id, metadata(state, step))
|
||||||
|
if (step?.type === "model_output") lifecycle = Lifecycle.textEnd(lifecycle, events, id)
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
...state,
|
||||||
|
hop: state.hop + 1,
|
||||||
|
lifecycle,
|
||||||
|
steps: {},
|
||||||
|
tools: ToolStream.empty<number>(),
|
||||||
|
usage: undefined,
|
||||||
|
continuedUsage: [...state.continuedUsage, state.usage],
|
||||||
|
},
|
||||||
|
events,
|
||||||
|
] satisfies StepResult
|
||||||
|
}
|
||||||
switch (event.event_type) {
|
switch (event.event_type) {
|
||||||
case "step.start":
|
case "step.start":
|
||||||
return yield* onStart(state, event.index, event.step)
|
return yield* onStart(state, event.index, event.step)
|
||||||
|
|
@ -532,8 +631,9 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
||||||
return yield* onDelta(state, event.index, event.delta)
|
return yield* onDelta(state, event.index, event.delta)
|
||||||
case "step.stop":
|
case "step.stop":
|
||||||
return yield* onStop(state, event.index)
|
return yield* onStop(state, event.index)
|
||||||
case "interaction.created":
|
|
||||||
case "interaction.status_update":
|
case "interaction.status_update":
|
||||||
|
return [{ ...state, usage: event.usage ?? state.usage }, []] satisfies StepResult
|
||||||
|
case "interaction.created":
|
||||||
case "unknown":
|
case "unknown":
|
||||||
return [state, []] satisfies StepResult
|
return [state, []] satisfies StepResult
|
||||||
case "error": {
|
case "error": {
|
||||||
|
|
@ -551,6 +651,8 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
||||||
}
|
}
|
||||||
case "interaction.completed": {
|
case "interaction.completed": {
|
||||||
const interaction = event.interaction
|
const interaction = event.interaction
|
||||||
|
if (interaction.status === CONTINUATION)
|
||||||
|
return [{ ...state, usage: interaction.usage ?? state.usage }, []] satisfies StepResult
|
||||||
if (interaction.status === "failed" || interaction.status === "cancelled") {
|
if (interaction.status === "failed" || interaction.status === "cancelled") {
|
||||||
const messages = (interaction.errors ?? []).flatMap((error) => (error.message?.trim() ? [error.message] : []))
|
const messages = (interaction.errors ?? []).flatMap((error) => (error.message?.trim() ? [error.message] : []))
|
||||||
const coded = interaction.errors?.find((error) => error.code)
|
const coded = interaction.errors?.find((error) => error.code)
|
||||||
|
|
@ -573,18 +675,17 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
||||||
)
|
)
|
||||||
const pending = yield* ToolStream.finishAll(ADAPTER, state.tools)
|
const pending = yield* ToolStream.finishAll(ADAPTER, state.tools)
|
||||||
const events = [...pending.events]
|
const events = [...pending.events]
|
||||||
const hasToolCalls = Object.values(state.steps).some((item) => item?.type === "function_call")
|
|
||||||
const lifecycle = Lifecycle.finish(state.lifecycle, events, {
|
const lifecycle = Lifecycle.finish(state.lifecycle, events, {
|
||||||
reason: {
|
reason: {
|
||||||
normalized:
|
normalized:
|
||||||
interaction.status === "requires_action" || (interaction.status === "completed" && hasToolCalls)
|
interaction.status === "requires_action" || (interaction.status === "completed" && state.hasToolCalls)
|
||||||
? "tool-calls"
|
? "tool-calls"
|
||||||
: interaction.status === "incomplete"
|
: interaction.status === "incomplete"
|
||||||
? "length"
|
? "length"
|
||||||
: "stop",
|
: "stop",
|
||||||
raw: interaction.status,
|
raw: interaction.status,
|
||||||
},
|
},
|
||||||
usage: mapUsage(interaction.usage, state.metadataKey),
|
usage: mapUsage(interaction.usage ?? state.usage, state.metadataKey, state.continuedUsage),
|
||||||
providerMetadata: { [state.metadataKey]: { interactionId: interaction.id } },
|
providerMetadata: { [state.metadataKey]: { interactionId: interaction.id } },
|
||||||
})
|
})
|
||||||
return [{ ...state, lifecycle, tools: pending.tools }, events] satisfies StepResult
|
return [{ ...state, lifecycle, tools: pending.tools }, events] satisfies StepResult
|
||||||
|
|
@ -592,6 +693,177 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// Transport
|
||||||
|
// =============================================================================
|
||||||
|
type Body = typeof Body.Type
|
||||||
|
export interface Prepared {
|
||||||
|
readonly http: HttpTransport.HttpPrepared<string>
|
||||||
|
readonly input: TransportPrepareInput<Body>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Resume {
|
||||||
|
readonly token: string
|
||||||
|
readonly owner?: string
|
||||||
|
readonly reconnectsWithoutProgress: number
|
||||||
|
readonly lastError?: AIError
|
||||||
|
}
|
||||||
|
|
||||||
|
const sse = HttpTransport.sseJson.with<Body>()
|
||||||
|
const WireEvent = Protocol.jsonEvent(Event)
|
||||||
|
const decodeEvent = Schema.decodeUnknownEffect(WireEvent)
|
||||||
|
|
||||||
|
export const transport: Transport<Body, Prepared, Event | NextRequest> = {
|
||||||
|
id: sse.id,
|
||||||
|
prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))),
|
||||||
|
execute: (prepared, request, runtime) =>
|
||||||
|
Effect.gen(function* () {
|
||||||
|
const label = `${request.model.provider}/${request.model.route.id}`
|
||||||
|
const raw = new WeakMap<object, string>()
|
||||||
|
const respond = (
|
||||||
|
execution: TransportExecution<string>,
|
||||||
|
resume?: Resume,
|
||||||
|
): Stream.Stream<Event | NextRequest, AIError> =>
|
||||||
|
Stream.suspend(() => {
|
||||||
|
let token = resume?.token
|
||||||
|
let owner: string | undefined
|
||||||
|
let status: string | undefined
|
||||||
|
let contentSinceToken = false
|
||||||
|
let terminal = false
|
||||||
|
let dropped: AIError | undefined
|
||||||
|
const pendingTools = new Set<number>()
|
||||||
|
return execution.frames.pipe(
|
||||||
|
Stream.mapEffect((frame) =>
|
||||||
|
decodeEvent(frame).pipe(
|
||||||
|
Effect.mapError((cause) =>
|
||||||
|
ProviderShared.eventError(ADAPTER, `Invalid ${label} stream event`, frame, cause),
|
||||||
|
),
|
||||||
|
Effect.map((event) => {
|
||||||
|
raw.set(event, frame)
|
||||||
|
switch (event.event_type) {
|
||||||
|
case "interaction.created":
|
||||||
|
owner = event.interaction.id
|
||||||
|
break
|
||||||
|
case "interaction.status_update":
|
||||||
|
status = event.status
|
||||||
|
owner = event.interaction_id ?? owner
|
||||||
|
if (event.continuation_token && event.continuation_token !== token) {
|
||||||
|
token = event.continuation_token
|
||||||
|
contentSinceToken = false
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case "interaction.completed":
|
||||||
|
terminal = true
|
||||||
|
status = event.interaction.status
|
||||||
|
owner = event.interaction.id ?? owner
|
||||||
|
if (event.interaction.continuation_token) {
|
||||||
|
token = event.interaction.continuation_token
|
||||||
|
contentSinceToken = false
|
||||||
|
}
|
||||||
|
break
|
||||||
|
case "step.start":
|
||||||
|
if (event.step.type === "function_call") pendingTools.add(event.index)
|
||||||
|
if (
|
||||||
|
pendingTools.has(event.index) ||
|
||||||
|
event.step.content?.length ||
|
||||||
|
event.step.summary?.length ||
|
||||||
|
event.step.signature
|
||||||
|
)
|
||||||
|
contentSinceToken = true
|
||||||
|
break
|
||||||
|
case "step.delta":
|
||||||
|
contentSinceToken = true
|
||||||
|
break
|
||||||
|
case "step.stop":
|
||||||
|
if (pendingTools.delete(event.index)) contentSinceToken = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return event
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Stream.takeUntil((event) => event.event_type === "interaction.completed"),
|
||||||
|
Stream.catchIf(
|
||||||
|
(error) => error.reason._tag === "Transport" && error.reason.code !== "Timeout",
|
||||||
|
(error) => {
|
||||||
|
dropped = error
|
||||||
|
return Stream.empty
|
||||||
|
},
|
||||||
|
),
|
||||||
|
Stream.concat(
|
||||||
|
Stream.suspend(() => {
|
||||||
|
const needsContinuation = status === CONTINUATION
|
||||||
|
const resumable = needsContinuation || (!terminal && (status === undefined || status === "in_progress"))
|
||||||
|
const newToken = token !== resume?.token
|
||||||
|
// An interrupted tool call may carry arguments across the checkpoint. Don't finalize it on EOF.
|
||||||
|
if (
|
||||||
|
token &&
|
||||||
|
resumable &&
|
||||||
|
!contentSinceToken &&
|
||||||
|
(terminal || pendingTools.size === 0) &&
|
||||||
|
(!needsContinuation || newToken)
|
||||||
|
) {
|
||||||
|
const reconnectsWithoutProgress = newToken ? 0 : (resume?.reconnectsWithoutProgress ?? 0) + 1
|
||||||
|
const lastError = dropped ?? (newToken ? undefined : resume?.lastError)
|
||||||
|
if (reconnectsWithoutProgress > MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS) {
|
||||||
|
if (!lastError) return Stream.empty
|
||||||
|
return Stream.fail(
|
||||||
|
new AIError({
|
||||||
|
reason: new InvalidProviderOutputError({
|
||||||
|
route: label,
|
||||||
|
message: lastError.reason.message,
|
||||||
|
classification: "incomplete-stream",
|
||||||
|
cause: lastError,
|
||||||
|
http: lastError.reason.http,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return Stream.concat(
|
||||||
|
Stream.succeed(new NextRequest()),
|
||||||
|
next({ token, owner: newToken ? owner : resume?.owner, reconnectsWithoutProgress, lastError }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (dropped) return Stream.fail(dropped)
|
||||||
|
if (terminal && needsContinuation && !token)
|
||||||
|
return Stream.fail(ProviderShared.eventError(label, "Google Interactions continued without a token"))
|
||||||
|
// No safe checkpoint. Leave EOF for the route's incomplete-stream check.
|
||||||
|
return Stream.empty
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
const next = (resume: Resume) => {
|
||||||
|
const body = prepared.input.body
|
||||||
|
return Stream.unwrap(
|
||||||
|
sse
|
||||||
|
.prepare({
|
||||||
|
...prepared.input,
|
||||||
|
body: {
|
||||||
|
...body,
|
||||||
|
continuation_token: resume.token,
|
||||||
|
...(body.store && resume.owner ? { input: undefined, previous_interaction_id: resume.owner } : {}),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.pipe(
|
||||||
|
Effect.flatMap((continued) => sse.execute(continued, request, runtime)),
|
||||||
|
Effect.map((execution) => respond(execution, resume)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const first = yield* sse.execute(prepared.http, request, runtime)
|
||||||
|
return {
|
||||||
|
frames: respond(first),
|
||||||
|
http: first.http,
|
||||||
|
body: (frame) => raw.get(frame),
|
||||||
|
raw: (frame) => {
|
||||||
|
const body = raw.get(frame)
|
||||||
|
return body === undefined ? undefined : ProviderShared.decodeJson(body)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
// Protocol And Route
|
// Protocol And Route
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
@ -600,16 +872,22 @@ export const protocol = Protocol.make({
|
||||||
sanitizer: "gemini",
|
sanitizer: "gemini",
|
||||||
body: { schema: Body, from: fromRequest },
|
body: { schema: Body, from: fromRequest },
|
||||||
stream: {
|
stream: {
|
||||||
event: Protocol.jsonEvent(Event),
|
event: Schema.Union([Schema.instanceOf(NextRequest), Schema.toType(Event), WireEvent]),
|
||||||
initial: (request): ParserState => ({
|
initial: (request): ParserState => ({
|
||||||
route: `${request.model.provider}/${request.model.route.id}`,
|
route: `${request.model.provider}/${request.model.route.id}`,
|
||||||
metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
|
||||||
lifecycle: Lifecycle.initial(),
|
lifecycle: Lifecycle.initial(),
|
||||||
|
hop: 0,
|
||||||
|
hasToolCalls: false,
|
||||||
|
continuedUsage: [],
|
||||||
steps: {},
|
steps: {},
|
||||||
tools: ToolStream.empty<number>(),
|
tools: ToolStream.empty<number>(),
|
||||||
}),
|
}),
|
||||||
step,
|
step,
|
||||||
terminal: (event) => event.event_type === "interaction.completed",
|
terminal: (event) =>
|
||||||
|
!(event instanceof NextRequest) &&
|
||||||
|
event.event_type === "interaction.completed" &&
|
||||||
|
event.interaction.status !== CONTINUATION,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -620,7 +898,7 @@ export const route = Route.make({
|
||||||
protocol,
|
protocol,
|
||||||
endpoint: Endpoint.path("/interactions", { baseURL: DEFAULT_BASE_URL }),
|
endpoint: Endpoint.path("/interactions", { baseURL: DEFAULT_BASE_URL }),
|
||||||
auth: Auth.none,
|
auth: Auth.none,
|
||||||
framing: Framing.sse,
|
transport,
|
||||||
})
|
})
|
||||||
|
|
||||||
export * as GoogleInteractions from "./google-interactions.js"
|
export * as GoogleInteractions from "./google-interactions.js"
|
||||||
|
|
|
||||||
|
|
@ -26,8 +26,8 @@ const Body = Schema.Struct({
|
||||||
})
|
})
|
||||||
|
|
||||||
const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request: LLMRequest) {
|
const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request: LLMRequest) {
|
||||||
const projected = ProviderShared.flattenToolRequest(request)
|
const body = yield* AnthropicMessages.protocol.body.from(request)
|
||||||
const body = yield* AnthropicMessages.protocol.body.from(projected.request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
return {
|
return {
|
||||||
...body,
|
...body,
|
||||||
messages: body.messages.map((message) => {
|
messages: body.messages.map((message) => {
|
||||||
|
|
@ -45,7 +45,7 @@ const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request: LL
|
||||||
? undefined
|
? undefined
|
||||||
: yield* Effect.forEach(body.tools, (tool, index) =>
|
: yield* Effect.forEach(body.tools, (tool, index) =>
|
||||||
Effect.gen(function* () {
|
Effect.gen(function* () {
|
||||||
const native = projected.tools[index]?.native
|
const native = definitions[index]?.native
|
||||||
if (native === undefined) return tool
|
if (native === undefined) return tool
|
||||||
const search = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MetaResponses.WebSearch))(
|
const search = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MetaResponses.WebSearch))(
|
||||||
native.meta,
|
native.meta,
|
||||||
|
|
@ -62,6 +62,8 @@ export const protocol = Protocol.make({
|
||||||
id: "meta-messages",
|
id: "meta-messages",
|
||||||
body: { schema: Body, from: fromRequest },
|
body: { schema: Body, from: fromRequest },
|
||||||
stream: AnthropicMessages.protocol.stream,
|
stream: AnthropicMessages.protocol.stream,
|
||||||
|
supportsEffortUpdates: AnthropicMessages.protocol.supportsEffortUpdates,
|
||||||
|
toolUpdates: AnthropicMessages.protocol.toolUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export * as MetaMessages from "./meta-messages.js"
|
export * as MetaMessages from "./meta-messages.js"
|
||||||
|
|
|
||||||
|
|
@ -242,6 +242,7 @@ export const protocol = Protocol.make({
|
||||||
step,
|
step,
|
||||||
terminal: OpenResponses.terminal,
|
terminal: OpenResponses.terminal,
|
||||||
},
|
},
|
||||||
|
supportsEffortUpdates: OpenResponses.protocol.supportsEffortUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const httpTransport = OpenResponses.httpTransport
|
export const httpTransport = OpenResponses.httpTransport
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { Duration, Effect, Schema } from "effect"
|
import { Duration, Effect, Schema } from "effect"
|
||||||
import type { HttpClientResponse } from "effect/http"
|
import type { HttpClientResponse } from "effect/http"
|
||||||
import type { Status } from "../generation.js"
|
|
||||||
import { Media } from "../media.js"
|
import { Media } from "../media.js"
|
||||||
import { MediaProtocol } from "../route/media-protocol.js"
|
import { MediaProtocol } from "../route/media-protocol.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
|
|
@ -47,7 +46,8 @@ export type Request = VideoRequest<VideoModel<MiniMaxVideoOptions>>
|
||||||
// 2. Token and response schemas
|
// 2. Token and response schemas
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const Token = Schema.Struct({ taskID: Schema.String })
|
/** The provider's job ID; it is all a later status, result or cancel call needs. */
|
||||||
|
export const Token = Schema.String
|
||||||
export type Token = Schema.Schema.Type<typeof Token>
|
export type Token = Schema.Schema.Type<typeof Token>
|
||||||
|
|
||||||
const BaseResp = optionalNull(
|
const BaseResp = optionalNull(
|
||||||
|
|
@ -99,20 +99,20 @@ const HailuoFile = Schema.Struct({
|
||||||
})
|
})
|
||||||
|
|
||||||
const STATUS = {
|
const STATUS = {
|
||||||
queued: "queued",
|
queued: "running",
|
||||||
running: "running",
|
running: "running",
|
||||||
succeeded: "completed",
|
succeeded: "completed",
|
||||||
failed: "failed",
|
failed: "failed",
|
||||||
cancelled: "cancelled",
|
cancelled: "cancelled",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
const HAILUO_STATUS = {
|
const HAILUO_STATUS = {
|
||||||
Preparing: "queued",
|
Preparing: "running",
|
||||||
Queueing: "queued",
|
Queueing: "running",
|
||||||
Processing: "running",
|
Processing: "running",
|
||||||
Success: "completed",
|
Success: "completed",
|
||||||
Fail: "failed",
|
Fail: "failed",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 3. Failures
|
// 3. Failures
|
||||||
|
|
@ -176,15 +176,20 @@ const reference = (asset: Media.Asset) =>
|
||||||
const resolution = (request: Request) => request.resolution?.toUpperCase()
|
const resolution = (request: Request) => request.resolution?.toUpperCase()
|
||||||
|
|
||||||
const fromRequest = Effect.fn("MiniMaxVideo.fromRequest")(function* (request: Request) {
|
const fromRequest = Effect.fn("MiniMaxVideo.fromRequest")(function* (request: Request) {
|
||||||
// H3 always generates a soundtrack and has no field to turn it off.
|
// H3 always generates a soundtrack and has no field for `sound`, so it isn't sent.
|
||||||
if (request.sound === false)
|
|
||||||
return yield* route.unsupported("video.sound", `${route.name} always generates sound and can't be silenced`)
|
|
||||||
const content = [
|
const content = [
|
||||||
{ type: "text", text: request.prompt },
|
{ type: "text", text: request.prompt },
|
||||||
...(request.start === undefined ? [] : [yield* item(request.start, "first_frame")]),
|
...(request.start === undefined ? [] : [yield* item(request.start, "first_frame")]),
|
||||||
...(request.end === undefined ? [] : [yield* item(request.end, "last_frame")]),
|
...(request.end === undefined ? [] : [yield* item(request.end, "last_frame")]),
|
||||||
...(yield* Effect.forEach(request.references ?? [], reference)),
|
...(yield* Effect.forEach(request.references ?? [], reference)),
|
||||||
]
|
]
|
||||||
|
// H3 rejects a t2va (text-only) request without a concrete `ratio`, so `auto` and unset default to `16:9`.
|
||||||
|
const ratio =
|
||||||
|
content.length === 1 && (request.aspect === undefined || request.aspect === "auto")
|
||||||
|
? "16:9"
|
||||||
|
: request.aspect === "auto"
|
||||||
|
? "adaptive"
|
||||||
|
: request.aspect
|
||||||
return MediaProtocol.json(
|
return MediaProtocol.json(
|
||||||
mergeJsonRecords(
|
mergeJsonRecords(
|
||||||
{
|
{
|
||||||
|
|
@ -192,7 +197,7 @@ const fromRequest = Effect.fn("MiniMaxVideo.fromRequest")(function* (request: Re
|
||||||
content,
|
content,
|
||||||
resolution: resolution(request),
|
resolution: resolution(request),
|
||||||
duration: request.duration === undefined ? undefined : seconds(request.duration),
|
duration: request.duration === undefined ? undefined : seconds(request.duration),
|
||||||
ratio: request.aspect === "auto" ? "adaptive" : request.aspect,
|
ratio,
|
||||||
},
|
},
|
||||||
request.providerOptions,
|
request.providerOptions,
|
||||||
request.http?.body,
|
request.http?.body,
|
||||||
|
|
@ -212,8 +217,7 @@ const hailuoFromRequest = Effect.fn("MiniMaxHailuoVideo.fromRequest")(function*
|
||||||
`${hailuoRoute.name} takes only image (subject) references`,
|
`${hailuoRoute.name} takes only image (subject) references`,
|
||||||
)
|
)
|
||||||
// Hailuo output is always silent and its shape follows the model or the first frame, with no field for either.
|
// Hailuo output is always silent and its shape follows the model or the first frame, with no field for either.
|
||||||
if (request.sound === true)
|
// `sound` has nothing to send, so it isn't; an aspect ratio would change the shape the caller asked for.
|
||||||
return yield* hailuoRoute.unsupported("video.sound", `${hailuoRoute.name} generates silent video only`)
|
|
||||||
if (request.aspect !== undefined && request.aspect !== "auto")
|
if (request.aspect !== undefined && request.aspect !== "auto")
|
||||||
return yield* hailuoRoute.unsupported("video.aspect", `${hailuoRoute.name} has no aspect ratio input`)
|
return yield* hailuoRoute.unsupported("video.aspect", `${hailuoRoute.name} has no aspect ratio input`)
|
||||||
const subjects = yield* Effect.forEach(references, (asset) =>
|
const subjects = yield* Effect.forEach(references, (asset) =>
|
||||||
|
|
@ -241,8 +245,8 @@ const hailuoFromRequest = Effect.fn("MiniMaxHailuoVideo.fromRequest")(function*
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
||||||
token: { taskID: value.task_id },
|
token: value.task_id,
|
||||||
snapshot: { id: value.task_id, status: "queued" },
|
snapshot: { id: value.task_id, status: "running" },
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const decodeTask = route.decodeJson(TaskResponse)
|
const decodeTask = route.decodeJson(TaskResponse)
|
||||||
|
|
@ -253,7 +257,7 @@ const decodeStatus = Effect.fn("MiniMaxVideo.decodeStatus")(function* (
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTask(response)
|
const output = yield* decodeTask(response)
|
||||||
const task = output.value.task ?? output.value
|
const task = output.value.task ?? output.value
|
||||||
return { id: context.token.taskID, status: MediaProtocol.status(STATUS, task.status ?? "") }
|
return { id: context.token, ...MediaProtocol.status(STATUS, task.status ?? "") }
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* (
|
const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* (
|
||||||
|
|
@ -262,12 +266,12 @@ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* (
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTask(response)
|
const output = yield* decodeTask(response)
|
||||||
const task = output.value.task ?? output.value
|
const task = output.value.task ?? output.value
|
||||||
const status = MediaProtocol.status(STATUS, task.status ?? "")
|
const status = MediaProtocol.state(STATUS, task.status ?? "")
|
||||||
if (status === "queued" || status === "running") return yield* output.pending(context.token.taskID)
|
if (status === "running") return yield* output.pending(context.token)
|
||||||
if (status === "failed")
|
if (status === "failed")
|
||||||
return yield* failed(output, route.name, task.error?.code ?? undefined, task.error?.message ?? undefined)
|
return yield* failed(output, route.name, task.error?.code ?? undefined, task.error?.message ?? undefined)
|
||||||
if (status !== "completed")
|
if (status !== "completed")
|
||||||
return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`)
|
return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`)
|
||||||
const url = task.content?.url ?? undefined
|
const url = task.content?.url ?? undefined
|
||||||
if (url === undefined) return yield* output.invalid(`${route.name} completed without a video URL`)
|
if (url === undefined) return yield* output.invalid(`${route.name} completed without a video URL`)
|
||||||
const duration = task.duration ?? undefined
|
const duration = task.duration ?? undefined
|
||||||
|
|
@ -283,7 +287,7 @@ const decodeResult = Effect.fn("MiniMaxVideo.decodeResult")(function* (
|
||||||
usage: typeof total === "number" ? { type: "seconds", seconds: total } : undefined,
|
usage: typeof total === "number" ? { type: "seconds", seconds: total } : undefined,
|
||||||
providerMetadata: {
|
providerMetadata: {
|
||||||
minimax: {
|
minimax: {
|
||||||
taskId: context.token.taskID,
|
taskId: context.token,
|
||||||
model: task.model ?? undefined,
|
model: task.model ?? undefined,
|
||||||
resolution: task.resolution ?? undefined,
|
resolution: task.resolution ?? undefined,
|
||||||
ratio: task.ratio ?? undefined,
|
ratio: task.ratio ?? undefined,
|
||||||
|
|
@ -301,7 +305,7 @@ const decodeHailuoStart = Effect.fn("MiniMaxHailuoVideo.decodeStart")(function*
|
||||||
if (error) return yield* error
|
if (error) return yield* error
|
||||||
const taskID = output.value.task_id ?? ""
|
const taskID = output.value.task_id ?? ""
|
||||||
if (taskID === "") return yield* output.invalid(`${hailuoRoute.name} returned no task_id`)
|
if (taskID === "") return yield* output.invalid(`${hailuoRoute.name} returned no task_id`)
|
||||||
return { token: { taskID }, snapshot: { id: taskID, status: "queued" as const } }
|
return { token: taskID, snapshot: { id: taskID, status: "running" as const } }
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeHailuoTask = hailuoRoute.decodeJson(HailuoTask)
|
const decodeHailuoTask = hailuoRoute.decodeJson(HailuoTask)
|
||||||
|
|
@ -313,9 +317,9 @@ const decodeHailuoStatus = Effect.fn("MiniMaxHailuoVideo.decodeStatus")(function
|
||||||
const output = yield* decodeHailuoTask(response)
|
const output = yield* decodeHailuoTask(response)
|
||||||
const status = MediaProtocol.status(HAILUO_STATUS, output.value.status ?? "")
|
const status = MediaProtocol.status(HAILUO_STATUS, output.value.status ?? "")
|
||||||
// A failed task also carries its reason in `base_resp`; any other non-zero code is a failed read.
|
// A failed task also carries its reason in `base_resp`; any other non-zero code is a failed read.
|
||||||
const error = status === "failed" ? undefined : baseError(output, output.value.base_resp)
|
const error = status.reason === "failed" ? undefined : baseError(output, output.value.base_resp)
|
||||||
if (error) return yield* error
|
if (error) return yield* error
|
||||||
return { id: context.token.taskID, status }
|
return { id: context.token, ...status }
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeHailuoFile = hailuoRoute.decodeJson(HailuoFile)
|
const decodeHailuoFile = hailuoRoute.decodeJson(HailuoFile)
|
||||||
|
|
@ -326,11 +330,11 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeHailuoTask(response)
|
const output = yield* decodeHailuoTask(response)
|
||||||
const task = output.value
|
const task = output.value
|
||||||
const status = MediaProtocol.status(HAILUO_STATUS, task.status ?? "")
|
const status = MediaProtocol.state(HAILUO_STATUS, task.status ?? "")
|
||||||
const error = baseError(output, task.base_resp)
|
const error = baseError(output, task.base_resp)
|
||||||
if (status === "failed") return yield* error ?? failed(output, hailuoRoute.name, undefined, undefined)
|
if (status === "failed") return yield* error ?? failed(output, hailuoRoute.name, undefined, undefined)
|
||||||
if (error) return yield* error
|
if (error) return yield* error
|
||||||
if (status !== "completed") return yield* output.pending(context.token.taskID)
|
if (status !== "completed") return yield* output.pending(context.token)
|
||||||
const fileID = task.file_id ?? ""
|
const fileID = task.file_id ?? ""
|
||||||
if (fileID === "") return yield* output.invalid(`${hailuoRoute.name} completed without a file_id`)
|
if (fileID === "") return yield* output.invalid(`${hailuoRoute.name} completed without a file_id`)
|
||||||
// The task names a file; its download URL takes a second lookup and is valid for one hour.
|
// The task names a file; its download URL takes a second lookup and is valid for one hour.
|
||||||
|
|
@ -349,7 +353,7 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
providerMetadata: {
|
providerMetadata: {
|
||||||
minimax: { taskId: context.token.taskID, fileId: fileID },
|
minimax: { taskId: context.token, fileId: fileID },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -361,13 +365,13 @@ const decodeHailuoResult = Effect.fn("MiniMaxHailuoVideo.decodeResult")(function
|
||||||
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
||||||
token: Token,
|
token: Token,
|
||||||
start: { body: { from: fromRequest }, decode: decodeStart },
|
start: { body: { from: fromRequest }, decode: decodeStart },
|
||||||
status: { path: (token) => `${STATUS_PATH}/${token.taskID}`, decode: decodeStatus },
|
status: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeStatus },
|
||||||
result: { path: (token) => `${STATUS_PATH}/${token.taskID}`, decode: decodeResult },
|
result: { path: (token) => `${STATUS_PATH}/${encodeURIComponent(token)}`, decode: decodeResult },
|
||||||
// Cancels a queued task; MiniMax rejects it once the task is running.
|
// Cancels a queued task; MiniMax rejects it once the task is running.
|
||||||
cancel: { method: "DELETE", path: (token) => `${PATH}/${token.taskID}` },
|
cancel: { method: "DELETE", path: (token) => `${PATH}/${encodeURIComponent(token)}` },
|
||||||
})
|
})
|
||||||
|
|
||||||
const hailuoStatusPath = (token: Token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token.taskID)}`
|
const hailuoStatusPath = (token: Token) => `${HAILUO_STATUS_PATH}?task_id=${encodeURIComponent(token)}`
|
||||||
|
|
||||||
export const hailuoProtocol = MediaProtocol.queued<Request, VideoResponse, Token>(hailuoRoute, {
|
export const hailuoProtocol = MediaProtocol.queued<Request, VideoResponse, Token>(hailuoRoute, {
|
||||||
token: Token,
|
token: Token,
|
||||||
|
|
@ -378,11 +382,11 @@ export const hailuoProtocol = MediaProtocol.queued<Request, VideoResponse, Token
|
||||||
|
|
||||||
/** H3 and later models on the v2 API. */
|
/** H3 and later models on the v2 API. */
|
||||||
export const h3Model = (input: MediaRoute.ModelInput) =>
|
export const h3Model = (input: MediaRoute.ModelInput) =>
|
||||||
VideoModel.fromRoute<MiniMaxVideoOptions, Token>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
|
VideoModel.fromRoute<MiniMaxVideoOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
|
||||||
|
|
||||||
/** Hailuo and the `*-01` models on the v1 API. */
|
/** Hailuo and the `*-01` models on the v1 API. */
|
||||||
export const hailuoModel = (input: MediaRoute.ModelInput) =>
|
export const hailuoModel = (input: MediaRoute.ModelInput) =>
|
||||||
VideoModel.fromRoute<MiniMaxVideoOptions, Token>(
|
VideoModel.fromRoute<MiniMaxVideoOptions>(
|
||||||
{ protocol: hailuoProtocol, baseURL: DEFAULT_BASE_URL, path: HAILUO_PATH },
|
{ protocol: hailuoProtocol, baseURL: DEFAULT_BASE_URL, path: HAILUO_PATH },
|
||||||
input,
|
input,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -369,6 +369,7 @@ const lowerTool = (tool: ToolDefinition): MistralTool => ({
|
||||||
function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: false },
|
function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, strict: false },
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
||||||
export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (request: LLMRequest) {
|
export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (request: LLMRequest) {
|
||||||
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MistralOptions))(
|
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(MistralOptions))(
|
||||||
request.providerOptions ?? {},
|
request.providerOptions ?? {},
|
||||||
|
|
@ -385,11 +386,10 @@ export const fromRequest = Effect.fn("MistralChat.fromRequest")(function* (reque
|
||||||
tool: (name) => ({ type: "function" as const, function: { name } }),
|
tool: (name) => ({ type: "function" as const, function: { name } }),
|
||||||
})
|
})
|
||||||
: undefined
|
: undefined
|
||||||
const flattened = ProviderShared.flattenToolRequest(request)
|
|
||||||
return {
|
return {
|
||||||
model: request.model.id,
|
model: request.model.id,
|
||||||
messages: yield* lowerMessages(flattened.request),
|
messages: yield* lowerMessages(request),
|
||||||
tools: flattened.tools.length > 0 ? flattened.tools.map(lowerTool) : undefined,
|
tools: request.tools.length > 0 ? ProviderShared.flattenTools(request.tools).map(lowerTool) : undefined,
|
||||||
tool_choice: toolChoice,
|
tool_choice: toolChoice,
|
||||||
stream: true as const,
|
stream: true as const,
|
||||||
max_tokens: request.maxTokens,
|
max_tokens: request.maxTokens,
|
||||||
|
|
|
||||||
|
|
@ -87,6 +87,8 @@ const comparable = (value: unknown) => {
|
||||||
name: value.name,
|
name: value.name,
|
||||||
arguments: json(value.arguments),
|
arguments: json(value.arguments),
|
||||||
}
|
}
|
||||||
|
if (value.type === "custom_tool_call")
|
||||||
|
return { type: value.type, call_id: value.call_id, name: value.name, input: value.input }
|
||||||
if (value.type === "reasoning")
|
if (value.type === "reasoning")
|
||||||
return {
|
return {
|
||||||
type: value.type,
|
type: value.type,
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,7 @@ import {
|
||||||
type ReasoningPart,
|
type ReasoningPart,
|
||||||
type TextPart,
|
type TextPart,
|
||||||
type ToolCallPart,
|
type ToolCallPart,
|
||||||
|
type ToolChanges,
|
||||||
type ToolDefinition,
|
type ToolDefinition,
|
||||||
type ToolResultPart,
|
type ToolResultPart,
|
||||||
type UserMessage,
|
type UserMessage,
|
||||||
|
|
@ -29,7 +30,8 @@ import {
|
||||||
withUntypedFrames,
|
withUntypedFrames,
|
||||||
} from "./shared.js"
|
} from "./shared.js"
|
||||||
import { classifyProviderFailure } from "../provider-error.js"
|
import { classifyProviderFailure } from "../provider-error.js"
|
||||||
import { effortUpdate } from "../effort-updates.js"
|
import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js"
|
||||||
|
import { toolsUpdate } from "../tool-updates.js"
|
||||||
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
|
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
|
||||||
import { Lifecycle } from "./utils/lifecycle.js"
|
import { Lifecycle } from "./utils/lifecycle.js"
|
||||||
import { ToolStream } from "./utils/tool-stream.js"
|
import { ToolStream } from "./utils/tool-stream.js"
|
||||||
|
|
@ -189,9 +191,49 @@ export const HostedToolReplay = Schema.StructWithRest(
|
||||||
)
|
)
|
||||||
export type HostedToolReplayItem = Schema.Schema.Type<typeof HostedToolReplay>
|
export type HostedToolReplayItem = Schema.Schema.Type<typeof HostedToolReplay>
|
||||||
|
|
||||||
|
export const Tool = Schema.Struct({
|
||||||
|
type: Schema.tag("function"),
|
||||||
|
name: Schema.String,
|
||||||
|
description: Schema.String,
|
||||||
|
parameters: JsonObject,
|
||||||
|
strict: Schema.optional(Schema.Boolean),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const CustomTool = Schema.Struct({
|
||||||
|
type: Schema.tag("custom"),
|
||||||
|
name: Schema.String,
|
||||||
|
description: Schema.String,
|
||||||
|
format: Schema.Union([
|
||||||
|
Schema.Struct({ type: Schema.tag("text") }),
|
||||||
|
Schema.Struct({
|
||||||
|
type: Schema.tag("grammar"),
|
||||||
|
syntax: Schema.Literals(["lark", "regex"]),
|
||||||
|
definition: Schema.String,
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
})
|
||||||
|
|
||||||
|
export const HostedTool = Schema.StructWithRest(
|
||||||
|
Schema.Struct({
|
||||||
|
type: Schema.String,
|
||||||
|
}),
|
||||||
|
[JsonObject],
|
||||||
|
)
|
||||||
|
export type HostedTool = Schema.Schema.Type<typeof HostedTool>
|
||||||
|
|
||||||
|
const NamedTool = Schema.Struct({ type: Schema.Literals(["function", "custom"]), name: Schema.String })
|
||||||
|
|
||||||
|
// Tools added mid-conversation. Only the OpenAI extension lowers it; other hosts fold tool updates.
|
||||||
|
export const AdditionalTools = Schema.Struct({
|
||||||
|
type: Schema.Literal("additional_tools"),
|
||||||
|
role: Schema.Literal("developer"),
|
||||||
|
tools: Schema.Array(Schema.Union([Tool, CustomTool, HostedTool])),
|
||||||
|
})
|
||||||
|
|
||||||
export const InputItem = Schema.Union([
|
export const InputItem = Schema.Union([
|
||||||
CompactionItem,
|
CompactionItem,
|
||||||
ConfigurationUpdate,
|
ConfigurationUpdate,
|
||||||
|
AdditionalTools,
|
||||||
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("system"), content: Schema.String }),
|
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("system"), content: Schema.String }),
|
||||||
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("developer"), content: Schema.String }),
|
Schema.Struct({ type: Schema.tag("message"), role: Schema.tag("developer"), content: Schema.String }),
|
||||||
Schema.Struct({
|
Schema.Struct({
|
||||||
|
|
@ -243,38 +285,6 @@ type OpenResponsesReasoningInput = {
|
||||||
summary: Array<{ type: "summary_text"; text: string }>
|
summary: Array<{ type: "summary_text"; text: string }>
|
||||||
encrypted_content?: string | null
|
encrypted_content?: string | null
|
||||||
}
|
}
|
||||||
export const Tool = Schema.Struct({
|
|
||||||
type: Schema.tag("function"),
|
|
||||||
name: Schema.String,
|
|
||||||
description: Schema.String,
|
|
||||||
parameters: JsonObject,
|
|
||||||
strict: Schema.optional(Schema.Boolean),
|
|
||||||
})
|
|
||||||
|
|
||||||
export const CustomTool = Schema.Struct({
|
|
||||||
type: Schema.tag("custom"),
|
|
||||||
name: Schema.String,
|
|
||||||
description: Schema.String,
|
|
||||||
format: Schema.Union([
|
|
||||||
Schema.Struct({ type: Schema.tag("text") }),
|
|
||||||
Schema.Struct({
|
|
||||||
type: Schema.tag("grammar"),
|
|
||||||
syntax: Schema.Literals(["lark", "regex"]),
|
|
||||||
definition: Schema.String,
|
|
||||||
}),
|
|
||||||
]),
|
|
||||||
})
|
|
||||||
|
|
||||||
export const HostedTool = Schema.StructWithRest(
|
|
||||||
Schema.Struct({
|
|
||||||
type: Schema.String,
|
|
||||||
}),
|
|
||||||
[JsonObject],
|
|
||||||
)
|
|
||||||
export type HostedTool = Schema.Schema.Type<typeof HostedTool>
|
|
||||||
|
|
||||||
const NamedTool = Schema.Struct({ type: Schema.Literals(["function", "custom"]), name: Schema.String })
|
|
||||||
|
|
||||||
export const ToolChoice = Schema.Union([
|
export const ToolChoice = Schema.Union([
|
||||||
Schema.Literals(["auto", "none", "required"]),
|
Schema.Literals(["auto", "none", "required"]),
|
||||||
NamedTool,
|
NamedTool,
|
||||||
|
|
@ -434,6 +444,8 @@ export interface ProviderAdapter {
|
||||||
readonly request: LLMRequest
|
readonly request: LLMRequest
|
||||||
}) => MediaInput | undefined
|
}) => MediaInput | undefined
|
||||||
readonly restoreHostedToolItem?: (item: unknown) => HostedToolReplayItem | undefined
|
readonly restoreHostedToolItem?: (item: unknown) => HostedToolReplayItem | undefined
|
||||||
|
/** Lowers a `Message.tools(...)` marker sent in place; routes without it must fold tool updates. */
|
||||||
|
readonly lowerToolChanges?: (changes: ToolChanges) => Effect.Effect<ReadonlyArray<OpenResponsesInputItem>, AIError>
|
||||||
}
|
}
|
||||||
|
|
||||||
const BASE_ADAPTER: ProviderAdapter = { id: ADAPTER, name: NAME }
|
const BASE_ADAPTER: ProviderAdapter = { id: ADAPTER, name: NAME }
|
||||||
|
|
@ -484,11 +496,11 @@ export const lowerTool = Effect.fnUntraced(function* (protocolName: string, tool
|
||||||
})
|
})
|
||||||
|
|
||||||
export const lowerCustomTool = (tool: ToolDefinition, custom: OpenAIFreeform.Custom) => {
|
export const lowerCustomTool = (tool: ToolDefinition, custom: OpenAIFreeform.Custom) => {
|
||||||
const grammar = OpenAIFreeform.grammar(custom.format)
|
const grammar = OpenAIFreeform.grammar(custom)
|
||||||
return {
|
return {
|
||||||
type: "custom" as const,
|
type: "custom" as const,
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
description: tool.description,
|
description: OpenAIFreeform.description(tool, custom),
|
||||||
format: grammar ? { type: "grammar" as const, ...grammar } : { type: "text" as const },
|
format: grammar ? { type: "grammar" as const, ...grammar } : { type: "text" as const },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -548,7 +560,7 @@ const lowerToolCall = (
|
||||||
...(id === undefined ? {} : { id }),
|
...(id === undefined ? {} : { id }),
|
||||||
call_id: part.id,
|
call_id: part.id,
|
||||||
name: part.name,
|
name: part.name,
|
||||||
input: OpenAIFreeform.toRaw(custom, part.input),
|
input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[providerMetadataKey]?.header),
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
type: "function_call",
|
type: "function_call",
|
||||||
|
|
@ -641,10 +653,17 @@ const lowerToolResultOutput = Effect.fnUntraced(function* (
|
||||||
|
|
||||||
const DEFAULT_EFFORT = "medium"
|
const DEFAULT_EFFORT = "medium"
|
||||||
|
|
||||||
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter: ProviderAdapter) {
|
// A call's output only follows the whole assistant turn, and Meta's Muse models, directly or through a gateway,
|
||||||
|
// reject a commentary message replayed while a call is waiting for it. Text after a call keeps its place without
|
||||||
|
// the phase there; other providers accept it and keep the phase.
|
||||||
|
const rejectsPendingCommentary = (request: LLMRequest) =>
|
||||||
|
request.model.provider === "meta" || /(?:^|\/)muse-/i.test(request.model.id)
|
||||||
|
|
||||||
|
export const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter: ProviderAdapter) {
|
||||||
const input: OpenResponsesInputItem[] = []
|
const input: OpenResponsesInputItem[] = []
|
||||||
const providerMetadataKey = metadataKey(request.model)
|
const providerMetadataKey = metadataKey(request.model)
|
||||||
const custom = OpenAIFreeform.tools(request)
|
const custom = OpenAIFreeform.tools(request)
|
||||||
|
const pendingCommentaryRejected = rejectsPendingCommentary(request)
|
||||||
const customTool = (part: ToolCallPart | ToolResultPart) =>
|
const customTool = (part: ToolCallPart | ToolResultPart) =>
|
||||||
part.namespace === undefined ? custom.get(part.name) : undefined
|
part.namespace === undefined ? custom.get(part.name) : undefined
|
||||||
|
|
||||||
|
|
@ -663,6 +682,13 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter:
|
||||||
input.push({ type: "configuration_update", reasoning: { effort: update.effort ?? DEFAULT_EFFORT } })
|
input.push({ type: "configuration_update", reasoning: { effort: update.effort ?? DEFAULT_EFFORT } })
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
// Planning folds every marker on routes whose protocol has no `toolUpdates`, so only adapters with
|
||||||
|
// `lowerToolChanges` see one.
|
||||||
|
const tools = toolsUpdate(message)
|
||||||
|
if (tools && adapter.lowerToolChanges) {
|
||||||
|
input.push(...(yield* adapter.lowerToolChanges(tools)))
|
||||||
|
if (message.content.length === 0) continue
|
||||||
|
}
|
||||||
input.push({
|
input.push({
|
||||||
type: "message",
|
type: "message",
|
||||||
role: "developer",
|
role: "developer",
|
||||||
|
|
@ -682,6 +708,7 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter:
|
||||||
const content: TextPart[] = []
|
const content: TextPart[] = []
|
||||||
const reasoningItems: Record<string, OpenResponsesReasoningInput> = {}
|
const reasoningItems: Record<string, OpenResponsesReasoningInput> = {}
|
||||||
const hostedToolItems = new Set<string>()
|
const hostedToolItems = new Set<string>()
|
||||||
|
let calledTool = false
|
||||||
const flushText = () => {
|
const flushText = () => {
|
||||||
if (content.length === 0) return
|
if (content.length === 0) return
|
||||||
const groups = content.reduce<
|
const groups = content.reduce<
|
||||||
|
|
@ -690,7 +717,8 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter:
|
||||||
const partMetadata = part.providerMetadata?.[providerMetadataKey]
|
const partMetadata = part.providerMetadata?.[providerMetadataKey]
|
||||||
const id = itemID(part.providerMetadata, providerMetadataKey) ?? metadata?.itemId
|
const id = itemID(part.providerMetadata, providerMetadataKey) ?? metadata?.itemId
|
||||||
const partPhase = messagePhase(partMetadata?.phase)
|
const partPhase = messagePhase(partMetadata?.phase)
|
||||||
const phase = partPhase === undefined ? metadata?.phase : partPhase
|
const declared = partPhase === undefined ? metadata?.phase : partPhase
|
||||||
|
const phase = calledTool && declared === "commentary" && pendingCommentaryRejected ? undefined : declared
|
||||||
const group = groups.at(-1)
|
const group = groups.at(-1)
|
||||||
if (group && group.id === id && group.phase === phase) group.parts.push(part)
|
if (group && group.id === id && group.phase === phase) group.parts.push(part)
|
||||||
else groups.push({ id, phase, parts: [part] })
|
else groups.push({ id, phase, parts: [part] })
|
||||||
|
|
@ -742,6 +770,7 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter:
|
||||||
flushText()
|
flushText()
|
||||||
if (part.providerExecuted === true) continue
|
if (part.providerExecuted === true) continue
|
||||||
input.push(lowerToolCall(part, providerMetadataKey, customTool(part)))
|
input.push(lowerToolCall(part, providerMetadataKey, customTool(part)))
|
||||||
|
calledTool = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if (part.type === "tool-result" && part.providerExecuted === true) {
|
if (part.type === "tool-result" && part.providerExecuted === true) {
|
||||||
|
|
@ -805,12 +834,15 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, adapter:
|
||||||
return input
|
return input
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// The system prompt leads `input` as a developer message: GPT-6.2 models never cache top-level `instructions`.
|
||||||
export const lowerConversation = Effect.fnUntraced(function* (request: LLMRequest, adapter: ProviderAdapter) {
|
export const lowerConversation = Effect.fnUntraced(function* (request: LLMRequest, adapter: ProviderAdapter) {
|
||||||
const instructions = ProviderShared.joinText(request.system)
|
const system = ProviderShared.joinText(request.system)
|
||||||
return {
|
return {
|
||||||
model: request.model.id,
|
model: request.model.id,
|
||||||
input: yield* lowerMessages(request, adapter),
|
input: [
|
||||||
...(instructions ? { instructions } : {}),
|
...(system ? [{ type: "message" as const, role: "developer" as const, content: system }] : []),
|
||||||
|
...(yield* lowerMessages(request, adapter)),
|
||||||
|
],
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -864,23 +896,26 @@ export const allowedToolChoice = (
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
||||||
export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (
|
export const fromRequestWithAdapter = Effect.fn("OpenResponses.fromRequestWithAdapter")(function* (
|
||||||
request: LLMRequest,
|
request: LLMRequest,
|
||||||
adapter: ProviderAdapter,
|
adapter: ProviderAdapter,
|
||||||
) {
|
) {
|
||||||
const projected = ProviderShared.flattenToolRequest(request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
const options = OpenResponsesOptions.resolve(request)
|
const options = OpenResponsesOptions.resolve(request)
|
||||||
const custom = OpenAIFreeform.tools(request)
|
const custom = OpenAIFreeform.tools(request)
|
||||||
|
const updates = resolveEffortUpdates(request, options.reasoningEffort)
|
||||||
return {
|
return {
|
||||||
...(yield* lowerConversation(projected.request, adapter)),
|
...(yield* lowerConversation(updates.request, adapter)),
|
||||||
...lowerGeneration(request, options),
|
...lowerGeneration(request, { ...options, reasoningEffort: updates.effort }),
|
||||||
tools: projected.tools.length === 0 ? undefined : yield* lowerTools(projected.tools, adapter, custom),
|
tools: definitions.length === 0 ? undefined : yield* lowerTools(definitions, adapter, custom),
|
||||||
tool_choice:
|
tool_choice:
|
||||||
allowedToolChoice(options, custom) ??
|
allowedToolChoice(options, custom) ??
|
||||||
(request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice, custom) : undefined),
|
(request.toolChoice ? yield* lowerToolChoice(adapter.name, request.toolChoice, custom) : undefined),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
||||||
export const fromRequest = (request: LLMRequest) => fromRequestWithAdapter(request, BASE_ADAPTER)
|
export const fromRequest = (request: LLMRequest) => fromRequestWithAdapter(request, BASE_ADAPTER)
|
||||||
|
|
||||||
// =============================================================================
|
// =============================================================================
|
||||||
|
|
@ -1313,19 +1348,25 @@ const onOutputItemDone = Effect.fnUntraced(function* (state: ParserState, item:
|
||||||
if (!item.call_id || !item.name) return [state, NO_EVENTS] satisfies StepResult
|
if (!item.call_id || !item.name) return [state, NO_EVENTS] satisfies StepResult
|
||||||
const custom = item.type === "custom_tool_call"
|
const custom = item.type === "custom_tool_call"
|
||||||
const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom))
|
const metadata = providerMetadata(state, OpenAIFreeform.metadata(item.id, custom))
|
||||||
const final = { custom: state.custom.get(item.name), raw: rawInput(item) }
|
|
||||||
const input = custom ? OpenAIFreeform.fromRaw(final.custom, final.raw) : item.arguments
|
|
||||||
const registered = state.tools[item.id] !== undefined
|
const registered = state.tools[item.id] !== undefined
|
||||||
const closed = custom ? OpenAIFreeform.close(state.tools, [item.id], final) : undefined
|
const started = registered
|
||||||
const tools = registered
|
? state.tools
|
||||||
? (closed?.tools ?? state.tools)
|
|
||||||
: ToolStream.start(state.tools, item.id, {
|
: ToolStream.start(state.tools, item.id, {
|
||||||
id: item.call_id,
|
id: item.call_id,
|
||||||
name: item.name,
|
name: item.name,
|
||||||
namespace: item.namespace,
|
namespace: item.namespace,
|
||||||
providerMetadata: metadata,
|
providerMetadata: metadata,
|
||||||
})
|
})
|
||||||
const result = yield* ToolStream.finish(state.id, tools, item.id, input)
|
// A custom call's final raw text sets its input, so it finishes without an override.
|
||||||
|
const closed = custom
|
||||||
|
? OpenAIFreeform.close(started, [item.id], state.custom, state.providerMetadataKey, rawInput(item))
|
||||||
|
: undefined
|
||||||
|
const result = yield* ToolStream.finish(
|
||||||
|
state.id,
|
||||||
|
closed?.tools ?? started,
|
||||||
|
item.id,
|
||||||
|
custom ? undefined : item.arguments,
|
||||||
|
)
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
const finished = [...(closed?.events ?? []), ...(result.events ?? [])]
|
const finished = [...(closed?.events ?? []), ...(result.events ?? [])]
|
||||||
// A done-only call never streamed a start event, so open its lifecycle here.
|
// A done-only call never streamed a start event, so open its lifecycle here.
|
||||||
|
|
@ -1417,7 +1458,16 @@ const onResponseFinish = Effect.fnUntraced(function* (state: ParserState, event:
|
||||||
events.push(...emitted)
|
events.push(...emitted)
|
||||||
}
|
}
|
||||||
// Some compatible providers omit output_item.done even after completing the response.
|
// Some compatible providers omit output_item.done even after completing the response.
|
||||||
const pending = yield* ToolStream.finishAll(current.id, current.tools)
|
const open = OpenAIFreeform.close(
|
||||||
|
current.tools,
|
||||||
|
Object.keys(current.tools).filter(
|
||||||
|
(key) => current.tools[key]?.providerMetadata?.[current.providerMetadataKey]?.custom === true,
|
||||||
|
),
|
||||||
|
current.custom,
|
||||||
|
current.providerMetadataKey,
|
||||||
|
)
|
||||||
|
events.push(...open.events)
|
||||||
|
const pending = yield* ToolStream.finishAll(current.id, open.tools)
|
||||||
current = {
|
current = {
|
||||||
...current,
|
...current,
|
||||||
tools: pending.tools,
|
tools: pending.tools,
|
||||||
|
|
@ -1590,6 +1640,8 @@ export const protocol = Protocol.make({
|
||||||
step: (state: ParserState, event: Event) => step(state, normalize(state, event)),
|
step: (state: ParserState, event: Event) => step(state, normalize(state, event)),
|
||||||
terminal,
|
terminal,
|
||||||
},
|
},
|
||||||
|
// Not every Open Responses server accepts `configuration_update`, so only models that opt in get it.
|
||||||
|
supportsEffortUpdates: (request) => request.model.capabilities?.reasoning?.updates === true,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const httpTransport = HttpTransport.sseJson.with<OpenResponsesBody>()
|
export const httpTransport = HttpTransport.sseJson.with<OpenResponsesBody>()
|
||||||
|
|
|
||||||
|
|
@ -406,12 +406,12 @@ const lowerTool = (
|
||||||
custom: OpenAIFreeform.Custom | undefined,
|
custom: OpenAIFreeform.Custom | undefined,
|
||||||
): OpenAIChatTool => {
|
): OpenAIChatTool => {
|
||||||
if (custom) {
|
if (custom) {
|
||||||
const grammar = OpenAIFreeform.grammar(custom.format)
|
const grammar = OpenAIFreeform.grammar(custom)
|
||||||
return {
|
return {
|
||||||
type: "custom",
|
type: "custom",
|
||||||
custom: {
|
custom: {
|
||||||
name: tool.name,
|
name: tool.name,
|
||||||
description: tool.description,
|
description: OpenAIFreeform.description(tool, custom),
|
||||||
format: grammar ? { type: "grammar", grammar } : { type: "text" },
|
format: grammar ? { type: "grammar", grammar } : { type: "text" },
|
||||||
},
|
},
|
||||||
cache_control: options.cacheControl?.(tool.cache),
|
cache_control: options.cacheControl?.(tool.cache),
|
||||||
|
|
@ -450,7 +450,10 @@ const lowerToolCall = (part: ToolCallPart, options: MessageLoweringOptions): Ope
|
||||||
return {
|
return {
|
||||||
id: options.toolCallID?.(part.id) ?? part.id,
|
id: options.toolCallID?.(part.id) ?? part.id,
|
||||||
type: "custom",
|
type: "custom",
|
||||||
custom: { name: part.name, input: OpenAIFreeform.toRaw(custom, part.input) },
|
custom: {
|
||||||
|
name: part.name,
|
||||||
|
input: OpenAIFreeform.toRaw(custom, part.input, part.providerMetadata?.[options.providerMetadataKey]?.header),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
id: options.toolCallID?.(part.id) ?? part.id,
|
id: options.toolCallID?.(part.id) ?? part.id,
|
||||||
|
|
@ -577,6 +580,9 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (
|
||||||
const opaque = reasoningOpaque(reasoning, options.providerMetadataKey)
|
const opaque = reasoningOpaque(reasoning, options.providerMetadataKey)
|
||||||
const reasoningText =
|
const reasoningText =
|
||||||
reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text
|
reasoning.length === 0 || (opaque !== undefined && text === "") ? (requireReasoning ? "" : undefined) : text
|
||||||
|
// A model that declares a different reasoning field reads reasoning there, so structured details and opaque values
|
||||||
|
// from earlier turns (including another model served under the same provider metadata key) must not be replayed.
|
||||||
|
const replaysStructured = configuredField === undefined || configuredField === "reasoning_details"
|
||||||
const result = {
|
const result = {
|
||||||
role: "assistant" as const,
|
role: "assistant" as const,
|
||||||
content: (() => {
|
content: (() => {
|
||||||
|
|
@ -585,10 +591,11 @@ const lowerAssistantMessage = Effect.fnUntraced(function* (
|
||||||
return content.map((part) => part.text).join("")
|
return content.map((part) => part.text).join("")
|
||||||
})(),
|
})(),
|
||||||
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
||||||
...(details !== undefined ? { reasoning_details: details } : {}),
|
...(details !== undefined && replaysStructured ? { reasoning_details: details } : {}),
|
||||||
...(opaque !== undefined ? { reasoning_opaque: opaque } : {}),
|
...(opaque !== undefined && replaysStructured ? { reasoning_opaque: opaque } : {}),
|
||||||
}
|
}
|
||||||
if (field === undefined || reasoningText === undefined) return result
|
// `reasoning_details` is the structured list itself, so scalar text must not be written over it.
|
||||||
|
if (field === undefined || reasoningText === undefined || field === "reasoning_details") return result
|
||||||
return { ...result, [field]: reasoningText }
|
return { ...result, [field]: reasoningText }
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -862,6 +869,7 @@ const lowerOptions = (request: LLMRequest, supportsStore: boolean, hasActiveTool
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Expects tool namespaces already flattened, as `protocol.body.from` passes it; otherwise run `ProviderShared.flattenRequest` first. */
|
||||||
export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||||
request: LLMRequest,
|
request: LLMRequest,
|
||||||
options: LoweringOptions = {},
|
options: LoweringOptions = {},
|
||||||
|
|
@ -873,7 +881,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||||
return yield* ProviderShared.invalidRequest(
|
return yield* ProviderShared.invalidRequest(
|
||||||
`OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`,
|
`OpenAI Chat reasoning field conflicts with reserved field ${reasoningField}`,
|
||||||
)
|
)
|
||||||
const flattened = ProviderShared.flattenToolRequest(request)
|
const definitions = ProviderShared.flattenTools(request.tools)
|
||||||
const provider = request.model.provider
|
const provider = request.model.provider
|
||||||
const baseURL = request.model.route.endpoint.baseURL
|
const baseURL = request.model.route.endpoint.baseURL
|
||||||
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
|
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
|
||||||
|
|
@ -883,18 +891,18 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
|
||||||
const zaiToolStream =
|
const zaiToolStream =
|
||||||
request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
|
request.model.compatibility?.zaiToolStream ?? detectZaiToolStream(provider, baseURL, request.model.id)
|
||||||
const hasHistory = hasToolHistory(request.messages)
|
const hasHistory = hasToolHistory(request.messages)
|
||||||
const hasActiveTools = flattened.tools.length > 0
|
const hasActiveTools = definitions.length > 0
|
||||||
const custom = OpenAIFreeform.tools(request)
|
const custom = OpenAIFreeform.tools(request)
|
||||||
const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom }
|
const lowering = { ...options, cacheControl: options.cacheControl ?? declaredCacheControl(request), custom }
|
||||||
return {
|
return {
|
||||||
model: request.model.id,
|
model: request.model.id,
|
||||||
messages: yield* lowerMessages(flattened.request, lowering),
|
messages: yield* lowerMessages(request, lowering),
|
||||||
tools:
|
tools:
|
||||||
flattened.tools.length === 0
|
definitions.length === 0
|
||||||
? hasHistory
|
? hasHistory
|
||||||
? []
|
? []
|
||||||
: undefined
|
: undefined
|
||||||
: flattened.tools.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
|
: definitions.map((tool) => lowerTool(tool, lowering, supportsStrictMode, custom.get(tool.name))),
|
||||||
tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined,
|
tool_choice: hasActiveTools && request.toolChoice ? yield* lowerToolChoice(request.toolChoice, custom) : undefined,
|
||||||
stream: true as const,
|
stream: true as const,
|
||||||
...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
|
...((request.model.capabilities?.streamUsage ?? true) ? { stream_options: { include_usage: true } } : {}),
|
||||||
|
|
@ -942,8 +950,12 @@ const mapFinishReason = Effect.fnUntraced(function* (event: OpenAIChatEvent, rea
|
||||||
case "end":
|
case "end":
|
||||||
return "stop" as const
|
return "stop" as const
|
||||||
case "length":
|
case "length":
|
||||||
|
// Z.AI stops with this when the prompt plus the generated output fill the context window.
|
||||||
|
case "model_context_window_exceeded":
|
||||||
return "length" as const
|
return "length" as const
|
||||||
case "content_filter":
|
case "content_filter":
|
||||||
|
// Z.AI ends a response its safety review blocked with "sensitive".
|
||||||
|
case "sensitive":
|
||||||
return "content-filter" as const
|
return "content-filter" as const
|
||||||
case "function_call":
|
case "function_call":
|
||||||
case "tool_calls":
|
case "tool_calls":
|
||||||
|
|
@ -1283,7 +1295,7 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||||
!incompleteTools &&
|
!incompleteTools &&
|
||||||
state.finishReason === undefined &&
|
state.finishReason === undefined &&
|
||||||
Object.keys(tools).length > 0
|
Object.keys(tools).length > 0
|
||||||
? yield* finishTools(tools, customCalls)
|
? yield* finishTools(state, tools, customCalls)
|
||||||
: undefined
|
: undefined
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|
@ -1312,8 +1324,12 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
||||||
})
|
})
|
||||||
|
|
||||||
// Custom calls close their JSON fragment before every pending call finishes.
|
// Custom calls close their JSON fragment before every pending call finishes.
|
||||||
const finishTools = Effect.fnUntraced(function* (tools: ParserState["tools"], customCalls: ReadonlySet<number>) {
|
const finishTools = Effect.fnUntraced(function* (
|
||||||
const closed = OpenAIFreeform.close(tools, customCalls)
|
state: ParserState,
|
||||||
|
tools: ParserState["tools"],
|
||||||
|
customCalls: ReadonlySet<number>,
|
||||||
|
) {
|
||||||
|
const closed = OpenAIFreeform.close(tools, customCalls, state.custom, state.providerMetadataKey)
|
||||||
const finished = yield* ToolStream.finishAll(ADAPTER, closed.tools)
|
const finished = yield* ToolStream.finishAll(ADAPTER, closed.tools)
|
||||||
return { tools: finished.tools, events: [...closed.events, ...finished.events] }
|
return { tools: finished.tools, events: [...closed.events, ...finished.events] }
|
||||||
})
|
})
|
||||||
|
|
@ -1330,7 +1346,7 @@ export const finishEvents = Effect.fnUntraced(function* (state: ParserState) {
|
||||||
const events: LLMEvent[] = []
|
const events: LLMEvent[] = []
|
||||||
const toolCallEvents =
|
const toolCallEvents =
|
||||||
state.finishReason === undefined && Object.keys(state.tools).length > 0
|
state.finishReason === undefined && Object.keys(state.tools).length > 0
|
||||||
? (yield* finishTools(state.tools, state.customCalls)).events
|
? (yield* finishTools(state, state.tools, state.customCalls)).events
|
||||||
: state.toolCallEvents
|
: state.toolCallEvents
|
||||||
const hasToolCalls = toolCallEvents.length > 0
|
const hasToolCalls = toolCallEvents.length > 0
|
||||||
const reason = state.finishReason
|
const reason = state.finishReason
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { Option, Schema } from "effect"
|
import { Option, Schema } from "effect"
|
||||||
import {
|
import {
|
||||||
|
JsonSchema,
|
||||||
ToolDefinition,
|
ToolDefinition,
|
||||||
type Freeform,
|
type Freeform,
|
||||||
type LLMEvent,
|
type LLMEvent,
|
||||||
|
|
@ -8,47 +9,205 @@ import {
|
||||||
} from "../schema/index.js"
|
} from "../schema/index.js"
|
||||||
import { encodeJson, flattenTools, isRecord } from "./shared.js"
|
import { encodeJson, flattenTools, isRecord } from "./shared.js"
|
||||||
import { ToolStream } from "./utils/tool-stream.js"
|
import { ToolStream } from "./utils/tool-stream.js"
|
||||||
|
import { toolsUpdate } from "../tool-updates.js"
|
||||||
|
|
||||||
// Freeform tools as OpenAI custom tools, shared by Responses and Chat Completions:
|
// Freeform tools as OpenAI custom tools, shared by Responses and Chat Completions:
|
||||||
// https://platform.openai.com/docs/guides/function-calling#custom-tools
|
// https://platform.openai.com/docs/guides/function-calling#custom-tools
|
||||||
// Calls keep the normal `{ field: raw }` input everywhere else; only the wire carries raw text.
|
// Calls keep the normal `{ field: raw }` input everywhere else; only the wire carries raw text.
|
||||||
|
|
||||||
export interface Custom {
|
export interface Custom {
|
||||||
/** The tool's one required string parameter, which the raw text fills. */
|
/** The tool's required string parameter, which the raw text fills. */
|
||||||
readonly field: string
|
readonly field: string
|
||||||
readonly format: Freeform
|
readonly format: Freeform
|
||||||
|
/** The tool's other parameters, set on a first line. */
|
||||||
|
readonly options?: {
|
||||||
|
readonly fields: ReadonlyArray<OptionField>
|
||||||
|
/** How to write the line, added to the custom tool's description. */
|
||||||
|
readonly description: string
|
||||||
|
/** The grammar for the line and the raw text, when the model takes Lark. */
|
||||||
|
readonly grammar?: string
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
|
interface OptionField {
|
||||||
export const resolve = (tool: ToolDefinition): Custom | undefined => {
|
readonly name: string
|
||||||
const field = ToolDefinition.freeformField(tool.inputSchema)
|
readonly schema: JsonSchema
|
||||||
|
readonly required: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// The other parameters go on a first line as a JSON object, `// @options: {"timeout": 5000}`, then the field's text.
|
||||||
|
// It is a JavaScript comment, so the line reads naturally before code.
|
||||||
|
export const PREFIX = "// @options:"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How a tool goes out: a custom tool when it declares `freeform` in a format the model accepts (`formats`; none when
|
||||||
|
* unset), with its required string parameter. Other parameters need a grammar for their values, and a raw
|
||||||
|
* text body when the model can't take Lark; otherwise the tool stays a JSON tool.
|
||||||
|
*/
|
||||||
|
export const resolve = (tool: ToolDefinition, formats: ReadonlyArray<Freeform["type"]> = []): Custom | undefined => {
|
||||||
|
const field = ToolDefinition.freeformField(tool.inputSchema, tool.freeform)
|
||||||
if (tool.freeform === undefined || tool.native !== undefined || field === undefined) return undefined
|
if (tool.freeform === undefined || tool.native !== undefined || field === undefined) return undefined
|
||||||
return { field, format: tool.freeform }
|
if (!formats.includes(tool.freeform.type)) return undefined
|
||||||
|
const lark = formats.includes("lark")
|
||||||
|
const required = Array.isArray(tool.inputSchema.required) ? tool.inputSchema.required : []
|
||||||
|
const fields = Object.entries(Schema.is(JsonSchema)(tool.inputSchema.properties) ? tool.inputSchema.properties : {})
|
||||||
|
.filter(([name]) => name !== field)
|
||||||
|
.map(([name, schema]) => ({
|
||||||
|
name,
|
||||||
|
schema: Schema.is(JsonSchema)(schema) ? schema : {},
|
||||||
|
required: required.includes(name),
|
||||||
|
}))
|
||||||
|
if (fields.length === 0) return { field, format: tool.freeform }
|
||||||
|
const rules = fields.flatMap((item) => valueRule(item.schema) ?? [])
|
||||||
|
if (rules.length !== fields.length || (!lark && tool.freeform.type !== "text")) return undefined
|
||||||
|
return {
|
||||||
|
field,
|
||||||
|
format: tool.freeform,
|
||||||
|
options: {
|
||||||
|
fields,
|
||||||
|
description: describe(field, fields),
|
||||||
|
grammar: lark ? lineGrammar(fields, rules, tool.freeform) : undefined,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Custom tools in this request, by flattened tool name. */
|
// Keys in any order, with spaces after `{`, `:` and `,` and before `}`. The tool's own schema checks the values it
|
||||||
export const tools = (request: LLMRequest): ReadonlyMap<string, Custom> =>
|
// gets, as it does for a JSON call. Without required parameters a call may leave the line out, so plain raw text
|
||||||
new Map(
|
// can't start with the prefix. A tool's own grammar becomes the body, its `start` renamed to `fb_start`.
|
||||||
flattenTools(request.tools).flatMap((tool) => {
|
const lineGrammar = (fields: ReadonlyArray<OptionField>, rules: ReadonlyArray<string>, format: Freeform) => {
|
||||||
const custom = resolve(tool)
|
const body = format.type === "text" ? "ff_body" : "fb_start"
|
||||||
|
const plain = format.type === "text" ? "ff_plain" : body
|
||||||
|
return [
|
||||||
|
`start: ff_line ${body}${fields.some((item) => item.required) ? "" : ` | ${plain}`}`,
|
||||||
|
`ff_line: ${larkString(PREFIX)} " "* "{" " "* ff_pair (" "* "," " "* ff_pair)* " "* "}" "\\n"`,
|
||||||
|
`ff_pair: ${fields.map((item, index) => `${larkString(encodeJson(item.name))} " "* ":" " "* ${rules[index]}`).join(" | ")}`,
|
||||||
|
...(format.type === "text"
|
||||||
|
? ["ff_body: /[\\s\\S]+/", `ff_plain: /${notStartingWith(PREFIX)}/`]
|
||||||
|
: format.type === "regex"
|
||||||
|
? [`fb_start: /${format.pattern.replace(/\\?\//g, "\\/")}/`]
|
||||||
|
: [format.grammar.replace(/^([ \t]*)start([ \t]*:)/m, "$1fb_start$2")]),
|
||||||
|
].join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
const valueRule = (schema: JsonSchema) => {
|
||||||
|
if (Array.isArray(schema.enum))
|
||||||
|
return schema.enum.length === 0
|
||||||
|
? undefined
|
||||||
|
: `(${schema.enum.map((item) => larkString(encodeJson(item))).join(" | ")})`
|
||||||
|
if (schema.type === "boolean") return '("true" | "false")'
|
||||||
|
if (schema.type === "number") return "/-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/"
|
||||||
|
if (schema.type === "string") return '/"(?:[^"\\\\\\x00-\\x1f]|\\\\["\\\\\\/bfnrt]|\\\\u[0-9a-fA-F]{4})*"/'
|
||||||
|
if (schema.type !== "integer") return undefined
|
||||||
|
const lowest = minimum(schema)
|
||||||
|
if (lowest >= 1) return "/[1-9][0-9]*/"
|
||||||
|
return lowest >= 0 ? "/0|[1-9][0-9]*/" : "/-?(?:0|[1-9][0-9]*)/"
|
||||||
|
}
|
||||||
|
|
||||||
|
const minimum = (schema: JsonSchema) =>
|
||||||
|
Math.max(
|
||||||
|
typeof schema.minimum === "number" ? schema.minimum : -Infinity,
|
||||||
|
typeof schema.exclusiveMinimum === "number" ? schema.exclusiveMinimum + 1 : -Infinity,
|
||||||
|
)
|
||||||
|
|
||||||
|
const describe = (field: string, fields: ReadonlyArray<OptionField>) => {
|
||||||
|
const required = fields.filter((item) => item.required)
|
||||||
|
const example = required.length > 0 ? required : [fields.find((item) => item.schema.type === "boolean") ?? fields[0]]
|
||||||
|
return [
|
||||||
|
required.length === 0
|
||||||
|
? `To set the parameters below, start with a \`${PREFIX}\` line holding a JSON object of them, then write \`${field}\` from the next line. Leave the line out to use the defaults.`
|
||||||
|
: `Start with a \`${PREFIX}\` line holding a JSON object of the parameters below, then write \`${field}\` from the next line.`,
|
||||||
|
...fields.map(
|
||||||
|
(item) =>
|
||||||
|
`- \`${item.name}\` (${Array.isArray(item.schema.enum) ? `one of ${item.schema.enum.map((value) => encodeJson(value)).join(", ")}` : String(item.schema.type)}${item.required ? ", required" : ""})${typeof item.schema.description === "string" ? `: ${item.schema.description}` : ""}`,
|
||||||
|
),
|
||||||
|
"For example:",
|
||||||
|
`${PREFIX} {${example.map((item) => `${encodeJson(item.name)}: ${encodeJson(sample(item.schema))}`).join(", ")}}`,
|
||||||
|
`<${field}>`,
|
||||||
|
].join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
const sample = (schema: JsonSchema) => {
|
||||||
|
if (Array.isArray(schema.enum)) return schema.enum[0]
|
||||||
|
if (schema.type === "boolean") return true
|
||||||
|
if (schema.type === "string") return "..."
|
||||||
|
return Math.max(1, minimum(schema))
|
||||||
|
}
|
||||||
|
|
||||||
|
const larkString = (text: string) => JSON.stringify(text)
|
||||||
|
|
||||||
|
// A regex for text that does not start with `prefix`: it differs from the prefix at some character, or is a shorter
|
||||||
|
// prefix of it.
|
||||||
|
const notStartingWith = (prefix: string) => {
|
||||||
|
const chars = [...prefix]
|
||||||
|
const head = (end: number) => chars.slice(0, end).map(escapeRegex).join("")
|
||||||
|
const differs = chars.map((char, index) => `${head(index)}[^${escapeClass(char)}]`)
|
||||||
|
const shorter = chars.slice(1).map((_, index) => head(index + 1))
|
||||||
|
return [`(?:${differs.join("|")})[\\s\\S]*`, ...shorter].join("|")
|
||||||
|
}
|
||||||
|
|
||||||
|
const escapeRegex = (char: string) => char.replace(/[\\^$.*+?()[\]{}|/]/g, "\\$&")
|
||||||
|
const escapeClass = (char: string) => char.replace(/[\\\]^\-/]/g, "\\$&")
|
||||||
|
|
||||||
|
/** Custom tools in this request, including ones added mid-conversation, by flattened tool name. */
|
||||||
|
export const tools = (request: LLMRequest): ReadonlyMap<string, Custom> => {
|
||||||
|
const formats = request.model.capabilities?.tools?.freeform
|
||||||
|
const added = request.messages.flatMap((message) => toolsUpdate(message)?.add ?? [])
|
||||||
|
return new Map(
|
||||||
|
flattenTools([...request.tools, ...added]).flatMap((tool) => {
|
||||||
|
const custom = resolve(tool, formats)
|
||||||
return custom ? [[tool.name, custom] as const] : []
|
return custom ? [[tool.name, custom] as const] : []
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
/** The format's grammar, or `undefined` for unconstrained text. */
|
|
||||||
export const grammar = (format: Freeform) =>
|
|
||||||
format.type === "text"
|
|
||||||
? undefined
|
|
||||||
: { syntax: format.type, definition: format.type === "regex" ? format.pattern : format.grammar }
|
|
||||||
|
|
||||||
/** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
|
|
||||||
export const toRaw = (custom: Custom, input: unknown) => {
|
|
||||||
const value = isRecord(input) ? input[custom.field] : undefined
|
|
||||||
return typeof value === "string" ? value : encodeJson(input ?? {})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
|
/** The grammar to send, or `undefined` for unconstrained text. */
|
||||||
export const fromRaw = (custom: Custom | undefined, raw: string) => encodeJson({ [field(custom)]: raw })
|
export const grammar = (custom: Custom) => {
|
||||||
|
if (custom.options)
|
||||||
|
return custom.options.grammar === undefined
|
||||||
|
? undefined
|
||||||
|
: { syntax: "lark" as const, definition: custom.options.grammar }
|
||||||
|
const format = custom.format
|
||||||
|
if (format.type === "text") return undefined
|
||||||
|
return { syntax: format.type, definition: format.type === "regex" ? format.pattern : format.grammar }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The custom tool's description, with how to write the line when the tool has other parameters. */
|
||||||
|
export const description = (tool: ToolDefinition, custom: Custom) =>
|
||||||
|
custom.options ? `${tool.description}\n\n${custom.options.description}` : tool.description
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw text replayed for a past call: its field after a line for the other parameters, or the whole input as JSON when
|
||||||
|
* the field is not a string. The line the model wrote, saved as `header`, replays as is while it still says the same,
|
||||||
|
* so the prompt cache holds; otherwise, as for a call another model made, a fresh line is written.
|
||||||
|
*/
|
||||||
|
export const toRaw = (custom: Custom, input: unknown, header?: unknown) => {
|
||||||
|
const value = isRecord(input) ? input[custom.field] : undefined
|
||||||
|
if (typeof value !== "string" || !isRecord(input)) return encodeJson(input ?? {})
|
||||||
|
const fields = custom.options?.fields ?? []
|
||||||
|
const options = encodeJson(pick(fields, input))
|
||||||
|
if (options === "{}") return value
|
||||||
|
const saved = typeof header === "string" ? Option.getOrUndefined(decodeLine(header)) : undefined
|
||||||
|
const same = saved !== undefined && encodeJson(pick(fields, saved)) === options
|
||||||
|
return `${same ? header : `${PREFIX} ${options}`}\n${value}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const pick = (fields: ReadonlyArray<OptionField>, input: Readonly<Record<string, unknown>>) =>
|
||||||
|
Object.fromEntries(fields.flatMap((item) => (input[item.name] === undefined ? [] : [[item.name, input[item.name]]])))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSON arguments for a raw call, with its line as `header`. A call to an undeclared custom tool fills `input`. A line
|
||||||
|
* that isn't a JSON object stays raw text, which fails as malformed JSON; the tool's schema checks the rest.
|
||||||
|
*/
|
||||||
|
export const parse = (custom: Custom | undefined, raw: string) => {
|
||||||
|
const end = raw.indexOf("\n")
|
||||||
|
if (!custom?.options || !raw.startsWith(PREFIX) || end === -1) return { input: encodeJson({ [field(custom)]: raw }) }
|
||||||
|
const header = raw.slice(0, end)
|
||||||
|
const options = Option.getOrUndefined(decodeLine(header))
|
||||||
|
if (options === undefined) return { input: raw }
|
||||||
|
return { input: encodeJson({ ...options, [custom.field]: raw.slice(end + 1) }), header }
|
||||||
|
}
|
||||||
|
|
||||||
|
const decodeLine = (header: string) => decodeArguments(header.slice(PREFIX.length))
|
||||||
|
|
||||||
const field = (custom: Custom | undefined) => custom?.field ?? "input"
|
const field = (custom: Custom | undefined) => custom?.field ?? "input"
|
||||||
|
|
||||||
|
|
@ -62,25 +221,59 @@ const STREAM_END = '"}'
|
||||||
const decodeArguments = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)))
|
const decodeArguments = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
|
* Close the JSON fragment of each open custom call, and set its input from the raw text. With a `final` raw input
|
||||||
* decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
|
* that the streamed fragments don't decode to, the final one sets the input and the streamed one stays unclosed. A
|
||||||
|
* line the model wrote goes in the call's provider metadata as `header`, so it replays exactly.
|
||||||
*/
|
*/
|
||||||
export const close = <K extends string | number>(
|
export const close = <K extends string | number>(
|
||||||
tools: ToolStream.State<K>,
|
tools: ToolStream.State<K>,
|
||||||
keys: Iterable<K>,
|
keys: Iterable<K>,
|
||||||
final?: { readonly custom: Custom | undefined; readonly raw: string },
|
custom: ReadonlyMap<string, Custom>,
|
||||||
|
metadataKey: string,
|
||||||
|
final?: string,
|
||||||
) =>
|
) =>
|
||||||
[...keys].reduce<{ readonly tools: ToolStream.State<K>; readonly events: ReadonlyArray<LLMEvent> }>(
|
[...keys].reduce<{ readonly tools: ToolStream.State<K>; readonly events: ReadonlyArray<LLMEvent> }>(
|
||||||
(result, key) => {
|
(result, key) => {
|
||||||
const pending = result.tools[key]
|
const pending = result.tools[key]
|
||||||
const streamed = pending && Option.getOrUndefined(decodeArguments(`${pending.input}${STREAM_END}`))
|
if (!pending) return result
|
||||||
if (!pending || (final !== undefined && streamed?.[field(final.custom)] !== final.raw)) return result
|
const definition = custom.get(pending.name)
|
||||||
|
const streamed = Option.getOrUndefined(decodeArguments(`${pending.input}${STREAM_END}`))?.[field(definition)]
|
||||||
|
if (final !== undefined && streamed !== final)
|
||||||
|
return {
|
||||||
|
tools: { ...result.tools, [key]: settle(pending, definition, metadataKey, final) },
|
||||||
|
events: result.events,
|
||||||
|
}
|
||||||
const appended = ToolStream.append(result.tools, key, STREAM_END)
|
const appended = ToolStream.append(result.tools, key, STREAM_END)
|
||||||
return appended ? { tools: appended.tools, events: [...result.events, ...appended.events] } : result
|
if (!appended) return result
|
||||||
|
return {
|
||||||
|
tools:
|
||||||
|
typeof streamed === "string"
|
||||||
|
? { ...appended.tools, [key]: settle(appended.tool, definition, metadataKey, streamed) }
|
||||||
|
: appended.tools,
|
||||||
|
events: [...result.events, ...appended.events],
|
||||||
|
}
|
||||||
},
|
},
|
||||||
{ tools, events: [] },
|
{ tools, events: [] },
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const settle = (
|
||||||
|
tool: ToolStream.PendingTool,
|
||||||
|
custom: Custom | undefined,
|
||||||
|
metadataKey: string,
|
||||||
|
raw: string,
|
||||||
|
): ToolStream.PendingTool => {
|
||||||
|
const parsed = parse(custom, raw)
|
||||||
|
if (parsed.header === undefined) return { ...tool, input: parsed.input }
|
||||||
|
return {
|
||||||
|
...tool,
|
||||||
|
input: parsed.input,
|
||||||
|
providerMetadata: {
|
||||||
|
...tool.providerMetadata,
|
||||||
|
[metadataKey]: { ...tool.providerMetadata?.[metadataKey], header: parsed.header },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Provider metadata marking a call that arrived as a custom tool call. */
|
/** Provider metadata marking a call that arrived as a custom tool call. */
|
||||||
export const metadata = (itemId: string, custom: boolean) => (custom ? { itemId, custom: true } : { itemId })
|
export const metadata = (itemId: string, custom: boolean) => (custom ? { itemId, custom: true } : { itemId })
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,9 +6,10 @@ import { Auth } from "../route/auth.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { Protocol } from "../route/protocol.js"
|
import { Protocol } from "../route/protocol.js"
|
||||||
import { HttpTransport } from "../route/transport/index.js"
|
import { HttpTransport } from "../route/transport/index.js"
|
||||||
import type { LLMRequest, ToolDefinition, ToolEntry } from "../schema/index.js"
|
import type { LLMRequest, ToolChanges, ToolDefinition, ToolEntry } from "../schema/index.js"
|
||||||
import { requestTTL } from "../cache-policy.js"
|
import { requestTTL } from "../cache-policy.js"
|
||||||
import { resolveEffortUpdates } from "../effort-updates.js"
|
import { resolveEffortUpdates } from "../effort-updates.js"
|
||||||
|
import { addsTools, toolUpdateKinds, type ToolUpdateEncoding } from "../tool-updates.js"
|
||||||
import { OpenResponses } from "./open-responses.js"
|
import { OpenResponses } from "./open-responses.js"
|
||||||
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
|
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
|
||||||
import { JsonObject, lenient, optionalArray, optionalNull, ProviderShared } from "./shared.js"
|
import { JsonObject, lenient, optionalArray, optionalNull, ProviderShared } from "./shared.js"
|
||||||
|
|
@ -173,6 +174,25 @@ const supportsEffortUpdates = (request: LLMRequest) => {
|
||||||
return match !== null && Number(match[1]) >= 6
|
return match !== null && Number(match[1]) >= 6
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `additional_tools` adds tools, and redefines one by name only when that one was declared through `additional_tools`
|
||||||
|
// too. So a model whose `tools.updates` includes "add" gets every tool the request declares in a leading
|
||||||
|
// `additional_tools` item instead of top-level `tools`; without "add" nothing goes in place. Later additions and
|
||||||
|
// redefinitions ("replace") are later items. The API can't withdraw a tool, so a removal ("remove") is announced in
|
||||||
|
// a developer message and the tool stays declared. Hosted tools stay in `tools`, since the model doesn't use one
|
||||||
|
// declared in `additional_tools`, and changing one folds.
|
||||||
|
const toolUpdates = {
|
||||||
|
kinds: ["add", "remove", "replace"],
|
||||||
|
placeable: (request) => declaresInPlace(request),
|
||||||
|
declarable: (tool) => !isHostedTool(tool),
|
||||||
|
} satisfies ToolUpdateEncoding
|
||||||
|
|
||||||
|
const isHostedTool = (tool: ToolEntry) => tool.type === "tool" && tool.native !== undefined
|
||||||
|
|
||||||
|
// Automatic `context_management` compaction drops developer messages, removal notices included, while the tools stay
|
||||||
|
// declared, so tool changes fold alongside it.
|
||||||
|
const declaresInPlace = (request: LLMRequest) =>
|
||||||
|
request.providerOptions?.contextManagement === undefined && toolUpdateKinds(request).includes("add")
|
||||||
|
|
||||||
const nativeImageToolInput = (tool: ToolDefinition) => {
|
const nativeImageToolInput = (tool: ToolDefinition) => {
|
||||||
const native = tool.native?.openai
|
const native = tool.native?.openai
|
||||||
return ProviderShared.isRecord(native) && native.type === "image_generation" ? native : undefined
|
return ProviderShared.isRecord(native) && native.type === "image_generation" ? native : undefined
|
||||||
|
|
@ -216,11 +236,59 @@ const lowerToolEntry = Effect.fnUntraced(function* (
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const lowerTools = (request: LLMRequest) => {
|
// Lowers one request's tool updates, in message order. Every `additional_tools` item after the first is preceded by
|
||||||
const custom = OpenAIFreeform.tools(request)
|
// a hint that it adds to the tools declared before it, naming tools removed and not declared again since. Without
|
||||||
return Effect.forEach(request.tools, (tool) => lowerToolEntry(tool, custom))
|
// it, models can read the latest item as the whole set.
|
||||||
|
const toolChangeLowering = (declaredInPlace: boolean, custom: ReadonlyMap<string, OpenAIFreeform.Custom>) => {
|
||||||
|
let declared = declaredInPlace
|
||||||
|
const unavailable = new Set<string>()
|
||||||
|
return Effect.fnUntraced(function* (changes: ToolChanges) {
|
||||||
|
changes.add.forEach((tool) => unavailable.delete(tool.name))
|
||||||
|
const hint = declared && changes.add.length > 0 ? [developer(incrementalNotice([...unavailable]))] : []
|
||||||
|
const additions =
|
||||||
|
changes.add.length === 0
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
{
|
||||||
|
type: "additional_tools" as const,
|
||||||
|
role: "developer" as const,
|
||||||
|
tools: yield* Effect.forEach(changes.add, (tool) => lowerToolEntry(tool, custom)),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
declared = declared || changes.add.length > 0
|
||||||
|
changes.remove.forEach((name) => unavailable.add(name))
|
||||||
|
return [...hint, ...additions, ...(changes.remove.length === 0 ? [] : [developer(removalNotice(changes.remove))])]
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const developer = (content: string) => ({ type: "message" as const, role: "developer" as const, content })
|
||||||
|
|
||||||
|
const incrementalNotice = (unavailable: ReadonlyArray<string>) =>
|
||||||
|
[
|
||||||
|
"Tool update: the tools below are added to the ones you already have. Earlier tools stay available unless marked unavailable, and a tool declared again replaces its earlier definition.",
|
||||||
|
...(unavailable.length === 0 ? [] : [`Still unavailable: ${unavailable.join(", ")}.`]),
|
||||||
|
].join("\n")
|
||||||
|
|
||||||
|
const removalNotice = (names: ReadonlyArray<string>) =>
|
||||||
|
`These tools are no longer available. Do not call them: ${names.join(", ")}.`
|
||||||
|
|
||||||
|
// The leading declaration: top-level `tools`, or a leading `additional_tools` item on models that add tools in place.
|
||||||
|
const lowerToolLayout = Effect.fnUntraced(function* (
|
||||||
|
request: LLMRequest,
|
||||||
|
custom: ReadonlyMap<string, OpenAIFreeform.Custom>,
|
||||||
|
) {
|
||||||
|
const lower = (tools: ReadonlyArray<ToolEntry>) => Effect.forEach(tools, (tool) => lowerToolEntry(tool, custom))
|
||||||
|
const declared = declaresInPlace(request) ? request.tools.filter((tool) => !isHostedTool(tool)) : []
|
||||||
|
const top = declared.length === 0 ? request.tools : request.tools.filter(isHostedTool)
|
||||||
|
return {
|
||||||
|
head:
|
||||||
|
declared.length === 0
|
||||||
|
? []
|
||||||
|
: [{ type: "additional_tools" as const, role: "developer" as const, tools: yield* lower(declared) }],
|
||||||
|
tools: top.length === 0 ? undefined : yield* lower(top),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
const lowerToolChoice = (
|
const lowerToolChoice = (
|
||||||
toolChoice: NonNullable<LLMRequest["toolChoice"]>,
|
toolChoice: NonNullable<LLMRequest["toolChoice"]>,
|
||||||
tools: ReadonlyArray<ToolEntry>,
|
tools: ReadonlyArray<ToolEntry>,
|
||||||
|
|
@ -245,8 +313,14 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
|
||||||
const updates = resolveEffortUpdates(request, options.reasoningEffort)
|
const updates = resolveEffortUpdates(request, options.reasoningEffort)
|
||||||
const generation = OpenResponses.lowerGeneration(request, { ...options, reasoningEffort: updates.effort })
|
const generation = OpenResponses.lowerGeneration(request, { ...options, reasoningEffort: updates.effort })
|
||||||
const custom = OpenAIFreeform.tools(request)
|
const custom = OpenAIFreeform.tools(request)
|
||||||
|
const layout = yield* lowerToolLayout(request, custom)
|
||||||
|
const conversation = yield* OpenResponses.lowerConversation(updates.request, {
|
||||||
|
...adapter,
|
||||||
|
lowerToolChanges: toolChangeLowering(layout.head.length > 0, custom),
|
||||||
|
})
|
||||||
return {
|
return {
|
||||||
...(yield* OpenResponses.lowerConversation(updates.request, adapter)),
|
model: conversation.model,
|
||||||
|
input: [...layout.head, ...conversation.input],
|
||||||
...generation,
|
...generation,
|
||||||
...Cache.openAIRequestTTL(requestTTL(request)),
|
...Cache.openAIRequestTTL(requestTTL(request)),
|
||||||
...(generation.reasoning || reasoning.reasoningMode || reasoning.reasoningContext
|
...(generation.reasoning || reasoning.reasoningMode || reasoning.reasoningContext
|
||||||
|
|
@ -259,9 +333,9 @@ const fromRequest = Effect.fn("OpenAIResponses.fromRequest")(function* (request:
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
context_management: management?.map((edit) => ({ type: edit.type, compact_threshold: edit.compactThreshold })),
|
context_management: management?.map((edit) => ({ type: edit.type, compact_threshold: edit.compactThreshold })),
|
||||||
tools: request.tools.length === 0 ? undefined : yield* lowerTools(request),
|
tools: layout.tools,
|
||||||
tool_choice:
|
tool_choice:
|
||||||
request.tools.length === 0
|
request.tools.length === 0 && !addsTools(request)
|
||||||
? undefined
|
? undefined
|
||||||
: (OpenResponses.allowedToolChoice(options, custom) ??
|
: (OpenResponses.allowedToolChoice(options, custom) ??
|
||||||
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools, custom) : undefined)),
|
(request.toolChoice ? yield* lowerToolChoice(request.toolChoice, request.tools, custom) : undefined)),
|
||||||
|
|
@ -334,6 +408,8 @@ export const protocol = Protocol.make({
|
||||||
: ProviderShared.eventError(ADAPTER, `${event.type} is missing item_id`)
|
: ProviderShared.eventError(ADAPTER, `${event.type} is missing item_id`)
|
||||||
}),
|
}),
|
||||||
supportsEffortUpdates,
|
supportsEffortUpdates,
|
||||||
|
toolUpdates,
|
||||||
|
namespaces: true,
|
||||||
})
|
})
|
||||||
|
|
||||||
const endpoint = Endpoint.path<OpenAIResponsesBody>(PATH, { baseURL: DEFAULT_BASE_URL })
|
const endpoint = Endpoint.path<OpenAIResponsesBody>(PATH, { baseURL: DEFAULT_BASE_URL })
|
||||||
|
|
@ -350,7 +426,10 @@ export const transport = channelTransport({
|
||||||
|
|
||||||
export const route = Route.make({
|
export const route = Route.make({
|
||||||
compact: {
|
compact: {
|
||||||
endpoint: ResponsesCompaction.make(adapter, lowerTools),
|
endpoint: ResponsesCompaction.make(adapter, (request) => {
|
||||||
|
const custom = OpenAIFreeform.tools(request)
|
||||||
|
return Effect.forEach(request.tools, (tool) => lowerToolEntry(tool, custom))
|
||||||
|
}),
|
||||||
trigger: ResponsesCheckpoint.make(checkpointBody),
|
trigger: ResponsesCheckpoint.make(checkpointBody),
|
||||||
},
|
},
|
||||||
id: ADAPTER,
|
id: ADAPTER,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { Effect, Schema } from "effect"
|
import { Effect, Schema } from "effect"
|
||||||
import type { HttpClientResponse } from "effect/http"
|
import type { HttpClientResponse } from "effect/http"
|
||||||
import type { Status } from "../generation.js"
|
|
||||||
import { Media } from "../media.js"
|
import { Media } from "../media.js"
|
||||||
import { MediaProtocol } from "../route/media-protocol.js"
|
import { MediaProtocol } from "../route/media-protocol.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
|
|
@ -43,7 +42,8 @@ export type Request = VideoRequest<VideoModel<OpenRouterVideoOptions>>
|
||||||
// 2. Token and response schemas
|
// 2. Token and response schemas
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const Token = Schema.Struct({ id: Schema.String })
|
/** The provider's job ID; it is all a later status, result or cancel call needs. */
|
||||||
|
export const Token = Schema.String
|
||||||
export type Token = Schema.Schema.Type<typeof Token>
|
export type Token = Schema.Schema.Type<typeof Token>
|
||||||
|
|
||||||
const StartResponse = Schema.Struct({ id: Schema.String, status: optionalNull(Schema.String) })
|
const StartResponse = Schema.Struct({ id: Schema.String, status: optionalNull(Schema.String) })
|
||||||
|
|
@ -68,13 +68,13 @@ const Job = Schema.Struct({
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const STATUS = {
|
const STATUS = {
|
||||||
pending: "queued",
|
pending: "running",
|
||||||
in_progress: "running",
|
in_progress: "running",
|
||||||
completed: "completed",
|
completed: "completed",
|
||||||
failed: "failed",
|
failed: "failed",
|
||||||
cancelled: "cancelled",
|
cancelled: "cancelled",
|
||||||
expired: "expired",
|
expired: "expired",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 4. Body construction
|
// 4. Body construction
|
||||||
|
|
@ -133,8 +133,8 @@ const resolution = (value: string) => (/^\dk$/.test(value) ? value.toUpperCase()
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
||||||
token: { id: value.id },
|
token: value.id,
|
||||||
snapshot: { id: value.id, status: MediaProtocol.status(STATUS, value.status ?? "pending") },
|
snapshot: { id: value.id, ...MediaProtocol.status(STATUS, value.status ?? "pending") },
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const decodeJob = route.decodeJson(Job)
|
const decodeJob = route.decodeJson(Job)
|
||||||
|
|
@ -144,7 +144,7 @@ const decodeStatus = Effect.fn("OpenRouterVideo.decodeStatus")(function* (
|
||||||
context: MediaProtocol.PollContext<Token>,
|
context: MediaProtocol.PollContext<Token>,
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeJob(response)
|
const output = yield* decodeJob(response)
|
||||||
return { id: context.token.id, status: MediaProtocol.status(STATUS, output.value.status) }
|
return { id: context.token, ...MediaProtocol.status(STATUS, output.value.status) }
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (
|
const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (
|
||||||
|
|
@ -153,8 +153,8 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeJob(response)
|
const output = yield* decodeJob(response)
|
||||||
const job = output.value
|
const job = output.value
|
||||||
const status = MediaProtocol.status(STATUS, job.status)
|
const status = MediaProtocol.state(STATUS, job.status)
|
||||||
if (status === "queued" || status === "running") return yield* output.pending(context.token.id)
|
if (status === "running") return yield* output.pending(context.token)
|
||||||
if (status === "failed") {
|
if (status === "failed") {
|
||||||
const message = `${route.name} generation failed${job.error ? `: ${job.error}` : ""}`
|
const message = `${route.name} generation failed${job.error ? `: ${job.error}` : ""}`
|
||||||
if (job.error && /content policy|moderat/i.test(job.error)) return yield* output.contentPolicy(message)
|
if (job.error && /content policy|moderat/i.test(job.error)) return yield* output.contentPolicy(message)
|
||||||
|
|
@ -163,18 +163,18 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (
|
||||||
if (status !== "completed")
|
if (status !== "completed")
|
||||||
return yield* output.ended(
|
return yield* output.ended(
|
||||||
status,
|
status,
|
||||||
`${route.name} job ${context.token.id} ${status}${job.error ? `: ${job.error}` : ""}`,
|
`${route.name} job ${context.token} ${status}${job.error ? `: ${job.error}` : ""}`,
|
||||||
)
|
)
|
||||||
const urls = job.unsigned_urls ?? []
|
const urls = job.unsigned_urls ?? []
|
||||||
if (urls.length === 0) return yield* output.invalid(`${route.name} completed without a video URL`)
|
if (urls.length === 0) return yield* output.invalid(`${route.name} completed without a video URL`)
|
||||||
// The content URLs are OpenRouter's own and only download with the API key.
|
// The content URLs are OpenRouter's own and only download with the API key.
|
||||||
const videos = yield* Effect.forEach(urls, (url) =>
|
const videos = yield* Effect.forEach(urls, (url) =>
|
||||||
context.headers(url).pipe(
|
context.credentials(url).pipe(
|
||||||
Effect.map((headers) =>
|
Effect.map((credentials) =>
|
||||||
Media.url(url, {
|
Media.url(url, {
|
||||||
mediaType: "video/mp4",
|
mediaType: "video/mp4",
|
||||||
expiresAt: job.expires_at === undefined || job.expires_at === null ? undefined : job.expires_at * 1000,
|
expiresAt: job.expires_at === undefined || job.expires_at === null ? undefined : job.expires_at * 1000,
|
||||||
headers,
|
...credentials,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
@ -183,7 +183,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (
|
||||||
videos,
|
videos,
|
||||||
providerMetadata: {
|
providerMetadata: {
|
||||||
openrouter: {
|
openrouter: {
|
||||||
id: context.token.id,
|
id: context.token,
|
||||||
generationId: job.generation_id ?? undefined,
|
generationId: job.generation_id ?? undefined,
|
||||||
cost: job.usage?.cost ?? undefined,
|
cost: job.usage?.cost ?? undefined,
|
||||||
isByok: job.usage?.is_byok ?? undefined,
|
isByok: job.usage?.is_byok ?? undefined,
|
||||||
|
|
@ -196,7 +196,7 @@ const decodeResult = Effect.fn("OpenRouterVideo.decodeResult")(function* (
|
||||||
// 6. Protocol and route
|
// 6. Protocol and route
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const jobPath = (token: Token) => `${PATH}/${encodeURIComponent(token.id)}`
|
const jobPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}`
|
||||||
|
|
||||||
// OpenRouter has no cancel endpoint; `cancelled` only appears when it stops a job itself.
|
// OpenRouter has no cancel endpoint; `cancelled` only appears when it stops a job itself.
|
||||||
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
||||||
|
|
@ -207,7 +207,7 @@ export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(rout
|
||||||
})
|
})
|
||||||
|
|
||||||
export const model = (input: MediaRoute.ModelInput) =>
|
export const model = (input: MediaRoute.ModelInput) =>
|
||||||
VideoModel.fromRoute<OpenRouterVideoOptions, Token>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
|
VideoModel.fromRoute<OpenRouterVideoOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
|
||||||
|
|
||||||
export const OpenRouterVideo = {
|
export const OpenRouterVideo = {
|
||||||
protocol,
|
protocol,
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { Duration, Effect, Schema } from "effect"
|
import { Duration, Effect, Schema } from "effect"
|
||||||
import type { HttpClientResponse } from "effect/http"
|
import type { HttpClientResponse } from "effect/http"
|
||||||
import type { Status } from "../generation.js"
|
|
||||||
import { Media } from "../media.js"
|
import { Media } from "../media.js"
|
||||||
import { MediaProtocol } from "../route/media-protocol.js"
|
import { MediaProtocol } from "../route/media-protocol.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
|
|
@ -47,7 +46,8 @@ export type Request = VideoRequest<VideoModel<SeedanceVideoOptions>>
|
||||||
// 2. Token and response schemas
|
// 2. Token and response schemas
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const Token = Schema.Struct({ taskID: Schema.String })
|
/** The provider's job ID; it is all a later status, result or cancel call needs. */
|
||||||
|
export const Token = Schema.String
|
||||||
export type Token = Schema.Schema.Type<typeof Token>
|
export type Token = Schema.Schema.Type<typeof Token>
|
||||||
|
|
||||||
const StartResponse = Schema.Struct({ id: Schema.String })
|
const StartResponse = Schema.Struct({ id: Schema.String })
|
||||||
|
|
@ -88,13 +88,13 @@ const Task = Schema.Struct({
|
||||||
})
|
})
|
||||||
|
|
||||||
const STATUS = {
|
const STATUS = {
|
||||||
queued: "queued",
|
queued: "running",
|
||||||
running: "running",
|
running: "running",
|
||||||
succeeded: "completed",
|
succeeded: "completed",
|
||||||
failed: "failed",
|
failed: "failed",
|
||||||
cancelled: "cancelled",
|
cancelled: "cancelled",
|
||||||
expired: "expired",
|
expired: "expired",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 3. Failures
|
// 3. Failures
|
||||||
|
|
@ -194,8 +194,8 @@ const make = (provider: Provider) => {
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
||||||
token: { taskID: value.id },
|
token: value.id,
|
||||||
snapshot: { id: value.id, status: "queued" },
|
snapshot: { id: value.id, status: "running" },
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const decodeTask = route.decodeJson(Task)
|
const decodeTask = route.decodeJson(Task)
|
||||||
|
|
@ -205,7 +205,7 @@ const make = (provider: Provider) => {
|
||||||
context: MediaProtocol.PollContext<Token>,
|
context: MediaProtocol.PollContext<Token>,
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTask(response)
|
const output = yield* decodeTask(response)
|
||||||
return { id: context.token.taskID, status: MediaProtocol.status(STATUS, output.value.status) }
|
return { id: context.token, ...MediaProtocol.status(STATUS, output.value.status) }
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeResult = Effect.fn("SeedanceVideo.decodeResult")(function* (
|
const decodeResult = Effect.fn("SeedanceVideo.decodeResult")(function* (
|
||||||
|
|
@ -214,8 +214,8 @@ const make = (provider: Provider) => {
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeTask(response)
|
const output = yield* decodeTask(response)
|
||||||
const task = output.value
|
const task = output.value
|
||||||
const status = MediaProtocol.status(STATUS, task.status)
|
const status = MediaProtocol.state(STATUS, task.status)
|
||||||
if (status === "queued" || status === "running") return yield* output.pending(context.token.taskID)
|
if (status === "running") return yield* output.pending(context.token)
|
||||||
if (status === "failed") {
|
if (status === "failed") {
|
||||||
const code = task.error?.code ?? undefined
|
const code = task.error?.code ?? undefined
|
||||||
const detail = task.error?.message ?? undefined
|
const detail = task.error?.message ?? undefined
|
||||||
|
|
@ -224,9 +224,8 @@ const make = (provider: Provider) => {
|
||||||
return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, code?.split(".")[0]))
|
return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, code?.split(".")[0]))
|
||||||
}
|
}
|
||||||
if (status === "cancelled")
|
if (status === "cancelled")
|
||||||
return yield* output.ended("cancelled", `${route.name} task ${context.token.taskID} was cancelled`)
|
return yield* output.ended("cancelled", `${route.name} task ${context.token} was cancelled`)
|
||||||
if (status === "expired")
|
if (status === "expired") return yield* output.ended("expired", `${route.name} task ${context.token} expired`)
|
||||||
return yield* output.ended("expired", `${route.name} task ${context.token.taskID} expired`)
|
|
||||||
const videoURL = task.content?.video_url ?? undefined
|
const videoURL = task.content?.video_url ?? undefined
|
||||||
if (videoURL === undefined) return yield* output.invalid(`${route.name} completed without a video URL`)
|
if (videoURL === undefined) return yield* output.invalid(`${route.name} completed without a video URL`)
|
||||||
const duration = durationSeconds(task)
|
const duration = durationSeconds(task)
|
||||||
|
|
@ -254,7 +253,7 @@ const make = (provider: Provider) => {
|
||||||
},
|
},
|
||||||
providerMetadata: {
|
providerMetadata: {
|
||||||
[provider]: {
|
[provider]: {
|
||||||
taskId: context.token.taskID,
|
taskId: context.token,
|
||||||
model: task.model ?? undefined,
|
model: task.model ?? undefined,
|
||||||
seed: task.seed ?? undefined,
|
seed: task.seed ?? undefined,
|
||||||
ratio: task.ratio ?? undefined,
|
ratio: task.ratio ?? undefined,
|
||||||
|
|
@ -272,7 +271,7 @@ const make = (provider: Provider) => {
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
const taskPath = (token: Token) => `${PATH}/${token.taskID}`
|
const taskPath = (token: Token) => `${PATH}/${encodeURIComponent(token)}`
|
||||||
|
|
||||||
// DELETE cancels a queued task. Ark refuses it for a running task, and deletes the record of a finished one.
|
// DELETE cancels a queued task. Ark refuses it for a running task, and deletes the record of a finished one.
|
||||||
const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
||||||
|
|
@ -284,7 +283,7 @@ const make = (provider: Provider) => {
|
||||||
})
|
})
|
||||||
|
|
||||||
const model = (input: MediaRoute.ModelInput) =>
|
const model = (input: MediaRoute.ModelInput) =>
|
||||||
VideoModel.fromRoute<SeedanceVideoOptions, Token>(
|
VideoModel.fromRoute<SeedanceVideoOptions>(
|
||||||
{
|
{
|
||||||
protocol,
|
protocol,
|
||||||
baseURL: provider === "volcengine" ? VOLCENGINE_BASE_URL : BYTEPLUS_BASE_URL,
|
baseURL: provider === "volcengine" ? VOLCENGINE_BASE_URL : BYTEPLUS_BASE_URL,
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,8 @@ import {
|
||||||
AssistantMessage,
|
AssistantMessage,
|
||||||
type LLMRequest,
|
type LLMRequest,
|
||||||
Message,
|
Message,
|
||||||
|
SystemMessage,
|
||||||
|
ToolChoice,
|
||||||
ToolDefinition,
|
ToolDefinition,
|
||||||
ToolMessage,
|
ToolMessage,
|
||||||
type ContentPart,
|
type ContentPart,
|
||||||
|
|
@ -24,6 +26,7 @@ import {
|
||||||
} from "../schema/index.js"
|
} from "../schema/index.js"
|
||||||
import { Json, decodeJson, encodeJson } from "../utils/json.js"
|
import { Json, decodeJson, encodeJson } from "../utils/json.js"
|
||||||
import { isRecord } from "../utils/record.js"
|
import { isRecord } from "../utils/record.js"
|
||||||
|
import { foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js"
|
||||||
export { Json, decodeJson, encodeJson, isRecord }
|
export { Json, decodeJson, encodeJson, isRecord }
|
||||||
|
|
||||||
const isJson = Schema.is(Schema.Json)
|
const isJson = Schema.is(Schema.Json)
|
||||||
|
|
@ -362,7 +365,8 @@ export const unsupportedOperation = (input: {
|
||||||
/**
|
/**
|
||||||
* Lower namespaces to flat definitions for protocols without a native
|
* Lower namespaces to flat definitions for protocols without a native
|
||||||
* namespace construct. Leaf names join their namespace path with `_` because
|
* namespace construct. Leaf names join their namespace path with `_` because
|
||||||
* `.` is not broadly accepted in provider tool names.
|
* `.` is not broadly accepted in provider tool names. A no-op on tools `flattenRequest` already flattened; adapters call
|
||||||
|
* it to type their tools.
|
||||||
*/
|
*/
|
||||||
export const flattenTools = (tools: ReadonlyArray<ToolEntry>, path: ReadonlyArray<string> = []) => {
|
export const flattenTools = (tools: ReadonlyArray<ToolEntry>, path: ReadonlyArray<string> = []) => {
|
||||||
const flat = tools.flatMap((tool): ReadonlyArray<ToolDefinition> => {
|
const flat = tools.flatMap((tool): ReadonlyArray<ToolDefinition> => {
|
||||||
|
|
@ -373,28 +377,84 @@ export const flattenTools = (tools: ReadonlyArray<ToolEntry>, path: ReadonlyArra
|
||||||
return [...new Map(flat.map((tool) => [tool.name, tool])).values()]
|
return [...new Map(flat.map((tool) => [tool.name, tool])).values()]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const flattenToolRequest = (request: LLMRequest) => {
|
/**
|
||||||
|
* The request as a protocol without native namespaces sees it: tools, tool updates, past calls and a forced choice all
|
||||||
|
* use flattened names. `Protocol.make` applies it before `body.from` for such protocols, so adapters only see flat
|
||||||
|
* requests.
|
||||||
|
*/
|
||||||
|
export const flattenRequest = (request: LLMRequest): LLMRequest => {
|
||||||
|
const all = [...request.tools, ...request.messages.flatMap((message) => toolsUpdate(message)?.add ?? [])]
|
||||||
|
const declared = new Set(flattenTools(all).map((tool) => tool.name))
|
||||||
|
const flatten = <Part extends ToolCallPart | ToolResultPart>(part: Part) => flattenToolName(part, declared)
|
||||||
|
// A tool update that redefines a namespace drops the tools it leaves out, which only the namespace shows, so name
|
||||||
|
// them as explicit removals.
|
||||||
|
let tools = request.tools
|
||||||
const messages = request.messages.map((message) => {
|
const messages = request.messages.map((message) => {
|
||||||
|
if (message.role === "system" && message.tools !== undefined) {
|
||||||
|
const next = foldTools(tools, message.tools.add, message.tools.remove)
|
||||||
|
const remove = withdrawnTools(tools, next)
|
||||||
|
tools = next
|
||||||
|
return new SystemMessage({ ...message, tools: { add: flattenTools(message.tools.add), remove } })
|
||||||
|
}
|
||||||
if (message.role === "assistant") {
|
if (message.role === "assistant") {
|
||||||
const content = message.content.map((part) =>
|
const content = message.content.map((part) =>
|
||||||
part.type === "tool-call" || part.type === "tool-result" ? flattenToolName(part) : part,
|
part.type === "tool-call" || part.type === "tool-result" ? flatten(part) : part,
|
||||||
)
|
)
|
||||||
return sameParts(content, message.content) ? message : new AssistantMessage({ ...message, content })
|
return sameParts(content, message.content) ? message : new AssistantMessage({ ...message, content })
|
||||||
}
|
}
|
||||||
if (message.role !== "tool") return message
|
if (message.role !== "tool") return message
|
||||||
const content = message.content.map(flattenToolName)
|
const content = message.content.map(flatten)
|
||||||
return sameParts(content, message.content) ? message : new ToolMessage({ ...message, content })
|
return sameParts(content, message.content) ? message : new ToolMessage({ ...message, content })
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
|
...request,
|
||||||
tools: flattenTools(request.tools),
|
tools: flattenTools(request.tools),
|
||||||
request: messages.every((message, index) => message === request.messages[index])
|
messages,
|
||||||
? request
|
toolChoice: flattenToolChoice(request.toolChoice, all, declared),
|
||||||
: { ...request, messages },
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const flattenToolName = <Part extends ToolCallPart | ToolResultPart>(part: Part): Part =>
|
/**
|
||||||
part.namespace === undefined ? part : { ...part, name: `${part.namespace}_${part.name}`, namespace: undefined }
|
* @deprecated Routes without native namespaces already receive flattened requests; use `flattenRequest`. Removed in
|
||||||
|
* the next minor.
|
||||||
|
*/
|
||||||
|
export const flattenToolRequest = (request: LLMRequest) => {
|
||||||
|
const flat = flattenRequest(request)
|
||||||
|
return { tools: flattenTools(flat.tools), request: flat }
|
||||||
|
}
|
||||||
|
|
||||||
|
// A forced choice names a namespaced tool by its path (`crm.lookup`); point it at the flattened definition.
|
||||||
|
const flattenToolChoice = (
|
||||||
|
choice: LLMRequest["toolChoice"],
|
||||||
|
tools: ReadonlyArray<ToolEntry>,
|
||||||
|
declared: ReadonlySet<string>,
|
||||||
|
) => {
|
||||||
|
if (choice?.type !== "tool" || choice.name === undefined || declared.has(choice.name)) return choice
|
||||||
|
const name = new Map(namespacedPaths(tools)).get(choice.name)
|
||||||
|
return name === undefined ? choice : new ToolChoice({ ...choice, name })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each namespaced tool's path and the name flattenTools gives it.
|
||||||
|
const namespacedPaths = (
|
||||||
|
tools: ReadonlyArray<ToolEntry>,
|
||||||
|
path: ReadonlyArray<string> = [],
|
||||||
|
): ReadonlyArray<readonly [string, string]> =>
|
||||||
|
tools.flatMap((tool) => {
|
||||||
|
if (tool.type === "namespace") return namespacedPaths(tool.tools, [...path, tool.name])
|
||||||
|
return path.length === 0 ? [] : [[[...path, tool.name].join("."), [...path, tool.name].join("_")] as const]
|
||||||
|
})
|
||||||
|
|
||||||
|
const flattenToolName = <Part extends ToolCallPart | ToolResultPart>(
|
||||||
|
part: Part,
|
||||||
|
declared: ReadonlySet<string>,
|
||||||
|
): Part => {
|
||||||
|
const flat = part.namespace === undefined ? part.name : `${part.namespace}_${part.name}`
|
||||||
|
// Models sometimes call names no tool declares, such as a Code Mode path like `a.b.c`. Several providers (OpenAI
|
||||||
|
// Chat Completions, Bedrock Converse) reject those characters when the call is replayed, so replace them. A
|
||||||
|
// declared name is kept as is, so a provider that accepts it sees calls under the tool's own name.
|
||||||
|
const name = declared.has(flat) ? flat : flat.replace(/[^a-zA-Z0-9_-]/g, "_") || "_"
|
||||||
|
return name === part.name && part.namespace === undefined ? part : { ...part, name, namespace: undefined }
|
||||||
|
}
|
||||||
|
|
||||||
const sameParts = (next: ReadonlyArray<ContentPart>, previous: ReadonlyArray<ContentPart>) =>
|
const sameParts = (next: ReadonlyArray<ContentPart>, previous: ReadonlyArray<ContentPart>) =>
|
||||||
next.every((part, index) => part === previous[index])
|
next.every((part, index) => part === previous[index])
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,8 @@ export function gatewayProtocol<Body, Event, State>(
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
supportsEffortUpdates: protocol.supportsEffortUpdates,
|
supportsEffortUpdates: protocol.supportsEffortUpdates,
|
||||||
|
toolUpdates: protocol.toolUpdates,
|
||||||
|
namespaces: protocol.namespaces,
|
||||||
sanitizer: protocol.sanitizer,
|
sanitizer: protocol.sanitizer,
|
||||||
stream: {
|
stream: {
|
||||||
event: protocol.stream.event,
|
event: protocol.stream.event,
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,30 @@ import {
|
||||||
type MediaUsage,
|
type MediaUsage,
|
||||||
type ProviderMetadata,
|
type ProviderMetadata,
|
||||||
} from "../../schema/index.js"
|
} from "../../schema/index.js"
|
||||||
import { ProviderShared } from "../shared.js"
|
import { knownString, ProviderShared } from "../shared.js"
|
||||||
import { MediaInput } from "./media-input.js"
|
import { MediaInput } from "./media-input.js"
|
||||||
|
|
||||||
const PROVIDER = ProviderID.make("google")
|
const PROVIDER = ProviderID.make("google")
|
||||||
|
|
||||||
|
export const SafetySetting = Schema.Struct({
|
||||||
|
category: knownString<
|
||||||
|
| "HARM_CATEGORY_UNSPECIFIED"
|
||||||
|
| "HARM_CATEGORY_HATE_SPEECH"
|
||||||
|
| "HARM_CATEGORY_DANGEROUS_CONTENT"
|
||||||
|
| "HARM_CATEGORY_HARASSMENT"
|
||||||
|
| "HARM_CATEGORY_SEXUALLY_EXPLICIT"
|
||||||
|
| "HARM_CATEGORY_CIVIC_INTEGRITY"
|
||||||
|
>(),
|
||||||
|
threshold: knownString<
|
||||||
|
| "HARM_BLOCK_THRESHOLD_UNSPECIFIED"
|
||||||
|
| "BLOCK_LOW_AND_ABOVE"
|
||||||
|
| "BLOCK_MEDIUM_AND_ABOVE"
|
||||||
|
| "BLOCK_ONLY_HIGH"
|
||||||
|
| "BLOCK_NONE"
|
||||||
|
| "OFF"
|
||||||
|
>(),
|
||||||
|
})
|
||||||
|
|
||||||
const UsageMetadata = Schema.Struct({
|
const UsageMetadata = Schema.Struct({
|
||||||
promptTokenCount: Schema.optional(Schema.Number),
|
promptTokenCount: Schema.optional(Schema.Number),
|
||||||
candidatesTokenCount: Schema.optional(Schema.Number),
|
candidatesTokenCount: Schema.optional(Schema.Number),
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { Effect, Schema, Stream } from "effect"
|
import { Effect, Schema } from "effect"
|
||||||
import {
|
import {
|
||||||
AIError,
|
AIError,
|
||||||
InvalidProviderOutputError,
|
InvalidProviderOutputError,
|
||||||
|
|
@ -12,6 +12,7 @@ import {
|
||||||
} from "../../schema/index.js"
|
} from "../../schema/index.js"
|
||||||
import type { CompactOperation } from "../../route/client.js"
|
import type { CompactOperation } from "../../route/client.js"
|
||||||
import { stripEffortUpdates } from "../../effort-updates.js"
|
import { stripEffortUpdates } from "../../effort-updates.js"
|
||||||
|
import { foldToolUpdates } from "../../tool-updates.js"
|
||||||
import { Endpoint } from "../../route/endpoint.js"
|
import { Endpoint } from "../../route/endpoint.js"
|
||||||
import { RequestExecutor } from "../../route/executor.js"
|
import { RequestExecutor } from "../../route/executor.js"
|
||||||
import { HttpTransport } from "../../route/transport/index.js"
|
import { HttpTransport } from "../../route/transport/index.js"
|
||||||
|
|
@ -75,6 +76,8 @@ const Response = Schema.Struct({
|
||||||
role: Schema.Literal("assistant"),
|
role: Schema.Literal("assistant"),
|
||||||
content: Schema.Array(Text).check(Schema.isMinLength(1)),
|
content: Schema.Array(Text).check(Schema.isMinLength(1)),
|
||||||
}),
|
}),
|
||||||
|
// The system prompt sent as a developer message, echoed back; the next request leads with its own.
|
||||||
|
Schema.Struct({ ...MessageFields, role: Schema.Literal("developer"), content: Schema.Unknown }),
|
||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
usage: Schema.optional(Schema.StructWithRest(OpenResponses.OpenResponsesUsage, [JsonObject])),
|
usage: Schema.optional(Schema.StructWithRest(OpenResponses.OpenResponsesUsage, [JsonObject])),
|
||||||
|
|
@ -86,10 +89,15 @@ export const make = (
|
||||||
): CompactOperation =>
|
): CompactOperation =>
|
||||||
Effect.fn("ResponsesCompaction.execute")(function* (request, executor, options) {
|
Effect.fn("ResponsesCompaction.execute")(function* (request, executor, options) {
|
||||||
const route = request.model.route
|
const route = request.model.route
|
||||||
// The standalone compaction endpoint rejects histories containing configuration updates.
|
// The standalone compaction endpoint rejects effort updates (`configuration_update`). Every tool goes in
|
||||||
const native = yield* OpenResponses.lowerConversation(stripEffortUpdates(request), adapter)
|
// top-level `tools`: after compacting a history whose tools were only in `additional_tools`, small models lost
|
||||||
|
// track of them more often.
|
||||||
|
const folded = foldToolUpdates(stripEffortUpdates(request))
|
||||||
|
// The system prompt leads `input` as a developer message, as every step's request does, so `/compact` reads the
|
||||||
|
// prefix those requests cached.
|
||||||
|
const native = yield* OpenResponses.lowerConversation(folded, adapter)
|
||||||
const generation = OpenResponses.lowerGeneration(request)
|
const generation = OpenResponses.lowerGeneration(request)
|
||||||
const tools = request.tools.length === 0 ? undefined : yield* lowerTools(request)
|
const tools = folded.tools.length === 0 ? undefined : yield* lowerTools(folded)
|
||||||
const body = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Body))(
|
const body = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Body))(
|
||||||
mergeJsonRecords(
|
mergeJsonRecords(
|
||||||
{
|
{
|
||||||
|
|
@ -117,7 +125,10 @@ export const make = (
|
||||||
auth: route.auth,
|
auth: route.auth,
|
||||||
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
|
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
|
||||||
})
|
})
|
||||||
const response = yield* RequestExecutor.withTls(executor.execute, request.http?.tls)(
|
const response = yield* RequestExecutor.withTimeout(
|
||||||
|
RequestExecutor.withTls(executor.execute, request.http?.tls),
|
||||||
|
request.timeout,
|
||||||
|
)(
|
||||||
ProviderShared.jsonPost({
|
ProviderShared.jsonPost({
|
||||||
url: parts.url,
|
url: parts.url,
|
||||||
body: parts.bodyText,
|
body: parts.bodyText,
|
||||||
|
|
@ -126,13 +137,7 @@ export const make = (
|
||||||
}),
|
}),
|
||||||
RequestExecutor.withFetch(request.fetch, options?.http),
|
RequestExecutor.withFetch(request.fetch, options?.http),
|
||||||
)
|
)
|
||||||
const text = yield* RequestExecutor.responseStream(response).pipe(
|
const text = yield* RequestExecutor.responseText(response)
|
||||||
Stream.decodeText(),
|
|
||||||
Stream.runFold(
|
|
||||||
() => "",
|
|
||||||
(text, chunk) => text + chunk,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
const invalid = (message: string, cause?: unknown) =>
|
const invalid = (message: string, cause?: unknown) =>
|
||||||
new AIError({
|
new AIError({
|
||||||
reason: new InvalidProviderOutputError({
|
reason: new InvalidProviderOutputError({
|
||||||
|
|
@ -149,12 +154,16 @@ export const make = (
|
||||||
if (!result.output.some((item) => item.type === "compaction"))
|
if (!result.output.some((item) => item.type === "compaction"))
|
||||||
return yield* invalid("Compaction response did not contain a checkpoint")
|
return yield* invalid("Compaction response did not contain a checkpoint")
|
||||||
return new CompactionResponse({
|
return new CompactionResponse({
|
||||||
replacement: result.output.map((item) => toMessage(item, request.model)),
|
replacement: result.output
|
||||||
|
.filter((item): item is Output => item.type !== "message" || item.role !== "developer")
|
||||||
|
.map((item) => toMessage(item, request.model)),
|
||||||
usage: OpenResponses.mapUsage(result.usage, OpenResponses.metadataKey(request.model)),
|
usage: OpenResponses.mapUsage(result.usage, OpenResponses.metadataKey(request.model)),
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
function toMessage(item: (typeof Response.Type.output)[number], model: LLMRequest["model"]): Message {
|
type Output = Exclude<(typeof Response.Type.output)[number], { readonly role: "developer" }>
|
||||||
|
|
||||||
|
function toMessage(item: Output, model: LLMRequest["model"]): Message {
|
||||||
if (item.type === "compaction")
|
if (item.type === "compaction")
|
||||||
return Message.assistant(
|
return Message.assistant(
|
||||||
CompactionPart.make({ provider: model.provider, id: item.id ?? undefined, encrypted: item.encrypted_content }),
|
CompactionPart.make({ provider: model.provider, id: item.id ?? undefined, encrypted: item.encrypted_content }),
|
||||||
|
|
|
||||||
|
|
@ -72,35 +72,33 @@ export const onDone: (
|
||||||
state: OpenResponses.ParserState,
|
state: OpenResponses.ParserState,
|
||||||
item: Item,
|
item: Item,
|
||||||
tools: Definitions,
|
tools: Definitions,
|
||||||
) => Effect.Effect<OpenResponses.StepResult, AIError> = Effect.fnUntraced(
|
) => Effect.Effect<OpenResponses.StepResult, AIError> = Effect.fnUntraced(function* (state, item, tools) {
|
||||||
function* (state, item, tools) {
|
const tool = tools[item.type]
|
||||||
const tool = tools[item.type]
|
if (!tool) return [state, []] satisfies OpenResponses.StepResult
|
||||||
if (!tool) return [state, []] satisfies OpenResponses.StepResult
|
const providerMetadata = OpenResponses.providerMetadata(state, { itemId: item.id })
|
||||||
const providerMetadata = OpenResponses.providerMetadata(state, { itemId: item.id })
|
const events: LLMEvent[] = []
|
||||||
const events: LLMEvent[] = []
|
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||||
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
events.push(
|
||||||
events.push(
|
LLMEvent.toolCall({
|
||||||
LLMEvent.toolCall({
|
id: item.id,
|
||||||
id: item.id,
|
name: tool.name,
|
||||||
name: tool.name,
|
input: tool.input(item),
|
||||||
input: tool.input(item),
|
providerExecuted: true,
|
||||||
providerExecuted: true,
|
providerMetadata,
|
||||||
providerMetadata,
|
}),
|
||||||
}),
|
LLMEvent.toolResult({
|
||||||
LLMEvent.toolResult({
|
id: item.id,
|
||||||
id: item.id,
|
name: tool.name,
|
||||||
name: tool.name,
|
result: tool.result
|
||||||
result: tool.result
|
? yield* tool.result(item)
|
||||||
? yield* tool.result(item)
|
: item.error !== undefined && item.error !== null
|
||||||
: item.error !== undefined && item.error !== null
|
? { type: "error", value: item.error }
|
||||||
? { type: "error", value: item.error }
|
: { type: "json", value: item },
|
||||||
: { type: "json", value: item },
|
providerExecuted: true,
|
||||||
providerExecuted: true,
|
providerMetadata,
|
||||||
providerMetadata,
|
}),
|
||||||
}),
|
)
|
||||||
)
|
return [{ ...state, lifecycle }, events] satisfies OpenResponses.StepResult
|
||||||
return [{ ...state, lifecycle }, events] satisfies OpenResponses.StepResult
|
})
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
export * as ResponsesHostedTools from "./responses-hosted-tools.js"
|
export * as ResponsesHostedTools from "./responses-hosted-tools.js"
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import { Effect, Schema } from "effect"
|
import { Effect, Schema } from "effect"
|
||||||
import { Protocol } from "../route/protocol.js"
|
import { Protocol } from "../route/protocol.js"
|
||||||
|
import type { CompactOperation } from "../route/client.js"
|
||||||
import type { LLMRequest } from "../schema/index.js"
|
import type { LLMRequest } from "../schema/index.js"
|
||||||
import { OpenResponses } from "./open-responses.js"
|
import { OpenResponses } from "./open-responses.js"
|
||||||
import { JsonObject, optionalNull, ProviderShared } from "./shared.js"
|
import { JsonObject, optionalNull, ProviderShared } from "./shared.js"
|
||||||
|
|
@ -91,10 +92,16 @@ export const protocol = Protocol.make({
|
||||||
from: fromRequest,
|
from: fromRequest,
|
||||||
},
|
},
|
||||||
stream: ResponsesHostedTools.stream(adapter, HOSTED_TOOLS),
|
stream: ResponsesHostedTools.stream(adapter, HOSTED_TOOLS),
|
||||||
|
supportsEffortUpdates: OpenResponses.protocol.supportsEffortUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const compact = ResponsesCompaction.make(adapter, (request) =>
|
const compactFlat = ResponsesCompaction.make(adapter, (request) =>
|
||||||
OpenResponses.lowerTools(ProviderShared.flattenTools(request.tools), adapter, OpenAIFreeform.tools(request)),
|
OpenResponses.lowerTools(ProviderShared.flattenTools(request.tools), adapter, OpenAIFreeform.tools(request)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// /compact lowers the history itself, so flatten the whole request as `Protocol.make` does before every step's body:
|
||||||
|
// past calls to namespaced tools then carry the same names as on those steps, and /compact reads the prefix they cached.
|
||||||
|
export const compact: CompactOperation = (request, executor, options) =>
|
||||||
|
compactFlat(ProviderShared.flattenRequest(request), executor, options)
|
||||||
|
|
||||||
export * as XAIResponses from "./xai-responses.js"
|
export * as XAIResponses from "./xai-responses.js"
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { Effect, Schema } from "effect"
|
import { Effect, Schema } from "effect"
|
||||||
import type { HttpClientResponse } from "effect/http"
|
import type { HttpClientResponse } from "effect/http"
|
||||||
import type { Status } from "../generation.js"
|
|
||||||
import { Media } from "../media.js"
|
import { Media } from "../media.js"
|
||||||
import { MediaProtocol } from "../route/media-protocol.js"
|
import { MediaProtocol } from "../route/media-protocol.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
|
|
@ -36,7 +35,8 @@ export type Request = VideoRequest<VideoModel<XAIVideoOptions>>
|
||||||
// 2. Token and response schemas
|
// 2. Token and response schemas
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const Token = Schema.Struct({ requestID: Schema.String })
|
/** The provider's job ID; it is all a later status, result or cancel call needs. */
|
||||||
|
export const Token = Schema.String
|
||||||
export type Token = Schema.Schema.Type<typeof Token>
|
export type Token = Schema.Schema.Type<typeof Token>
|
||||||
|
|
||||||
const StartResponse = Schema.Struct({ request_id: Schema.String })
|
const StartResponse = Schema.Struct({ request_id: Schema.String })
|
||||||
|
|
@ -65,7 +65,7 @@ const STATUS = {
|
||||||
done: "completed",
|
done: "completed",
|
||||||
failed: "failed",
|
failed: "failed",
|
||||||
expired: "expired",
|
expired: "expired",
|
||||||
} as const satisfies Record<string, Status>
|
} as const satisfies Record<string, MediaProtocol.State>
|
||||||
|
|
||||||
// Documented video error codes; `service_unavailable`, `internal_error`, and unknown codes are provider-side.
|
// Documented video error codes; `service_unavailable`, `internal_error`, and unknown codes are provider-side.
|
||||||
const FAILURE = {
|
const FAILURE = {
|
||||||
|
|
@ -132,7 +132,7 @@ const fromRequest = Effect.fn("XAIVideo.fromRequest")(function* (request: Reques
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
const decodeStart = route.decodeStarted(StartResponse, (value) => ({
|
||||||
token: { requestID: value.request_id },
|
token: value.request_id,
|
||||||
snapshot: { id: value.request_id, status: "running" },
|
snapshot: { id: value.request_id, status: "running" },
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
@ -147,8 +147,11 @@ const decodeStatus = Effect.fn("XAIVideo.decodeStatus")(function* (
|
||||||
context: MediaProtocol.PollContext<Token>,
|
context: MediaProtocol.PollContext<Token>,
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeVideoStatus(response)
|
const output = yield* decodeVideoStatus(response)
|
||||||
const status = MediaProtocol.status(STATUS, output.value.status)
|
return {
|
||||||
return { id: context.token.requestID, status, progress: fraction(output.value.progress) }
|
id: context.token,
|
||||||
|
...MediaProtocol.status(STATUS, output.value.status),
|
||||||
|
progress: fraction(output.value.progress),
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (
|
const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (
|
||||||
|
|
@ -157,8 +160,8 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (
|
||||||
) {
|
) {
|
||||||
const output = yield* decodeVideoStatus(response)
|
const output = yield* decodeVideoStatus(response)
|
||||||
const decoded = output.value
|
const decoded = output.value
|
||||||
const status = MediaProtocol.status(STATUS, decoded.status)
|
const status = MediaProtocol.state(STATUS, decoded.status)
|
||||||
if (status === "running") return yield* output.pending(context.token.requestID)
|
if (status === "running") return yield* output.pending(context.token)
|
||||||
if (status === "failed") {
|
if (status === "failed") {
|
||||||
const code = decoded.error?.code ?? undefined
|
const code = decoded.error?.code ?? undefined
|
||||||
const message = decoded.error?.message ?? undefined
|
const message = decoded.error?.message ?? undefined
|
||||||
|
|
@ -168,8 +171,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (
|
||||||
MediaProtocol.failure(FAILURE, code),
|
MediaProtocol.failure(FAILURE, code),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (status !== "completed")
|
if (status !== "completed") return yield* output.ended("expired", `${route.name} request ${context.token} expired`)
|
||||||
return yield* output.ended("expired", `${route.name} request ${context.token.requestID} expired`)
|
|
||||||
// `respect_moderation: false` marks a filtered result; a URL may still be present, so only a missing one fails.
|
// `respect_moderation: false` marks a filtered result; a URL may still be present, so only a missing one fails.
|
||||||
const moderated = decoded.video?.respect_moderation === false
|
const moderated = decoded.video?.respect_moderation === false
|
||||||
const url = decoded.video?.url ?? undefined
|
const url = decoded.video?.url ?? undefined
|
||||||
|
|
@ -186,7 +188,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (
|
||||||
],
|
],
|
||||||
providerMetadata: {
|
providerMetadata: {
|
||||||
xai: {
|
xai: {
|
||||||
requestId: context.token.requestID,
|
requestId: context.token,
|
||||||
model: decoded.model ?? undefined,
|
model: decoded.model ?? undefined,
|
||||||
respectModeration: decoded.video?.respect_moderation ?? undefined,
|
respectModeration: decoded.video?.respect_moderation ?? undefined,
|
||||||
},
|
},
|
||||||
|
|
@ -198,7 +200,7 @@ const decodeResult = Effect.fn("XAIVideo.decodeResult")(function* (
|
||||||
// 7. Protocol and route
|
// 7. Protocol and route
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const statusPath = (token: Token) => `${STATUS_PATH}/${token.requestID}`
|
const statusPath = (token: Token) => `${STATUS_PATH}/${encodeURIComponent(token)}`
|
||||||
|
|
||||||
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(route, {
|
||||||
token: Token,
|
token: Token,
|
||||||
|
|
@ -215,7 +217,7 @@ const startPath = (request: Request) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const model = (input: MediaRoute.ModelInput) =>
|
export const model = (input: MediaRoute.ModelInput) =>
|
||||||
VideoModel.fromRoute<XAIVideoOptions, Token>(
|
VideoModel.fromRoute<XAIVideoOptions>(
|
||||||
{
|
{
|
||||||
protocol,
|
protocol,
|
||||||
baseURL: DEFAULT_BASE_URL,
|
baseURL: DEFAULT_BASE_URL,
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,8 @@ export const protocol = Protocol.make({
|
||||||
id: "zai-messages",
|
id: "zai-messages",
|
||||||
body: { schema: Body, from: fromRequest },
|
body: { schema: Body, from: fromRequest },
|
||||||
stream: AnthropicMessages.protocol.stream,
|
stream: AnthropicMessages.protocol.stream,
|
||||||
|
supportsEffortUpdates: AnthropicMessages.protocol.supportsEffortUpdates,
|
||||||
|
toolUpdates: AnthropicMessages.protocol.toolUpdates,
|
||||||
})
|
})
|
||||||
|
|
||||||
export * as ZAIMessages from "./zai-messages.js"
|
export * as ZAIMessages from "./zai-messages.js"
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,8 @@ const patterns = [
|
||||||
/input is too long for (?:the )?(?:requested|selected) model/i,
|
/input is too long for (?:the )?(?:requested|selected) model/i,
|
||||||
// OpenCode Go
|
// OpenCode Go
|
||||||
/too large for the model'?s configured input limit/i,
|
/too large for the model'?s configured input limit/i,
|
||||||
|
// Tencent TokenHub code 400003, which OpenCode Go passes through for Hy models.
|
||||||
|
/input tokens exceeds? the model'?s? context limit/i,
|
||||||
// Cloudflare Workers AI reports this as HTTP 413.
|
// Cloudflare Workers AI reports this as HTTP 413.
|
||||||
/exceeded this model context window limit/i,
|
/exceeded this model context window limit/i,
|
||||||
/exceeds the context window/i,
|
/exceeds the context window/i,
|
||||||
|
|
@ -128,6 +130,8 @@ const CONTENT_POLICY_CODES = new Set([
|
||||||
"responsibleaipolicyviolation",
|
"responsibleaipolicyviolation",
|
||||||
"content_policy_violation",
|
"content_policy_violation",
|
||||||
"image_content_policy_violation",
|
"image_content_policy_violation",
|
||||||
|
// OpenAI's cybersecurity safeguard, as an HTTP 400 or a mid-stream error frame.
|
||||||
|
"cyber_policy",
|
||||||
"refusal",
|
"refusal",
|
||||||
"datainspectionfailed",
|
"datainspectionfailed",
|
||||||
"moderation_blocked",
|
"moderation_blocked",
|
||||||
|
|
@ -154,7 +158,7 @@ const QUOTA_TEXT =
|
||||||
// Bedrock Mantle reuses it for schema validation; Anthropic reports blocked output
|
// Bedrock Mantle reuses it for schema validation; Anthropic reports blocked output
|
||||||
// under `invalid_request_error`. The Vercel AI Gateway drops OpenAI's `moderation_blocked` code.
|
// under `invalid_request_error`. The Vercel AI Gateway drops OpenAI's `moderation_blocked` code.
|
||||||
const CONTENT_POLICY_TEXT =
|
const CONTENT_POLICY_TEXT =
|
||||||
/violating our usage policy|blocked by content filtering policy|content[-_\s]?policy|rejected (?:as a result of our|by the) safety system|detected potentially unsafe or sensitive content/i
|
/violating our usage policy|blocked by content filtering policy|content[-_\s]?policy|rejected (?:as a result of our|by the) safety system|detected potentially unsafe or sensitive content|rejected in accordance with our terms of use/i
|
||||||
const SERVER_ERROR_TEXT =
|
const SERVER_ERROR_TEXT =
|
||||||
/\b(?:try again|(?:please |you can )?retry (?:the |this |your )?request|try (?:the |this |your )?request again|(?:currently |temporarily )?at capacity|overloaded|temporarily unavailable|service[-_\s]?unavailable|(?:server|internal)[-_\s]?error|server (?:is )?busy|provider returned (?:an )?error|resource[-_\s]?exhausted|upstream (?:connect|connection|request)|request buffer limit while retrying upstream)\b/i
|
/\b(?:try again|(?:please |you can )?retry (?:the |this |your )?request|try (?:the |this |your )?request again|(?:currently |temporarily )?at capacity|overloaded|temporarily unavailable|service[-_\s]?unavailable|(?:server|internal)[-_\s]?error|server (?:is )?busy|provider returned (?:an )?error|resource[-_\s]?exhausted|upstream (?:connect|connection|request)|request buffer limit while retrying upstream)\b/i
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import { Endpoint } from "../route/endpoint.js"
|
||||||
import { Framing } from "../route/framing.js"
|
import { Framing } from "../route/framing.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import {
|
import {
|
||||||
|
mergeTransport,
|
||||||
ProviderConfigurationError,
|
ProviderConfigurationError,
|
||||||
ProviderID,
|
ProviderID,
|
||||||
ToolDefinition,
|
ToolDefinition,
|
||||||
|
|
@ -123,8 +124,7 @@ export const configure = (input: Config) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: common.endpoint,
|
endpoint: common.endpoint,
|
||||||
auth: opts.auth,
|
auth: opts.auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
const embedding = (id: string | ModelID, providerOptions?: ProviderOptions) =>
|
const embedding = (id: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||||
embeddingRoute.model({ id, providerOptions })
|
embeddingRoute.model({ id, providerOptions })
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,18 @@
|
||||||
import { Auth } from "../route/auth.js"
|
import { Auth } from "../route/auth.js"
|
||||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||||
import { AssemblyAITranscription } from "../protocols/assemblyai-transcription.js"
|
import { AssemblyAITranscription } from "../protocols/assemblyai-transcription.js"
|
||||||
|
|
||||||
export type { AssemblyAITranscriptionOptions } from "../protocols/assemblyai-transcription.js"
|
export type { AssemblyAITranscriptionOptions } from "../protocols/assemblyai-transcription.js"
|
||||||
|
|
||||||
export const id = ProviderID.make("assemblyai")
|
export const id = ProviderID.make("assemblyai")
|
||||||
|
|
||||||
export type Config = ProviderAuthOption<"optional"> & {
|
export type Config = TransportOptions &
|
||||||
/** `https://api.eu.assemblyai.com` for the EU region. */
|
ProviderAuthOption<"optional"> & {
|
||||||
readonly baseURL?: string
|
/** `https://api.eu.assemblyai.com` for the EU region. */
|
||||||
readonly headers?: Record<string, string>
|
readonly baseURL?: string
|
||||||
readonly http?: HttpOptions
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// The key is the whole `authorization` value, without a scheme.
|
// The key is the whole `authorization` value, without a scheme.
|
||||||
const auth = (options: ProviderAuthOption<"optional">) =>
|
const auth = (options: ProviderAuthOption<"optional">) =>
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import { Endpoint } from "../route/endpoint.js"
|
||||||
import type { ProviderPackage } from "../provider-package.js"
|
import type { ProviderPackage } from "../provider-package.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import {
|
import {
|
||||||
|
mergeTransport,
|
||||||
ProviderConfigurationError,
|
ProviderConfigurationError,
|
||||||
ProviderID,
|
ProviderID,
|
||||||
type ModelID,
|
type ModelID,
|
||||||
|
|
@ -158,14 +159,9 @@ export const configure = (input: Config) => {
|
||||||
|
|
||||||
const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => {
|
const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => {
|
||||||
const target = endpoint(input, modelID)
|
const target = endpoint(input, modelID)
|
||||||
const media = MediaRoute.deployment({ ...input, baseURL: target.baseURL }, auth(input))
|
const transport = mergeTransport(input, { http: { query: target.query } })
|
||||||
return OpenAIImages.model({
|
const media = MediaRoute.deployment({ ...transport, baseURL: target.baseURL }, auth(input))
|
||||||
...media,
|
return OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions })
|
||||||
id: modelID,
|
|
||||||
provider: id,
|
|
||||||
providerOptions,
|
|
||||||
http: { ...media.http, query: { ...media.http?.query, ...target.query } },
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||||
|
|
@ -174,8 +170,7 @@ export const configure = (input: Config) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: endpoint(input, modelID),
|
endpoint: endpoint(input, modelID),
|
||||||
auth: auth(input),
|
auth: auth(input),
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
.model({ id: modelID, providerOptions })
|
.model({ id: modelID, providerOptions })
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { DecisionRoute } from "../route/decision.js"
|
import { DecisionRoute } from "../route/decision.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||||
|
|
||||||
|
|
@ -63,8 +63,7 @@ export const configure = (input: Config = {}) => {
|
||||||
protocol: decisionProtocol,
|
protocol: decisionProtocol,
|
||||||
endpoint: Endpoint.path("/systemone", { baseURL: options.endpoint.baseURL }),
|
endpoint: Endpoint.path("/systemone", { baseURL: options.endpoint.baseURL }),
|
||||||
auth: options.auth,
|
auth: options.auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||||
decisionRoute.model<BasetenDecisionOptions>({ id: modelID, providerOptions })
|
decisionRoute.model<BasetenDecisionOptions>({ id: modelID, providerOptions })
|
||||||
|
|
|
||||||
|
|
@ -2,16 +2,15 @@ import type { ProviderPackage } from "../provider-package.js"
|
||||||
import { SeedanceVideo } from "../protocols/seedance-video.js"
|
import { SeedanceVideo } from "../protocols/seedance-video.js"
|
||||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { type HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js"
|
import { ProviderID, type ModelID, type ProviderOptions, type TransportOptions } from "../schema/index.js"
|
||||||
import { toConfig } from "./settings.js"
|
import { toConfig } from "./settings.js"
|
||||||
|
|
||||||
export const id = ProviderID.make("byteplus")
|
export const id = ProviderID.make("byteplus")
|
||||||
|
|
||||||
export type Config = ProviderAuthOption<"optional"> & {
|
export type Config = TransportOptions &
|
||||||
readonly baseURL?: string
|
ProviderAuthOption<"optional"> & {
|
||||||
readonly headers?: Record<string, string>
|
readonly baseURL?: string
|
||||||
readonly http?: HttpOptions
|
}
|
||||||
}
|
|
||||||
|
|
||||||
export type Settings = ProviderPackage.Settings & {
|
export type Settings = ProviderPackage.Settings & {
|
||||||
readonly apiKey?: string | false
|
readonly apiKey?: string | false
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,16 @@
|
||||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||||
import { CartesiaSpeech } from "../protocols/cartesia-speech.js"
|
import { CartesiaSpeech } from "../protocols/cartesia-speech.js"
|
||||||
|
|
||||||
export type { CartesiaEncoding, CartesiaSpeechOptions } from "../protocols/cartesia-speech.js"
|
export type { CartesiaEncoding, CartesiaSpeechOptions } from "../protocols/cartesia-speech.js"
|
||||||
|
|
||||||
export const id = ProviderID.make("cartesia")
|
export const id = ProviderID.make("cartesia")
|
||||||
|
|
||||||
export type Config = ProviderAuthOption<"optional"> & {
|
export type Config = TransportOptions &
|
||||||
readonly baseURL?: string
|
ProviderAuthOption<"optional"> & {
|
||||||
readonly headers?: Record<string, string>
|
readonly baseURL?: string
|
||||||
readonly http?: HttpOptions
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const auth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "CARTESIA_API_KEY")
|
const auth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "CARTESIA_API_KEY")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { CloudflareRunDecisions } from "../protocols/cloudflare-run-decisions.js
|
||||||
import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../protocols/index.js"
|
import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../protocols/index.js"
|
||||||
import { Auth } from "../route/auth.js"
|
import { Auth } from "../route/auth.js"
|
||||||
import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js"
|
import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||||
import { encodeJson } from "../utils/json.js"
|
import { encodeJson } from "../utils/json.js"
|
||||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||||
import { CloudflareShared } from "./cloudflare-shared.js"
|
import { CloudflareShared } from "./cloudflare-shared.js"
|
||||||
|
|
@ -96,6 +96,7 @@ export const configure = (input: Config) => {
|
||||||
endpoint: { baseURL: baseURL(input) },
|
endpoint: { baseURL: baseURL(input) },
|
||||||
auth: custom ?? credential(input, (credential) => credential.bearer()),
|
auth: custom ?? credential(input, (credential) => credential.bearer()),
|
||||||
headers: { "cf-aig-gateway-id": gatewayId(input), ...headers(input) },
|
headers: { "cf-aig-gateway-id": gatewayId(input), ...headers(input) },
|
||||||
|
timeout: input.timeout,
|
||||||
http: input.http,
|
http: input.http,
|
||||||
providerOptions: input.providerOptions,
|
providerOptions: input.providerOptions,
|
||||||
}
|
}
|
||||||
|
|
@ -130,8 +131,7 @@ export const configure = (input: Config) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: { baseURL: runBaseURL(input) },
|
endpoint: { baseURL: runBaseURL(input) },
|
||||||
auth: rest.auth,
|
auth: rest.auth,
|
||||||
headers: rest.headers,
|
...mergeTransport(input, { headers: rest.headers }),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
.model({ id: value, providerOptions })
|
.model({ id: value, providerOptions })
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||||
import { CloudflareShared } from "./cloudflare-shared.js"
|
import { CloudflareShared } from "./cloudflare-shared.js"
|
||||||
|
|
||||||
|
|
@ -61,8 +61,7 @@ export const configure = (input: Config) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: { baseURL: runBaseURL(input) },
|
endpoint: { baseURL: runBaseURL(input) },
|
||||||
auth: auth,
|
auth: auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
.model({ id: modelID, providerOptions })
|
.model({ id: modelID, providerOptions })
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { OpenAIEmbeddings } from "../protocols/openai-embeddings.js"
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { ProviderID, type ModelID, type OpenString, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type OpenString, type RequestOptions } from "../schema/index.js"
|
||||||
import type { ProviderPackage } from "../provider-package.js"
|
import type { ProviderPackage } from "../provider-package.js"
|
||||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||||
|
|
||||||
|
|
@ -40,8 +40,7 @@ export const configure = (input: Config = {}) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: compatibility.endpoint,
|
endpoint: compatibility.endpoint,
|
||||||
auth: options.auth,
|
auth: options.auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Auth } from "../route/auth.js"
|
import { Auth } from "../route/auth.js"
|
||||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||||
import { DeepgramSpeech } from "../protocols/deepgram-speech.js"
|
import { DeepgramSpeech } from "../protocols/deepgram-speech.js"
|
||||||
import { DeepgramTranscription } from "../protocols/deepgram-transcription.js"
|
import { DeepgramTranscription } from "../protocols/deepgram-transcription.js"
|
||||||
|
|
||||||
|
|
@ -10,11 +10,10 @@ export type { DeepgramTranscriptionOptions } from "../protocols/deepgram-transcr
|
||||||
|
|
||||||
export const id = ProviderID.make("deepgram")
|
export const id = ProviderID.make("deepgram")
|
||||||
|
|
||||||
export type Config = ProviderAuthOption<"optional"> & {
|
export type Config = TransportOptions &
|
||||||
readonly baseURL?: string
|
ProviderAuthOption<"optional"> & {
|
||||||
readonly headers?: Record<string, string>
|
readonly baseURL?: string
|
||||||
readonly http?: HttpOptions
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const auth = (options: ProviderAuthOption<"optional">) =>
|
const auth = (options: ProviderAuthOption<"optional">) =>
|
||||||
AuthOptions.apiKey(options, "DEEPGRAM_API_KEY", Auth.scheme("Token"))
|
AuthOptions.apiKey(options, "DEEPGRAM_API_KEY", Auth.scheme("Token"))
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { OpenAIEmbeddings } from "../protocols/openai-embeddings.js"
|
||||||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||||
|
|
||||||
|
|
@ -47,8 +47,7 @@ export const configure = (input: Config = {}) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: options.endpoint,
|
endpoint: options.endpoint,
|
||||||
auth: options.auth,
|
auth: options.auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ import { Route } from "../route/client.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { Protocol } from "../route/protocol.js"
|
import { Protocol } from "../route/protocol.js"
|
||||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||||
import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js"
|
import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js"
|
||||||
import { bearerRouteDefaults } from "./settings.js"
|
import { bearerRouteDefaults } from "./settings.js"
|
||||||
|
|
@ -71,8 +71,7 @@ export const configure = (input: Config = {}) => {
|
||||||
endpoint: options.endpoint,
|
endpoint: options.endpoint,
|
||||||
auth: options.auth,
|
auth: options.auth,
|
||||||
// DigitalOcean serves TypeSafe's Jev, which needs this header for images.
|
// DigitalOcean serves TypeSafe's Jev, which needs this header for images.
|
||||||
headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers },
|
...mergeTransport({ headers: { "TypeSafe-Danger-Zone-Images": "true" } }, input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||||
decisionRoute.model({ id: modelID, providerOptions })
|
decisionRoute.model({ id: modelID, providerOptions })
|
||||||
|
|
@ -83,8 +82,7 @@ export const configure = (input: Config = {}) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: options.endpoint,
|
endpoint: options.endpoint,
|
||||||
auth: options.auth,
|
auth: options.auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||||
embeddingRoute.model({ id: modelID, providerOptions })
|
embeddingRoute.model({ id: modelID, providerOptions })
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { Auth } from "../route/auth.js"
|
import { Auth } from "../route/auth.js"
|
||||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { MediaRoute } from "../route/media.js"
|
import { MediaRoute } from "../route/media.js"
|
||||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||||
import { ElevenLabsSpeech } from "../protocols/elevenlabs-speech.js"
|
import { ElevenLabsSpeech } from "../protocols/elevenlabs-speech.js"
|
||||||
import { ElevenLabsTranscription } from "../protocols/elevenlabs-transcription.js"
|
import { ElevenLabsTranscription } from "../protocols/elevenlabs-transcription.js"
|
||||||
|
|
||||||
|
|
@ -10,11 +10,10 @@ export type { ElevenLabsTranscriptionOptions } from "../protocols/elevenlabs-tra
|
||||||
|
|
||||||
export const id = ProviderID.make("elevenlabs")
|
export const id = ProviderID.make("elevenlabs")
|
||||||
|
|
||||||
export type Config = ProviderAuthOption<"optional"> & {
|
export type Config = TransportOptions &
|
||||||
readonly baseURL?: string
|
ProviderAuthOption<"optional"> & {
|
||||||
readonly headers?: Record<string, string>
|
readonly baseURL?: string
|
||||||
readonly http?: HttpOptions
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const auth = (options: ProviderAuthOption<"optional">) =>
|
const auth = (options: ProviderAuthOption<"optional">) =>
|
||||||
AuthOptions.apiKey(options, "ELEVENLABS_API_KEY", Auth.header("xi-api-key"))
|
AuthOptions.apiKey(options, "ELEVENLABS_API_KEY", Auth.header("xi-api-key"))
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { OpenAIEmbeddings } from "../protocols/openai-embeddings.js"
|
||||||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||||
|
|
||||||
|
|
@ -41,8 +41,7 @@ export const configure = (input: Config = {}) => {
|
||||||
provider: id,
|
provider: id,
|
||||||
endpoint: options.endpoint,
|
endpoint: options.endpoint,
|
||||||
auth: options.auth,
|
auth: options.auth,
|
||||||
headers: input.headers,
|
...mergeTransport(input),
|
||||||
http: input.http,
|
|
||||||
})
|
})
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ import { GoogleInteractions } from "../protocols/google-interactions.js"
|
||||||
import { Auth } from "../route/auth.js"
|
import { Auth } from "../route/auth.js"
|
||||||
import { Route } from "../route/client.js"
|
import { Route } from "../route/client.js"
|
||||||
import { Endpoint } from "../route/endpoint.js"
|
import { Endpoint } from "../route/endpoint.js"
|
||||||
import { Framing } from "../route/framing.js"
|
|
||||||
import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js"
|
import { ProviderConfigurationError, ProviderID, type ModelID, type RequestOptions } from "../schema/index.js"
|
||||||
import { GoogleVertexShared } from "./google-vertex-shared.js"
|
import { GoogleVertexShared } from "./google-vertex-shared.js"
|
||||||
|
|
||||||
|
|
@ -41,7 +40,7 @@ const route = Route.make({
|
||||||
const serviceTier = request.providerOptions?.serviceTier
|
const serviceTier = request.providerOptions?.serviceTier
|
||||||
return typeof serviceTier === "string" ? { "x-vertex-ai-llm-shared-request-type": serviceTier } : {}
|
return typeof serviceTier === "string" ? { "x-vertex-ai-llm-shared-request-type": serviceTier } : {}
|
||||||
},
|
},
|
||||||
framing: Framing.sse,
|
transport: GoogleInteractions.transport,
|
||||||
})
|
})
|
||||||
|
|
||||||
export const routes = [route]
|
export const routes = [route]
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,7 @@ const route = Route.make({
|
||||||
},
|
},
|
||||||
stream: AnthropicMessages.protocol.stream,
|
stream: AnthropicMessages.protocol.stream,
|
||||||
supportsEffortUpdates: AnthropicMessages.protocol.supportsEffortUpdates,
|
supportsEffortUpdates: AnthropicMessages.protocol.supportsEffortUpdates,
|
||||||
|
toolUpdates: AnthropicMessages.protocol.toolUpdates,
|
||||||
}),
|
}),
|
||||||
endpoint: Endpoint.path(({ request }) => `/${request.model.id}:streamRawPredict`),
|
endpoint: Endpoint.path(({ request }) => `/${request.model.id}:streamRawPredict`),
|
||||||
auth: Auth.none,
|
auth: Auth.none,
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue