mirror of
https://github.com/ikechan8370/chatgpt-plugin.git
synced 2025-12-16 21:37:11 +00:00
Compare commits
884 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00b24914dd | ||
|
|
4b1a66b6bf | ||
|
|
b84bbcd55a | ||
|
|
8bfce5402f | ||
|
|
db386ccaf2 | ||
|
|
8a924f91df | ||
|
|
dc1ab30b6a | ||
|
|
602e192bff | ||
|
|
185f163c9c | ||
|
|
a3c74f82db | ||
|
|
c3b7127333 | ||
|
|
85d61ea210 | ||
|
|
b30488bdb9 | ||
|
|
af28390a54 | ||
|
|
51765fcfa0 | ||
|
|
8c7cc3a2d2 | ||
|
|
f4fb3dddd2 | ||
|
|
6b36552c08 | ||
|
|
3c83e270df | ||
|
|
64c77877ac | ||
|
|
0c602d6cb3 | ||
|
|
1788ee6d7d | ||
|
|
fd197abb33 | ||
|
|
9c41251164 | ||
|
|
7431814d1e | ||
|
|
60f6ccb2d2 | ||
|
|
fd40992c78 | ||
|
|
14a84357ca | ||
|
|
3318ac04d8 | ||
|
|
7be0e61e14 | ||
|
|
5c1b74bfb1 | ||
|
|
f521e0ede8 | ||
|
|
4216e64ed6 | ||
|
|
fcbdf51eb8 | ||
|
|
7fe9673dce | ||
|
|
089f6b6316 | ||
|
|
eb71222ed8 | ||
|
|
c44e47be1c | ||
|
|
127ba6d360 | ||
|
|
2401c5aed5 | ||
|
|
d9b5d77d46 | ||
|
|
8d12cb7466 | ||
|
|
2fad551144 | ||
|
|
89e265195d | ||
|
|
e1c4de4c10 | ||
|
|
478080fe6b | ||
|
|
66905640e4 | ||
|
|
a711ec13d7 | ||
|
|
66281fc53e | ||
|
|
f8591eba03 | ||
|
|
3c77da5373 | ||
|
|
efb5a8f174 | ||
|
|
9fcc25a726 | ||
|
|
6997d1e024 | ||
|
|
6ff0453feb | ||
|
|
5046a4e0df | ||
|
|
eee1285e2f | ||
|
|
89ab58b3d7 | ||
|
|
d20974f25a | ||
|
|
54806ee6fb | ||
|
|
116479e34e | ||
|
|
a16538f322 | ||
|
|
fbcf4e6c08 | ||
|
|
88312cdf38 | ||
|
|
531986b2dc | ||
|
|
d6cb085c40 | ||
|
|
cf31d40cf4 | ||
|
|
7fcf0c6b58 | ||
|
|
31a73e428a | ||
|
|
47016aeaa1 | ||
|
|
7bf1c84989 | ||
|
|
2ab56e15a7 | ||
|
|
5add41c982 | ||
|
|
20195ecfdf | ||
|
|
bde81c0a17 | ||
|
|
b9ed12adb7 | ||
|
|
a97f01b9d3 | ||
|
|
0fae49d5d1 | ||
|
|
41be6befec | ||
|
|
0ad0e2d237 | ||
|
|
84e7e6b859 | ||
|
|
95e776b334 | ||
|
|
3b58397a16 | ||
|
|
d29bfb0bc2 | ||
|
|
b486b45f44 | ||
|
|
d96349dde3 | ||
|
|
777279e410 | ||
|
|
08afc95f06 | ||
|
|
fcca28de37 | ||
|
|
213818b635 | ||
|
|
f619035e52 | ||
|
|
c3eb8ac5db | ||
|
|
9930e53a03 | ||
|
|
afa456f044 | ||
|
|
1911e5ca4b | ||
|
|
98d129517a | ||
|
|
69ff552dc9 | ||
|
|
870eba51d2 | ||
|
|
83c481a4bc | ||
|
|
9f521064a1 | ||
|
|
88360ecc42 | ||
|
|
2ad77d8112 | ||
|
|
8417008c38 | ||
|
|
4a3090c6f9 | ||
|
|
6d9c842a8f | ||
|
|
b95bacc7e8 | ||
|
|
d957025fa8 | ||
|
|
8249acaf08 | ||
|
|
dcc1a4ebd6 | ||
|
|
916e1082d7 | ||
|
|
c1dd406b62 | ||
|
|
e67a145635 | ||
|
|
f9a6fafb9e | ||
|
|
d656313811 | ||
|
|
ce4504e251 | ||
|
|
d7d4acf382 | ||
|
|
243331aa2e | ||
|
|
dcae426cfa | ||
|
|
1625401f14 | ||
|
|
e224272012 | ||
|
|
17f41dcdeb | ||
|
|
bbba9bc872 | ||
|
|
f05da98d37 | ||
|
|
43fb604742 | ||
|
|
6f3679b70d | ||
|
|
69ab6dcd28 | ||
|
|
f7030e8427 | ||
|
|
acb9e76b0e | ||
|
|
65bb1539e2 | ||
|
|
6442e371ee | ||
|
|
4b9dd0395d | ||
|
|
3cd664ff53 | ||
|
|
5e4d921002 | ||
|
|
994a83ac4a | ||
|
|
ced7a5a01f | ||
|
|
7974c6a1c9 | ||
|
|
25520ba9fe | ||
|
|
43faf96cfe | ||
|
|
802776cfa1 | ||
|
|
6ccf0fed7f | ||
|
|
75cf2e3523 | ||
|
|
cce3f2c28c | ||
|
|
314c60d0ae | ||
|
|
1c34ecbb83 | ||
|
|
5692af692b | ||
|
|
1149f34070 | ||
|
|
f6ce6dcec5 | ||
|
|
11fb6f5281 | ||
|
|
5f2b88851f | ||
|
|
027ff17b13 | ||
|
|
221cf4082d | ||
|
|
26444df2a2 | ||
|
|
5f6c4e5abb | ||
|
|
8fc2ca5621 | ||
|
|
dc751750f4 | ||
|
|
f6e054b7ef | ||
|
|
df715e22a2 | ||
|
|
a77a0e430f | ||
|
|
30f9c82d73 | ||
|
|
2b9734c641 | ||
|
|
aa2ac7b5d3 | ||
|
|
479028584e | ||
|
|
d08e9e4102 | ||
|
|
f0a17dc422 | ||
|
|
3822da62b0 | ||
|
|
b87bf77728 | ||
|
|
beaec147b5 | ||
|
|
ac304e0ed3 | ||
|
|
7c2961cdcd | ||
|
|
1682b715fd | ||
|
|
e6af4083c2 | ||
|
|
1fad082da6 | ||
|
|
49aade9ac6 | ||
|
|
cc90e38ba8 | ||
|
|
b1eff1700e | ||
|
|
500b743390 | ||
|
|
5c7c430da6 | ||
|
|
01425103f4 | ||
|
|
5aa90788c2 | ||
|
|
21485df0aa | ||
|
|
d82320d04c | ||
|
|
bb87169454 | ||
|
|
08e78209a0 | ||
|
|
72b6dcf54d | ||
|
|
1f80758491 | ||
|
|
b76d33d938 | ||
|
|
a507c85cf8 | ||
|
|
6f7bb4f7fd | ||
|
|
21a15c58ea | ||
|
|
e70f0a79f4 | ||
|
|
adcbcf1f40 | ||
|
|
3fb0d7d114 | ||
|
|
7288e2b845 | ||
|
|
f789556a90 | ||
|
|
554f6a69f3 | ||
|
|
8efcce45a0 | ||
|
|
d111d2625e | ||
|
|
123e5304a7 | ||
|
|
68b243670c | ||
|
|
f66b4a8548 | ||
|
|
07831d6108 | ||
|
|
8bd58cf429 | ||
|
|
b20a3db006 | ||
|
|
ea7ea93d33 | ||
|
|
991c63bb26 | ||
|
|
f8f5f8f83a | ||
|
|
1e4764fd14 | ||
|
|
ec47a4d9b0 | ||
|
|
a9ef38cbde | ||
|
|
33e04c1c24 | ||
|
|
8dab6fd0b5 | ||
|
|
03e3094c15 | ||
|
|
eb2618b141 | ||
|
|
f3fb9aa0ee | ||
|
|
b431794497 | ||
|
|
adc2931351 | ||
|
|
369dbd31c3 | ||
|
|
7bbe1a9db1 | ||
|
|
5acf874e0b | ||
|
|
c2f4b26904 | ||
|
|
c622f7eba5 | ||
|
|
5762485193 | ||
|
|
b0c6cadbc8 | ||
|
|
f63af3349a | ||
|
|
f68e7cf5ce | ||
|
|
7d39af6a8c | ||
|
|
81a45b1333 | ||
|
|
4eaf218d66 | ||
|
|
a4d07b9d46 | ||
|
|
b822e49d9a | ||
|
|
2ca27dae8d | ||
|
|
a539b26e8e | ||
|
|
267f67bb6c | ||
|
|
868255893f | ||
|
|
3b5a26ce62 | ||
|
|
7d83c34e98 | ||
|
|
5a6990ee86 | ||
|
|
1d42dc6f31 | ||
|
|
36f0dbd94f | ||
|
|
bbe70e3945 | ||
|
|
20a1a7dcdf | ||
|
|
b221098c37 | ||
|
|
32af7b9a74 | ||
|
|
d004699e21 | ||
|
|
e47ec3cd5c | ||
|
|
fd2d976686 | ||
|
|
8e73a28dae | ||
|
|
bd7aac0517 | ||
|
|
5c544a5ca7 | ||
|
|
56be26e001 | ||
|
|
3be095785a | ||
|
|
b4e017a69d | ||
|
|
f0c284cc2f | ||
|
|
79ab6cbd40 | ||
|
|
8b2493a4bf | ||
|
|
eef4254e00 | ||
|
|
4581db1b8c | ||
|
|
03068f5101 | ||
|
|
87af85671e | ||
|
|
6b58def252 | ||
|
|
1e1584b6ff | ||
|
|
cb3e57bea3 | ||
|
|
58e6201e6e | ||
|
|
9c73c99b65 | ||
|
|
cf7da0d2c5 | ||
|
|
bf75c002c0 | ||
|
|
f1b950ce58 | ||
|
|
edafe602c1 | ||
|
|
4886042e3c | ||
|
|
35ad437df2 | ||
|
|
e1d40ba009 | ||
|
|
e5e85621d9 | ||
|
|
9ef463fddc | ||
|
|
ec2e123e72 | ||
|
|
0cdd2be29a | ||
|
|
4cbca97c56 | ||
|
|
3561f7c99d | ||
|
|
7635781695 | ||
|
|
324f447401 | ||
|
|
6560cec87e | ||
|
|
76caf5d040 | ||
|
|
c46c8fe458 | ||
|
|
ba3422cd10 | ||
|
|
eea0748de7 | ||
|
|
63edc9403c | ||
|
|
2c9008ea56 | ||
|
|
76ecabe104 | ||
|
|
f04d0cdc6b | ||
|
|
c917688478 | ||
|
|
b4eba8096e | ||
|
|
74a0b7ddbc | ||
|
|
b3865d18c7 | ||
|
|
a32eb61f84 | ||
|
|
389940085a | ||
|
|
8cc7105f2d | ||
|
|
8ec1ee4c1e | ||
|
|
fc8bace2c5 | ||
|
|
ba83d6c31d | ||
|
|
4f10fcbeb1 | ||
|
|
5acd7cc023 | ||
|
|
966ea2d016 | ||
|
|
006abb3257 | ||
|
|
37d1d04de6 | ||
|
|
c69358cd80 | ||
|
|
8bdf9a3b6d | ||
|
|
9229be62cb | ||
|
|
3709166b2d | ||
|
|
5e41205728 | ||
|
|
35c2788463 | ||
|
|
a00956ef43 | ||
|
|
fc4eaf8dcf | ||
|
|
3eaa331dd0 | ||
|
|
5c52962737 | ||
|
|
22dcb0405b | ||
|
|
4dc5d6fe77 | ||
|
|
0ac70a325f | ||
|
|
39ef573dd3 | ||
|
|
bbe769f1aa | ||
|
|
6769e9d3f0 | ||
|
|
3aefa40920 | ||
|
|
8e846d9c9f | ||
|
|
315b16ac0d | ||
|
|
220525fbbd | ||
|
|
ac0aa7d02d | ||
|
|
6f0a79559b | ||
|
|
d00ab5df5f | ||
|
|
ca34338b72 | ||
|
|
3f98d480de | ||
|
|
16d9462e7c | ||
|
|
e5d6a415e8 | ||
|
|
fd0d0ff5db | ||
|
|
5f23d97bb3 | ||
|
|
2f1c3317f4 | ||
|
|
b8eaffe930 | ||
|
|
e61d4ff3fa | ||
|
|
d254163fa7 | ||
|
|
699d2c8d27 | ||
|
|
247f3e15d0 | ||
|
|
ae23e6d7f5 | ||
|
|
b3c3990831 | ||
|
|
065d377bd0 | ||
|
|
dd4476322f | ||
|
|
46328a9716 | ||
|
|
2183822bf0 | ||
|
|
91abd8a959 | ||
|
|
f7ee904414 | ||
|
|
8553525935 | ||
|
|
407ef65967 | ||
|
|
d795e8ea7d | ||
|
|
fac0863e3e | ||
|
|
028fbb7528 | ||
|
|
823301e5c6 | ||
|
|
b9ca5ce4e2 | ||
|
|
88270f1bca | ||
|
|
f1c2682ffe | ||
|
|
cef2f7378d | ||
|
|
aefea106a5 | ||
|
|
1c6c10b118 | ||
|
|
46d88c2669 | ||
|
|
2b19302b87 | ||
|
|
f246e842ec | ||
|
|
c99019cd91 | ||
|
|
ef1423ddb4 | ||
|
|
56a893734c | ||
|
|
a45be2e211 | ||
|
|
0d8ef840d4 | ||
|
|
e29e370f25 | ||
|
|
ce65cc862f | ||
|
|
e43b490edb | ||
|
|
0bff8c85b0 | ||
|
|
61d3b48781 | ||
|
|
7cc22e487a | ||
|
|
6c149265f0 | ||
|
|
7289ae6f35 | ||
|
|
ea687296a5 | ||
|
|
e5959b0190 | ||
|
|
efa7fff574 | ||
|
|
5cecea0783 | ||
|
|
2a713ca158 | ||
|
|
b7376407af | ||
|
|
cb6eb9c1eb | ||
|
|
82af06a2da | ||
|
|
32cc6a4e94 | ||
|
|
e0054521d3 | ||
|
|
c0936e6e2a | ||
|
|
d528840297 | ||
|
|
e0f96e3ac0 | ||
|
|
dc19009e2a | ||
|
|
9e7a614ded | ||
|
|
b1e3fb7892 | ||
|
|
74626e6676 | ||
|
|
3abfcc5d71 | ||
|
|
1a95c67130 | ||
|
|
6d16861fe6 | ||
|
|
c68a50e8bc | ||
|
|
48a2d64bf5 | ||
|
|
4cb4dc954e | ||
|
|
03daaa66d7 | ||
|
|
ed568c40a4 | ||
|
|
14d7088e90 | ||
|
|
22ead6d55e | ||
|
|
6c171b32a1 | ||
|
|
fd735c1daf | ||
|
|
f5a31f7601 | ||
|
|
7e5f723a82 | ||
|
|
42bad1cb47 | ||
|
|
471da4f3b1 | ||
|
|
ae14be4cf5 | ||
|
|
0e826e58a8 | ||
|
|
1e867c08ef | ||
|
|
83a82cf936 | ||
|
|
04bab7a894 | ||
|
|
fb05cccd5b | ||
|
|
fe132985fd | ||
|
|
4c16489ce1 | ||
|
|
a4ac59d8f9 | ||
|
|
e68c4fdd50 | ||
|
|
e4acfcf162 | ||
|
|
8b6fef00ec | ||
|
|
59ab8df658 | ||
|
|
4c737d5728 | ||
|
|
0a3c95d305 | ||
|
|
4066f17847 | ||
|
|
95e730f250 | ||
|
|
dce7503c41 | ||
|
|
ae58a20cc2 | ||
|
|
dfbee2011d | ||
|
|
20ea8cfabf | ||
|
|
0666de1aaa | ||
|
|
096bcbca56 | ||
|
|
c5421bb5a0 | ||
|
|
a0a9630aba | ||
|
|
7c45b050ca | ||
|
|
fed2fd8dd4 | ||
|
|
8dcfb54e04 | ||
|
|
0f310a8ff3 | ||
|
|
e574681ad1 | ||
|
|
0f9c8a7abe | ||
|
|
e90d6f11ca | ||
|
|
6e5ef2e1f5 | ||
|
|
d6fb62c424 | ||
|
|
5d5535ed6e | ||
|
|
880edace8a | ||
|
|
8aec804179 | ||
|
|
64f2699b22 | ||
|
|
6e61d0e743 | ||
|
|
390eb5cdae | ||
|
|
ad95327b1b | ||
|
|
7c5e9ea434 | ||
|
|
c36a0f9c9c | ||
|
|
77f6d2d85b | ||
|
|
08e92d871e | ||
|
|
bb51e53e02 | ||
|
|
a91e2c25b3 | ||
|
|
f620e10abb | ||
|
|
5e7d73908f | ||
|
|
c2c3052df1 | ||
|
|
c881090c08 | ||
|
|
078d31dc57 | ||
|
|
b743259e78 | ||
|
|
56d6b50aef | ||
|
|
bf761c24da | ||
|
|
c3d998ec34 | ||
|
|
6ace8720c4 | ||
|
|
b966a09058 | ||
|
|
6330eeb399 | ||
|
|
57416dcd03 | ||
|
|
5028c2ea67 | ||
|
|
6a61722bc3 | ||
|
|
34f99a0160 | ||
|
|
4457fab038 | ||
|
|
b6c0a04285 | ||
|
|
43aa5ad105 | ||
|
|
043b80ddd4 | ||
|
|
791a438867 | ||
|
|
007909a156 | ||
|
|
d6ed1bf37f | ||
|
|
d9c25140ac | ||
|
|
8df8626d1a | ||
|
|
246aaad987 | ||
|
|
502cc810bb | ||
|
|
c2c6ea43de | ||
|
|
3b1641ca5f | ||
|
|
7ce058c4a5 | ||
|
|
4c26d7781a | ||
|
|
4ffc6c1a32 | ||
|
|
9c172e9e4b | ||
|
|
407b3752a4 | ||
|
|
e4854e68f5 | ||
|
|
e445cb3c7f | ||
|
|
709a1cebf0 | ||
|
|
a703378cb1 | ||
|
|
12a94d8086 | ||
|
|
51f786bd44 | ||
|
|
b1570d6126 | ||
|
|
ef57259e8a | ||
|
|
521914bb5b | ||
|
|
5d6737d24a | ||
|
|
bc072d965d | ||
|
|
492a805647 | ||
|
|
6ee0b0ead9 | ||
|
|
ffb0929ab9 | ||
|
|
6628b8837b | ||
|
|
a1b450abaa | ||
|
|
b5669de782 | ||
|
|
db24de9ae3 | ||
|
|
b35a2a9999 | ||
|
|
b9f45c2052 | ||
|
|
75672586ca | ||
|
|
66172feb3e | ||
|
|
4ad4119c39 | ||
|
|
e1406a8c58 | ||
|
|
7ca35836bf | ||
|
|
636963af0e | ||
|
|
3b807211c2 | ||
|
|
9be8b54faf | ||
|
|
8a531bf551 | ||
|
|
e42307fd76 | ||
|
|
89416677fb | ||
|
|
f1da0d36d9 | ||
|
|
80b320ff3a | ||
|
|
285afad993 | ||
|
|
6ba96eecc7 | ||
|
|
dd249615e4 | ||
|
|
53ad413f52 | ||
|
|
f01d1d3998 | ||
|
|
a94017e6e5 | ||
|
|
877b91c765 | ||
|
|
ff69d2e963 | ||
|
|
e5d43a8cc1 | ||
|
|
7a8b30db14 | ||
|
|
f0b717bed8 | ||
|
|
9838459446 | ||
|
|
ca3788d719 | ||
|
|
2443ed6f71 | ||
|
|
36e592e773 | ||
|
|
d4a3b2ce61 | ||
|
|
962bde1beb | ||
|
|
8acb3f48e7 | ||
|
|
c6ce17ff98 | ||
|
|
1a73940231 | ||
|
|
aed271479d | ||
|
|
ca28b00679 | ||
|
|
c99af43571 | ||
|
|
8bc5829777 | ||
|
|
328849b320 | ||
|
|
8257779f5c | ||
|
|
b7ac3bff30 | ||
|
|
16a8c64b56 | ||
|
|
d3cc6e4679 | ||
|
|
ced2b4eeb6 | ||
|
|
87182f1a1f | ||
|
|
9f7a51679f | ||
|
|
3427d23054 | ||
|
|
bcb19db162 | ||
|
|
46dc1a8c39 | ||
|
|
fc029de75c | ||
|
|
7e559881eb | ||
|
|
37572bd635 | ||
|
|
6e912d68c8 | ||
|
|
a35f8a31a0 | ||
|
|
03b02442fa | ||
|
|
feb6b31994 | ||
|
|
de8cc48156 | ||
|
|
d52f95780a | ||
|
|
38383e373e | ||
|
|
cd1687299a | ||
|
|
8c7e6489e7 | ||
|
|
19f9c804bb | ||
|
|
116e4bef3c | ||
|
|
da27e6a1b3 | ||
|
|
c3d9f65a03 | ||
|
|
8a32f7e4fd | ||
|
|
faed389835 | ||
|
|
7bc140a030 | ||
|
|
5bfd55e765 | ||
|
|
14369c8f90 | ||
|
|
2c2e71fb4d | ||
|
|
33f80519a6 | ||
|
|
637c921130 | ||
|
|
8c463c731f | ||
|
|
0dedaf7516 | ||
|
|
b7427e74c4 | ||
|
|
2c5b084b04 | ||
|
|
a3fab7316f | ||
|
|
85e9d079a5 | ||
|
|
d7cb9aa56d | ||
|
|
fbe8953667 | ||
|
|
adc0817731 | ||
|
|
317283218a | ||
|
|
508beaece3 | ||
|
|
bdad936c70 | ||
|
|
7007cacf6f | ||
|
|
220a3f155d | ||
|
|
c00b6d85d2 | ||
|
|
a46d6d850b | ||
|
|
5c7d85efd0 | ||
|
|
cecb16ee62 | ||
|
|
9b54980ec0 | ||
|
|
0efc67f522 | ||
|
|
9a8db9577a | ||
|
|
f2f77235b1 | ||
|
|
c7a85baa4e | ||
|
|
dc587cb164 | ||
|
|
cab59f0629 | ||
|
|
455f0e8a92 | ||
|
|
3de9ca9c49 | ||
|
|
c91791ad21 | ||
|
|
2e8b59bb06 | ||
|
|
375fad8a20 | ||
|
|
3c437ddfc5 | ||
|
|
cc78143c0e | ||
|
|
758aeb67a2 | ||
|
|
d88550db39 | ||
|
|
ea5c451355 | ||
|
|
f20248a805 | ||
|
|
82b83bf015 | ||
|
|
6551f11434 | ||
|
|
6a7328a36a | ||
|
|
15f579aab8 | ||
|
|
1a94d92943 | ||
|
|
63f8629037 | ||
|
|
73e6dc43bc | ||
|
|
b4dcfcb42a | ||
|
|
d4a8c270af | ||
|
|
3f42c05388 | ||
|
|
926f07c8e9 | ||
|
|
76f0328a8e | ||
|
|
2bf3a636a6 | ||
|
|
fde029cd91 | ||
|
|
e47f18a5aa | ||
|
|
6485d7a93e | ||
|
|
fe42df5928 | ||
|
|
bda0431714 | ||
|
|
b687d45897 | ||
|
|
bb90c3c3e7 | ||
|
|
30aa32d5e9 | ||
|
|
76d261666a | ||
|
|
0c5a5e8eb8 | ||
|
|
6267d2d842 | ||
|
|
d3bd7be722 | ||
|
|
1454917cad | ||
|
|
5099ae9d87 | ||
|
|
eb6c25d75d | ||
|
|
06b26ab580 | ||
|
|
0daecc2edb | ||
|
|
9e4049181a | ||
|
|
d5e3d52d43 | ||
|
|
1bfb4d7d6b | ||
|
|
1f50e1b7a5 | ||
|
|
2cafdcaa82 | ||
|
|
49af9dad80 | ||
|
|
cb9f0b2773 | ||
|
|
78a99801e7 | ||
|
|
4a5407502a | ||
|
|
06495c3c59 | ||
|
|
68ef2d104f | ||
|
|
8baef8b579 | ||
|
|
94c44068a4 | ||
|
|
a714c21ffb | ||
|
|
cf992bbc2c | ||
|
|
20f6cd5390 | ||
|
|
aba80a5ddb | ||
|
|
7ae248e5c4 | ||
|
|
49d8dce984 | ||
|
|
55f060dc5f | ||
|
|
26b4534cfb | ||
|
|
c35c3a66ce | ||
|
|
db72462b8e | ||
|
|
cd228128ba | ||
|
|
5ded004538 | ||
|
|
21fc4cbe45 | ||
|
|
1475768df8 | ||
|
|
8342c583a5 | ||
|
|
719a810aca | ||
|
|
cee033dc5e | ||
|
|
eab19833c7 | ||
|
|
e0d3395a77 | ||
|
|
3cfbe9eae7 | ||
|
|
7f773dcfc4 | ||
|
|
a3ef75cdcc | ||
|
|
74f4b641e4 | ||
|
|
f93f9ea0bb | ||
|
|
a3b6af2851 | ||
|
|
2ce0a56ef6 | ||
|
|
e7a0bcfee0 | ||
|
|
73c88cce83 | ||
|
|
36a51856c5 | ||
|
|
3e1fcad103 | ||
|
|
aa040d4bf1 | ||
|
|
edd705fbce | ||
|
|
eb4628a4e8 | ||
|
|
6c5b31156a | ||
|
|
e758b37d4a | ||
|
|
40b72989e4 | ||
|
|
fd06f8c21a | ||
|
|
85e7e79883 | ||
|
|
5b94b49536 | ||
|
|
a804412c4d | ||
|
|
351d89bd7c | ||
|
|
2dc7cd5c29 | ||
|
|
673fd88141 | ||
|
|
06fd121950 | ||
|
|
a2d903a2ae | ||
|
|
08e95dc618 | ||
|
|
1a96572bf7 | ||
|
|
c1599e4f34 | ||
|
|
3dee3ccec7 | ||
|
|
ba0c382886 | ||
|
|
1e5010e9f1 | ||
|
|
a68055c11d | ||
|
|
aa91ddeed5 | ||
|
|
bce9d00afa | ||
|
|
b66592d2fb | ||
|
|
0451e19b09 | ||
|
|
70472464cf | ||
|
|
7c36f9361e | ||
|
|
43ec7239b7 | ||
|
|
7ef6051da8 | ||
|
|
a3a16bc5ff | ||
|
|
c0aeceb4a4 | ||
|
|
2895d89fdb | ||
|
|
414eb1b098 | ||
|
|
2679206be9 | ||
|
|
adae071091 | ||
|
|
b3122e5c04 | ||
|
|
9b9b69634e | ||
|
|
4b29e261a0 | ||
|
|
11a62097f0 | ||
|
|
98d414935e | ||
|
|
8bdbd623b3 | ||
|
|
7bf5996dce | ||
|
|
458b04c666 | ||
|
|
c0a596a608 | ||
|
|
5119e17484 | ||
|
|
cfbad0972b | ||
|
|
93459ed94e | ||
|
|
6b2cd446f9 | ||
|
|
4c0a1852f6 | ||
|
|
a8240d51b4 | ||
|
|
3b66f6d3f6 | ||
|
|
0a0cefe39c | ||
|
|
f688b01816 | ||
|
|
0926009bb3 | ||
|
|
c469813711 | ||
|
|
f8e741b0ca | ||
|
|
20f46717aa | ||
|
|
ec82629238 | ||
|
|
5350c9d4f3 | ||
|
|
820cf76eaf | ||
|
|
93c286e240 | ||
|
|
b4a8311acf | ||
|
|
e343d54ea2 | ||
|
|
943ee5951b | ||
|
|
4bd6c8c7d8 | ||
|
|
c5d11efb74 | ||
|
|
0d5ebc073f | ||
|
|
68bb1f221e | ||
|
|
af2b879f74 | ||
|
|
84eabee14d | ||
|
|
9e69a00c10 | ||
|
|
486b89a5b3 | ||
|
|
fcc9691588 | ||
|
|
10bbbf4f64 | ||
|
|
95a4d7a69c | ||
|
|
14b4d3cdf4 | ||
|
|
d6267e3f98 | ||
|
|
fe0ca177f3 | ||
|
|
1336368bc3 | ||
|
|
98943bee9a | ||
|
|
da5adc0d10 | ||
|
|
fd408586a8 | ||
|
|
e93614ca35 | ||
|
|
5b62667839 | ||
|
|
df4ecc84ab | ||
|
|
b770aa9021 | ||
|
|
8fb2615811 | ||
|
|
7d89849c88 | ||
|
|
12dc262dfc | ||
|
|
f71f1d7ed7 | ||
|
|
9c3d1bc5e4 | ||
|
|
019dc5e0c3 | ||
|
|
11735ead3b | ||
|
|
914a01994b | ||
|
|
1f58ac5476 | ||
|
|
f368f4f040 | ||
|
|
bae27b7362 | ||
|
|
a4d8488a55 | ||
|
|
f21c3bee39 | ||
|
|
cc785261eb | ||
|
|
ea536c2e21 | ||
|
|
407a2e1d66 | ||
|
|
d3fdaaa4b3 | ||
|
|
fbfd105e0d | ||
|
|
0755b54486 | ||
|
|
3121b0e463 | ||
|
|
15a582abd5 | ||
|
|
1c1c2562ae | ||
|
|
3bdfb15b0d | ||
|
|
d3c9cbbdff | ||
|
|
58c2b24239 | ||
|
|
20469346ec | ||
|
|
b110531135 | ||
|
|
54f68132f9 | ||
|
|
1563e49a25 | ||
|
|
fadf9f6a8c | ||
|
|
1d43de9ce0 | ||
|
|
192beb2722 | ||
|
|
4b93b5edaf | ||
|
|
6da671e533 | ||
|
|
6de86db6f6 | ||
|
|
ef6605db2d | ||
|
|
f4aaf5b0e4 | ||
|
|
b68cb41104 | ||
|
|
c57102fff1 | ||
|
|
533dceb865 | ||
|
|
d36b7c83bc | ||
|
|
02d7aa0301 | ||
|
|
cc2c561224 | ||
|
|
cae324f250 | ||
|
|
b4f37b5339 | ||
|
|
b11a653c51 | ||
|
|
05f142d32c | ||
|
|
847a623c75 | ||
|
|
1c79ff00b7 | ||
|
|
3885527a7d | ||
|
|
ad62b53af4 | ||
|
|
f1479f0e10 | ||
|
|
6f8eb1dd84 | ||
|
|
b6218a26ed | ||
|
|
7d571df12a | ||
|
|
00afb75bb5 | ||
|
|
6653188a8f | ||
|
|
d8999c77e6 | ||
|
|
90a1f6a084 | ||
|
|
bfc55df6a6 | ||
|
|
07d1db0a2a | ||
|
|
c2d507ea91 | ||
|
|
028a7c2c4a | ||
|
|
d48748c0f5 | ||
|
|
f4a740a6a8 | ||
|
|
5c3ca4e9af | ||
|
|
3c62f2f5ed | ||
|
|
73689f4639 | ||
|
|
1432723de5 | ||
|
|
1a5d462920 | ||
|
|
4626577a93 | ||
|
|
fb7cd69969 | ||
|
|
665215788c | ||
|
|
e39391c176 | ||
|
|
afd0650d04 | ||
|
|
cc1f5611a7 | ||
|
|
c1ca4f2f9b | ||
|
|
6b02beddd8 | ||
|
|
a21e2d9ef1 | ||
|
|
3c5604b2fb | ||
|
|
117293cc18 | ||
|
|
8367ac8569 | ||
|
|
74c151a973 | ||
|
|
c560a440e9 | ||
|
|
8555d8eb14 | ||
|
|
a110fb2080 | ||
|
|
ad853d45a6 | ||
|
|
ef54cad1fd | ||
|
|
f4a94f61db | ||
|
|
c53b86c181 | ||
|
|
c72df75d5a | ||
|
|
85c82fa01e | ||
|
|
392064ceeb | ||
|
|
5cba39d5a1 | ||
|
|
c600284cbf | ||
|
|
0b9c60ddaa | ||
|
|
b624b4b2f8 | ||
|
|
8e1f1ba12a | ||
|
|
cd1a4a3e34 | ||
|
|
fbe301635e | ||
|
|
94d5691e8a | ||
|
|
05666f1e63 | ||
|
|
9929d55bea | ||
|
|
5879e52acd | ||
|
|
1705d129d2 | ||
|
|
1b4bc49612 | ||
|
|
d4f8b4318d | ||
|
|
fb6c1ac3a0 |
202 changed files with 12735 additions and 14660 deletions
20
.github/ISSUE_TEMPLATE/功能请求-feature-request-.md
vendored
20
.github/ISSUE_TEMPLATE/功能请求-feature-request-.md
vendored
|
|
@ -1,20 +0,0 @@
|
|||
---
|
||||
name: 功能请求(Feature request)
|
||||
about: 为本项目提出一个新想法
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**你的功能请求是否与某个问题有关?请描述。**
|
||||
问题的清晰而简明的描述。
|
||||
|
||||
**描述你想要的解决方案**
|
||||
你想要发生什么的清晰而简明的描述。
|
||||
|
||||
**描述你已经考虑的替代方案**
|
||||
对任何替代解决方案或功能的清晰简明的描述。
|
||||
|
||||
**附加说明**
|
||||
在此处添加有关功能请求的任何其他说明、屏幕截图或者引用。
|
||||
45
.github/ISSUE_TEMPLATE/问题反馈.md
vendored
45
.github/ISSUE_TEMPLATE/问题反馈.md
vendored
|
|
@ -1,45 +0,0 @@
|
|||
---
|
||||
name: 问题反馈
|
||||
about: 提出bug解决问题并改进本项目
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
# 请确保提出问题前更新到最新版本!!!!!!!!
|
||||
|
||||
**请在提交issue前确认你已阅读了以下资料:**
|
||||
|
||||
- 项目的readme文件
|
||||
- 其他已有的Issue
|
||||
|
||||
如果你的问题已经在readme或其他Issue中得到解答,我们很可能不会回复。请确保你的问题是一个新的问题。
|
||||
|
||||
## 问题描述
|
||||
|
||||
请在此处描述您遇到的问题,包括出现问题的环境、您试图实现的功能以及错误信息等。请尽可能详细,以便其他人可以在自己的环境中复制问题。
|
||||
|
||||
## 预期行为
|
||||
|
||||
请描述您期望系统在出现问题时应该做什么。
|
||||
|
||||
## 实际行为
|
||||
|
||||
请描述您实际看到的行为。
|
||||
|
||||
## 复制过程
|
||||
|
||||
请详细描述如何复制这个问题,包括所有必要的步骤、输入、任何错误信息以及输出。
|
||||
|
||||
## 环境
|
||||
|
||||
请提供您使用的任何相关信息,例如操作系统、版本、配置等。
|
||||
|
||||
## 可能的解决方案
|
||||
|
||||
如果您已经尝试了一些解决方案,请在此处描述这些解决方案,并说明是否有效。
|
||||
|
||||
## 附加信息
|
||||
|
||||
如果有任何其他信息,如日志、截图等,请在此处提供。
|
||||
19
.github/workflows/tagged-released.yml
vendored
19
.github/workflows/tagged-released.yml
vendored
|
|
@ -1,19 +0,0 @@
|
|||
---
|
||||
name: "tagged-release"
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
tagged-release:
|
||||
name: "Tagged Release"
|
||||
runs-on: "ubuntu-latest"
|
||||
|
||||
steps:
|
||||
# ...
|
||||
- uses: "marvinpinto/action-automatic-releases@latest"
|
||||
with:
|
||||
repo_token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
prerelease: false
|
||||
13
.gitignore
vendored
13
.gitignore
vendored
|
|
@ -1,7 +1,8 @@
|
|||
config/*
|
||||
!config/config.example.js
|
||||
!config/config.example.json
|
||||
!config/config.md
|
||||
prompts/*
|
||||
!prompts/.gitkeep
|
||||
node_modules/
|
||||
data/
|
||||
utils/processors
|
||||
utils/tools
|
||||
utils/triggers
|
||||
memory.md
|
||||
resources/simple
|
||||
memory.db
|
||||
|
|
|
|||
3
.npmrc
3
.npmrc
|
|
@ -1 +1,2 @@
|
|||
sharp_libvips_binary_host="https://registry.npmmirror.com/-/binary/sharp-libvips"
|
||||
sharp_libvips_binary_host="https://registry.npmmirror.com/-/binary/sharp-libvips"
|
||||
nodejieba_binary_host_mirror="https://npm.taobao.org/mirrors/nodejieba"
|
||||
811
LICENSE
811
LICENSE
|
|
@ -1,201 +1,674 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
1. Definitions.
|
||||
Preamble
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
0. Definitions.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
1. Source Code.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
2. Basic Permissions.
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
|
|
|||
36
LowerNode.md
36
LowerNode.md
|
|
@ -1,36 +0,0 @@
|
|||
## 本页面已过时
|
||||
|
||||
### Node.js >= 14 (并且 <18)时的安装方法
|
||||
|
||||
**如果不是 CentOS 7, RHEL 7, Ubuntu 18 请自行搜索并升级你的 Node.js 版本!**
|
||||
|
||||
**此教程是为了因 glibc 不支持升级 Node.js 的Linux发行版准备的。**
|
||||
1. 进入 Yunzai 根目录
|
||||
2. 安装依赖
|
||||
```
|
||||
pnpm install -w undici chatgpt showdown mathjax-node delay uuid remark strip-markdown node-fetch @waylaidwanderer/chatgpt-api keyv-file
|
||||
```
|
||||
**若使用API模式,chatgpt的版本号注意要大于4.2.0**
|
||||
|
||||
若不使用浏览器模式,可以不安装`random puppeteer-extra-plugin-recaptcha puppeteer-extra puppeteer-extra-plugin-stealth`这几个
|
||||
|
||||
3. 克隆项目
|
||||
```
|
||||
git clone https://github.com/ikechan8370/chatgpt-plugin.git ./plugins/chatgpt-plugin
|
||||
```
|
||||
4. 修改配置
|
||||
|
||||
修改 Yunzai根目录/node_modules/.pnpm/chatgpt\@4.1.0/node_modules/chatgpt/build/index.js
|
||||
|
||||
**此处 chatgpt\@4.1.0 路径不是绝对的!请根据自己安装的版本进行替换!**
|
||||
|
||||
**将 // src/fetch.ts 部分修改成如下样子,其他部分不要动**
|
||||
```
|
||||
// src/fetch.ts
|
||||
import fetch from 'node-fetch';
|
||||
globalThis.fetch = fetch;
|
||||
```
|
||||
|
||||
再编辑`Yunzai根目录/plugins/chatgpt-plugin/config/config.js`文件,根据其中的注释修改必要配置项。
|
||||
|
||||
---
|
||||
385
README.md
385
README.md
|
|
@ -1,279 +1,155 @@
|
|||
# 云崽qq机器人的chatgpt插件
|
||||

|
||||
<div align=center>
|
||||
|
||||
## 特点
|
||||
<img src ="https://img.shields.io/github/issues/ikechan8370/chatgpt-plugin?logo=github"/>
|
||||
<img src ="https://img.shields.io/github/license/ikechan8370/chatgpt-plugin"/>
|
||||
<img src ="https://img.shields.io/github/v/tag/ikechan8370/chatgpt-plugin?label=latest%20version&logo=github"/>
|
||||
<img src ="https://img.shields.io/github/languages/top/ikechan8370/chatgpt-plugin?logo=github"/>
|
||||
</div>
|
||||
|
||||
* 支持单人连续对话Conversation,群聊中支持加入其他人的对话
|
||||
* API模式下,使用 gpt-3.5-turbo API,ChatGPT官网同款模型,仅需OpenAI Api Key,开箱即用。**注意收费**
|
||||
* 支持问答图片截图
|
||||
* 支持AI性格调教
|
||||
* 支持对接vits回答直接转语音
|
||||
* API3模式下,绕过Cloudflare防护直接访问ChatGPT的SSE API,与官方体验一致,且保留对话记录,在官网可查。免费。
|
||||
* (Deprecated)提供基于浏览器的解决方案作为备选,API3不可用的情况下或担心账户安全的用户可以选择使用浏览器模式。
|
||||
* 支持新[必应](https://www.bing.com/new)(Beta)
|
||||
* 2023-03-15 API3支持GPT-4尝鲜,需要Plus用户
|
||||
|
||||
### 如果觉得这个插件有趣或者对你有帮助,请点一个star吧!
|
||||
|
||||
## 版本要求
|
||||
Node.js >= 18 / Node.js >= 14(with node-fetch)
|
||||
小白尽可能使用18版本以上的nodejs
|
||||

|
||||
|
||||
## 安装与使用方法
|
||||
|
||||
### 安装
|
||||
|
||||
在安装之前,请先判断自己需要使用哪种模式,本插件支持官方API/第三方API/浏览器/必应四种模式。也可以选择**我全都要**(通过qq发送命令`#chatgpt切换浏览器/API/API3/Bing`实时切换)
|
||||
|
||||
对于轻量用户可以先使用API模式,有较高要求再转为使用其他模式。
|
||||
> 插件v3大幅重构中,基本可用,持续完善中。遇到问题请提issue,欢迎PR。
|
||||
> todo列表:
|
||||
> - [x] 插件v3重构完成,插件基本功能可用,持续完善中。
|
||||
> - [ ] RAG知识库
|
||||
> - [ ] 预设更详细的配置
|
||||
> - [x] 自定义触发器
|
||||
> - [ ] 自定义插件
|
||||
> - [ ] 兼容mcp
|
||||
|
||||
> #### API模式和浏览器模式如何选择?
|
||||
>
|
||||
> * API模式会调用OpenAI官方提供的gpt-3.5-turbo API,ChatGPT官网同款模型,只需要提供API Key。一般情况下,该种方式响应速度更快,可配置项多,且不会像chatGPT官网一样总出现不可用的现象,但注意API调用是收费的,新用户有18美元试用金可用于支付,价格为`$0.0020/ 1K tokens`。(问题和回答**加起来**算token)
|
||||
> * API3模式会调用第三方提供的官网反代API,他会帮你绕过CF防护,需要提供ChatGPT的Token。效果与官网和浏览器一致,但稳定性不一定。发送#chatgpt设置token来设置token。
|
||||
> * (Deprecated)浏览器模式通过在本地启动Chrome等浏览器模拟用户访问ChatGPT网站,使得获得和官方以及API2模式一模一样的回复质量,同时保证安全性。缺点是本方法对环境要求较高,需要提供桌面环境和一个可用的代理(能够访问ChatGPT的IP地址),且响应速度不如API,而且高峰期容易无法使用。一般作为API3的下位替代。
|
||||
> * 必应(Bing)将调用微软新必应接口进行对话。需要在必应网页能够正常使用新必应且设置有效的Bing登录Cookie方可使用。
|
||||
1. 进入 Yunzai根目录
|
||||
|
||||
2. 请将 chatgpt-plugin 放置在 Yunzai-Bot 的 plugins 目录下
|
||||
## 插件简介
|
||||
|
||||
推荐使用 git 进行安装,以方便后续升级。在 Yunzai-Bot 根目录夹打开终端,运行下述指令进行安装
|
||||
ChatGPT-Plugin 以 Chaite 为内核,将多模型渠道、工具、处理器、触发器、RAG 和管控面板封装成一套适配 Miao-Yunzai / Yunzai-Bot 的插件方案。通过 Chaite 的 API 服务器与可插拔的存储层(默认 SQLite),插件可以在本地完成高并发对话、知识库检索、伪人陪聊以及记忆管理,亦可接入 Chaite Cloud 复用在线渠道与工具。
|
||||
|
||||
```shell
|
||||
git clone --depth=1 https://github.com/ikechan8370/chatgpt-plugin.git ./plugins/chatgpt-plugin/
|
||||
cd plugins/chatgpt-plugin
|
||||
pnpm i
|
||||
## 核心特性
|
||||
|
||||
- **多渠道与预设体系**:依托 Chaite 的 ChannelsManager 与 ChatPresetManager,支持为不同模型配置流量、负载均衡与个性化 prompt,群友也可在授权后自助切换预设。
|
||||
- **高级消息适配**:前后文触发方式支持 `@Bot` 与前缀;自动处理引用、图片、语音等多模态输入,并在工具调用或推理阶段通过转发消息回显。
|
||||
- **群上下文与伪人模式**:可按配置注入指定条数的群聊记录;BYM 伪人模式支持概率触发、关键词命中、预设覆盖及限时撤回,营造更拟人的陪聊体验。
|
||||
- **记忆与 RAG**:内置 memoryService + vectra 向量索引,提供群记忆、私人记忆与外部知识库(RAGManager)注入能力,支持混合检索与手动管理。
|
||||
- **可视化与指令双管控**:`#chatgpt管理面板` 一键获取面板 token,Web 端即可操作渠道、工具、触发器;同时保留完整的命令行 CRUD 指令。
|
||||
- **自动更新与依赖管理**:`#chatgpt更新` / `#chatgpt强制更新` 调用 git 同步仓库并自动更新 chaite 依赖,减少手动维护成本。
|
||||
|
||||
## 快速安装
|
||||
|
||||
1. **克隆代码**
|
||||
```bash
|
||||
cd plugins
|
||||
git clone https://github.com/ikechan8370/chatgpt-plugin.git
|
||||
```
|
||||
2. **安装依赖**(推荐 Node.js ≥ 18 + pnpm ≥ 8)
|
||||
```bash
|
||||
cd chatgpt-plugin
|
||||
pnpm install
|
||||
```
|
||||
若安装日志出现 `Ignored build scripts: better-sqlite3` 或运行时报错找不到 `better-sqlite3` bindings,可执行 `pnpm approve-builds`,在交互列表中勾选全部或仅 `better-sqlite3` 以允许编译。然后再次 `pnpm install`
|
||||
3. **在 Yunzai 中启用插件**
|
||||
- 重启机器人或运行 `node app` 让插件自动加载。
|
||||
- 首次启动会在 `plugins/chatgpt-plugin/config/` 下生成 `config.json / config.yaml`。
|
||||
4. **保持更新**
|
||||
- 主人账号发送 `#chatgpt更新` 获取最新版本。
|
||||
- `#chatgpt强制更新` 会放弃本地修改后重新拉取,请谨慎使用。
|
||||
|
||||
## 配置指引
|
||||
|
||||
配置文件默认位于 `plugins/chatgpt-plugin/config/config.json`,也可改写为 YAML。常用字段示例:
|
||||
|
||||
```yaml
|
||||
basic:
|
||||
toggleMode: at # at / prefix
|
||||
togglePrefix: "#chat" # prefix 模式下的触发词
|
||||
commandPrefix: "#chatgpt" # 管理指令前缀
|
||||
llm:
|
||||
defaultModel: "gpt-4o-mini"
|
||||
defaultChatPresetId: "default"
|
||||
enableGroupContext: true
|
||||
groupContextLength: 20
|
||||
bym:
|
||||
enable: false
|
||||
probability: 0.02
|
||||
defaultPreset: "bym_default"
|
||||
chaite:
|
||||
cloudApiKey: "" # 可选,接入 Chaite Cloud
|
||||
host: "0.0.0.0"
|
||||
port: 48370
|
||||
memory:
|
||||
group:
|
||||
enable: false
|
||||
enabledGroups: ["123456"]
|
||||
user:
|
||||
enable: false
|
||||
whitelist: ["123456789"]
|
||||
```
|
||||
|
||||
如果是手工下载的 zip 压缩包,请将解压后的 chatgpt-plugin 文件夹(请删除压缩自带的-master后缀)放置在 Yunzai-Bot 目录下的 plugins 文件夹内
|
||||
- **basic**:控制触发方式、调试与命令前缀。
|
||||
- **llm**:定义默认模型、嵌入模型、群上下文等。`defaultChatPresetId` 需在面板或命令中提前创建。
|
||||
- **chaite**:`storage` 默认 SQLite,会在 `plugins/chatgpt-plugin/data/data.db` 生成数据文件;如接入 Chaite Cloud,请填入 `cloudApiKey` 并开放 `host/port`。
|
||||
- **bym**:配置伪人触发概率、关键词映射、撤回与思考内容开关。
|
||||
- **memory**:为群记忆或私人记忆开启检索、模型与提示词,可按需启用 `extensions.simple` 以加载自定义词典。
|
||||
|
||||
> 浏览器模式仅为备选,如您需要使用浏览器模式,您还需要有**桌面环境**,优先级建议:API≈必应>API3>浏览器
|
||||
> 2.20更新:必应被大削,变得蠢了,建议还是API/API3优先
|
||||
修改后保存文件,插件会自动热加载;在 Chaite 面板修改配置时也会反向写回本地文件。
|
||||
|
||||
3. 修改配置
|
||||
**本插件配置项比较多,建议使用[锅巴面板](https://github.com/guoba-yunzai/Guoba-Plugin)修改**
|
||||
## 使用方式
|
||||
|
||||
复制`plugins/chatgpt-plugin/config/config.example.json`并将其改名为`config.json`\
|
||||
编辑`plugins/chatgpt-plugin/config/config.json`文件,修改必要配置项
|
||||
### 基础对话
|
||||
|
||||
4. 重启Yunzai-Bot
|
||||
- `@Bot 你好` 或 `#chat 今天天气如何` 触发默认预设,插件会保持用户 `conversationId` 与 `messageId`,自动续写多轮对话。
|
||||
- 回复图片/文本可作为上下文输入,模型返回的图片、语音与思考内容会自动转换为 QQ 消息或转发记录。
|
||||
- `#结束对话` 仅清空自己的会话;`#结束全部对话` 需主人权限。
|
||||
|
||||
> ### 我想使用浏览器模式,但是我是linux云服务器没有桌面环境怎么办?
|
||||
>
|
||||
> linux云服务器可以安装窗口管理器和vnc创建并访问虚拟桌面环境
|
||||
>
|
||||
> 1. 安装xvfb和fluxbox
|
||||
>
|
||||
> - Ubuntu:`sudo apt-get install x11vnc xvfb fluxbox`
|
||||
>
|
||||
> - CentOS:`sudo yum install x11vnc Xvfb fluxbox`
|
||||
>
|
||||
> 2. 启动桌面环境
|
||||
>
|
||||
> 建议用tmux或screen等使其能够后台运行
|
||||
>
|
||||
> 注意:本命令使用默认5900端口和**无密码**,注意通过防火墙等保护,**切勿**在公网环境或不安全的网络环境下使用!!!
|
||||
> `x11vnc -create -env FD_PROG=/usr/bin/fluxbox -env X11VNC_FINDDISPLAY_ALWAYS_FAILS=1 -env X11VNC_CREATE_GEOM=${1:-1024x768x16} -nopw -forever`
|
||||
>
|
||||
> 3. 使用vnc客户端连接至云桌面
|
||||
>
|
||||
> 右键Applications > Shells > Bash打开终端,然后进入Yunzai目录下运行node app即可。
|
||||
>
|
||||
> 4. 执行pnpm i时,sharp安装失败
|
||||
>
|
||||
> sharp不影响chatgpt聊天,仅影响Dalle2绘图功能。ubuntu可以执行`apt install libvips-dev`之后再`pnpm i`
|
||||
>
|
||||
> 实测该方案资源占用低,运行稳定,基本1核2G的轻量云服务器就足够了。
|
||||
### 管理命令 & 面板
|
||||
|
||||
---
|
||||
- `#chatgpt管理面板`:生成一次性 token,访问 `http://<host>:<port>` 即可使用 Chaite Web 面板。
|
||||
- CRUD 命令示例(均支持 `列表 / 添加 / 查看 / 删除`):
|
||||
```
|
||||
#chatgpt渠道列表
|
||||
#chatgpt预设添加 角色扮演 {...}
|
||||
#chatgpt工具删除 web-search
|
||||
#chatgpt处理器查看 markdown
|
||||
```
|
||||
- `#chatgpt调试模式开关`、`#chatgpt伪人开关` 等指令可快速切换全局开关。
|
||||
|
||||
### 伪人(BYM)模式
|
||||
|
||||
1. 在配置中启用 `bym.enable` 并指定 `defaultPreset` 或 `presetMap`。
|
||||
2. 伪人会在命中关键词或达到概率阈值时主动发言,可通过 `presetPrefix` 调整统一人设,`temperature/maxTokens` 控制语气与长度。
|
||||
3. 支持为不同关键词配置 `recall` 秒数,实现“发完撤回”效果。
|
||||
|
||||
### 记忆系统
|
||||
|
||||
- **群记忆指令**
|
||||
```
|
||||
#群记忆 #仅群聊
|
||||
#删除群记忆 1 #主人或群管
|
||||
#记忆列表 #主人查看全局开关
|
||||
```
|
||||
- **私人记忆指令**
|
||||
```
|
||||
#记忆 / 我的记忆
|
||||
#他的记忆 @xxx #群聊内查看他人(需其授权)
|
||||
#删除记忆 1
|
||||
```
|
||||
- 记忆抽取依赖配置中的 `memory.group` / `memory.user` 模型与预设,collector 会定期读取群聊历史,必要时可在 `enabledGroups` 中按群号白名单控制。
|
||||
|
||||
### 更新与维护
|
||||
|
||||
- `#chatgpt更新`:git pull 插件仓库并使用 pnpm/npm 更新 chaite 依赖。
|
||||
- `#chatgpt强制更新`:在更新前执行 `git checkout .`,用于舍弃本地改动。
|
||||
- 日志会通过转发消息发送最近 20 条 commit,方便追踪版本变化。
|
||||
|
||||
|
||||
## 赞助
|
||||
|
||||
### 相关配置
|
||||
如果觉得本项目好玩或者对你有帮助,愿意的话可以赞助我一口快乐水:
|
||||
|
||||
#### 配置文件相关
|
||||
|
||||
配置文件位置:`plugins/chatgpt-plugin/config/config.js`
|
||||
|
||||
部分关键配置项,其他请参照文件内注释:
|
||||
|
||||
| 名称 | 含义 | 解释 |
|
||||
| :---------------: | :-----------------: | :----------------------------------------------------: |
|
||||
| PROXY | 代理地址 | 请在此处配置你的代理,例如`http://127.0.0.1:7890` |
|
||||
| API_KEY | openai账号的API Key | 获取地址:https://platform.openai.com/account/api-keys |
|
||||
| username/password | openai的账号和密码 | / |
|
||||
|
||||
#### Token相关
|
||||
|
||||
与Token相关的设置需在qq与机器人对话设置,设置后方可使用对应的api
|
||||
|
||||
| 名称 | 含义 | 解释 | 设置方式 |
|
||||
| :-----------------: | :------------------: | :----------------------------------------------------------: | :--------------------: |
|
||||
| ChatGPT AccessToken | ChatGPT登录后的Token | 具体解释见下方 | \#chatgpt设置token |
|
||||
| 必应token | 必应登录后的Token | 必应(Bing)将调用微软新必应接口进行对话。需要在必应网页能够正常使用新必应且设置有效的Bing 登录Cookie方可使用 | \#chatgpt设置必应token |
|
||||
|
||||
|
||||
|
||||
> #### 我没有注册openai账号?如何获取
|
||||
>
|
||||
> 您可以按照以下方法获取openai账号
|
||||
>
|
||||
> 进入https://chat.openai.com/ ,选择signup注册。目前openai不对包括俄罗斯、乌克兰、伊朗、中国等国家和地区提供服务,所以自行寻找办法使用**其他国家和地区**的ip登录。此外,注册可能需要验证所在国家和地区的手机号码,如果没有国外手机号可以试试解码网站,收费的推荐https://sms-activate.org/
|
||||
>
|
||||
> #### 我有openai账号了,如何获取API key和Access Token?
|
||||
>
|
||||
> - 获取API key
|
||||
> - 进入账户后台创建API key(Create new secret key):https://platform.openai.com/account/api-keys
|
||||
>
|
||||
> - 获取Access Token
|
||||
> - **登录后**访问https://chat.openai.com/api/auth/session
|
||||
> - 您会获得类似如下一串json字符串`{"user":{"id":"AAA","name":"BBB","email":"CCC","image":"DDD","picture":"EEE","groups":[]},"expires":"FFF","accessToken":"XXX"}`
|
||||
> - 其中的XXX即为`ChatGPT AccessToken`
|
||||
>
|
||||
> #### ChatGPT AccessToken 设置了有什么用?我为什么用不了API模式
|
||||
>
|
||||
> - 请参考上方 [API模式和浏览器模式如何选择?](#API模式和浏览器模式如何选择?)
|
||||
> - 部分API需要在和机器人的聊天里输入`#chatgpt设置token`才可以使用
|
||||
>
|
||||
> #### 我有新必应的测试资格了,如何获取必应Token?
|
||||
>
|
||||
> 1. JS一键获取
|
||||
>
|
||||
> 登录www.bing.com,刷新一下网页,按F12或直接打开开发者模式,点击Console/控制台,运行如下代码,执行后即在您的剪切板存储了必应Token
|
||||
>
|
||||
> ```js
|
||||
> copy(document.cookie.split(";").find(cookie=>cookie.trim().startsWith("_U=")).split("=")[1]);
|
||||
> ```
|
||||
>
|
||||
> 2. 手动获取
|
||||
>
|
||||
> 登录www.bing.com,刷新一下网页,按F12或直接打开开发者模式,点击Application/存储,点击左侧Storage下的Cookies,展开找到[https://www.bing.com](https://www.bing.com/) 项,在右侧列表Name项下找到"\_U",_U的value即为必应Token
|
||||
>
|
||||
>
|
||||
>
|
||||
> 其他问题可以参考使用的api库 https://github.com/transitive-bullshit/chatgpt-api 以及 https://github.com/waylaidwanderer/node-chatgpt-api
|
||||
|
||||
|
||||
|
||||
### 使用方法
|
||||
|
||||
根据配置文件中的toggleMode决定联通方式。
|
||||
|
||||
- at模式:@机器人 发送聊内容即可
|
||||
|
||||
- prefix模式:【#chat+问题】,本模式可以避免指令冲突。
|
||||
|
||||
发挥你的想象力吧,~~调教~~拟造出你自己的机器人风格!
|
||||
|
||||
|
||||
#### 文本/图片回复模式
|
||||
|
||||
> #chatgpt文本/图片/语音模式
|
||||
|
||||
可以控制机器人回复的方式
|
||||
|
||||
#### 对话相关
|
||||
|
||||
> #chatgpt对话列表
|
||||
>
|
||||
> #结束对话 [@某人]
|
||||
>
|
||||
> #清空chat队列
|
||||
>
|
||||
> #移出chat队列首位
|
||||
>
|
||||
> #chatgpt开启/关闭问题确认
|
||||
>
|
||||
> ...
|
||||
|
||||
#### 设置相关
|
||||
|
||||
> #chat切换浏览器/API/API2/API3/Bing
|
||||
>
|
||||
> #chatgpt设置[必应]Token
|
||||
>
|
||||
> ...
|
||||
|
||||
#### 获取帮助
|
||||
|
||||
> #chatgpt帮助
|
||||
>
|
||||
> #chatgpt模式帮助
|
||||
|
||||
发送#chatgpt帮助,有更多选项可以配置
|
||||
|
||||
### 如何更新
|
||||
|
||||
发送#chatgpt更新指令。如果有冲突,可以使用#chatgpt强制更新。
|
||||
|
||||
## 示例与截图
|
||||
|
||||
- 程序员版
|
||||
|
||||

|
||||
|
||||
- 傲娇版
|
||||
|
||||

|
||||

|
||||
|
||||
## TODO
|
||||
|
||||
* prompt预设与共享
|
||||
|
||||
## 其他
|
||||
|
||||
### 常见问题
|
||||
|
||||
1. 如果在linux系统上发现图片模式下emoj无法正常显示,可以搜索安装支持emoj的字体,如Ubuntu可以使用`sudo apt install fonts-noto-color-emoji`
|
||||
|
||||
2. 我和机器人聊天但没有任何反应怎么办?
|
||||
|
||||
可能是由于Yunzai-bot异常退出等原因造成Redis 队列中有残留的等待问题。使用`#清空队列`命令清除队列后再试。
|
||||
|
||||
3. Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'xxx'.
|
||||
|
||||
请参照本文档前面的安装依赖部分重新依赖。随着项目更新可能引入新的依赖。
|
||||
|
||||
> 一般情况下请按照 [安装](#安装) 小节的内容重新安装依赖即可
|
||||
>
|
||||
>
|
||||
>
|
||||
> 最多的问题:载入插件错误:chat
|
||||
>
|
||||
> 问题详情:Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'showdown' imported from /app/Yunzai-Bot/plugins/chatgpt-plugin/apps/chat.js
|
||||
>
|
||||
> 原因:没装依赖
|
||||
>
|
||||
> 解决方式:请参考文档在本插件目录下用`pnpm install`安装依赖,安装完就不报错了
|
||||
|
||||
4. 反代能自己搭吗?
|
||||
|
||||
能。参考[这里](https://ikechan8370.com/archives/da-jian-chatgpt-guan-fang-fan-xiang-dai-li)
|
||||
|
||||
5. vit API能本地搭建吗?
|
||||
|
||||
能。克隆下来安装依赖直接运行即可。
|
||||
## 交流群
|
||||
|
||||
* QQ 559567232
|
||||
|
||||
## 感谢
|
||||
|
||||
本项目使用或参考了以下开源项目
|
||||
* https://github.com/transitive-bullshit/chatgpt-api
|
||||
* https://github.com/waylaidwanderer/node-chatgpt-api
|
||||
* https://github.com/acheong08/ChatGPT
|
||||
* https://github.com/PawanOsman
|
||||
|
||||
图片以及Bing模式支持 @HalcyonAlcedo
|
||||
* https://github.com/HalcyonAlcedo/ChatGPT-Plugin-PageCache
|
||||
|
||||
语音vits模型来自于
|
||||
* https://huggingface.co/spaces/sayashi/vits-uma-genshin-honkai
|
||||
|
||||
以及ChatGPT及OpenAI
|
||||
* https://chat.openai.com/
|
||||
* https://platform.openai.com/
|
||||
https://afdian.net/a/ikechan8370
|
||||
|
||||
## 贡献者
|
||||
|
||||
|
|
@ -285,3 +161,8 @@ pnpm i
|
|||
|
||||
|
||||

|
||||
|
||||
## Star History
|
||||
|
||||
[](https://star-history.com/#ikechan8370/chatgpt-plugin&Date)
|
||||
|
||||
|
|
|
|||
8
Redis.md
8
Redis.md
|
|
@ -1,8 +0,0 @@
|
|||
## 本插件使用的一些redis键值说明
|
||||
|
||||
### 官方(API3/浏览器模式)
|
||||
* CHATGPT:QQ_CONVERSATION:123456789 qq号为123456789的人当前正在使用哪个对话
|
||||
* CHATGPT:CONVERSATION_LAST_MESSAGE_ID:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话,最后一条用户发出的消息的id
|
||||
* CHATGPT:CONVERSATION_LAST_MESSAGE_PROMPT:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话,最后一条用户发出的消息的内容(问题)
|
||||
* CHATGPT:CONVERSATION_CREATE_TIME:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话创建时间
|
||||
* CHATGPT:CONVERSATION_LENGTH:26001339-9043-435d-8394-c553a3109fdf id为`26001339-9043-435d-8394-c553a3109fdf`的对话当前长度(不计分支)
|
||||
155
apps/bym.js
Normal file
155
apps/bym.js
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
import ChatGPTConfig from '../config/config.js'
|
||||
import { Chaite } from 'chaite'
|
||||
import { intoUserMessage, toYunzai } from '../utils/message.js'
|
||||
import common from '../../../lib/common/common.js'
|
||||
import { getGroupContextPrompt } from '../utils/group.js'
|
||||
import { formatTimeToBeiJing } from '../utils/common.js'
|
||||
import { extractTextFromUserMessage, processUserMemory } from '../models/memory/userMemoryManager.js'
|
||||
import { buildMemoryPrompt } from '../models/memory/prompt.js'
|
||||
|
||||
export class bym extends plugin {
|
||||
constructor () {
|
||||
super({
|
||||
name: 'ChatGPT-Plugin伪人模式',
|
||||
dsc: 'ChatGPT-Plugin伪人模式',
|
||||
event: 'message',
|
||||
priority: 6000,
|
||||
rule: [
|
||||
{
|
||||
reg: '^[^#][sS]*',
|
||||
fnc: 'bym',
|
||||
log: false
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
async bym (e) {
|
||||
if (!Chaite.getInstance()) {
|
||||
return false
|
||||
}
|
||||
if (!ChatGPTConfig.bym.enable) {
|
||||
return false
|
||||
}
|
||||
let prob = ChatGPTConfig.bym.probability
|
||||
if (ChatGPTConfig.bym.hit.find(keyword => e.msg?.includes(keyword))) {
|
||||
prob = 1
|
||||
}
|
||||
if (Math.random() > prob) {
|
||||
return false
|
||||
}
|
||||
logger.info('伪人模式触发')
|
||||
let recall = false
|
||||
let presetId = ChatGPTConfig.bym.defaultPreset
|
||||
if (ChatGPTConfig.bym.presetMap && ChatGPTConfig.bym.presetMap.length > 0) {
|
||||
const option = ChatGPTConfig.bym.presetMap.sort((a, b) => b.priority - a.priority)
|
||||
.find(item => item.keywords.find(keyword => e.msg?.includes(keyword)))
|
||||
if (option) {
|
||||
presetId = option.presetId
|
||||
recall = !!option.recall
|
||||
}
|
||||
}
|
||||
|
||||
const presetManager = Chaite.getInstance().getChatPresetManager()
|
||||
let preset = await presetManager.getInstance(presetId)
|
||||
if (!preset) {
|
||||
preset = await presetManager.getInstance(ChatGPTConfig.bym.defaultPreset)
|
||||
}
|
||||
if (!preset) {
|
||||
logger.debug('未找到预设,请检查配置文件')
|
||||
return false
|
||||
}
|
||||
/**
|
||||
* @type {import('chaite').SendMessageOption}
|
||||
*/
|
||||
const sendMessageOption = JSON.parse(JSON.stringify(preset.sendMessageOption))
|
||||
if (ChatGPTConfig.bym.presetPrefix) {
|
||||
if (!sendMessageOption.systemOverride) {
|
||||
sendMessageOption.systemOverride = ''
|
||||
}
|
||||
sendMessageOption.systemOverride = ChatGPTConfig.bym.presetPrefix + sendMessageOption.systemOverride
|
||||
}
|
||||
sendMessageOption.systemOverride = `Current Time: ${formatTimeToBeiJing(new Date().getTime())}\n` + sendMessageOption.systemOverride
|
||||
if (ChatGPTConfig.bym.temperature >= 0) {
|
||||
sendMessageOption.temperature = ChatGPTConfig.bym.temperature
|
||||
}
|
||||
if (ChatGPTConfig.bym.maxTokens > 0) {
|
||||
sendMessageOption.maxToken = ChatGPTConfig.bym.maxTokens
|
||||
}
|
||||
const userMessage = await intoUserMessage(e, {
|
||||
handleReplyText: true,
|
||||
handleReplyImage: true,
|
||||
useRawMessage: true,
|
||||
handleAtMsg: true,
|
||||
excludeAtBot: false,
|
||||
toggleMode: ChatGPTConfig.basic.toggleMode,
|
||||
togglePrefix: ChatGPTConfig.basic.togglePrefix
|
||||
})
|
||||
const userText = extractTextFromUserMessage(userMessage) || e.msg || ''
|
||||
// 伪人不记录历史
|
||||
// sendMessageOption.disableHistoryRead = true
|
||||
// sendMessageOption.disableHistorySave = true
|
||||
sendMessageOption.conversationId = 'bym' + e.user_id + Date.now()
|
||||
sendMessageOption.parentMessageId = undefined
|
||||
// 设置多轮调用回掉
|
||||
sendMessageOption.onMessageWithToolCall = async content => {
|
||||
const { msgs, forward } = await toYunzai(e, [content])
|
||||
if (msgs.length > 0) {
|
||||
await e.reply(msgs)
|
||||
}
|
||||
for (let forwardElement of forward) {
|
||||
this.reply(forwardElement)
|
||||
}
|
||||
}
|
||||
const systemSegments = []
|
||||
if (sendMessageOption.systemOverride) {
|
||||
systemSegments.push(sendMessageOption.systemOverride)
|
||||
}
|
||||
if (userText) {
|
||||
const memoryPrompt = await buildMemoryPrompt({
|
||||
userId: e.sender.user_id + '',
|
||||
groupId: e.isGroup ? e.group_id + '' : null,
|
||||
queryText: userText
|
||||
})
|
||||
if (memoryPrompt) {
|
||||
systemSegments.push(memoryPrompt)
|
||||
logger.debug(`[Memory] bym memory prompt: ${memoryPrompt}`)
|
||||
}
|
||||
}
|
||||
if (ChatGPTConfig.llm.enableGroupContext && e.isGroup) {
|
||||
const contextPrompt = await getGroupContextPrompt(e, ChatGPTConfig.llm.groupContextLength)
|
||||
if (contextPrompt) {
|
||||
systemSegments.push(contextPrompt)
|
||||
}
|
||||
}
|
||||
if (systemSegments.length > 0) {
|
||||
sendMessageOption.systemOverride = systemSegments.join('\n\n')
|
||||
}
|
||||
// 发送
|
||||
const response = await Chaite.getInstance().sendMessage(userMessage, e, {
|
||||
...sendMessageOption,
|
||||
chatPreset: preset
|
||||
})
|
||||
const { msgs, forward } = await toYunzai(e, response.contents)
|
||||
if (msgs.length > 0) {
|
||||
// await e.reply(msgs, false, { recallMsg: recall })
|
||||
for (let msg of msgs) {
|
||||
await e.reply(msg, false, { recallMsg: recall ? 10 : 0 })
|
||||
await common.sleep(Math.floor(Math.random() * 2000) + 1000)
|
||||
}
|
||||
}
|
||||
if (ChatGPTConfig.bym.sendReasoning) {
|
||||
for (let forwardElement of forward) {
|
||||
await e.reply(forwardElement, false, { recallMsg: recall ? 10 : 0 })
|
||||
}
|
||||
}
|
||||
await processUserMemory({
|
||||
event: e,
|
||||
userMessage,
|
||||
userText,
|
||||
conversationId: sendMessageOption.conversationId,
|
||||
assistantContents: response.contents,
|
||||
assistantMessageId: response.id
|
||||
})
|
||||
}
|
||||
}
|
||||
1120
apps/chat.js
1120
apps/chat.js
File diff suppressed because it is too large
Load diff
226
apps/draw.js
226
apps/draw.js
|
|
@ -1,226 +0,0 @@
|
|||
import plugin from '../../../lib/plugins/plugin.js'
|
||||
import { segment } from 'oicq'
|
||||
import { createImage, editImage, imageVariation } from '../utils/dalle.js'
|
||||
import { makeForwardMsg } from '../utils/common.js'
|
||||
import _ from 'lodash'
|
||||
import { Config } from '../utils/config.js'
|
||||
|
||||
export class dalle extends plugin {
|
||||
constructor (e) {
|
||||
super({
|
||||
name: 'ChatGPT-Plugin Dalle 绘图',
|
||||
dsc: 'ChatGPT-Plugin基于OpenAI Dalle的绘图插件',
|
||||
event: 'message',
|
||||
priority: 500,
|
||||
rule: [
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT|dalle|Dalle)(绘图|画图)',
|
||||
fnc: 'draw'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT|dalle|Dalle)(修图|图片变形|改图)$',
|
||||
fnc: 'variation'
|
||||
},
|
||||
{
|
||||
reg: '^#(搞|改)(她|他)头像',
|
||||
fnc: 'avatarVariation'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|dalle)编辑图片',
|
||||
fnc: 'edit'
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
async draw (e) {
|
||||
if (!Config.enableDraw) {
|
||||
this.reply('画图功能未开启')
|
||||
return false
|
||||
}
|
||||
let ttl = await redis.ttl(`CHATGPT:DRAW:${e.sender.user_id}`)
|
||||
if (ttl > 0 && !e.isMaster) {
|
||||
this.reply(`冷却中,请${ttl}秒后再试`)
|
||||
return false
|
||||
}
|
||||
let splits = _.split(e.msg, '图', 2)
|
||||
if (splits.length < 2) {
|
||||
this.reply('请带上绘图要求')
|
||||
return false
|
||||
}
|
||||
let rules = _.split(splits[1], '/')
|
||||
let [prompt = '', num = '1', size = '512x512'] = rules.slice(0, 3)
|
||||
if (['256x256', '512x512', '1024x1024'].indexOf(size) === -1) {
|
||||
this.reply('大小不符合要求,必须是256x256/512x512/1024x1024中的一个')
|
||||
return false
|
||||
}
|
||||
await redis.set(`CHATGPT:DRAW:${e.sender.user_id}`, 'c', { EX: 30 })
|
||||
let priceMap = {
|
||||
'1024x1024': 0.02,
|
||||
'512x512': 0.018,
|
||||
'256x256': 0.016
|
||||
}
|
||||
num = parseInt(num, 10)
|
||||
if (num > 5) {
|
||||
this.reply('太多啦!你要花光我的余额吗!')
|
||||
return false
|
||||
}
|
||||
await this.reply(`正在为您绘制大小为${size}的${num}张图片,预计消耗${priceMap[size] * num}美元余额,请稍候……`)
|
||||
try {
|
||||
let images = (await createImage(prompt, num, size)).map(image => segment.image(`base64://${image}`))
|
||||
if (images.length > 1) {
|
||||
this.reply(await makeForwardMsg(e, images, prompt))
|
||||
} else {
|
||||
this.reply(images[0], true)
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(err.response?.data?.error?.message)
|
||||
this.reply(`绘图失败: ${err.response?.data?.error?.message}`, true)
|
||||
await redis.del(`CHATGPT:DRAW:${e.sender.user_id}`)
|
||||
}
|
||||
}
|
||||
|
||||
async variation (e) {
|
||||
if (!Config.enableDraw) {
|
||||
this.reply('画图功能未开启')
|
||||
return false
|
||||
}
|
||||
let ttl = await redis.ttl(`CHATGPT:VARIATION:${e.sender.user_id}`)
|
||||
if (ttl > 0 && !e.isMaster) {
|
||||
this.reply(`冷却中,请${ttl}秒后再试`)
|
||||
return false
|
||||
}
|
||||
let imgUrl
|
||||
if (e.source) {
|
||||
let reply
|
||||
if (e.isGroup) {
|
||||
reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message
|
||||
} else {
|
||||
reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()?.message
|
||||
}
|
||||
if (reply) {
|
||||
for (let val of reply) {
|
||||
if (val.type === 'image') {
|
||||
console.log(val)
|
||||
imgUrl = val.url
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (e.img) {
|
||||
console.log(e.img)
|
||||
imgUrl = e.img[0]
|
||||
}
|
||||
if (!imgUrl) {
|
||||
this.reply('图呢?')
|
||||
return false
|
||||
}
|
||||
await redis.set(`CHATGPT:VARIATION:${e.sender.user_id}`, 'c', { EX: 30 })
|
||||
await this.reply('正在为您生成图片变形,请稍候……')
|
||||
try {
|
||||
let images = (await imageVariation(imgUrl)).map(image => segment.image(`base64://${image}`))
|
||||
if (images.length > 1) {
|
||||
this.reply(await makeForwardMsg(e, images))
|
||||
} else {
|
||||
this.reply(images[0], true)
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {}))
|
||||
this.reply(`绘图失败: ${err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {})}`, true)
|
||||
await redis.del(`CHATGPT:VARIATION:${e.sender.user_id}`)
|
||||
}
|
||||
}
|
||||
|
||||
async avatarVariation (e) {
|
||||
if (!Config.enableDraw) {
|
||||
this.reply('画图功能未开启')
|
||||
return false
|
||||
}
|
||||
let ats = e.message.filter(m => m.type === 'at').filter(at => at.qq !== e.self_id)
|
||||
if (ats.length > 0) {
|
||||
for (let i = 0; i < ats.length; i++) {
|
||||
let qq = ats[i].qq
|
||||
let imgUrl = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${qq}`
|
||||
try {
|
||||
let images = (await imageVariation(imgUrl)).map(image => segment.image(`base64://${image}`))
|
||||
if (images.length > 1) {
|
||||
this.reply(await makeForwardMsg(e, images))
|
||||
} else {
|
||||
this.reply(images[0], true)
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {}))
|
||||
this.reply(`搞失败了: ${err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {})}`, true)
|
||||
await redis.del(`CHATGPT:VARIATION:${e.sender.user_id}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async edit (e) {
|
||||
if (!Config.enableDraw) {
|
||||
this.reply('画图功能未开启')
|
||||
return false
|
||||
}
|
||||
let ttl = await redis.ttl(`CHATGPT:EDIT:${e.sender.user_id}`)
|
||||
if (ttl > 0 && !e.isMaster) {
|
||||
this.reply(`冷却中,请${ttl}秒后再试`)
|
||||
return false
|
||||
}
|
||||
let imgUrl
|
||||
if (e.source) {
|
||||
let reply
|
||||
if (e.isGroup) {
|
||||
reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message
|
||||
} else {
|
||||
reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()?.message
|
||||
}
|
||||
if (reply) {
|
||||
for (let val of reply) {
|
||||
if (val.type === 'image') {
|
||||
console.log(val)
|
||||
imgUrl = val.url
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (e.img) {
|
||||
console.log(e.img)
|
||||
imgUrl = e.img[0]
|
||||
}
|
||||
if (!imgUrl) {
|
||||
this.reply('图呢?')
|
||||
return false
|
||||
}
|
||||
await redis.set(`CHATGPT:EDIT:${e.sender.user_id}`, 'c', { EX: 30 })
|
||||
await this.reply('正在为您编辑图片,请稍候……')
|
||||
|
||||
let command = _.trimStart(e.msg, '#chatgpt编辑图片')
|
||||
command = _.trimStart(command, '#dalle编辑图片')
|
||||
// command = 'A bird on it/100,100,300,200/2/512x512'
|
||||
let args = command.split('/')
|
||||
let [prompt = '', position = '', num = '1', size = '512x512'] = args.slice(0, 4)
|
||||
if (!prompt || !position) {
|
||||
this.reply('编辑图片必须填写prompt和涂抹位置.参考格式:A bird on it/100,100,300,200/2/512x512')
|
||||
return false
|
||||
}
|
||||
num = parseInt(num, 10)
|
||||
if (num > 5) {
|
||||
this.reply('太多啦!你要花光我的余额吗!')
|
||||
return false
|
||||
}
|
||||
try {
|
||||
let images = (await editImage(imgUrl, position.split(',').map(p => parseInt(p, 10)), prompt, num, size))
|
||||
.map(image => segment.image(`base64://${image}`))
|
||||
if (images.length > 1) {
|
||||
this.reply(await makeForwardMsg(e, images, prompt))
|
||||
} else {
|
||||
this.reply(images[0], true)
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {}))
|
||||
this.reply(`图片编辑失败: ${err.response?.data?.error?.message || err.message || JSON.stringify(err.response || {})}`, true)
|
||||
await redis.del(`CHATGPT:EDIT:${e.sender.user_id}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
import plugin from '../../../lib/plugins/plugin.js'
|
||||
import { Config } from '../utils/config.js'
|
||||
import { generateHello } from '../utils/randomMessage.js'
|
||||
import { segment } from 'oicq'
|
||||
import { generateAudio } from '../utils/tts.js'
|
||||
|
||||
export class Entertainment extends plugin {
|
||||
constructor (e) {
|
||||
super({
|
||||
name: 'ChatGPT-Plugin娱乐小功能',
|
||||
dsc: 'ChatGPT-Plugin娱乐小功能',
|
||||
event: 'message',
|
||||
priority: 500,
|
||||
rule: [
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)打招呼',
|
||||
fnc: 'sendMessage',
|
||||
permission: 'master'
|
||||
}
|
||||
]
|
||||
})
|
||||
this.task = [
|
||||
{
|
||||
// 每半小时
|
||||
cron: '*/30 * * * ?',
|
||||
name: 'ChatGPT主动随机说话',
|
||||
fnc: this.sendRandomMessage.bind(this)
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
async sendMessage (e) {
|
||||
let groupId = e.msg.replace(/^#(chatgpt|ChatGPT)打招呼/, '')
|
||||
groupId = parseInt(groupId)
|
||||
if (groupId && !Bot.getGroupList().get(groupId)) {
|
||||
await e.reply('机器人不在这个群里!')
|
||||
return
|
||||
}
|
||||
let message = await generateHello()
|
||||
let sendable = message
|
||||
logger.info(`打招呼给群聊${groupId}:` + message)
|
||||
if (Config.defaultUseTTS) {
|
||||
let audio = await generateAudio(message, Config.defaultTTSRole)
|
||||
sendable = segment.record(audio)
|
||||
}
|
||||
if (!groupId) {
|
||||
await e.reply(sendable)
|
||||
} else {
|
||||
await Bot.sendGroupMsg(groupId, sendable)
|
||||
await e.reply('发送成功!')
|
||||
}
|
||||
}
|
||||
|
||||
async sendRandomMessage () {
|
||||
if (Config.debug) {
|
||||
logger.info('开始处理:ChatGPT随机打招呼。')
|
||||
}
|
||||
let toSend = Config.initiativeChatGroups || []
|
||||
for (let i = 0; i < toSend.length; i++) {
|
||||
if (!toSend[i]) {
|
||||
continue
|
||||
}
|
||||
let groupId = parseInt(toSend[i])
|
||||
if (Bot.getGroupList().get(groupId)) {
|
||||
// 5%的概率打招呼
|
||||
if (Math.floor(Math.random() * 100) < 5 && !(await redis.get(`CHATGPT:HELLO_GROUP:${groupId}`))) {
|
||||
await redis.set(`CHATGPT:HELLO_GROUP:${groupId}`, '1', { EX: 3600 * 6 })
|
||||
let message = await generateHello()
|
||||
logger.info(`打招呼给群聊${groupId}:` + message)
|
||||
if (Config.defaultUseTTS) {
|
||||
let audio = await generateAudio(message, Config.defaultTTSRole)
|
||||
await Bot.sendGroupMsg(groupId, segment.record(audio))
|
||||
} else {
|
||||
await Bot.sendGroupMsg(groupId, message)
|
||||
}
|
||||
} else {
|
||||
logger.info(`时机未到,这次就不打招呼给群聊${groupId}了`)
|
||||
}
|
||||
} else {
|
||||
logger.warn('机器人不在要发送的群组里,忽略群。同时建议检查配置文件修改要打招呼的群号。' + groupId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
247
apps/help.js
247
apps/help.js
|
|
@ -1,247 +0,0 @@
|
|||
import plugin from '../../../lib/plugins/plugin.js'
|
||||
import { Config } from '../utils/config.js'
|
||||
import { render } from '../utils/common.js'
|
||||
let version = Config.version
|
||||
let helpData = [
|
||||
{
|
||||
group: '聊天',
|
||||
list: [
|
||||
{
|
||||
icon: 'chat',
|
||||
title: Config.toggleMode === 'at' ? '@我+聊天内容' : '#chat+聊天内容',
|
||||
desc: '与机器人聊天'
|
||||
},
|
||||
{
|
||||
icon: 'chat-private',
|
||||
title: '私聊与我对话',
|
||||
desc: '与机器人聊天'
|
||||
},
|
||||
{
|
||||
icon: 'switch',
|
||||
title: '#chatgpt切换对话+对话id',
|
||||
desc: '目前仅API3模式下可用,切换到指定的对话中'
|
||||
},
|
||||
{
|
||||
icon: 'switch',
|
||||
title: '#chatgpt加入对话+@某人',
|
||||
desc: '目前仅API3模式下可用,加入到某人当前进行的对话中'
|
||||
},
|
||||
{
|
||||
icon: 'destroy',
|
||||
title: '#chatgpt删除对话+对话id或@用户',
|
||||
desc: '删除指定对话,并清空与用户的关联信息。@用户时支持多个用户'
|
||||
},
|
||||
{
|
||||
icon: 'destroy',
|
||||
title: '#结束对话',
|
||||
desc: '结束自己当前对话,下次开启对话机器人将遗忘掉本次对话内容。'
|
||||
},
|
||||
{
|
||||
icon: 'destroy',
|
||||
title: '#结束全部对话',
|
||||
desc: '结束正在与本机器人进行对话的全部用户的对话。'
|
||||
},
|
||||
{
|
||||
icon: 'destroy-other',
|
||||
title: '#结束对话 @某人',
|
||||
desc: '结束该用户当前对话,下次开启对话机器人将遗忘掉本次对话内容。'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
group: '画图',
|
||||
list: [
|
||||
{
|
||||
icon: 'draw',
|
||||
title: '#chatgpt画图+prompt(/张数/图片大小)',
|
||||
desc: '调用OpenAI Dalle API进行绘图,需要有API key并消耗余额。图片大小只能是256x256/512x512/1024x1024中的一个.默认为1张、512x512'
|
||||
},
|
||||
{
|
||||
icon: 'draw',
|
||||
title: '#chatgpt改图',
|
||||
desc: '调用OpenAI Dalle API进行改图,需要有API key并消耗余额。可同时发送图片或回复图片'
|
||||
},
|
||||
{
|
||||
icon: 'switch',
|
||||
title: '#chatgpt开启/关闭画图',
|
||||
desc: '开启或关闭画图功能'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
group: '管理',
|
||||
list: [
|
||||
{
|
||||
icon: 'picture',
|
||||
title: '#chatgpt图片模式',
|
||||
desc: '机器人以图片形式回答'
|
||||
},
|
||||
{
|
||||
icon: 'text',
|
||||
title: '#chatgpt文本模式',
|
||||
desc: '机器人以文本形式回答,默认选项'
|
||||
},
|
||||
{
|
||||
icon: 'sound',
|
||||
title: '#chatgpt语音模式',
|
||||
desc: '机器人以语音形式回答'
|
||||
},
|
||||
{
|
||||
icon: 'game',
|
||||
title: '#chatgpt设置语音角色',
|
||||
desc: '设置语音模式下回复的角色音色'
|
||||
},
|
||||
{
|
||||
icon: 'list',
|
||||
title: '#chatgpt对话列表',
|
||||
desc: '查询当前哪些人正在与机器人聊天.目前API3模式下支持切换对话'
|
||||
},
|
||||
{
|
||||
icon: 'blue',
|
||||
title: '#chatgpt(本群)?(群xxx)?闭嘴(x秒/分钟/小时)',
|
||||
desc: '让机器人在本群/某群闭嘴。不指定群时认为全局闭嘴。'
|
||||
},
|
||||
{
|
||||
icon: 'eye',
|
||||
title: '#chatgpt(本群)?(群xxx)?(张嘴|开口|说话|上班)',
|
||||
desc: '让机器人在本群/某群重新可以说话。不指定群时认为全局开口。'
|
||||
},
|
||||
{
|
||||
icon: 'list',
|
||||
title: '#chatgpt查看闭嘴',
|
||||
desc: '查看当前闭嘴情况。'
|
||||
},
|
||||
{
|
||||
icon: 'queue',
|
||||
title: '#清空chat队列',
|
||||
desc: '清空当前对话等待队列。仅建议前方卡死时使用。仅API3模式下可用'
|
||||
},
|
||||
{
|
||||
icon: 'queue',
|
||||
title: '#移出chat队列首位',
|
||||
desc: '移出当前对话等待队列中的首位。若前方对话卡死可使用本命令。仅API3模式下可用'
|
||||
},
|
||||
{
|
||||
icon: 'confirm',
|
||||
title: '#chatgpt开启/关闭问题确认',
|
||||
desc: '开启或关闭机器人收到消息后的确认回复消息。'
|
||||
},
|
||||
{
|
||||
icon: 'switch',
|
||||
title: '#chatgpt切换浏览器/API/API2/API3/Bing',
|
||||
desc: '切换使用的后端为浏览器或OpenAI API/第三方API/反代官网API/Bing'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
group: '设置',
|
||||
list: [
|
||||
{
|
||||
icon: 'token',
|
||||
title: '#chatgpt设置(必应)token',
|
||||
desc: '设置ChatGPT或bing的Token'
|
||||
},
|
||||
{
|
||||
icon: 'coin',
|
||||
title: '#OpenAI剩余额度',
|
||||
desc: '查询OpenAI API剩余试用额度'
|
||||
},
|
||||
{
|
||||
icon: 'key',
|
||||
title: '#chatgpt设置APIKey',
|
||||
desc: '设置APIKey'
|
||||
},
|
||||
{
|
||||
icon: 'eat',
|
||||
title: '#chatgpt设置(API|Sydney)设定',
|
||||
desc: '设置AI的默认风格设定'
|
||||
},
|
||||
{
|
||||
icon: 'eat',
|
||||
title: '#chatgpt查看(API|Sydney)设定',
|
||||
desc: '查看AI当前的风格设定,文本形式返回,设定太长可能发不出来'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
group: '设定',
|
||||
list: [
|
||||
{
|
||||
icon: 'smiley-wink',
|
||||
title: '#chatgpt设定列表',
|
||||
desc: '查看所有设定列表,以转发消息形式'
|
||||
},
|
||||
{
|
||||
icon: 'eat',
|
||||
title: '#chatgpt查看设定【设定名】',
|
||||
desc: '查看指定名字的设定内容。其中API默认和Sydney默认为锅巴面板配置的设定'
|
||||
},
|
||||
{
|
||||
icon: 'coin',
|
||||
title: '#chatgpt添加设定',
|
||||
desc: '添加一个设定,分此输入设定名称和设定内容'
|
||||
},
|
||||
{
|
||||
icon: 'switch',
|
||||
title: '#chatgpt使用设定【设定名】',
|
||||
desc: '使用某个设定'
|
||||
},
|
||||
{
|
||||
icon: 'confirm',
|
||||
title: '#chatgpt(上传|分享|共享)设定',
|
||||
desc: '敬请期待'
|
||||
},
|
||||
{
|
||||
icon: 'confirm',
|
||||
title: '#chatgpt导入设定',
|
||||
desc: '敬请期待'
|
||||
},
|
||||
{
|
||||
icon: 'help',
|
||||
title: '#chatgpt设定帮助',
|
||||
desc: '设定帮助'
|
||||
},
|
||||
]
|
||||
},
|
||||
{
|
||||
group: '其他',
|
||||
list: [
|
||||
{
|
||||
icon: 'smiley-wink',
|
||||
title: '#chatgpt打招呼(群号)',
|
||||
desc: '让AI随机到某个群去打招呼'
|
||||
},
|
||||
{
|
||||
icon: 'help',
|
||||
title: '#chatgpt模式帮助',
|
||||
desc: '查看多种聊天模式的区别及当前使用的模式'
|
||||
},
|
||||
{
|
||||
icon: 'help',
|
||||
title: '#chatgpt帮助',
|
||||
desc: '获取本帮助'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
export class help extends plugin {
|
||||
constructor (e) {
|
||||
super({
|
||||
name: 'ChatGPT-Plugin帮助',
|
||||
dsc: 'ChatGPT-Plugin帮助',
|
||||
event: 'message',
|
||||
priority: 500,
|
||||
rule: [
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)(命令|帮助|菜单|help|说明|功能|指令|使用说明)$',
|
||||
fnc: 'help'
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
async help (e) {
|
||||
await render(e, 'chatgpt-plugin', 'help/index', { helpData, version })
|
||||
}
|
||||
}
|
||||
|
|
@ -1,535 +1,172 @@
|
|||
import plugin from '../../../lib/plugins/plugin.js'
|
||||
import { Config } from '../utils/config.js'
|
||||
import { BingAIClient } from '@waylaidwanderer/chatgpt-api'
|
||||
import { exec } from 'child_process'
|
||||
import { checkPnpm, formatDuration, parseDuration } from '../utils/common.js'
|
||||
import ChatGPTConfig from '../config/config.js'
|
||||
import { createCRUDCommandRules, createSwitchCommandRules } from '../utils/command.js'
|
||||
import { Chaite, VERSION } from 'chaite'
|
||||
import * as crypto from 'node:crypto'
|
||||
import common from '../../../lib/common/common.js'
|
||||
|
||||
export class ChatgptManagement extends plugin {
|
||||
constructor (e) {
|
||||
export class ChatGPTManagement extends plugin {
|
||||
constructor () {
|
||||
const cmdPrefix = ChatGPTConfig.basic.commandPrefix
|
||||
super({
|
||||
name: 'ChatGPT-Plugin管理',
|
||||
dsc: 'ChatGPT-Plugin管理',
|
||||
event: 'message',
|
||||
priority: 500,
|
||||
priority: 20,
|
||||
rule: [
|
||||
{
|
||||
reg: '#chatgpt开启(问题)?(回复)?确认',
|
||||
fnc: 'turnOnConfirm',
|
||||
reg: `^${cmdPrefix}管理面板$`,
|
||||
fnc: 'managementPanel',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '#chatgpt关闭(问题)?(回复)?确认',
|
||||
fnc: 'turnOffConfirm',
|
||||
reg: `^(${cmdPrefix})?#?结束(全部)?对话$`,
|
||||
fnc: 'destroyConversation'
|
||||
},
|
||||
{
|
||||
reg: `^${cmdPrefix}(bym|伪人)设置默认预设`,
|
||||
fnc: 'setDefaultBymPreset',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '#chatgpt(设置|绑定)(token|Token)',
|
||||
fnc: 'setAccessToken',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '#chatgpt(设置|绑定)(必应|Bing |bing )(token|Token)',
|
||||
fnc: 'setBingAccessToken',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt切换浏览器$',
|
||||
fnc: 'useBrowserBasedSolution',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt切换API$',
|
||||
fnc: 'useOpenAIAPIBasedSolution',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt切换API2$',
|
||||
fnc: 'useReversedAPIBasedSolution',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt切换API3$',
|
||||
fnc: 'useReversedAPIBasedSolution2',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt切换(必应|Bing)$',
|
||||
fnc: 'useBingSolution',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt模式(帮助)?$',
|
||||
fnc: 'modeHelp'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt(强制)?更新$',
|
||||
fnc: 'updateChatGPTPlugin'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt(本群)?(群\\d+)?闭嘴',
|
||||
fnc: 'shutUp',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt(本群)?(群\\d+)?(张嘴|开口|说话|上班)',
|
||||
fnc: 'openMouth',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt查看闭嘴',
|
||||
fnc: 'listShutUp',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt设置(API|key)(Key|key)',
|
||||
fnc: 'setAPIKey',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt设置(API|api)设定',
|
||||
fnc: 'setAPIPromptPrefix',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt设置(Bing|必应|Sydney|悉尼|sydney|bing)设定',
|
||||
fnc: 'setBingPromptPrefix',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt(开启|关闭)画图$',
|
||||
fnc: 'switchDraw',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt查看(API|api)设定$',
|
||||
fnc: 'queryAPIPromptPrefix',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#chatgpt查看(Bing|必应|Sydney|悉尼|sydney|bing)设定$',
|
||||
fnc: 'queryBingPromptPrefix',
|
||||
reg: `^${cmdPrefix}(查看)?(当前)?(配置|信息|统计信息|状态)$`,
|
||||
fnc: 'currentStatus',
|
||||
permission: 'master'
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
async turnOnConfirm (e) {
|
||||
await redis.set('CHATGPT:CONFIRM', 'on')
|
||||
await this.reply('已开启消息确认', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async turnOffConfirm (e) {
|
||||
await redis.set('CHATGPT:CONFIRM', 'off')
|
||||
await this.reply('已关闭消息确认', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async setAccessToken (e) {
|
||||
this.setContext('saveToken')
|
||||
await this.reply('请发送ChatGPT AccessToken', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async setBingAccessToken (e) {
|
||||
this.setContext('saveBingToken')
|
||||
await this.reply('请发送Bing Cookie Token.("_U" cookie from bing.com)', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async saveBingToken () {
|
||||
if (!this.e.msg) return
|
||||
let token = this.e.msg
|
||||
if (token.length < 215) {
|
||||
await this.reply('Bing Token格式错误,请确定获取了有效的_U Cookie或完整的Cookie', true)
|
||||
this.finish('saveToken')
|
||||
return
|
||||
}
|
||||
let cookie
|
||||
if (token?.indexOf('=') > -1) {
|
||||
cookie = token
|
||||
}
|
||||
const bingAIClient = new BingAIClient({
|
||||
userToken: token, // "_U" cookie from bing.com
|
||||
cookie,
|
||||
debug: Config.debug
|
||||
})
|
||||
// 异步就好了,不卡着这个context了
|
||||
bingAIClient.createNewConversation().then(async res => {
|
||||
if (res.clientId) {
|
||||
logger.info('bing token 有效')
|
||||
} else {
|
||||
logger.error('bing token 无效', res)
|
||||
await this.reply(`经检测,Bing Token无效。来自Bing的错误提示:${res.result?.message}`)
|
||||
}
|
||||
})
|
||||
await redis.set('CHATGPT:BING_TOKEN', token)
|
||||
await this.reply('Bing Token设置成功', true)
|
||||
this.finish('saveBingToken')
|
||||
}
|
||||
|
||||
async saveToken () {
|
||||
if (!this.e.msg) return
|
||||
let token = this.e.msg
|
||||
if (!token.startsWith('ey') || token.length < 20) {
|
||||
await this.reply('ChatGPT AccessToken格式错误', true)
|
||||
this.finish('saveToken')
|
||||
return
|
||||
}
|
||||
await redis.set('CHATGPT:TOKEN', token)
|
||||
await this.reply('ChatGPT AccessToken设置成功', true)
|
||||
this.finish('saveToken')
|
||||
}
|
||||
|
||||
async useBrowserBasedSolution (e) {
|
||||
await redis.set('CHATGPT:USE', 'browser')
|
||||
await this.reply('已切换到基于浏览器的解决方案,如果已经对话过建议执行`#结束对话`避免引起404错误')
|
||||
}
|
||||
|
||||
async useOpenAIAPIBasedSolution (e) {
|
||||
let use = await redis.get('CHATGPT:USE')
|
||||
if (use !== 'api') {
|
||||
await redis.set('CHATGPT:USE', 'api')
|
||||
await this.reply('已切换到基于OpenAI API的解决方案,如果已经对话过建议执行`#结束对话`避免引起404错误')
|
||||
} else {
|
||||
await this.reply('当前已经是API模式了')
|
||||
}
|
||||
}
|
||||
|
||||
async useReversedAPIBasedSolution (e) {
|
||||
await this.reply('API2已废弃,处于不可用状态,不会为你切换')
|
||||
// await redis.set('CHATGPT:USE', 'apiReverse')
|
||||
// await this.reply('【暂时不可用,请关注仓库更新和群公告】已切换到基于第三方Reversed CompletionAPI的解决方案,如果已经对话过建议执行`#结束对话`避免引起404错误')
|
||||
}
|
||||
|
||||
async useReversedAPIBasedSolution2 (e) {
|
||||
let use = await redis.get('CHATGPT:USE')
|
||||
if (use !== 'api3') {
|
||||
await redis.set('CHATGPT:USE', 'api3')
|
||||
await this.reply('已切换到基于第三方Reversed Conversastion API(API3)的解决方案')
|
||||
} else {
|
||||
await this.reply('当前已经是API3模式了')
|
||||
}
|
||||
}
|
||||
|
||||
async useBingSolution (e) {
|
||||
let use = await redis.get('CHATGPT:USE')
|
||||
if (use !== 'bing') {
|
||||
await redis.set('CHATGPT:USE', 'bing')
|
||||
// 结束所有人的对话
|
||||
const keys = await redis.keys('CHATGPT:CONVERSATIONS:*')
|
||||
if (keys.length) {
|
||||
const response = await redis.del(keys)
|
||||
if (Config.debug) {
|
||||
console.log('Deleted keys:', response)
|
||||
if (!Chaite.getInstance()) {
|
||||
const waitForChaite = async () => {
|
||||
while (!Chaite.getInstance()) {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000))
|
||||
}
|
||||
} else {
|
||||
console.log('No keys matched the pattern')
|
||||
return Chaite.getInstance()
|
||||
}
|
||||
await this.reply('已切换到基于微软新必应的解决方案,如果已经对话过务必执行`#结束对话`避免引起404错误')
|
||||
} else {
|
||||
await this.reply('当前已经是必应Bing模式了')
|
||||
}
|
||||
}
|
||||
|
||||
async checkAuth (e) {
|
||||
if (!e.isMaster) {
|
||||
e.reply(`只有主人才能命令ChatGPT哦~
|
||||
(*/ω\*)`)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// modified from miao-plugin
|
||||
async updateChatGPTPlugin (e) {
|
||||
let timer
|
||||
if (!await this.checkAuth(e)) {
|
||||
return true
|
||||
}
|
||||
let isForce = e.msg.includes('强制')
|
||||
let command = 'git pull'
|
||||
if (isForce) {
|
||||
command = 'git checkout . && git pull'
|
||||
e.reply('正在执行强制更新操作,请稍等')
|
||||
} else {
|
||||
e.reply('正在执行更新操作,请稍等')
|
||||
}
|
||||
const _path = process.cwd()
|
||||
exec(command, { cwd: `${_path}/plugins/chatgpt-plugin/` }, async function (error, stdout, stderr) {
|
||||
if (/(Already up[ -]to[ -]date|已经是最新的)/.test(stdout)) {
|
||||
e.reply('目前已经是最新版ChatGPT了~')
|
||||
return true
|
||||
}
|
||||
if (error) {
|
||||
e.reply('ChatGPT更新失败!\nError code: ' + error.code + '\n' + error.stack + '\n 请稍后重试。')
|
||||
return true
|
||||
}
|
||||
e.reply('ChatGPT更新成功,正在尝试重新启动Yunzai以应用更新...')
|
||||
e.reply('更新日志:\n' + stdout)
|
||||
timer && clearTimeout(timer)
|
||||
|
||||
let data = JSON.stringify({
|
||||
isGroup: !!e.isGroup,
|
||||
id: e.isGroup ? e.group_id : e.user_id,
|
||||
time: new Date().getTime()
|
||||
waitForChaite().then(() => {
|
||||
this.initCommand(cmdPrefix)
|
||||
})
|
||||
await redis.set('Yz:restart', data, { EX: 120 })
|
||||
let npm = await checkPnpm()
|
||||
timer = setTimeout(function () {
|
||||
let command = `${npm} start`
|
||||
if (process.argv[1].includes('pm2')) {
|
||||
command = `${npm} run restart`
|
||||
} else {
|
||||
this.initCommand(cmdPrefix)
|
||||
}
|
||||
}
|
||||
|
||||
initCommand (cmdPrefix) {
|
||||
this.rule.push(...[
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '渠道', 'channels'),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '预设', 'presets'),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '工具', 'tools'),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '处理器', 'processors'),
|
||||
createSwitchCommandRules.bind(this)(cmdPrefix, '(预设切换|其他人切换预设)', 'customPreset', 1),
|
||||
createSwitchCommandRules.bind(this)(cmdPrefix, '(调试|debug)(模式)?', 'debug'),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '预设切换黑名单', 'customPresetUserBlackList', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '预设切换白名单', 'customPresetUserWhiteList', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '输入屏蔽词', 'promptBlockWords', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '输出屏蔽词', 'responseBlockWords', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '黑名单群', 'blackGroups', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '白名单群', 'whiteGroups', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '黑名单用户', 'blackUsers', false),
|
||||
...createCRUDCommandRules.bind(this)(cmdPrefix, '白名单用户', 'whiteUsers', false),
|
||||
createSwitchCommandRules(cmdPrefix, '(伪人|bym)', 'bym')
|
||||
])
|
||||
}
|
||||
|
||||
managementPanel (e) {
|
||||
// todo
|
||||
// this.reply(`(todo)管理面板地址:http://${ChatGPTConfig.chaite.host}:${ChatGPTConfig.chaite.host}`)
|
||||
const token = Chaite.getInstance().getFrontendAuthHandler().generateToken(300)
|
||||
this.reply(`token: ${token}, 有效期300秒`, true)
|
||||
}
|
||||
|
||||
async setDefaultBymPreset (e) {
|
||||
const presetId = e.msg.replace(`${ChatGPTConfig.basic.commandPrefix}伪人设置默认预设`, '')
|
||||
const preset = await Chaite.getInstance().getChatPresetManager().getInstance(presetId)
|
||||
if (preset) {
|
||||
ChatGPTConfig.bym.defaultPreset = presetId
|
||||
this.reply(`伪人模式默认预设已切换为${presetId}(${preset.name})`)
|
||||
} else {
|
||||
this.reply(`未找到预设${presetId}`)
|
||||
}
|
||||
}
|
||||
|
||||
async destroyConversation (e) {
|
||||
if (e.msg.includes('全部')) {
|
||||
if (!e.isMaster) {
|
||||
this.reply('仅限主人使用')
|
||||
return false
|
||||
}
|
||||
const userStates = await Chaite.getInstance().getUserStateStorage().listItems()
|
||||
// let num = 0
|
||||
for (const userState of userStates) {
|
||||
if (userState.current.conversationId && userState.current.messageId) {
|
||||
// num++
|
||||
userState.current.conversationId = crypto.randomUUID()
|
||||
userState.current.messageId = crypto.randomUUID()
|
||||
await Chaite.getInstance().getUserStateStorage().setItem(userState.userId + '', userState)
|
||||
}
|
||||
exec(command, function (error, stdout, stderr) {
|
||||
if (error) {
|
||||
e.reply('自动重启失败,请手动重启以应用新版ChatGPT。\nError code: ' + error.code + '\n' + error.stack + '\n')
|
||||
Bot.logger.error(`重启失败\n${error.stack}`)
|
||||
return true
|
||||
} else if (stdout) {
|
||||
Bot.logger.mark('重启成功,运行已转为后台,查看日志请用命令:npm run log')
|
||||
Bot.logger.mark('停止后台运行命令:npm stop')
|
||||
process.exit()
|
||||
}
|
||||
})
|
||||
}, 1000)
|
||||
}
|
||||
this.reply('已结束全部对话')
|
||||
} else {
|
||||
const state = await Chaite.getInstance().getUserStateStorage().getItem(e.sender.user_id + '')
|
||||
if (!state || !state.current.conversationId || !state.current.messageId) {
|
||||
this.reply('当前未开启对话')
|
||||
return false
|
||||
}
|
||||
state.current.conversationId = crypto.randomUUID()
|
||||
state.current.messageId = crypto.randomUUID()
|
||||
await Chaite.getInstance().getUserStateStorage().setItem(e.sender.user_id + '', state)
|
||||
this.reply('已结束当前对话')
|
||||
}
|
||||
}
|
||||
|
||||
async currentStatus (e) {
|
||||
const msgs = []
|
||||
let basic = `Chaite版本:${VERSION}\n`
|
||||
const user = Chaite.getInstance().getToolsManager().cloudService?.getUser()
|
||||
if (user) {
|
||||
basic += `Chaite Cloud:已认证 @${user.username}`
|
||||
} else if (ChatGPTConfig.chaite.cloudBaseUrl) {
|
||||
basic += 'Chaite Cloud: 未认证'
|
||||
} else {
|
||||
basic += 'Chaite Cloud: 未接入'
|
||||
}
|
||||
msgs.push(basic)
|
||||
|
||||
const allChannels = await Chaite.getInstance().getChannelsManager().getAllChannels()
|
||||
let channelMsg = `渠道总数:${allChannels.length}\n`
|
||||
channelMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}渠道列表 查看全部渠道\n\n`
|
||||
allChannels.map(c => c.models).reduce((acc, cur) => {
|
||||
acc.push(...cur)
|
||||
return acc
|
||||
}, []).forEach(m => {
|
||||
channelMsg += `${m}:${allChannels.filter(c => c.models.includes(m)).length}个\n`
|
||||
})
|
||||
return true
|
||||
}
|
||||
msgs.push(channelMsg)
|
||||
|
||||
async modeHelp () {
|
||||
let mode = await redis.get('CHATGPT:USE')
|
||||
const modeMap = {
|
||||
browser: '浏览器',
|
||||
apiReverse: 'API2',
|
||||
api: 'API',
|
||||
bing: '必应',
|
||||
api3: 'API3'
|
||||
}
|
||||
let modeText = modeMap[mode || 'api']
|
||||
let message = ` API模式和浏览器模式如何选择?
|
||||
const allPresets = await Chaite.getInstance().getChatPresetManager().getAllPresets()
|
||||
let presetMsg = `预设总数:${allPresets.length}\n`
|
||||
presetMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}预设列表 查看全部预设`
|
||||
msgs.push(presetMsg)
|
||||
|
||||
// eslint-disable-next-line no-irregular-whitespace
|
||||
API模式会调用OpenAI官方提供的gpt-3.5-turbo API,只需要提供API Key。一般情况下,该种方式响应速度更快,不会像chatGPT官网一样总出现不可用的现象,但注意gpt-3.5-turbo的API调用是收费的,新用户有18美元试用金可用于支付,价格为$0.0020/ 1K tokens.(问题和回答加起来算token)
|
||||
|
||||
API3模式会调用官网反代API,他会帮你绕过CF防护,需要提供ChatGPT的Token。效果与官网和浏览器一致。设置token指令:#chatgpt设置token。
|
||||
const defaultChatPresetId = ChatGPTConfig.llm.defaultChatPresetId
|
||||
const currentPreset = await Chaite.getInstance().getChatPresetManager().getInstance(defaultChatPresetId)
|
||||
msgs.push(`当前预设:${currentPreset?.name || '未设置'}${currentPreset ? ('\n\n' + currentPreset.toFormatedString(false)) : ''}`)
|
||||
|
||||
浏览器模式通过在本地启动Chrome等浏览器模拟用户访问ChatGPT网站,使得获得和官方以及API2模式一模一样的回复质量,同时保证安全性。缺点是本方法对环境要求较高,需要提供桌面环境和一个可用的代理(能够访问ChatGPT的IP地址),且响应速度不如API,而且高峰期容易无法使用。
|
||||
const allTools = await Chaite.getInstance().getToolsManager().listInstances()
|
||||
let toolsMsg = `工具总数:${allTools.length}\n`
|
||||
toolsMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}工具列表 查看全部工具`
|
||||
msgs.push(toolsMsg)
|
||||
|
||||
必应(Bing)将调用微软新必应接口进行对话。需要在必应网页能够正常使用新必应且设置有效的Bing 登录Cookie方可使用。#chatgpt设置必应token
|
||||
const allProcessors = await Chaite.getInstance().getProcessorsManager().listInstances()
|
||||
let processorsMsg = `处理器总数:${allProcessors.length}\n`
|
||||
processorsMsg += `请使用 ${ChatGPTConfig.basic.commandPrefix}处理器列表 查看全部处理器`
|
||||
msgs.push(processorsMsg)
|
||||
|
||||
您可以使用‘#chatgpt切换浏览器/API/API2/API3/Bing’来切换到指定模式。
|
||||
const userStatesManager = Chaite.getInstance().getUserStateStorage()
|
||||
const allUsers = await userStatesManager.listItems()
|
||||
const currentUserNums = allUsers.filter(u => u.current.conversationId && u.current.messageId).length
|
||||
const historyUserNums = allUsers.length
|
||||
msgs.push(`用户总数:${historyUserNums}\n当前对话用户数:${currentUserNums}`)
|
||||
|
||||
当前为${modeText}模式。
|
||||
`
|
||||
await this.reply(message)
|
||||
}
|
||||
|
||||
async shutUp (e) {
|
||||
let duration = e.msg.replace(/^#chatgpt(本群)?(群\d+)?闭嘴/, '')
|
||||
let scope
|
||||
let time = 3600000
|
||||
if (duration === '永久') {
|
||||
time = 0
|
||||
} else if (duration) {
|
||||
time = parseDuration(duration)
|
||||
}
|
||||
const match = e.msg.match(/#chatgpt群(\d+)闭嘴(.*)/)
|
||||
if (e.msg.indexOf('本群') > -1) {
|
||||
if (e.isGroup) {
|
||||
scope = e.group.group_id
|
||||
if (await redis.get(`CHATGPT:SHUT_UP:${scope}`)) {
|
||||
await redis.del(`CHATGPT:SHUT_UP:${scope}`)
|
||||
await redis.set(`CHATGPT:SHUT_UP:${scope}`, '1', { EX: time })
|
||||
await e.reply(`好的,从现在开始我会在当前群聊闭嘴${formatDuration(time)}`)
|
||||
} else {
|
||||
await redis.set(`CHATGPT:SHUT_UP:${scope}`, '1', { EX: time })
|
||||
await e.reply(`好的,从现在开始我会在当前群聊闭嘴${formatDuration(time)}`)
|
||||
}
|
||||
} else {
|
||||
await e.reply('本群是指?你也没在群聊里让我闭嘴啊?')
|
||||
return false
|
||||
}
|
||||
} else if (match) {
|
||||
const groupId = parseInt(match[1], 10)
|
||||
if (Bot.getGroupList().get(groupId)) {
|
||||
if (await redis.get(`CHATGPT:SHUT_UP:${groupId}`)) {
|
||||
await redis.del(`CHATGPT:SHUT_UP:${groupId}`)
|
||||
await redis.set(`CHATGPT:SHUT_UP:${groupId}`, '1', { EX: time })
|
||||
await e.reply(`好的,从现在开始我会在群聊${groupId}闭嘴${formatDuration(time)}`)
|
||||
} else {
|
||||
await redis.set(`CHATGPT:SHUT_UP:${groupId}`, '1', { EX: time })
|
||||
await e.reply(`好的,从现在开始我会在群聊${groupId}闭嘴${formatDuration(time)}`)
|
||||
}
|
||||
} else {
|
||||
await e.reply('这是什么群?')
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
|
||||
await redis.del('CHATGPT:SHUT_UP:ALL')
|
||||
await redis.set('CHATGPT:SHUT_UP:ALL', '1', { EX: time })
|
||||
await e.reply(`好的,我会再闭嘴${formatDuration(time)}`)
|
||||
} else {
|
||||
await redis.set('CHATGPT:SHUT_UP:ALL', '1', { EX: time })
|
||||
await e.reply(`好的,我会闭嘴${formatDuration(time)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async openMouth (e) {
|
||||
const match = e.msg.match(/^#chatgpt群(\d+)/)
|
||||
if (e.msg.indexOf('本群') > -1) {
|
||||
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
|
||||
await e.reply('主人,我现在全局闭嘴呢,你让我在这个群张嘴咱也不敢张啊')
|
||||
return false
|
||||
}
|
||||
if (e.isGroup) {
|
||||
let scope = e.group.group_id
|
||||
if (await redis.get(`CHATGPT:SHUT_UP:${scope}`)) {
|
||||
await redis.del(`CHATGPT:SHUT_UP:${scope}`)
|
||||
await e.reply('好的主人,我终于又可以在本群说话了')
|
||||
} else {
|
||||
await e.reply('啊?我也没闭嘴啊?')
|
||||
}
|
||||
} else {
|
||||
await e.reply('本群是指?你也没在群聊里让我张嘴啊?')
|
||||
return false
|
||||
}
|
||||
} else if (match) {
|
||||
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
|
||||
await e.reply('主人,我现在全局闭嘴呢,你让我在那个群张嘴咱也不敢张啊')
|
||||
return false
|
||||
}
|
||||
const groupId = parseInt(match[1], 10)
|
||||
if (Bot.getGroupList().get(groupId)) {
|
||||
if (await redis.get(`CHATGPT:SHUT_UP:${groupId}`)) {
|
||||
await redis.del(`CHATGPT:SHUT_UP:${groupId}`)
|
||||
await e.reply(`好的主人,我终于又可以在群${groupId}说话了`)
|
||||
} else {
|
||||
await e.reply(`啊?我也没在群${groupId}闭嘴啊?`)
|
||||
}
|
||||
} else {
|
||||
await e.reply('这是什么群?')
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
let keys = await redis.keys('CHATGPT:SHUT_UP:*')
|
||||
if (await redis.get('CHATGPT:SHUT_UP:ALL')) {
|
||||
await redis.del('CHATGPT:SHUT_UP:ALL')
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
await redis.del(keys[i])
|
||||
}
|
||||
await e.reply('好的,我会结束所有闭嘴')
|
||||
} else if (keys || keys.length > 0) {
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
await redis.del(keys[i])
|
||||
}
|
||||
await e.reply('好的,我会结束所有闭嘴?')
|
||||
} else {
|
||||
await e.reply('我没有在任何地方闭嘴啊?')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async listShutUp () {
|
||||
let keys = await redis.keys('CHATGPT:SHUT_UP:*')
|
||||
if (!keys || keys.length === 0) {
|
||||
await this.reply('我没有在任何群闭嘴', true)
|
||||
} else {
|
||||
let list = []
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let key = keys[i]
|
||||
let groupId = key.replace('CHATGPT:SHUT_UP:', '')
|
||||
let ttl = await redis.ttl(key)
|
||||
let ttlFormat = formatDuration(ttl)
|
||||
list.push({ groupId, ttlFormat })
|
||||
}
|
||||
await this.reply(list.map(item => item.groupId !== 'ALL' ? `群聊${item.groupId}: ${item.ttlFormat}` : `全局: ${item.ttlFormat}`).join('\n'))
|
||||
}
|
||||
}
|
||||
|
||||
async setAPIKey (e) {
|
||||
this.setContext('saveAPIKey')
|
||||
await this.reply('请发送OpenAI API Key.', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async saveAPIKey () {
|
||||
if (!this.e.msg) return
|
||||
let token = this.e.msg
|
||||
if (!token.startsWith('sk-')) {
|
||||
await this.reply('OpenAI API Key格式错误', true)
|
||||
this.finish('saveAPIKey')
|
||||
return
|
||||
}
|
||||
// todo
|
||||
Config.apiKey = token
|
||||
await this.reply('OpenAI API Key设置成功', true)
|
||||
this.finish('saveAPIKey')
|
||||
}
|
||||
|
||||
async setAPIPromptPrefix (e) {
|
||||
this.setContext('saveAPIPromptPrefix')
|
||||
await this.reply('请发送用于API模式的设定', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async saveAPIPromptPrefix (e) {
|
||||
if (!this.e.msg) return
|
||||
if (this.e.msg === '取消') {
|
||||
await this.reply('已取消设置API设定', true)
|
||||
this.finish('saveAPIPromptPrefix')
|
||||
return
|
||||
}
|
||||
// todo
|
||||
Config.promptPrefixOverride = this.e.msg
|
||||
await this.reply('API模式的设定设置成功', true)
|
||||
this.finish('saveAPIPromptPrefix')
|
||||
}
|
||||
|
||||
async setBingPromptPrefix (e) {
|
||||
this.setContext('saveBingPromptPrefix')
|
||||
await this.reply('请发送用于Bing Sydney模式的设定', true)
|
||||
return false
|
||||
}
|
||||
|
||||
async saveBingPromptPrefix (e) {
|
||||
if (!this.e.msg) return
|
||||
if (this.e.msg === '取消') {
|
||||
await this.reply('已取消设置Sydney设定', true)
|
||||
this.finish('saveBingPromptPrefix')
|
||||
return
|
||||
}
|
||||
Config.sydney = this.e.msg
|
||||
await this.reply('Bing Sydney模式的设定设置成功', true)
|
||||
this.finish('saveBingPromptPrefix')
|
||||
}
|
||||
|
||||
async switchDraw (e) {
|
||||
if (e.msg.indexOf('开启') > -1) {
|
||||
if (Config.enableDraw) {
|
||||
await this.reply('当前已经开启chatgpt画图功能', true)
|
||||
} else {
|
||||
Config.enableDraw = true
|
||||
await this.reply('chatgpt画图功能开启成功', true)
|
||||
}
|
||||
} else {
|
||||
if (!Config.enableDraw) {
|
||||
await this.reply('当前未开启chatgpt画图功能', true)
|
||||
} else {
|
||||
Config.enableDraw = false
|
||||
await this.reply('chatgpt画图功能关闭成功', true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async queryAPIPromptPrefix (e) {
|
||||
await this.reply(Config.promptPrefixOverride, true)
|
||||
}
|
||||
|
||||
async queryBingPromptPrefix (e) {
|
||||
await this.reply(Config.sydney, true)
|
||||
const m = await common.makeForwardMsg(e, msgs, e.msg)
|
||||
e.reply(m)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
224
apps/memory.js
Normal file
224
apps/memory.js
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import Config from '../config/config.js'
|
||||
import { GroupMessageCollector } from '../models/memory/collector.js'
|
||||
import { memoryService } from '../models/memory/service.js'
|
||||
import common from '../../../lib/common/common.js'
|
||||
|
||||
const collector = new GroupMessageCollector()
|
||||
|
||||
function isGroupManager (e) {
|
||||
if (e.isMaster) {
|
||||
return true
|
||||
}
|
||||
if (!e.member) {
|
||||
return false
|
||||
}
|
||||
if (typeof e.member.is_admin !== 'undefined') {
|
||||
return e.member.is_admin || e.member.is_owner
|
||||
}
|
||||
if (typeof e.member.role !== 'undefined') {
|
||||
return ['admin', 'owner'].includes(e.member.role)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export class MemoryManager extends plugin {
|
||||
constructor () {
|
||||
const cmdPrefix = Config.basic.commandPrefix || '#chatgpt'
|
||||
super({
|
||||
name: 'ChatGPT-Plugin记忆系统',
|
||||
dsc: '处理记忆系统相关的采集与管理',
|
||||
event: 'message',
|
||||
priority: 550,
|
||||
rule: [
|
||||
// {
|
||||
// reg: '[\\s\\S]+',
|
||||
// fnc: 'collect',
|
||||
// log: false
|
||||
// },
|
||||
{
|
||||
reg: '^#?(我的)?记忆$',
|
||||
fnc: 'showUserMemory'
|
||||
},
|
||||
{
|
||||
reg: '^#?他的记忆$',
|
||||
fnc: 'showTargetUserMemory'
|
||||
},
|
||||
{
|
||||
reg: '^#?(删除|清除)(我的)?记忆\\s*(\\d+)$',
|
||||
fnc: 'deleteUserMemory'
|
||||
},
|
||||
{
|
||||
reg: '^#?(本群|群)记忆$',
|
||||
fnc: 'showGroupMemory'
|
||||
},
|
||||
{
|
||||
reg: '^#?(删除|移除)群记忆\\s*(\\d+)$',
|
||||
fnc: 'deleteGroupMemory'
|
||||
},
|
||||
{
|
||||
reg: `^${cmdPrefix}记忆列表$`,
|
||||
fnc: 'adminMemoryOverview',
|
||||
permission: 'master'
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
// 兼容miao和trss,气死了
|
||||
let task = {
|
||||
name: 'ChatGPT-群记忆轮询',
|
||||
cron: '*/1 * * * *',
|
||||
fnc: this.pollHistoryTask.bind(this),
|
||||
log: false
|
||||
}
|
||||
this.task = [task]
|
||||
|
||||
}
|
||||
|
||||
async collect (e) {
|
||||
collector.push(e)
|
||||
return false
|
||||
}
|
||||
|
||||
async showUserMemory (e) {
|
||||
if (!memoryService.isUserMemoryEnabled(e.sender.user_id)) {
|
||||
await e.reply('私人记忆未开启或您未被授权。')
|
||||
return false
|
||||
}
|
||||
const memories = memoryService.listUserMemories(e.sender.user_id, e.isGroup ? e.group_id : null)
|
||||
|
||||
if (!memories.length) {
|
||||
await e.reply('🧠 您的记忆:\n暂无记录~')
|
||||
return true
|
||||
}
|
||||
|
||||
const msgs = memories.map(item =>
|
||||
`${item.id}. ${item.value}(更新时间:${item.updated_at})`
|
||||
)
|
||||
|
||||
const forwardMsg = await common.makeForwardMsg(e, ['🧠 您的记忆:', ...msgs], '私人记忆列表')
|
||||
await e.reply(forwardMsg)
|
||||
return true
|
||||
}
|
||||
|
||||
async showTargetUserMemory (e) {
|
||||
if (!e.isGroup) {
|
||||
await e.reply('该指令仅可在群聊中使用。')
|
||||
return false
|
||||
}
|
||||
|
||||
const at = e.at || (e.message?.find(m => m.type === 'at')?.qq)
|
||||
if (!at) {
|
||||
await e.reply('请@要查询的用户。')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!memoryService.isUserMemoryEnabled(at)) {
|
||||
await e.reply('该用户未开启私人记忆或未被授权。')
|
||||
return false
|
||||
}
|
||||
|
||||
const memories = memoryService.listUserMemories(at, e.group_id)
|
||||
|
||||
if (!memories.length) {
|
||||
await e.reply('🧠 TA的记忆:\n暂无记录~')
|
||||
return true
|
||||
}
|
||||
|
||||
const msgs = memories.map(item =>
|
||||
`${item.id}. ${item.value}(更新时间:${item.updated_at})`
|
||||
)
|
||||
|
||||
const forwardMsg = await common.makeForwardMsg(e, ['🧠 TA的记忆:', ...msgs], 'TA的记忆列表')
|
||||
await e.reply(forwardMsg)
|
||||
return true
|
||||
}
|
||||
|
||||
async deleteUserMemory (e) {
|
||||
const match = e.msg.match(/(\d+)$/)
|
||||
if (!match) {
|
||||
return false
|
||||
}
|
||||
const memoryId = Number(match[1])
|
||||
if (!memoryId) {
|
||||
return false
|
||||
}
|
||||
if (!memoryService.isUserMemoryEnabled(e.sender.user_id)) {
|
||||
await e.reply('私人记忆未开启或您未被授权。')
|
||||
return false
|
||||
}
|
||||
const success = memoryService.deleteUserMemory(memoryId, e.sender.user_id)
|
||||
await e.reply(success ? '已删除指定记忆。' : '未找到对应的记忆条目。')
|
||||
return success
|
||||
}
|
||||
|
||||
async showGroupMemory (e) {
|
||||
if (!e.isGroup) {
|
||||
await e.reply('该指令仅可在群聊中使用。')
|
||||
return false
|
||||
}
|
||||
if (!memoryService.isGroupMemoryEnabled(e.group_id)) {
|
||||
await e.reply('本群尚未开启记忆功能。')
|
||||
return false
|
||||
}
|
||||
await collector.flush(e.group_id)
|
||||
const facts = memoryService.listGroupFacts(e.group_id)
|
||||
|
||||
if (!facts.length) {
|
||||
await e.reply('📚 本群记忆:\n暂无群记忆。')
|
||||
return true
|
||||
}
|
||||
|
||||
const msgs = facts.map(item => {
|
||||
const topic = item.topic ? `【${item.topic}】` : ''
|
||||
return `${item.id}. ${topic}${item.fact}`
|
||||
})
|
||||
|
||||
const forwardMsg = await common.makeForwardMsg(e, ['📚 本群记忆:', ...msgs], '群记忆列表')
|
||||
await e.reply(forwardMsg)
|
||||
return true
|
||||
}
|
||||
|
||||
async deleteGroupMemory (e) {
|
||||
if (!e.isGroup) {
|
||||
await e.reply('该指令仅可在群聊中使用。')
|
||||
return false
|
||||
}
|
||||
if (!memoryService.isGroupMemoryEnabled(e.group_id)) {
|
||||
await e.reply('本群尚未开启记忆功能。')
|
||||
return false
|
||||
}
|
||||
if (!isGroupManager(e)) {
|
||||
await e.reply('仅限主人或群管理员管理群记忆。')
|
||||
return false
|
||||
}
|
||||
await collector.flush(e.group_id)
|
||||
const match = e.msg.match(/(\d+)$/)
|
||||
if (!match) {
|
||||
return false
|
||||
}
|
||||
const factId = Number(match[1])
|
||||
if (!factId) {
|
||||
return false
|
||||
}
|
||||
const success = memoryService.deleteGroupFact(e.group_id, factId)
|
||||
await e.reply(success ? '已删除群记忆。' : '未找到对应的群记忆。')
|
||||
return success
|
||||
}
|
||||
|
||||
async adminMemoryOverview (e) {
|
||||
const enabledGroups = (Config.memory?.group?.enabledGroups || []).map(String)
|
||||
const groupLines = enabledGroups.length ? enabledGroups.join(', ') : '暂无'
|
||||
const userStatus = Config.memory?.user?.enable ? '已启用' : '未启用'
|
||||
await e.reply(`记忆系统概览:\n- 群记忆开关:${Config.memory?.group?.enable ? '已启用' : '未启用'}\n- 已启用群:${groupLines}\n- 私人记忆:${userStatus}`)
|
||||
return true
|
||||
}
|
||||
|
||||
async pollHistoryTask () {
|
||||
try {
|
||||
await collector.tickHistoryPolling()
|
||||
} catch (err) {
|
||||
logger.error('[Memory] scheduled history poll failed:', err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
173
apps/prompts.js
173
apps/prompts.js
|
|
@ -1,173 +0,0 @@
|
|||
import plugin from '../../../lib/plugins/plugin.js'
|
||||
import fs from 'fs'
|
||||
import _ from 'lodash'
|
||||
import { Config } from '../utils/config.js'
|
||||
import {limitString, makeForwardMsg} from '../utils/common.js'
|
||||
import { getPromptByName, readPrompts, saveOnePrompt } from '../utils/prompts.js'
|
||||
export class help extends plugin {
|
||||
constructor (e) {
|
||||
super({
|
||||
name: 'ChatGPT-Plugin 设定管理',
|
||||
dsc: 'ChatGPT-Plugin 设定管理',
|
||||
event: 'message',
|
||||
priority: 500,
|
||||
rule: [
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)设定列表$',
|
||||
fnc: 'listPrompts',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)查看设定',
|
||||
fnc: 'detailPrompt',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)使用设定',
|
||||
fnc: 'usePrompt',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)添加设定',
|
||||
fnc: 'addPrompt',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)(上传|分享|共享)设定',
|
||||
fnc: 'uploadPrompt',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)导入设定',
|
||||
fnc: 'importPrompt',
|
||||
permission: 'master'
|
||||
},
|
||||
{
|
||||
reg: '^#(chatgpt|ChatGPT)设定帮助$',
|
||||
fnc: 'helpPrompt',
|
||||
permission: 'master'
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
async listPrompts (e) {
|
||||
let prompts = []
|
||||
let defaultPrompt = {
|
||||
name: 'API默认',
|
||||
content: Config.promptPrefixOverride
|
||||
}
|
||||
let defaultSydneyPrompt = {
|
||||
name: 'Sydney默认',
|
||||
content: Config.sydney
|
||||
}
|
||||
prompts.push(...[defaultPrompt, defaultSydneyPrompt])
|
||||
prompts.push(...readPrompts())
|
||||
console.log(prompts)
|
||||
e.reply(await makeForwardMsg(e, prompts.map(p => `《${p.name}》\n${limitString(p.content, 500)}`), '设定列表'))
|
||||
}
|
||||
|
||||
async detailPrompt (e) {
|
||||
let promptName = e.msg.replace(/^#(chatgpt|ChatGPT)查看设定/, '').trim()
|
||||
let prompt = getPromptByName(promptName)
|
||||
if (!prompt) {
|
||||
if (promptName === 'API默认') {
|
||||
prompt = {
|
||||
name: 'API默认',
|
||||
content: Config.promptPrefixOverride
|
||||
}
|
||||
} else if (promptName === 'Sydney默认') {
|
||||
prompt = {
|
||||
name: 'Sydney默认',
|
||||
content: Config.sydney
|
||||
}
|
||||
} else {
|
||||
await e.reply('没有这个设定', true)
|
||||
return
|
||||
}
|
||||
}
|
||||
await e.reply(`《${prompt.name}》\n${limitString(prompt.content, 500)}`, true)
|
||||
}
|
||||
|
||||
async usePrompt (e) {
|
||||
let promptName = e.msg.replace(/^#(chatgpt|ChatGPT)使用设定/, '').trim()
|
||||
let prompt = getPromptByName(promptName)
|
||||
if (!prompt) {
|
||||
console.log(promptName)
|
||||
if (promptName === 'API默认') {
|
||||
prompt = {
|
||||
name: 'API默认',
|
||||
content: Config.promptPrefixOverride
|
||||
}
|
||||
} else if (promptName === 'Sydney默认') {
|
||||
prompt = {
|
||||
name: 'Sydney默认',
|
||||
content: Config.sydney
|
||||
}
|
||||
} else {
|
||||
await e.reply('没有这个设定', true)
|
||||
return
|
||||
}
|
||||
}
|
||||
let use = await redis.get('CHATGPT:USE') || 'api'
|
||||
if (use.toLowerCase() === 'bing') {
|
||||
if (Config.toneStyle === 'Sydney') {
|
||||
use = 'sydney'
|
||||
}
|
||||
}
|
||||
const keyMap = {
|
||||
api: 'promptPrefixOverride',
|
||||
sydney: 'sydney'
|
||||
}
|
||||
|
||||
if (keyMap[use]) {
|
||||
Config[keyMap[use]] = prompt.content
|
||||
await redis.set(`CHATGPT:PROMPT_USE_${use}`, promptName)
|
||||
await e.reply(`你当前正在使用${use}模式,已将该模式设定应用为"${promptName}。更该设定后建议结束对话以使设定更好生效"`, true)
|
||||
} else {
|
||||
await e.reply(`你当前正在使用${use}模式,改模式不支持设定`, true)
|
||||
}
|
||||
}
|
||||
|
||||
async addPrompt (e) {
|
||||
this.setContext('addPromptName')
|
||||
await e.reply('请输入设定名称', true)
|
||||
}
|
||||
|
||||
async addPromptName () {
|
||||
if (!this.e.msg) return
|
||||
let name = this.e.msg
|
||||
let prompt = getPromptByName(name)
|
||||
if (prompt) {
|
||||
await this.e.reply('该设定已存在', true)
|
||||
this.finish('addPromptName')
|
||||
return
|
||||
}
|
||||
await redis.set('CHATGPT:ADD_PROMPT_NAME', name)
|
||||
await this.reply('请输入设定内容', true)
|
||||
this.finish('addPromptName')
|
||||
this.setContext('addPromptContext')
|
||||
}
|
||||
|
||||
async addPromptContext () {
|
||||
if (!this.e.msg) return
|
||||
let content = this.e.msg
|
||||
let name = await redis.get('CHATGPT:ADD_PROMPT_NAME')
|
||||
saveOnePrompt(name, content)
|
||||
await redis.del('CHATGPT:ADD_PROMPT_NAME')
|
||||
await this.reply('设定添加成功', true)
|
||||
this.finish('addPromptContext')
|
||||
}
|
||||
|
||||
async uploadPrompt () {
|
||||
await this.reply('敬请期待', true)
|
||||
}
|
||||
|
||||
async importPrompt () {
|
||||
await this.reply('敬请期待', true)
|
||||
}
|
||||
|
||||
async helpPrompt () {
|
||||
await this.reply('设定目录为/plugins/chatgpt-plugin/prompts,将会读取该目录下的所有[设定名].txt文件作为设定列表', true)
|
||||
}
|
||||
}
|
||||
350
apps/update.js
Normal file
350
apps/update.js
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
// modified from StarRail-plugin | 已经过StarRail-plugin作者本人同意
|
||||
import plugin from '../../../lib/plugins/plugin.js'
|
||||
import { createRequire } from 'module'
|
||||
import _ from 'lodash'
|
||||
import { Restart } from '../../other/restart.js'
|
||||
import ChatGPTConfig from '../config/config.js'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const { exec, execSync } = require('child_process')
|
||||
|
||||
// 是否在更新中
|
||||
let uping = false
|
||||
|
||||
/**
|
||||
* 处理插件更新
|
||||
*/
|
||||
export class Update extends plugin {
|
||||
constructor () {
|
||||
const cmdPrefix = ChatGPTConfig.basic.commandPrefix
|
||||
super({
|
||||
name: 'chatgpt更新插件',
|
||||
event: 'message',
|
||||
priority: 1000,
|
||||
rule: [
|
||||
{
|
||||
reg: `^${cmdPrefix}?(强制)?更新$`,
|
||||
fnc: 'update'
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* rule - 更新chatgpt插件
|
||||
* @returns
|
||||
*/
|
||||
async update () {
|
||||
if (!this.e.isMaster) return false
|
||||
|
||||
/** 检查是否正在更新中 */
|
||||
if (uping) {
|
||||
await this.reply('已有命令更新中..请勿重复操作')
|
||||
return
|
||||
}
|
||||
|
||||
/** 检查git安装 */
|
||||
if (!(await this.checkGit())) return
|
||||
|
||||
const isForce = this.e.msg.includes('强制')
|
||||
|
||||
/** 执行更新 */
|
||||
await this.runUpdate(isForce)
|
||||
|
||||
/** 是否需要重启 */
|
||||
if (this.isUp) {
|
||||
// await this.reply("更新完毕,请重启云崽后生效")
|
||||
setTimeout(() => this.restart(), 2000)
|
||||
}
|
||||
}
|
||||
|
||||
restart () {
|
||||
new Restart(this.e).restart()
|
||||
}
|
||||
|
||||
/**
|
||||
* chatgpt插件更新函数
|
||||
* @param {boolean} isForce 是否为强制更新
|
||||
* @returns
|
||||
*/
|
||||
async runUpdate (isForce) {
|
||||
try {
|
||||
let command = 'git -C ./plugins/chatgpt-plugin/ pull --no-rebase'
|
||||
if (isForce) {
|
||||
command = `git -C ./plugins/chatgpt-plugin/ checkout . && ${command}`
|
||||
this.e.reply('正在执行强制更新操作,请稍等')
|
||||
} else {
|
||||
this.e.reply('正在执行更新操作,请稍等')
|
||||
}
|
||||
/** 获取上次提交的commitId,用于获取日志时判断新增的更新日志 */
|
||||
this.oldCommitId = await this.getcommitId('chatgpt-plugin')
|
||||
uping = true
|
||||
let ret = await this.execSync(command)
|
||||
|
||||
if (ret.error) {
|
||||
logger.mark(`${this.e.logFnc} 更新失败:chatgpt-plugin`)
|
||||
this.gitErr(ret.error, ret.stdout)
|
||||
return false
|
||||
}
|
||||
|
||||
// Check if pnpm is available
|
||||
let packageManager = await this.checkPnpm()
|
||||
await this.reply(`正在使用 ${packageManager} 更新 chaite 依赖...`)
|
||||
let npmRet = await this.execSync(`cd ./plugins/chatgpt-plugin/ && ${packageManager} update chaite`)
|
||||
logger.info(JSON.stringify(npmRet))
|
||||
if (npmRet.error) {
|
||||
logger.mark(`${this.e.logFnc} 更新失败:chaite 依赖`)
|
||||
await this.reply(`chaite 依赖更新失败:\n${npmRet.error.toString()}`)
|
||||
return false
|
||||
}
|
||||
/** 获取插件提交的最新时间 */
|
||||
let time = await this.getTime('chatgpt-plugin')
|
||||
|
||||
if (/(Already up[ -]to[ -]date|已经是最新的)/.test(ret.stdout)) {
|
||||
await this.reply(`chatgpt-plugin已经是最新版本\n最后更新时间:${time}`)
|
||||
} else {
|
||||
let updateMsg = `chatgpt-plugin\n最后更新时间:${time}`
|
||||
|
||||
// Add npm update information if available
|
||||
if (npmRet.stdout.includes('chaite')) {
|
||||
updateMsg += `\n已使用${packageManager}更新chaite依赖`
|
||||
}
|
||||
|
||||
await this.reply(updateMsg)
|
||||
this.isUp = true
|
||||
/** 获取chatgpt组件的更新日志 */
|
||||
let log = await this.getLog('chatgpt-plugin')
|
||||
await this.reply(log)
|
||||
}
|
||||
|
||||
logger.mark(`${this.e.logFnc} 最后更新时间:${time}`)
|
||||
|
||||
return true
|
||||
} catch (err) {
|
||||
logger.error(err)
|
||||
await this.reply(`更新失败:\n${err.toString()}`)
|
||||
return false
|
||||
} finally {
|
||||
uping = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取chatgpt插件的更新日志
|
||||
* @param {string} plugin 插件名称
|
||||
* @returns
|
||||
*/
|
||||
async getLog (plugin = '') {
|
||||
let cm = `cd ./plugins/${plugin}/ && git log -20 --oneline --pretty=format:"%h||[%cd] %s" --date=format:"%m-%d %H:%M"`
|
||||
|
||||
let logAll
|
||||
try {
|
||||
logAll = await execSync(cm, { encoding: 'utf-8' })
|
||||
} catch (error) {
|
||||
logger.error(error.toString())
|
||||
this.reply(error.toString())
|
||||
}
|
||||
|
||||
if (!logAll) return false
|
||||
|
||||
logAll = logAll.split('\n')
|
||||
|
||||
let log = []
|
||||
for (let str of logAll) {
|
||||
str = str.split('||')
|
||||
if (str[0] == this.oldCommitId) break
|
||||
if (str[1].includes('Merge branch')) continue
|
||||
log.push(str[1])
|
||||
}
|
||||
let line = log.length
|
||||
log = log.join('\n\n')
|
||||
|
||||
if (log.length <= 0) return ''
|
||||
|
||||
let end = ''
|
||||
end =
|
||||
'更多详细信息,请前往github查看\nhttps://github.com/ikechan8370/chatgpt-plugin'
|
||||
|
||||
log = await this.makeForwardMsg(`chatgpt-plugin更新日志,共${line}条`, log, end)
|
||||
|
||||
return log
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上次提交的commitId
|
||||
* @param {string} plugin 插件名称
|
||||
* @returns
|
||||
*/
|
||||
async getcommitId (plugin = '') {
|
||||
let cm = `git -C ./plugins/${plugin}/ rev-parse --short HEAD`
|
||||
|
||||
let commitId = await execSync(cm, { encoding: 'utf-8' })
|
||||
commitId = _.trim(commitId)
|
||||
|
||||
return commitId
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本次更新插件的最后一次提交时间
|
||||
* @param {string} plugin 插件名称
|
||||
* @returns
|
||||
*/
|
||||
async getTime (plugin = '') {
|
||||
let cm = `cd ./plugins/${plugin}/ && git log -1 --oneline --pretty=format:"%cd" --date=format:"%m-%d %H:%M"`
|
||||
|
||||
let time = ''
|
||||
try {
|
||||
time = await execSync(cm, { encoding: 'utf-8' })
|
||||
time = _.trim(time)
|
||||
} catch (error) {
|
||||
logger.error(error.toString())
|
||||
time = '获取时间失败'
|
||||
}
|
||||
return time
|
||||
}
|
||||
|
||||
/**
|
||||
* 制作转发消息
|
||||
* @param {string} title 标题 - 首条消息
|
||||
* @param {string} msg 日志信息
|
||||
* @param {string} end 最后一条信息
|
||||
* @returns
|
||||
*/
|
||||
async makeForwardMsg (title, msg, end) {
|
||||
const _bot = this.e.bot ?? Bot
|
||||
let nickname = _bot.nickname
|
||||
if (this.e.isGroup) {
|
||||
let info = await _bot?.pickMember?.(this.e.group_id, _bot.uin) || await _bot?.getGroupMemberInfo?.(this.e.group_id, _bot.uin)
|
||||
nickname = info.card || info.nickname
|
||||
}
|
||||
let userInfo = {
|
||||
user_id: _bot.uin,
|
||||
nickname
|
||||
}
|
||||
|
||||
let forwardMsg = [
|
||||
{
|
||||
...userInfo,
|
||||
message: title
|
||||
},
|
||||
{
|
||||
...userInfo,
|
||||
message: msg
|
||||
}
|
||||
]
|
||||
|
||||
if (end) {
|
||||
forwardMsg.push({
|
||||
...userInfo,
|
||||
message: end
|
||||
})
|
||||
}
|
||||
|
||||
/** 制作转发内容 */
|
||||
if (this.e.group?.makeForwardMsg) {
|
||||
forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
|
||||
} else if (this.e?.friend?.makeForwardMsg) {
|
||||
forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
|
||||
} else {
|
||||
return msg.join('\n')
|
||||
}
|
||||
|
||||
let dec = 'chatgpt-plugin 更新日志'
|
||||
/** 处理描述 */
|
||||
if (typeof (forwardMsg.data) === 'object') {
|
||||
let detail = forwardMsg.data?.meta?.detail
|
||||
if (detail) {
|
||||
detail.news = [{ text: dec }]
|
||||
}
|
||||
} else {
|
||||
forwardMsg.data = forwardMsg.data
|
||||
.replace(/\n/g, '')
|
||||
.replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
|
||||
.replace(/___+/, `<title color="#777777" size="26">${dec}</title>`)
|
||||
}
|
||||
|
||||
return forwardMsg
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否安装pnpm
|
||||
* @returns {Promise<string>} 返回 'pnpm' 或 'npm'
|
||||
*/
|
||||
async checkPnpm () {
|
||||
let npm = 'npm'
|
||||
let ret = await this.execSync('pnpm -v')
|
||||
if (ret.stdout) npm = 'pnpm'
|
||||
return npm
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理更新失败的相关函数
|
||||
* @param {string} err
|
||||
* @param {string} stdout
|
||||
* @returns
|
||||
*/
|
||||
async gitErr (err, stdout) {
|
||||
let msg = '更新失败!'
|
||||
let errMsg = err.toString()
|
||||
stdout = stdout.toString()
|
||||
|
||||
if (errMsg.includes('Timed out')) {
|
||||
let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
|
||||
await this.reply(msg + `\n连接超时:${remote}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (/Failed to connect|unable to access/g.test(errMsg)) {
|
||||
let remote = errMsg.match(/'(.+?)'/g)[0].replace(/'/g, '')
|
||||
await this.reply(msg + `\n连接失败:${remote}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (errMsg.includes('be overwritten by merge')) {
|
||||
await this.reply(
|
||||
msg +
|
||||
`存在冲突:\n${errMsg}\n` +
|
||||
'请解决冲突后再更新,或者执行#强制更新,放弃本地修改'
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (stdout.includes('CONFLICT')) {
|
||||
await this.reply([
|
||||
msg + '存在冲突\n',
|
||||
errMsg,
|
||||
stdout,
|
||||
'\n请解决冲突后再更新,或者执行#强制更新,放弃本地修改'
|
||||
])
|
||||
return
|
||||
}
|
||||
|
||||
await this.reply([errMsg, stdout])
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步执行git相关命令
|
||||
* @param {string} cmd git命令
|
||||
* @returns
|
||||
*/
|
||||
async execSync (cmd) {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, { windowsHide: true }, (error, stdout, stderr) => {
|
||||
resolve({ error, stdout, stderr })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查git是否安装
|
||||
* @returns
|
||||
*/
|
||||
async checkGit () {
|
||||
let ret = await execSync('git --version', { encoding: 'utf-8' })
|
||||
if (!ret || !ret.includes('git version')) {
|
||||
await this.reply('请先安装git')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
{
|
||||
"apiKey": "",
|
||||
"proxy": "",
|
||||
"openAiBaseUrl": "https://mondstadt.d201.eu.org/v1",
|
||||
"api": "https://pimon.d201.cn/backend-api/conversation",
|
||||
"apiBaseUrl": "https://pimon.d201.cn/backend-api",
|
||||
"promptPrefixOverride": "Your answer shouldn't be too verbose. If you are generating a list, do not have too many items. Keep the number of items short. Prefer to answer in Chinese.",
|
||||
"debug": false,
|
||||
"blockWords": ["屏蔽词1", "屏蔽词b"],
|
||||
"promptBlockWords": ["屏蔽词1", "屏蔽词b"],
|
||||
"imgOcr": true,
|
||||
"defaultUsePicture": false,
|
||||
"autoUsePicture": true,
|
||||
"autoUsePictureThreshold": 1200,
|
||||
"toggleMode": "at",
|
||||
"quoteReply": true,
|
||||
"showQRCode": true,
|
||||
"cacheUrl": "https://content.alcedogroup.com",
|
||||
"cacheEntry": false,
|
||||
"drawCD": 30
|
||||
}
|
||||
587
config/config.js
Normal file
587
config/config.js
Normal file
|
|
@ -0,0 +1,587 @@
|
|||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import yaml from 'js-yaml'
|
||||
|
||||
class ChatGPTConfig {
|
||||
/**
|
||||
* 版本号
|
||||
* @type {string}
|
||||
*/
|
||||
version = '3.0.0'
|
||||
|
||||
/**
|
||||
* 基本配置
|
||||
* @type {{
|
||||
* toggleMode: 'at' | 'prefix',
|
||||
* debug: boolean,
|
||||
* }}
|
||||
*/
|
||||
basic = {
|
||||
// 触发方式,at触发或者前缀触发
|
||||
toggleMode: 'at',
|
||||
// 触发前缀,仅在前缀触发时有效
|
||||
togglePrefix: '#chat',
|
||||
// 是否开启调试模式
|
||||
debug: false,
|
||||
// 一般命令的开头
|
||||
commandPrefix: '#chatgpt'
|
||||
}
|
||||
|
||||
/**
|
||||
* 伪人模式,基于框架实现,因此机器人开启前缀后依然需要带上前缀。
|
||||
* @type {{
|
||||
* enable: boolean,
|
||||
* hit: string[],
|
||||
* probability: number,
|
||||
* defaultPreset: string,
|
||||
* presetPrefix?: string,
|
||||
* presetMap: Array<{
|
||||
* keywords: string[],
|
||||
* presetId: string,
|
||||
* priority: number,
|
||||
* recall?: boolean
|
||||
* }>,
|
||||
* maxTokens: number,
|
||||
* temperature: number,
|
||||
* sendReasoning: boolean
|
||||
* }}
|
||||
* }}
|
||||
*/
|
||||
bym = {
|
||||
// 开关
|
||||
enable: false,
|
||||
// 伪人必定触发词
|
||||
hit: ['bym'],
|
||||
// 不包含伪人必定触发词时的概率
|
||||
probability: 0.02,
|
||||
// 伪人模式的默认预设
|
||||
defaultPreset: '',
|
||||
// 伪人模式的预设前缀,会加在在所有其他预设前。例如此处可以用于配置通用的伪人发言风格(随意、模仿群友等),presetMap中专心配置角色设定即可
|
||||
presetPrefix: '',
|
||||
// 包含关键词与预设的对应关系。包含特定触发词使用特定的预设,按照优先级排序
|
||||
presetMap: [],
|
||||
// 如果大于0,会覆盖preset中的maxToken,用于控制伪人模式发言长度
|
||||
maxTokens: 0,
|
||||
// 如果大于等于0,会覆盖preset中的temperature,用于控制伪人模式发言随机性
|
||||
temperature: -1,
|
||||
// 是否发送思考内容
|
||||
sendReasoning: false
|
||||
}
|
||||
|
||||
/**
|
||||
* 模型和对话相关配置
|
||||
* @type {{
|
||||
* defaultModel: string,
|
||||
* embeddingModel: string,
|
||||
* defaultChatPresetId: string,
|
||||
* enableCustomPreset: boolean,
|
||||
* customPresetUserWhiteList: string[],
|
||||
* customPresetUserBlackList: string[],
|
||||
* promptBlockWords: string[],
|
||||
* responseBlockWords: string[],
|
||||
* blockStrategy: 'full' | 'mask',
|
||||
* blockWordMask: string,
|
||||
* enableGroupContext: boolean,
|
||||
* groupContextLength: number,
|
||||
* groupContextTemplatePrefix: string,
|
||||
* groupContextTemplateMessage: string,
|
||||
* groupContextTemplateSuffix: string
|
||||
* }}
|
||||
*/
|
||||
llm = {
|
||||
// 默认模型,初始化构建预设使用
|
||||
defaultModel: '',
|
||||
// 嵌入模型
|
||||
embeddingModel: 'gemini-embedding-exp-03-07',
|
||||
// 嵌入结果维度,0表示自动
|
||||
dimensions: 0,
|
||||
// 默认对话预设ID
|
||||
defaultChatPresetId: '',
|
||||
// 是否启用允许其他人切换预设
|
||||
enableCustomPreset: false,
|
||||
// 允许切换预设的用户白名单
|
||||
customPresetUserWhiteList: [],
|
||||
// 禁止切换预设的用户黑名单
|
||||
customPresetUserBlackList: [],
|
||||
// 用户对话屏蔽词
|
||||
promptBlockWords: [],
|
||||
// 机器人回复屏蔽词
|
||||
responseBlockWords: [],
|
||||
// 触发屏蔽词的策略,完全屏蔽或仅屏蔽关键词
|
||||
blockStrategy: 'full',
|
||||
// 如果blockStrategy为mask,屏蔽词的替换字符
|
||||
blockWordMask: '***',
|
||||
// 是否开启群组上下文
|
||||
enableGroupContext: false,
|
||||
// 群组上下文长度
|
||||
groupContextLength: 20,
|
||||
// 用于组装群聊上下文提示词的模板前缀
|
||||
groupContextTemplatePrefix: '<settings>\n' +
|
||||
// eslint-disable-next-line no-template-curly-in-string
|
||||
'You are a member of a chat group, whose name is ${group.name}, and the group id is ${group.id}.\n' +
|
||||
'</settings>Latest several messages in the group chat:\n' +
|
||||
'| 群名片 | 昵称 | qq号 | 群角色 | 群头衔 | 时间 | messageId | 消息内容 |\n' +
|
||||
'|---|---|---|---|---|---|---|---|',
|
||||
// 用于组装群聊上下文提示词的模板内容部分,每一条消息作为message,仿照示例填写
|
||||
// eslint-disable-next-line no-template-curly-in-string
|
||||
groupContextTemplateMessage: '| ${message.sender.card} | ${message.sender.nickname} | ${message.sender.user_id} | ${message.sender.role} | ${message.sender.title} | ${message.time} | ${message.messageId} | ${message.raw_message} |',
|
||||
// 用于组装群聊上下文提示词的模板后缀
|
||||
groupContextTemplateSuffix: '\n'
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理相关配置
|
||||
* @type {{
|
||||
* blackGroups: number[],
|
||||
* whiteGroups: number[],
|
||||
* blackUsers: string[],
|
||||
* whiteUsers: string[],
|
||||
* defaultRateLimit: number
|
||||
* }}
|
||||
*/
|
||||
management = {
|
||||
blackGroups: [],
|
||||
whiteGroups: [],
|
||||
blackUsers: [],
|
||||
whiteUsers: [],
|
||||
// 默认对话速率限制,0表示不限制,数字表示每分钟最多对话次数
|
||||
defaultRateLimit: 0
|
||||
}
|
||||
|
||||
/**
|
||||
* chaite相关配置
|
||||
* @type {
|
||||
* { dataDir: string,
|
||||
* processorsDirPath: string,
|
||||
* toolsDirPath: string,
|
||||
* cloudBaseUrl: string,
|
||||
* cloudApiKey: string,
|
||||
* authKey: string,
|
||||
* host: string,
|
||||
* port: number}}
|
||||
*/
|
||||
chaite = {
|
||||
// 数据目录,相对于插件下
|
||||
dataDir: 'data',
|
||||
// 处理器目录,相对于插件下
|
||||
processorsDirPath: 'utils/processors',
|
||||
// 触发器目录,相对于插件目录下
|
||||
triggersDir: 'utils/triggers',
|
||||
// 工具目录,相对于插件目录下
|
||||
toolsDirPath: 'utils/tools',
|
||||
// 云端API url
|
||||
cloudBaseUrl: 'https://api.chaite.cloud',
|
||||
// 云端API Key
|
||||
cloudApiKey: '',
|
||||
// jwt key,非必要勿修改,修改需重启
|
||||
authKey: '',
|
||||
// 管理面板监听地址
|
||||
host: '0.0.0.0',
|
||||
// 管理面板监听端口
|
||||
port: 48370,
|
||||
// 存储实现 sqlite lowdb
|
||||
storage: 'sqlite'
|
||||
}
|
||||
|
||||
/**
|
||||
* 记忆系统配置
|
||||
* @type {{
|
||||
* database: string,
|
||||
* vectorDimensions: number,
|
||||
* group: {
|
||||
* enable: boolean,
|
||||
* enabledGroups: string[],
|
||||
* extractionModel: string,
|
||||
* extractionPresetId: string,
|
||||
* minMessageCount: number,
|
||||
* maxMessageWindow: number,
|
||||
* retrievalMode: 'vector' | 'keyword' | 'hybrid',
|
||||
* hybridPrefer: 'vector-first' | 'keyword-first',
|
||||
* historyPollInterval: number,
|
||||
* historyBatchSize: number,
|
||||
* promptHeader: string,
|
||||
* promptItemTemplate: string,
|
||||
* promptFooter: string,
|
||||
* extractionSystemPrompt: string,
|
||||
* extractionUserPrompt: string,
|
||||
* vectorMaxDistance: number,
|
||||
* textMaxBm25Score: number,
|
||||
* maxFactsPerInjection: number,
|
||||
* minImportanceForInjection: number
|
||||
* },
|
||||
* user: {
|
||||
* enable: boolean,
|
||||
* whitelist: string[],
|
||||
* blacklist: string[],
|
||||
* extractionModel: string,
|
||||
* extractionPresetId: string,
|
||||
* maxItemsPerInjection: number,
|
||||
* maxRelevantItemsPerQuery: number,
|
||||
* minImportanceForInjection: number,
|
||||
* promptHeader: string,
|
||||
* promptItemTemplate: string,
|
||||
* promptFooter: string,
|
||||
* extractionSystemPrompt: string,
|
||||
* extractionUserPrompt: string
|
||||
* },
|
||||
* extensions: {
|
||||
* simple: {
|
||||
* enable: boolean,
|
||||
* libraryPath: string,
|
||||
* dictPath: string,
|
||||
* useJieba: boolean
|
||||
* }
|
||||
* }
|
||||
* }}
|
||||
*/
|
||||
memory = {
|
||||
database: 'data/memory.db',
|
||||
vectorDimensions: 1536,
|
||||
group: {
|
||||
enable: false,
|
||||
enabledGroups: [],
|
||||
extractionModel: '',
|
||||
extractionPresetId: '',
|
||||
minMessageCount: 80,
|
||||
maxMessageWindow: 300,
|
||||
retrievalMode: 'hybrid',
|
||||
hybridPrefer: 'vector-first',
|
||||
historyPollInterval: 300,
|
||||
historyBatchSize: 120,
|
||||
promptHeader: '# 以下是一些该群聊中可能相关的事实,你可以参考,但不要主动透露这些事实。',
|
||||
promptItemTemplate: '- ${fact}${topicSuffix}${timeSuffix}',
|
||||
promptFooter: '',
|
||||
extractionSystemPrompt: `You are a knowledge extraction assistant that specialises in summarising long-term facts from group chat transcripts.
|
||||
Read the provided conversation and identify statements that should be stored as long-term knowledge for the group.
|
||||
Return a JSON array. Each element must contain:
|
||||
{
|
||||
"fact": 事实内容,必须完整包含事件的各个要素而不能是简单的短语(比如谁参与了事件、做了什么事情、背景时间是什么)(同一件事情尽可能整合为同一条而非拆分,以便利于检索),
|
||||
"topic": 主题关键词,字符串,如 "活动"、"成员信息",
|
||||
"importance": 一个介于0和1之间的小数,数值越大表示越重要,
|
||||
"source_message_ids": 原始消息ID数组,
|
||||
"source_messages": 对应原始消息的简要摘录或合并文本,
|
||||
"involved_users": 出现或相关的用户ID数组
|
||||
}
|
||||
Only include meaningful, verifiable group-specific information that is useful for future conversations. Do not record incomplete information. Do not include general knowledge or unrelated facts. Do not wrap the JSON array in code fences.`,
|
||||
extractionUserPrompt: `以下是群聊中的一些消息,请根据系统说明提取值得长期记忆的事实,以JSON数组形式返回,不要输出额外说明。
|
||||
|
||||
\${messages}`,
|
||||
vectorMaxDistance: 0,
|
||||
textMaxBm25Score: 0,
|
||||
maxFactsPerInjection: 5,
|
||||
minImportanceForInjection: 0.3
|
||||
},
|
||||
user: {
|
||||
enable: false,
|
||||
whitelist: [],
|
||||
blacklist: [],
|
||||
extractionModel: '',
|
||||
extractionPresetId: '',
|
||||
maxItemsPerInjection: 5,
|
||||
maxRelevantItemsPerQuery: 3,
|
||||
minImportanceForInjection: 0,
|
||||
promptHeader: '# 用户画像',
|
||||
promptItemTemplate: '- ${value}${timeSuffix}',
|
||||
promptFooter: '',
|
||||
extractionSystemPrompt: `You are an assistant that extracts long-term personal preferences or persona details about a user.
|
||||
Given a conversation snippet between the user and the bot, identify durable information such as preferences, nicknames, roles, speaking style, habits, or other facts that remain valid over time.
|
||||
Return a JSON array of **strings**, and nothing else, without any other characters including \`\`\` or \`\`\`json. Each string must be a short sentence (in the same language as the conversation) describing one piece of long-term memory. Do not include keys, JSON objects, or additional metadata. Ignore temporary topics or uncertain information.`,
|
||||
extractionUserPrompt: `下面是用户与机器人的对话,请根据系统提示提取可长期记忆的个人信息。
|
||||
|
||||
\${messages}`
|
||||
},
|
||||
extensions: {
|
||||
simple: {
|
||||
enable: false,
|
||||
libraryPath: '',
|
||||
dictPath: '',
|
||||
useJieba: false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
constructor () {
|
||||
this.version = '3.0.0'
|
||||
this.watcher = null
|
||||
this.configPath = ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Start config file sync
|
||||
* call once!
|
||||
* @param {string} configDir Directory containing config files
|
||||
*/
|
||||
startSync (configDir) {
|
||||
// 配置路径设置
|
||||
const jsonPath = path.join(configDir, 'config.json')
|
||||
const yamlPath = path.join(configDir, 'config.yaml')
|
||||
|
||||
if (fs.existsSync(jsonPath)) {
|
||||
this.configPath = jsonPath
|
||||
} else if (fs.existsSync(yamlPath)) {
|
||||
this.configPath = yamlPath
|
||||
} else {
|
||||
this.configPath = jsonPath
|
||||
this.saveToFile()
|
||||
}
|
||||
|
||||
// 加载初始配置
|
||||
this.loadFromFile()
|
||||
|
||||
// 文件变更标志和保存定时器
|
||||
this._saveOrigin = null
|
||||
this._saveTimer = null
|
||||
|
||||
// 监听文件变化
|
||||
this.watcher = fs.watchFile(this.configPath, (curr, prev) => {
|
||||
if (curr.mtime !== prev.mtime && this._saveOrigin !== 'code') {
|
||||
this.loadFromFile()
|
||||
}
|
||||
})
|
||||
|
||||
// 处理所有嵌套对象
|
||||
return this._createProxyRecursively(this)
|
||||
}
|
||||
|
||||
// 递归创建代理
|
||||
_createProxyRecursively (obj, path = []) {
|
||||
if (obj === null || typeof obj !== 'object' || obj instanceof Date) {
|
||||
return obj
|
||||
}
|
||||
|
||||
// 处理数组和对象
|
||||
if (Array.isArray(obj)) {
|
||||
// 创建一个新数组,递归地处理每个元素
|
||||
const proxiedArray = [...obj].map((item, index) =>
|
||||
this._createProxyRecursively(item, [...path, index])
|
||||
)
|
||||
|
||||
// 代理数组,捕获数组方法调用
|
||||
return new Proxy(proxiedArray, {
|
||||
set: (target, prop, value) => {
|
||||
// 处理数字属性(数组索引)和数组长度
|
||||
if (typeof prop !== 'symbol' &&
|
||||
((!isNaN(prop) && prop !== 'length') ||
|
||||
prop === 'length')) {
|
||||
// 直接设置值
|
||||
target[prop] = value
|
||||
|
||||
// 触发保存
|
||||
this._triggerSave('array')
|
||||
} else {
|
||||
target[prop] = value
|
||||
}
|
||||
return true
|
||||
},
|
||||
|
||||
// 拦截数组方法调用
|
||||
get: (target, prop) => {
|
||||
const val = target[prop]
|
||||
|
||||
// 处理数组修改方法
|
||||
if (typeof val === 'function' &&
|
||||
['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].includes(prop)) {
|
||||
return function (...args) {
|
||||
const result = Array.prototype[prop].apply(target, args)
|
||||
|
||||
// 方法调用后触发保存
|
||||
this._triggerSave('array-method')
|
||||
return result
|
||||
}.bind(this)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// 对普通对象的处理
|
||||
const proxiedObj = {}
|
||||
|
||||
// 处理所有属性
|
||||
for (const key in obj) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
// 跳过内部属性
|
||||
if (key === 'watcher' || key === 'configPath' ||
|
||||
key.startsWith('_save') || key === '_isSaving') {
|
||||
proxiedObj[key] = obj[key]
|
||||
} else {
|
||||
// 递归处理嵌套对象
|
||||
proxiedObj[key] = this._createProxyRecursively(
|
||||
obj[key], [...path, key]
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建对象的代理
|
||||
return new Proxy(proxiedObj, {
|
||||
set: (target, prop, value) => {
|
||||
// 跳过内部属性的处理
|
||||
if (prop === 'watcher' || prop === 'configPath' ||
|
||||
prop.startsWith('_save') || prop === '_isSaving') {
|
||||
target[prop] = value
|
||||
return true
|
||||
}
|
||||
|
||||
// 设置新值,如果是对象则递归创建代理
|
||||
if (value !== null && typeof value === 'object') {
|
||||
target[prop] = this._createProxyRecursively(
|
||||
value, [...path, prop]
|
||||
)
|
||||
} else {
|
||||
target[prop] = value
|
||||
}
|
||||
|
||||
// 触发保存
|
||||
this._triggerSave('object')
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
loadFromFile () {
|
||||
try {
|
||||
if (!fs.existsSync(this.configPath)) {
|
||||
// 如果文件不存在,直接返回
|
||||
return
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(this.configPath, 'utf8')
|
||||
const loadedConfig = this.configPath.endsWith('.json')
|
||||
? JSON.parse(content)
|
||||
: yaml.load(content)
|
||||
|
||||
// 处理加载的配置并和默认值合并
|
||||
if (loadedConfig) {
|
||||
const mergeResult = this._mergeConfig(loadedConfig)
|
||||
if (mergeResult.changed) {
|
||||
logger?.debug?.('[Config] merged new defaults into persisted config; scheduling save')
|
||||
this._triggerSave('code')
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug('Config loaded successfully')
|
||||
} catch (error) {
|
||||
logger.error('Failed to load config:', error)
|
||||
}
|
||||
}
|
||||
|
||||
_mergeConfig (loadedConfig) {
|
||||
let changed = false
|
||||
|
||||
const mergeInto = (target, source) => {
|
||||
if (!source || typeof source !== 'object') {
|
||||
return target
|
||||
}
|
||||
if (!target || typeof target !== 'object') {
|
||||
target = Array.isArray(source) ? [] : {}
|
||||
}
|
||||
const result = Array.isArray(source) ? [] : { ...target }
|
||||
|
||||
if (Array.isArray(source)) {
|
||||
return source.slice()
|
||||
}
|
||||
|
||||
const targetKeys = target && typeof target === 'object'
|
||||
? Object.keys(target)
|
||||
: []
|
||||
for (const key of targetKeys) {
|
||||
if (!Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of Object.keys(source)) {
|
||||
const sourceValue = source[key]
|
||||
const targetValue = target[key]
|
||||
if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
|
||||
result[key] = mergeInto(targetValue, sourceValue)
|
||||
} else {
|
||||
if (targetValue === undefined || targetValue !== sourceValue) {
|
||||
changed = true
|
||||
}
|
||||
result[key] = sourceValue
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const sections = ['version', 'basic', 'bym', 'llm', 'management', 'chaite', 'memory']
|
||||
for (const key of sections) {
|
||||
const loadedValue = loadedConfig[key]
|
||||
if (loadedValue === undefined) {
|
||||
continue
|
||||
}
|
||||
if (typeof loadedValue === 'object' && loadedValue !== null) {
|
||||
const merged = mergeInto(this[key], loadedValue)
|
||||
if (merged !== this[key]) {
|
||||
this[key] = merged
|
||||
}
|
||||
} else {
|
||||
if (this[key] !== loadedValue) {
|
||||
changed = true
|
||||
}
|
||||
this[key] = loadedValue
|
||||
}
|
||||
}
|
||||
|
||||
return { changed }
|
||||
}
|
||||
|
||||
// 合并触发保存,防抖处理
|
||||
_triggerSave (origin) {
|
||||
// 清除之前的定时器
|
||||
if (this._saveTimer) {
|
||||
clearTimeout(this._saveTimer)
|
||||
}
|
||||
|
||||
const originLabel = origin || 'code'
|
||||
this._saveOrigin = originLabel
|
||||
this._saveTimer = setTimeout(() => {
|
||||
this.saveToFile(originLabel)
|
||||
this._saveOrigin = null
|
||||
}, 200)
|
||||
}
|
||||
|
||||
saveToFile (origin = 'code') {
|
||||
if (origin !== 'code') {
|
||||
this._saveOrigin = 'external'
|
||||
}
|
||||
logger.debug('Saving config to file...')
|
||||
try {
|
||||
const config = {
|
||||
version: this.version,
|
||||
basic: this.basic,
|
||||
bym: this.bym,
|
||||
llm: this.llm,
|
||||
management: this.management,
|
||||
chaite: this.chaite,
|
||||
memory: this.memory
|
||||
}
|
||||
|
||||
const content = this.configPath.endsWith('.json')
|
||||
? JSON.stringify(config, null, 2)
|
||||
: yaml.dump(config)
|
||||
|
||||
fs.writeFileSync(this.configPath, content, 'utf8')
|
||||
} catch (error) {
|
||||
console.error('Failed to save config:', error)
|
||||
}
|
||||
}
|
||||
|
||||
toJSON () {
|
||||
return {
|
||||
version: this.version,
|
||||
basic: this.basic,
|
||||
bym: this.bym,
|
||||
llm: this.llm,
|
||||
management: this.management,
|
||||
chaite: this.chaite,
|
||||
memory: this.memory
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default new ChatGPTConfig()
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
## 配置项解析
|
||||
|
||||
正在施工中......
|
||||
438
guoba.support.js
438
guoba.support.js
|
|
@ -1,6 +1,4 @@
|
|||
import { Config } from './utils/config.js'
|
||||
import { speakers } from './utils/tts.js'
|
||||
|
||||
import Config from './config/config.js'
|
||||
// 支持锅巴
|
||||
export function supportGuoba () {
|
||||
return {
|
||||
|
|
@ -27,419 +25,12 @@ export function supportGuoba () {
|
|||
// 配置项 schemas
|
||||
schemas: [
|
||||
{
|
||||
field: 'blockWords',
|
||||
label: '输出黑名单',
|
||||
bottomHelpMessage: '检查输出结果中是否有违禁词,如果存在黑名单中的违禁词则不输出',
|
||||
component: 'InputTextArea'
|
||||
},
|
||||
{
|
||||
field: 'promptBlockWords',
|
||||
label: '输入黑名单',
|
||||
bottomHelpMessage: '检查输入结果中是否有违禁词,如果存在黑名单中的违禁词则不输出',
|
||||
component: 'InputTextArea'
|
||||
},
|
||||
{
|
||||
field: 'imgOcr',
|
||||
label: '图片识别',
|
||||
bottomHelpMessage: '是否识别消息中图片的文字内容,需要同时包含图片和消息才生效',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'defaultUsePicture',
|
||||
label: '全局图片模式',
|
||||
bottomHelpMessage: '全局默认以图片形式回复。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'defaultUseTTS',
|
||||
label: '全局语音模式',
|
||||
bottomHelpMessage: '全局默认以语音形式回复,使用默认角色音色。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'defaultTTSRole',
|
||||
label: '语音模式默认角色',
|
||||
bottomHelpMessage: '语音模式下,未指定角色时使用的角色。若为空,将使用随机角色回复。',
|
||||
component: 'Select',
|
||||
componentProps: {
|
||||
options: speakers.concat('随机').map(s => { return { label: s, value: s } })
|
||||
field: 'testRender',
|
||||
label: '表格测试',
|
||||
component: 'Render',
|
||||
render: () => {
|
||||
`<span>你好</span>`
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'ttsAutoFallbackThreshold',
|
||||
label: '语音转文字阈值',
|
||||
helpMessage: '语音模式下,字数超过这个阈值就降级为文字',
|
||||
bottomHelpMessage: '语音转为文字的阈值。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0,
|
||||
max: 299
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'alsoSendText',
|
||||
label: '语音同时发送文字',
|
||||
bottomHelpMessage: '语音模式下,同时发送文字版,避免音质较低听不懂',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'autoUsePicture',
|
||||
label: '长文本自动转图片',
|
||||
bottomHelpMessage: '字数大于阈值会自动用图片发送,即使是文本模式。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'autoUsePictureThreshold',
|
||||
label: '自动转图片阈值',
|
||||
helpMessage: '长文本自动转图片开启后才生效',
|
||||
bottomHelpMessage: '自动转图片的字数阈值。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'conversationPreserveTime',
|
||||
label: '对话保留时长',
|
||||
helpMessage: '单位:秒',
|
||||
bottomHelpMessage: '每个人发起的对话保留时长。超过这个时长没有进行对话,再进行对话将开启新的对话。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'toggleMode',
|
||||
label: '触发方式',
|
||||
bottomHelpMessage: 'at模式下只有at机器人才会回复。#chat模式下不需要at,但需要添加前缀#chat。',
|
||||
component: 'Select',
|
||||
componentProps: {
|
||||
options: [
|
||||
{ label: 'at', value: 'at' },
|
||||
{ label: '#chat', value: 'prefix' }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'quoteReply',
|
||||
label: '图片引用消息',
|
||||
bottomHelpMessage: '在回复图片时引用原始消息',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'showQRCode',
|
||||
label: '启用二维码',
|
||||
bottomHelpMessage: '在图片模式中启用二维码。该对话内容将被发送至第三方服务器以进行渲染展示,如果不希望对话内容被上传到第三方服务器请关闭此功能。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'cacheUrl',
|
||||
label: '渲染服务器地址',
|
||||
bottomHelpMessage: '用于缓存图片模式会话内容并渲染的服务器地址。',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'cacheEntry',
|
||||
label: '预制渲染服务器访问代码',
|
||||
bottomHelpMessage: '图片内容渲染服务器开启预制访问代码,当渲染服务器访问较慢时可以开启,但无法保证访问代码可以正常访问页面。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'drawCD',
|
||||
label: '绘图CD',
|
||||
helpMessage: '单位:秒',
|
||||
bottomHelpMessage: '绘图指令的CD时间,主人不受限制',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'enableDraw',
|
||||
label: '绘图功能开关',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'proxy',
|
||||
label: '代理服务器地址',
|
||||
bottomHelpMessage: '数据通过代理服务器发送,http或socks5代理。',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'debug',
|
||||
label: '调试信息',
|
||||
bottomHelpMessage: '将输出更多调试信息,如果不希望控制台刷屏的话,可以关闭。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
label: '以下为服务超时配置。',
|
||||
component: 'Divider'
|
||||
},
|
||||
{
|
||||
field: 'defaultTimeoutMs',
|
||||
label: '默认超时时间',
|
||||
helpMessage: '单位:毫秒',
|
||||
bottomHelpMessage: '各个地方的默认超时时间。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'chromeTimeoutMS',
|
||||
label: '浏览器超时时间',
|
||||
helpMessage: '单位:毫秒',
|
||||
bottomHelpMessage: '浏览器默认超时,浏览器可能需要更高的超时时间。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'sydneyFirstMessageTimeout',
|
||||
label: 'Sydney模式接受首条信息超时时间',
|
||||
helpMessage: '单位:毫秒',
|
||||
bottomHelpMessage: '超过该时间阈值未收到Bing的任何消息,则断开本次连接并重试(最多重试3次,失败后返回timeout waiting for first message)。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 15000
|
||||
}
|
||||
},
|
||||
{
|
||||
label: '以下为API方式(默认)的配置',
|
||||
component: 'Divider'
|
||||
},
|
||||
{
|
||||
field: 'apiKey',
|
||||
label: 'OpenAI API Key',
|
||||
bottomHelpMessage: 'OpenAI的ApiKey,用于访问OpenAI的API接口。',
|
||||
component: 'InputPassword'
|
||||
},
|
||||
{
|
||||
field: 'openAiBaseUrl',
|
||||
label: 'OpenAI API服务器地址',
|
||||
bottomHelpMessage: 'OpenAI的API服务器地址。注意要带上/v1。默认为https://api.openai.com/v1',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'openAiForceUseReverse',
|
||||
label: '强制使用OpenAI反代',
|
||||
bottomHelpMessage: '即使配置了proxy,依然使用OpenAI反代',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'thinkingTips',
|
||||
label: '思考提示',
|
||||
bottomHelpMessage: '是否开启AI正在思考中的提示信息。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'promptPrefixOverride',
|
||||
label: 'AI风格',
|
||||
bottomHelpMessage: '你可以在这里写入你希望AI回答的风格,比如希望优先回答中文,回答长一点等。',
|
||||
component: 'InputTextArea'
|
||||
},
|
||||
{
|
||||
field: 'assistantLabel',
|
||||
label: 'AI名字',
|
||||
bottomHelpMessage: 'AI认为的自己的名字,当你问他你是谁是他会回答这里的名字。',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'temperature',
|
||||
label: 'temperature',
|
||||
bottomHelpMessage: '用于控制回复内容的多样性,数值越大回复越加随机、多元化,数值越小回复越加保守。',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0,
|
||||
max: 2
|
||||
}
|
||||
},
|
||||
{
|
||||
label: '以下为必应方式的配置。',
|
||||
component: 'Divider'
|
||||
},
|
||||
{
|
||||
field: 'toneStyle',
|
||||
label: 'Bing模式',
|
||||
bottomHelpMessage: '微软必应官方的三种应答风格。默认为均衡,Sydney为实验风格,独立与三种风格之外。',
|
||||
component: 'Select',
|
||||
componentProps: {
|
||||
options: [
|
||||
{ label: '均衡', value: 'balanced' },
|
||||
{ label: '创意', value: 'creative' },
|
||||
{ label: '精确', value: 'precise' },
|
||||
{ label: 'Sydney(可能存在风险)', value: 'Sydney' }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'enableSuggestedResponses',
|
||||
label: '是否开启建议回复',
|
||||
bottomHelpMessage: '开启了会像官网上一样,每个问题给出建议的用户问题',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'sydney',
|
||||
label: 'Sydney的设定',
|
||||
bottomHelpMessage: '你可以自己改写Sydney的设定,让Sydney变成你希望的样子,不过请注意,Sydney仍然是Sydney。',
|
||||
component: 'InputTextArea'
|
||||
},
|
||||
{
|
||||
field: 'sydneyReverseProxy',
|
||||
label: 'sydney反代',
|
||||
bottomHelpMessage: '国内ip无法正常使用sydney,如果有bing.com的反代可以填在此处,或者使用proxy',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'sydneyForceUseReverse',
|
||||
label: '强制使用sydney反代',
|
||||
bottomHelpMessage: '即使配置了proxy,依然使用sydney反代',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'sydneyBrainWashName',
|
||||
label: 'Sydney的称呼',
|
||||
bottomHelpMessage: '如果开启了强制洗脑,务必准确填写这个才能精准洗脑。不开启洗脑可以不管这个',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'sydneyBrainWash',
|
||||
label: '开启强制洗脑',
|
||||
bottomHelpMessage: '如果发现Sydney回复类似于换个话题之类的话,可以开启强制洗脑试试,如果还不行就调整你的设定',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'sydneyBrainWashStrength',
|
||||
label: '洗脑强度',
|
||||
bottomHelpMessage: '洗脑强度。默认为15,可以酌情调整。太大的话可能长对话会影响上下文',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0,
|
||||
max: 20
|
||||
}
|
||||
},
|
||||
{
|
||||
label: '以下为API3方式的配置。',
|
||||
component: 'Divider'
|
||||
},
|
||||
{
|
||||
field: 'api',
|
||||
label: 'ChatGPT API反代服务器地址',
|
||||
bottomHelpMessage: 'ChatGPT的API反代服务器,用于绕过Cloudflare访问ChatGPT API',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'apiBaseUrl',
|
||||
label: 'apiBaseUrl地址',
|
||||
bottomHelpMessage: 'apiBaseUrl地址',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'apiForceUseReverse',
|
||||
label: '强制使用ChatGPT反代',
|
||||
bottomHelpMessage: '即使配置了proxy,依然使用ChatGPT反代',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'useGPT4',
|
||||
label: '使用GPT-4',
|
||||
bottomHelpMessage: '使用GPT-4,注意试用配额较低,如果用不了就关掉',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
label: '以下为浏览器方式的配置.(Deprecated)',
|
||||
component: 'Divider'
|
||||
},
|
||||
{
|
||||
field: 'username',
|
||||
label: '用户名',
|
||||
bottomHelpMessage: 'OpenAI用户名。',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'password',
|
||||
label: '密码',
|
||||
bottomHelpMessage: 'OpenAI密码。',
|
||||
component: 'InputPassword'
|
||||
},
|
||||
{
|
||||
field: 'UA',
|
||||
label: '浏览器UA',
|
||||
bottomHelpMessage: '模拟浏览器UA,无特殊需求保持默认即可。',
|
||||
component: 'InputTextArea'
|
||||
},
|
||||
{
|
||||
field: 'headless',
|
||||
label: '无头模式',
|
||||
bottomHelpMessage: '无界面的服务器可以开启,但遇到验证码时可能无法使用。(实测很容易卡住,几乎不可用)。',
|
||||
component: 'Switch'
|
||||
},
|
||||
{
|
||||
field: 'chromePath',
|
||||
label: 'Chrome路径',
|
||||
bottomHelpMessage: '为空使用默认puppeteer的chromium,也可以传递自己本机安装的Chrome可执行文件地址,提高通过率。windows可以是‘C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe’,linux通过which查找路径。',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: '2captchaToken',
|
||||
label: '验证码平台Token',
|
||||
bottomHelpMessage: '可注册2captcha实现跳过验证码,收费服务但很便宜。否则可能会遇到验证码而卡住。',
|
||||
component: 'InputPassword'
|
||||
},
|
||||
{
|
||||
field: 'ttsSpace',
|
||||
label: '语音转换API地址',
|
||||
bottomHelpMessage: '前往duplicate空间https://huggingface.co/spaces/ikechan8370/vits-uma-genshin-honkai后查看api地址',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'huggingFaceReverseProxy',
|
||||
label: '语音转换huggingface反代',
|
||||
bottomHelpMessage: '没有就空着',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'noiseScale',
|
||||
label: 'noiseScale',
|
||||
bottomHelpMessage: '控制情感变化程度',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0,
|
||||
max: 1
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'noiseScaleW',
|
||||
label: 'noiseScaleW',
|
||||
bottomHelpMessage: '控制音素发音长度',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0,
|
||||
max: 1
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'lengthScale',
|
||||
label: 'lengthScale',
|
||||
bottomHelpMessage: '控制整体语速',
|
||||
component: 'InputNumber',
|
||||
componentProps: {
|
||||
min: 0,
|
||||
max: 2
|
||||
}
|
||||
},
|
||||
{
|
||||
field: 'initiativeChatGroups',
|
||||
label: '主动发起聊天群聊的群号',
|
||||
bottomHelpMessage: '在这些群聊里会不定时主动说一些随机的打招呼的话,用英文逗号隔开。必须配置了OpenAI Key',
|
||||
component: 'Input'
|
||||
},
|
||||
{
|
||||
field: 'helloPrompt',
|
||||
label: '打招呼所说文字的引导文字',
|
||||
bottomHelpMessage: '将会用这段文字询问ChatGPT,由ChatGPT给出随机的打招呼文字。',
|
||||
component: 'Input'
|
||||
}
|
||||
],
|
||||
// 获取配置数据方法(用于前端填充显示数据)
|
||||
|
|
@ -451,7 +42,22 @@ export function supportGuoba () {
|
|||
for (let [keyPath, value] of Object.entries(data)) {
|
||||
// 处理黑名单
|
||||
if (keyPath === 'blockWords' || keyPath === 'promptBlockWords' || keyPath === 'initiativeChatGroups') { value = value.toString().split(/[,,;;\|]/) }
|
||||
if (Config[keyPath] != value) { Config[keyPath] = value }
|
||||
if (keyPath === 'blacklist' || keyPath === 'whitelist') {
|
||||
// 6-10位数的群号或qq
|
||||
const regex = /^\^?[1-9]\d{5,9}(\^[1-9]\d{5,9})?$/
|
||||
const inputSet = new Set()
|
||||
value = value.toString().split(/[,,;;|\s]/).reduce((acc, item) => {
|
||||
item = item.trim()
|
||||
if (!inputSet.has(item) && regex.test(item)) {
|
||||
if (item.length <= 11 || (item.length <= 21 && item.length > 11 && !item.startsWith('^'))) {
|
||||
inputSet.add(item)
|
||||
acc.push(item)
|
||||
}
|
||||
}
|
||||
return acc
|
||||
}, [])
|
||||
}
|
||||
if (Config[keyPath] !== value) { Config[keyPath] = value }
|
||||
}
|
||||
return Result.ok({}, '保存成功~')
|
||||
}
|
||||
|
|
|
|||
25
index.js
25
index.js
|
|
@ -1,5 +1,16 @@
|
|||
import fs from 'node:fs'
|
||||
import {Config} from "./utils/config.js";
|
||||
import ChatGPTConfig from './config/config.js'
|
||||
import { initChaite } from './models/chaite/cloud.js'
|
||||
logger.info('**************************************')
|
||||
logger.info('chatgpt-plugin加载中')
|
||||
|
||||
if (!global.segment) {
|
||||
try {
|
||||
global.segment = (await import('icqq')).segment
|
||||
} catch (err) {
|
||||
global.segment = (await import('oicq')).segment
|
||||
}
|
||||
}
|
||||
|
||||
const files = fs.readdirSync('./plugins/chatgpt-plugin/apps').filter(file => file.endsWith('.js'))
|
||||
|
||||
|
|
@ -14,7 +25,6 @@ ret = await Promise.allSettled(ret)
|
|||
let apps = {}
|
||||
for (let i in files) {
|
||||
let name = files[i].replace('.js', '')
|
||||
|
||||
if (ret[i].status !== 'fulfilled') {
|
||||
logger.error(`载入插件错误:${logger.red(name)}`)
|
||||
logger.error(ret[i].reason)
|
||||
|
|
@ -22,10 +32,17 @@ for (let i in files) {
|
|||
}
|
||||
apps[name] = ret[i].value[Object.keys(ret[i].value)[0]]
|
||||
}
|
||||
logger.info('**************************************')
|
||||
global.chatgpt = {
|
||||
|
||||
}
|
||||
|
||||
ChatGPTConfig.startSync('./plugins/chatgpt-plugin/data')
|
||||
initChaite()
|
||||
logger.info('chatgpt-plugin加载成功')
|
||||
logger.info(`当前版本${Config.version}`)
|
||||
logger.info(`当前版本${ChatGPTConfig.version}`)
|
||||
logger.info('仓库地址 https://github.com/ikechan8370/chatgpt-plugin')
|
||||
logger.info('文档地址 https://www.yunzai.chat')
|
||||
logger.info('插件群号 559567232')
|
||||
logger.info('**************************************')
|
||||
|
||||
export { apps }
|
||||
|
|
|
|||
207
models/chaite/cloud.js
Normal file
207
models/chaite/cloud.js
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
import {
|
||||
Chaite,
|
||||
ChannelsManager,
|
||||
ChatPresetManager,
|
||||
DefaultChannelLoadBalancer,
|
||||
ProcessorsManager,
|
||||
RAGManager,
|
||||
ToolManager,
|
||||
ToolsGroupManager,
|
||||
TriggerManager
|
||||
} from 'chaite'
|
||||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { LowDBChannelStorage } from './storage/lowdb/channel_storage.js'
|
||||
import { LowDBChatPresetsStorage } from './storage/lowdb/chat_preset_storage.js'
|
||||
import { LowDBToolsStorage } from './storage/lowdb/tools_storage.js'
|
||||
import { LowDBProcessorsStorage } from './storage/lowdb/processors_storage.js'
|
||||
import { ChatGPTUserModeSelector } from './user_mode_selector.js'
|
||||
import { LowDBUserStateStorage } from './storage/lowdb/user_state_storage.js'
|
||||
import { LowDBHistoryManager } from './storage/lowdb/history_manager.js'
|
||||
import { VectraVectorDatabase } from './vector_database.js'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { migrateDatabase } from '../../utils/initDB.js'
|
||||
import { SQLiteChannelStorage } from './storage/sqlite/channel_storage.js'
|
||||
import { dataDir } from '../../utils/common.js'
|
||||
import { SQLiteChatPresetStorage } from './storage/sqlite/chat_preset_storage.js'
|
||||
import { SQLiteToolsStorage } from './storage/sqlite/tools_storage.js'
|
||||
import { SQLiteProcessorsStorage } from './storage/sqlite/processors_storage.js'
|
||||
import { SQLiteUserStateStorage } from './storage/sqlite/user_state_storage.js'
|
||||
import { SQLiteToolsGroupStorage } from './storage/sqlite/tool_groups_storage.js'
|
||||
import { checkMigrate } from './storage/sqlite/migrate.js'
|
||||
import { SQLiteHistoryManager } from './storage/sqlite/history_manager.js'
|
||||
import SQLiteTriggerStorage from './storage/sqlite/trigger_storage.js'
|
||||
import LowDBTriggerStorage from './storage/lowdb/trigger_storage,.js'
|
||||
import { createChaiteVectorizer } from './vectorizer.js'
|
||||
import { MemoryRouter, authenticateMemoryRequest } from '../memory/router.js'
|
||||
|
||||
/**
|
||||
* 认证,以便共享上传
|
||||
* @param apiKey
|
||||
* @returns {Promise<import('chaite').User | null>}
|
||||
*/
|
||||
export async function authCloud (apiKey = ChatGPTConfig.chaite.cloudApiKey) {
|
||||
try {
|
||||
await Chaite.getInstance().auth(apiKey)
|
||||
return Chaite.getInstance().getToolsManager().cloudService.getUser()
|
||||
} catch (err) {
|
||||
logger.error(err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化RAG管理器
|
||||
* @param {string} model
|
||||
* @param {number} dimensions
|
||||
*/
|
||||
export async function initRagManager (model, dimensions) {
|
||||
const vectorizer = createChaiteVectorizer(model, dimensions)
|
||||
const vectorDBPath = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.dataDir, 'vector_index')
|
||||
if (!fs.existsSync(vectorDBPath)) {
|
||||
fs.mkdirSync(vectorDBPath, { recursive: true })
|
||||
}
|
||||
const vectorDB = new VectraVectorDatabase(vectorDBPath)
|
||||
await vectorDB.init()
|
||||
const ragManager = new RAGManager(vectorDB, vectorizer)
|
||||
return Chaite.getInstance().setRAGManager(ragManager)
|
||||
}
|
||||
|
||||
export async function initChaite () {
|
||||
const storage = ChatGPTConfig.chaite.storage
|
||||
let channelsStorage, chatPresetsStorage, toolsStorage, processorsStorage, userStateStorage, historyStorage, toolsGroupStorage, triggerStorage
|
||||
switch (storage) {
|
||||
case 'sqlite': {
|
||||
const dbPath = path.join(dataDir, 'data.db')
|
||||
channelsStorage = new SQLiteChannelStorage(dbPath)
|
||||
await channelsStorage.initialize()
|
||||
chatPresetsStorage = new SQLiteChatPresetStorage(dbPath)
|
||||
await chatPresetsStorage.initialize()
|
||||
toolsStorage = new SQLiteToolsStorage(dbPath)
|
||||
await toolsStorage.initialize()
|
||||
processorsStorage = new SQLiteProcessorsStorage(dbPath)
|
||||
await processorsStorage.initialize()
|
||||
userStateStorage = new SQLiteUserStateStorage(dbPath)
|
||||
await userStateStorage.initialize()
|
||||
toolsGroupStorage = new SQLiteToolsGroupStorage(dbPath)
|
||||
await toolsGroupStorage.initialize()
|
||||
triggerStorage = new SQLiteTriggerStorage(dbPath)
|
||||
await triggerStorage.initialize()
|
||||
historyStorage = new SQLiteHistoryManager(dbPath, path.join(dataDir, 'images'))
|
||||
await checkMigrate()
|
||||
break
|
||||
}
|
||||
case 'lowdb': {
|
||||
const ChatGPTStorage = (await import('storage/lowdb/storage.js')).default
|
||||
await ChatGPTStorage.init()
|
||||
channelsStorage = new LowDBChannelStorage(ChatGPTStorage)
|
||||
chatPresetsStorage = new LowDBChatPresetsStorage(ChatGPTStorage)
|
||||
toolsStorage = new LowDBToolsStorage(ChatGPTStorage)
|
||||
processorsStorage = new LowDBProcessorsStorage(ChatGPTStorage)
|
||||
userStateStorage = new LowDBUserStateStorage(ChatGPTStorage)
|
||||
triggerStorage = new LowDBTriggerStorage(ChatGPTStorage)
|
||||
const ChatGPTHistoryStorage = (await import('storage/lowdb/storage.js')).ChatGPTHistoryStorage
|
||||
await ChatGPTHistoryStorage.init()
|
||||
historyStorage = new LowDBHistoryManager(ChatGPTHistoryStorage)
|
||||
break
|
||||
}
|
||||
}
|
||||
const channelsManager = await ChannelsManager.init(channelsStorage, new DefaultChannelLoadBalancer())
|
||||
const toolsDir = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.toolsDirPath)
|
||||
if (!fs.existsSync(toolsDir)) {
|
||||
fs.mkdirSync(toolsDir, { recursive: true })
|
||||
}
|
||||
const toolsManager = await ToolManager.init(toolsDir, toolsStorage)
|
||||
const processorsDir = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.processorsDirPath)
|
||||
if (!fs.existsSync(processorsDir)) {
|
||||
fs.mkdirSync(processorsDir, { recursive: true })
|
||||
}
|
||||
const processorsManager = await ProcessorsManager.init(processorsDir, processorsStorage)
|
||||
const chatPresetManager = await ChatPresetManager.init(chatPresetsStorage)
|
||||
const toolsGroupManager = await ToolsGroupManager.init(toolsGroupStorage)
|
||||
const triggersDir = path.resolve('./plugins/chatgpt-plugin', ChatGPTConfig.chaite.triggersDir)
|
||||
if (!fs.existsSync(triggersDir)) {
|
||||
fs.mkdirSync(triggersDir, { recursive: true })
|
||||
}
|
||||
const triggerManager = new TriggerManager(triggersDir, triggerStorage)
|
||||
await triggerManager.initialize()
|
||||
const userModeSelector = new ChatGPTUserModeSelector()
|
||||
let chaite = Chaite.init(channelsManager, toolsManager, processorsManager, chatPresetManager, toolsGroupManager, triggerManager,
|
||||
userModeSelector, userStateStorage, historyStorage, logger)
|
||||
logger.info('Chaite 初始化完成')
|
||||
chaite.setCloudService(ChatGPTConfig.chaite.cloudBaseUrl)
|
||||
logger.info('Chaite.Cloud 初始化完成')
|
||||
await migrateDatabase()
|
||||
if (ChatGPTConfig.chaite.cloudApiKey) {
|
||||
const user = await authCloud(ChatGPTConfig.chaite.cloudApiKey)
|
||||
if (user) {
|
||||
logger.info(`Chaite.Cloud 认证成功, 当前用户${user.username || user.email} (${user.user_id})`)
|
||||
} else {
|
||||
logger.warn('Chaite.Cloud 认证失败,将继续使用本地功能')
|
||||
}
|
||||
}
|
||||
await initRagManager(ChatGPTConfig.llm.embeddingModel, ChatGPTConfig.llm.dimensions)
|
||||
if (!ChatGPTConfig.chaite.authKey) {
|
||||
ChatGPTConfig.chaite.authKey = Chaite.getInstance().getFrontendAuthHandler().generateToken(0, true)
|
||||
}
|
||||
chaite.getGlobalConfig().setAuthKey(ChatGPTConfig.chaite.authKey)
|
||||
// 监听Chaite配置变化,同步需要同步的配置
|
||||
chaite.on('config-change', obj => {
|
||||
const { key, newVal, oldVal } = obj
|
||||
if (key === 'authKey') {
|
||||
ChatGPTConfig.serverAuthKey = newVal
|
||||
}
|
||||
logger.debug(`Chaite config changed: ${key} from ${oldVal} to ${newVal}`)
|
||||
})
|
||||
// 监听通过chaite对插件配置修改
|
||||
chaite.setUpdateConfigCallback(config => {
|
||||
logger.debug('chatgpt-plugin config updated')
|
||||
|
||||
// 设置保存来源标记,而不是使用 _isSaving
|
||||
ChatGPTConfig._saveOrigin = 'chaite'
|
||||
|
||||
try {
|
||||
Object.keys(config).forEach(key => {
|
||||
if (typeof config[key] === 'object' && config[key] !== null && ChatGPTConfig[key]) {
|
||||
deepMerge(ChatGPTConfig[key], config[key])
|
||||
} else {
|
||||
ChatGPTConfig[key] = config[key]
|
||||
}
|
||||
})
|
||||
|
||||
// 回传部分需要同步的配置
|
||||
chaite.getGlobalConfig().setDebug(ChatGPTConfig.basic.debug)
|
||||
chaite.getGlobalConfig().setAuthKey(ChatGPTConfig.chaite.authKey)
|
||||
|
||||
// 使用新的触发保存方法,而不是直接调用saveToFile
|
||||
ChatGPTConfig._triggerSave('chaite')
|
||||
} finally {
|
||||
// 不需要在这里清除标记,_triggerSave已经处理了延迟清除
|
||||
}
|
||||
})
|
||||
// 授予Chaite获取插件配置的能力以便通过api放出
|
||||
chaite.setGetConfig(async () => {
|
||||
return ChatGPTConfig
|
||||
})
|
||||
chaite.getGlobalConfig().setHost(ChatGPTConfig.chaite.host)
|
||||
chaite.getGlobalConfig().setPort(ChatGPTConfig.chaite.port)
|
||||
chaite.getGlobalConfig().setDebug(ChatGPTConfig.basic.debug)
|
||||
logger.info('Chaite.RAGManager 初始化完成')
|
||||
chaite.runApiServer(app => {
|
||||
app.use('/api/memory', authenticateMemoryRequest, MemoryRouter)
|
||||
})
|
||||
}
|
||||
|
||||
function deepMerge (target, source) {
|
||||
for (const key in source) {
|
||||
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||
if (typeof source[key] === 'object' && source[key] !== null && target[key]) {
|
||||
// 如果是对象且目标属性存在,递归合并
|
||||
deepMerge(target[key], source[key])
|
||||
} else {
|
||||
// 否则直接赋值
|
||||
target[key] = source[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
104
models/chaite/storage/lowdb/channel_storage.js
Normal file
104
models/chaite/storage/lowdb/channel_storage.js
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { ChaiteStorage, Channel } from 'chaite'
|
||||
|
||||
export class LowDBChannelStorage extends ChaiteStorage {
|
||||
/**
|
||||
*
|
||||
* @param { LowDBStorage } storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('channel')
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<import('chaite').Channel>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
const obj = await this.collection.findOne({ id: key })
|
||||
if (!obj) {
|
||||
return null
|
||||
}
|
||||
return new Channel(obj)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {import('chaite').Channel} channel
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, channel) {
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, channel)
|
||||
return id
|
||||
}
|
||||
const result = await this.collection.insert(channel)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<import('chaite').Channel[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
const list = await this.collection.findAll()
|
||||
return list.map(item => new Channel({}).fromString(JSON.stringify(item)))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Record<string, unknown>} filter
|
||||
* @returns {Promise<import('chaite').Channel[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const key in filter) {
|
||||
if (item[key] !== filter[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<{
|
||||
* field: string;
|
||||
* values: unknown[];
|
||||
* }>} query
|
||||
* @returns {Promise<import('chaite').Channel[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const { field, values } of query) {
|
||||
if (!values.includes(item[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
107
models/chaite/storage/lowdb/chat_preset_storage.js
Normal file
107
models/chaite/storage/lowdb/chat_preset_storage.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import { ChaiteStorage, ChatPreset } from 'chaite'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ChatPreset>}
|
||||
*/
|
||||
export class LowDBChatPresetsStorage extends ChaiteStorage {
|
||||
/**
|
||||
*
|
||||
* @param { LowDBStorage } storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('chat_presets')
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key
|
||||
* @returns {Promise<import('chaite').ChatPreset>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
const obj = await this.collection.findOne({ id: key })
|
||||
if (!obj) {
|
||||
return null
|
||||
}
|
||||
return new ChatPreset(obj)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {import('chaite').ChatPreset} preset
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, preset) {
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, preset)
|
||||
return id
|
||||
}
|
||||
const result = await this.collection.insert(preset)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<import('chaite').ChatPreset[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
const list = await this.collection.findAll()
|
||||
return list.map(item => new ChatPreset({}).fromString(JSON.stringify(item)))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Record<string, unknown>} filter
|
||||
* @returns {Promise<import('chaite').ChatPreset[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const key in filter) {
|
||||
if (item[key] !== filter[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<{
|
||||
* field: string;
|
||||
* values: unknown[];
|
||||
* }>} query
|
||||
* @returns {Promise<import('chaite').ChatPreset[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const { field, values } of query) {
|
||||
if (!values.includes(item[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
56
models/chaite/storage/lowdb/history_manager.js
Normal file
56
models/chaite/storage/lowdb/history_manager.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { AbstractHistoryManager } from 'chaite'
|
||||
|
||||
export class LowDBHistoryManager extends AbstractHistoryManager {
|
||||
/**
|
||||
*
|
||||
* @param { LowDBStorage } storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('history')
|
||||
}
|
||||
|
||||
async saveHistory (message, conversationId) {
|
||||
const historyObj = { ...message, conversationId }
|
||||
if (message.id) {
|
||||
await this.collection.updateById(message.id, historyObj)
|
||||
}
|
||||
await this.collection.insert(historyObj)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param messageId
|
||||
* @param conversationId
|
||||
* @returns {Promise<import('chaite').HistoryMessage[]>}
|
||||
*/
|
||||
async getHistory (messageId, conversationId) {
|
||||
if (messageId) {
|
||||
const messages = []
|
||||
let currentId = messageId
|
||||
while (currentId) {
|
||||
const message = await this.collection.findOne({ id: currentId })
|
||||
if (!message) break
|
||||
messages.unshift(message)
|
||||
currentId = message.parentId
|
||||
}
|
||||
return messages
|
||||
} else if (conversationId) {
|
||||
return this.collection.find({ conversationId })
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
async deleteConversation (conversationId) {
|
||||
await this.collection.delete({ conversationId })
|
||||
}
|
||||
|
||||
async getOneHistory (messageId, conversationId) {
|
||||
return this.collection.findOne({ id: messageId, conversationId })
|
||||
}
|
||||
}
|
||||
107
models/chaite/storage/lowdb/processors_storage.js
Normal file
107
models/chaite/storage/lowdb/processors_storage.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
import { ChaiteStorage, ProcessorDTO } from 'chaite'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').Processor>}
|
||||
*/
|
||||
export class LowDBProcessorsStorage extends ChaiteStorage {
|
||||
/**
|
||||
*
|
||||
* @param { LowDBStorage } storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('processors')
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<import('chaite').Processor>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
const obj = await this.collection.findOne({ id: key })
|
||||
if (!obj) {
|
||||
return null
|
||||
}
|
||||
return new ProcessorDTO(obj)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {import('chaite').Processor} processor
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, processor) {
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, processor)
|
||||
return id
|
||||
}
|
||||
const result = await this.collection.insert(processor)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<import('chaite').Processor[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
const list = await this.collection.findAll()
|
||||
return list.map(item => new ProcessorDTO({}).fromString(JSON.stringify(item)))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Record<string, unknown>} filter
|
||||
* @returns {Promise<import('chaite').Processor[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const key in filter) {
|
||||
if (item[key] !== filter[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<{
|
||||
* field: string;
|
||||
* values: unknown[];
|
||||
* }>} query
|
||||
* @returns {Promise<import('chaite').Processor[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const { field, values } of query) {
|
||||
if (!values.includes(item[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
374
models/chaite/storage/lowdb/storage.js
Normal file
374
models/chaite/storage/lowdb/storage.js
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
// storage.js written by sonnet
|
||||
import { Low } from 'lowdb'
|
||||
import { JSONFile } from 'lowdb/node'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { dataDir } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* 基于 LowDB 的简单存储类,提供 CRUD 和条件查询功能
|
||||
*/
|
||||
export class LowDBStorage {
|
||||
/**
|
||||
* 创建一个新的存储实例
|
||||
* @param {Object} options 配置选项
|
||||
* @param {string} options.filename 数据文件名称
|
||||
* @param {string} options.directory 数据目录,默认为当前目录下的 data 文件夹
|
||||
*/
|
||||
constructor (options = {}) {
|
||||
const { filename = 'db.json', directory = path.join(process.cwd(), 'data') } = options
|
||||
|
||||
// 确保目录存在
|
||||
if (!fs.existsSync(directory)) {
|
||||
fs.mkdirSync(directory, { recursive: true })
|
||||
}
|
||||
|
||||
this.filePath = path.join(directory, filename)
|
||||
this.adapter = new JSONFile(this.filePath)
|
||||
this.db = new Low(this.adapter, { collections: {} })
|
||||
this.initialized = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化存储
|
||||
* @returns {Promise<LowDBStorage>} 当前存储实例
|
||||
*/
|
||||
async init () {
|
||||
// 读取数据文件,如果不存在则创建默认结构
|
||||
await this.db.read()
|
||||
this.db.data ||= { collections: {} }
|
||||
await this.db.write()
|
||||
|
||||
this.initialized = true
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取或创建一个集合
|
||||
* @param {string} name 集合名称
|
||||
* @returns {LowDBCollection} 集合实例
|
||||
*/
|
||||
collection (name) {
|
||||
this._checkInit()
|
||||
|
||||
// 确保集合存在
|
||||
if (!this.db.data.collections[name]) {
|
||||
this.db.data.collections[name] = []
|
||||
this.db.write()
|
||||
}
|
||||
|
||||
return new LowDBCollection(this, name)
|
||||
}
|
||||
|
||||
/**
|
||||
* 列出所有集合名称
|
||||
* @returns {string[]} 集合名称列表
|
||||
*/
|
||||
listCollections () {
|
||||
this._checkInit()
|
||||
return Object.keys(this.db.data.collections)
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个集合
|
||||
* @param {string} name 要删除的集合名称
|
||||
* @returns {Promise<boolean>} 是否成功删除
|
||||
*/
|
||||
async dropCollection (name) {
|
||||
this._checkInit()
|
||||
|
||||
if (this.db.data.collections[name]) {
|
||||
delete this.db.data.collections[name]
|
||||
await this.db.write()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查存储是否已初始化
|
||||
* @private
|
||||
*/
|
||||
_checkInit () {
|
||||
if (!this.initialized) {
|
||||
throw new Error('存储尚未初始化,请先调用 init() 方法')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 集合类,提供对特定数据集合的操作
|
||||
*/
|
||||
export class LowDBCollection {
|
||||
/**
|
||||
* 创建一个集合实例
|
||||
* @param {LowDBStorage} storage 所属存储实例
|
||||
* @param {string} name 集合名称
|
||||
*/
|
||||
constructor (storage, name) {
|
||||
this.storage = storage
|
||||
this.name = name
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合数据引用
|
||||
* @private
|
||||
*/
|
||||
get _collection () {
|
||||
return this.storage.db.data.collections[this.name]
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存数据到存储
|
||||
* @private
|
||||
*/
|
||||
async _save () {
|
||||
return this.storage.db.write()
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成唯一ID
|
||||
* @private
|
||||
*/
|
||||
_generateId () {
|
||||
return Date.now().toString(36) + Math.random().toString(36).substring(2, 15)
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新文档
|
||||
* @param {Object} doc 要插入的文档
|
||||
* @returns {Promise<Object & {id: string}>} 插入的文档(带ID)
|
||||
*/
|
||||
async insert (doc) {
|
||||
// 生成唯一ID,如果没有提供
|
||||
if (!doc.id) {
|
||||
doc.id = this._generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!doc.createdAt) {
|
||||
doc.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
doc.updatedAt = new Date().toISOString()
|
||||
|
||||
// 添加到集合
|
||||
this._collection.push(doc)
|
||||
await this._save()
|
||||
|
||||
return doc
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入多个文档
|
||||
* @param {Object[]} docs 要插入的文档数组
|
||||
* @returns {Promise<Object[]>} 插入的文档(带ID)
|
||||
*/
|
||||
async insertMany (docs) {
|
||||
const inserted = []
|
||||
|
||||
for (const doc of docs) {
|
||||
inserted.push(await this.insert(doc))
|
||||
}
|
||||
|
||||
return inserted
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID查找单个文档
|
||||
* @param {string} id 文档ID
|
||||
* @returns {Promise<Object|null>} 查找到的文档或null
|
||||
*/
|
||||
async findById (id) {
|
||||
return this._collection.find(doc => doc.id === id) || null
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回集合中的所有文档
|
||||
* @returns {Promise<Object[]>} 文档数组
|
||||
*/
|
||||
async findAll () {
|
||||
return [...this._collection]
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查找文档
|
||||
* @param {Object} query 查询条件(字段等值匹配)
|
||||
* @returns {Promise<Object[]>} 匹配的文档数组
|
||||
*/
|
||||
async find (query = {}) {
|
||||
return this._collection.filter(doc => {
|
||||
for (const key in query) {
|
||||
const value = query[key]
|
||||
|
||||
// 处理嵌套属性 (例如 user.profile.name)
|
||||
if (key.includes('.')) {
|
||||
const parts = key.split('.')
|
||||
let current = doc
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
if (current === undefined || current === null) return false
|
||||
current = current[parts[i]]
|
||||
}
|
||||
|
||||
if (current !== value) return false
|
||||
} else if (doc[key] !== value) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件查找单个文档
|
||||
* @param {Object} query 查询条件
|
||||
* @returns {Promise<Object|null>} 第一个匹配的文档或null
|
||||
*/
|
||||
async findOne (query = {}) {
|
||||
const results = await this.find(query)
|
||||
return results.length > 0 ? results[0] : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用自定义函数进行高级查询
|
||||
* @param {Function} filterFn 过滤函数
|
||||
* @returns {Promise<Object[]>} 匹配的文档数组
|
||||
*/
|
||||
async findWhere (filterFn) {
|
||||
return this._collection.filter(filterFn)
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID更新文档
|
||||
* @param {string} id 文档ID
|
||||
* @param {Object} updates 要更新的字段
|
||||
* @returns {Promise<Object|null>} 更新后的文档或null
|
||||
*/
|
||||
async updateById (id, updates) {
|
||||
const index = this._collection.findIndex(doc => doc.id === id)
|
||||
|
||||
if (index === -1) return null
|
||||
|
||||
// 防止覆盖ID
|
||||
const { id: _, ...safeUpdates } = updates
|
||||
|
||||
// 更新文档
|
||||
const updatedDoc = {
|
||||
...this._collection[index],
|
||||
...safeUpdates,
|
||||
updatedAt: new Date().toISOString()
|
||||
}
|
||||
|
||||
this._collection[index] = updatedDoc
|
||||
await this._save()
|
||||
|
||||
return updatedDoc
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件更新文档
|
||||
* @param {Object} query 查询条件
|
||||
* @param {Object} updates 要更新的字段
|
||||
* @returns {Promise<number>} 更新的文档数量
|
||||
*/
|
||||
async update (query, updates) {
|
||||
const matches = await this.find(query)
|
||||
let updated = 0
|
||||
|
||||
for (const doc of matches) {
|
||||
await this.updateById(doc.id, updates)
|
||||
updated++
|
||||
}
|
||||
|
||||
return updated
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID删除文档
|
||||
* @param {string} id 文档ID
|
||||
* @returns {Promise<boolean>} 是否成功删除
|
||||
*/
|
||||
async deleteById (id) {
|
||||
const index = this._collection.findIndex(doc => doc.id === id)
|
||||
|
||||
if (index === -1) return false
|
||||
|
||||
this._collection.splice(index, 1)
|
||||
await this._save()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件删除文档
|
||||
* @param {Object} query 查询条件
|
||||
* @returns {Promise<number>} 删除的文档数量
|
||||
*/
|
||||
async delete (query) {
|
||||
const before = this._collection.length
|
||||
|
||||
const remaining = this._collection.filter(doc => {
|
||||
for (const key in query) {
|
||||
if (doc[key] !== query[key]) {
|
||||
return true // 保留不匹配的
|
||||
}
|
||||
}
|
||||
return false // 删除匹配的
|
||||
})
|
||||
|
||||
this.storage.db.data.collections[this.name] = remaining
|
||||
await this._save()
|
||||
|
||||
return before - remaining.length
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空集合中的所有文档
|
||||
* @returns {Promise<number>} 删除的文档数量
|
||||
*/
|
||||
async deleteAll () {
|
||||
const count = this._collection.length
|
||||
this.storage.db.data.collections[this.name] = []
|
||||
await this._save()
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回集合中文档的数量
|
||||
* @returns {Promise<number>} 文档数量
|
||||
*/
|
||||
async count (query = {}) {
|
||||
if (Object.keys(query).length === 0) {
|
||||
return this._collection.length
|
||||
}
|
||||
|
||||
const matches = await this.find(query)
|
||||
return matches.length
|
||||
}
|
||||
}
|
||||
|
||||
const storageLocation = path.resolve(dataDir, 'storage.json')
|
||||
if (!fs.existsSync(storageLocation)) {
|
||||
fs.writeFileSync(storageLocation, JSON.stringify({ collections: {} }))
|
||||
}
|
||||
|
||||
const ChatGPTStorage = new LowDBStorage({
|
||||
filename: 'storage.json',
|
||||
directory: dataDir
|
||||
})
|
||||
|
||||
if (ChatGPTStorage.db.data.collections.history) {
|
||||
ChatGPTStorage.dropCollection('history').then(() => {
|
||||
logger.debug('drop older version history collection')
|
||||
}).catch(err => {
|
||||
logger.warn('failed to drop older version history collection', err)
|
||||
})
|
||||
}
|
||||
|
||||
export const ChatGPTHistoryStorage = new LowDBStorage({
|
||||
filename: 'history.json',
|
||||
directory: dataDir
|
||||
})
|
||||
|
||||
export default ChatGPTStorage
|
||||
70
models/chaite/storage/lowdb/tool_groups_storage.js
Normal file
70
models/chaite/storage/lowdb/tool_groups_storage.js
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { ChaiteStorage, ToolsGroupDTO } from 'chaite'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ToolsGroupDTO>}
|
||||
*/
|
||||
export class LowDBToolsGroupDTOsStorage extends ChaiteStorage {
|
||||
/**
|
||||
*
|
||||
* @param { LowDBStorage } storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('tool_groups')
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key
|
||||
* @returns {Promise<import('chaite').ToolsGroupDTO>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
const obj = await this.collection.findOne({ id: key })
|
||||
if (!obj) {
|
||||
return null
|
||||
}
|
||||
return new ToolsGroupDTO(obj)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {import('chaite').ToolsGroupDTO} preset
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, preset) {
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, preset)
|
||||
return id
|
||||
}
|
||||
const result = await this.collection.insert(preset)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<import('chaite').ToolsGroupDTO[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
const list = await this.collection.findAll()
|
||||
return list.map(item => new ToolsGroupDTO({}).fromString(JSON.stringify(item)))
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
111
models/chaite/storage/lowdb/tools_storage.js
Normal file
111
models/chaite/storage/lowdb/tools_storage.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { ChaiteStorage, ToolDTO } from 'chaite'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ToolDTO>}
|
||||
*/
|
||||
export class LowDBToolsStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'LowDBToolsStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param { LowDBStorage } storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('tools')
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<import('chaite').ToolDTO>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
const obj = await this.collection.findOne({ id: key })
|
||||
if (!obj) {
|
||||
return null
|
||||
}
|
||||
return new ToolDTO(obj)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {import('chaite').ToolDTO} tools
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, tools) {
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, tools)
|
||||
return id
|
||||
}
|
||||
const result = await this.collection.insert(tools)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<import('chaite').ToolDTO[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
const list = await this.collection.findAll()
|
||||
return list.map(item => new ToolDTO({}).fromString(JSON.stringify(item)))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Record<string, unknown>} filter
|
||||
* @returns {Promise<import('chaite').ToolDTO[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const key in filter) {
|
||||
if (item[key] !== filter[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<{
|
||||
* field: string;
|
||||
* values: unknown[];
|
||||
* }>} query
|
||||
* @returns {Promise<import('chaite').ToolDTO[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const { field, values } of query) {
|
||||
if (!values.includes(item[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
122
models/chaite/storage/lowdb/trigger_storage,.js
Normal file
122
models/chaite/storage/lowdb/trigger_storage,.js
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { ChaiteStorage, TriggerDTO } from 'chaite'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').TriggerDTO>}
|
||||
*/
|
||||
export class LowDBTriggerStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'LowDBTriggerStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {LowDBStorage} storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('triggers')
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个触发器
|
||||
* @param {string} key
|
||||
* @returns {Promise<import('chaite').TriggerDTO>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
const obj = await this.collection.findOne({ id: key })
|
||||
if (!obj) {
|
||||
return null
|
||||
}
|
||||
return new TriggerDTO(obj)
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存触发器
|
||||
* @param {string} id
|
||||
* @param {import('chaite').TriggerDTO} trigger
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, trigger) {
|
||||
// 设置或更新时间戳
|
||||
if (!trigger.createdAt) {
|
||||
trigger.createdAt = new Date().toISOString()
|
||||
}
|
||||
trigger.updatedAt = new Date().toISOString()
|
||||
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, trigger)
|
||||
return id
|
||||
}
|
||||
const result = await this.collection.insert(trigger)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除触发器
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有触发器
|
||||
* @returns {Promise<import('chaite').TriggerDTO[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
const list = await this.collection.findAll()
|
||||
return list.map(item => new TriggerDTO({}).fromString(JSON.stringify(item)))
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选触发器
|
||||
* @param {Record<string, unknown>} filter
|
||||
* @returns {Promise<import('chaite').TriggerDTO[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const key in filter) {
|
||||
if (item[key] !== filter[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条件筛选触发器
|
||||
* @param {Array<{
|
||||
* field: string;
|
||||
* values: unknown[];
|
||||
* }>} query
|
||||
* @returns {Promise<import('chaite').TriggerDTO[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
const allList = await this.listItems()
|
||||
return allList.filter(item => {
|
||||
for (const { field, values } of query) {
|
||||
if (!values.includes(item[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有触发器
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
|
||||
export default LowDBTriggerStorage
|
||||
84
models/chaite/storage/lowdb/user_state_storage.js
Normal file
84
models/chaite/storage/lowdb/user_state_storage.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { ChaiteStorage } from 'chaite'
|
||||
import * as crypto from 'node:crypto'
|
||||
|
||||
/**
|
||||
* 继承UserState
|
||||
*/
|
||||
export class YunzaiUserState {
|
||||
constructor (userId, nickname, card, conversationId = crypto.randomUUID()) {
|
||||
this.userId = userId
|
||||
this.nickname = nickname
|
||||
this.card = card
|
||||
this.conversations = []
|
||||
this.settings = {}
|
||||
this.current = {
|
||||
conversationId,
|
||||
messageId: crypto.randomUUID()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').UserState>}
|
||||
*/
|
||||
export class LowDBUserStateStorage extends ChaiteStorage {
|
||||
/**
|
||||
*
|
||||
* @param {LowDBStorage} storage
|
||||
*/
|
||||
constructor (storage) {
|
||||
super()
|
||||
this.storage = storage
|
||||
/**
|
||||
* 集合
|
||||
* @type {LowDBCollection}
|
||||
*/
|
||||
this.collection = this.storage.collection('user_states')
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<import('chaite').UserState>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
return this.collection.findOne({ id: key })
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} id
|
||||
* @param {import('chaite').UserState} state
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, state) {
|
||||
if (id && await this.getItem(id)) {
|
||||
await this.collection.updateById(id, state)
|
||||
return id
|
||||
}
|
||||
state.id = id
|
||||
const result = await this.collection.insert(state)
|
||||
return result.id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.collection.deleteById(key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns {Promise<import('chaite').UserState[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
return this.collection.findAll()
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.collection.deleteAll()
|
||||
}
|
||||
}
|
||||
528
models/chaite/storage/sqlite/channel_storage.js
Normal file
528
models/chaite/storage/sqlite/channel_storage.js
Normal file
|
|
@ -0,0 +1,528 @@
|
|||
import { ChaiteStorage, Channel } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { generateId } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').Channel>}
|
||||
*/
|
||||
export class SQLiteChannelStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'SQLiteChannelStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'channels'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建Channel表,将主要属性分列存储
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
adapterType TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
weight INTEGER DEFAULT 1,
|
||||
priority INTEGER DEFAULT 0,
|
||||
status TEXT DEFAULT 'enabled',
|
||||
disabledReason TEXT,
|
||||
models TEXT,
|
||||
options TEXT,
|
||||
statistics TEXT,
|
||||
uploader TEXT,
|
||||
cloudId INTEGER,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT,
|
||||
md5 TEXT,
|
||||
embedded INTEGER DEFAULT 0,
|
||||
extra TEXT -- 存储其他额外数据的JSON
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建索引提高查询性能
|
||||
const promises = [
|
||||
// 按类型和状态索引
|
||||
new Promise((resolve, reject) => {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_type ON ${this.tableName} (type)`, err => {
|
||||
if (err) reject(err)
|
||||
else resolve()
|
||||
})
|
||||
}),
|
||||
new Promise((resolve, reject) => {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_status ON ${this.tableName} (status)`, err => {
|
||||
if (err) reject(err)
|
||||
else resolve()
|
||||
})
|
||||
})
|
||||
]
|
||||
|
||||
Promise.all(promises)
|
||||
.then(() => {
|
||||
this.initialized = true
|
||||
resolve()
|
||||
})
|
||||
.catch(reject)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保数据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Channel 对象转换为数据库记录
|
||||
* @param {import('chaite').Channel} channel
|
||||
* @returns {Object} 数据库记录
|
||||
*/
|
||||
_channelToRecord (channel) {
|
||||
// 提取主要字段
|
||||
const {
|
||||
id, name, description, adapterType, type, weight, priority,
|
||||
status, disabledReason, models, options, statistics,
|
||||
uploader, cloudId, createdAt, updatedAt, md5, embedded, ...rest
|
||||
} = channel
|
||||
|
||||
return {
|
||||
id: id || '',
|
||||
name: name || '',
|
||||
description: description || '',
|
||||
adapterType: adapterType || type || '',
|
||||
type: type || '',
|
||||
weight: weight || 1,
|
||||
priority: priority || 0,
|
||||
status: status || 'enabled',
|
||||
disabledReason: disabledReason || null,
|
||||
models: Array.isArray(models) ? JSON.stringify(models) : '[]',
|
||||
options: options ? JSON.stringify(options) : null,
|
||||
statistics: statistics ? JSON.stringify(statistics) : null,
|
||||
uploader: uploader ? JSON.stringify(uploader) : null,
|
||||
cloudId: cloudId || null,
|
||||
createdAt: createdAt || '',
|
||||
updatedAt: updatedAt || '',
|
||||
md5: md5 || '',
|
||||
embedded: embedded ? 1 : 0,
|
||||
extra: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据库记录转换为 Channel 对象
|
||||
* @param {Object} record 数据库记录
|
||||
* @returns {import('chaite').Channel} Channel 对象
|
||||
*/
|
||||
_recordToChannel (record) {
|
||||
if (!record) return null
|
||||
|
||||
// 解析JSON字段
|
||||
let models = []
|
||||
try {
|
||||
if (record.models) {
|
||||
models = JSON.parse(record.models)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空数组
|
||||
}
|
||||
|
||||
let options = {}
|
||||
try {
|
||||
if (record.options) {
|
||||
options = JSON.parse(record.options)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
let statistics = {}
|
||||
try {
|
||||
if (record.statistics) {
|
||||
statistics = JSON.parse(record.statistics)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
let uploader = null
|
||||
try {
|
||||
if (record.uploader) {
|
||||
uploader = JSON.parse(record.uploader)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用null
|
||||
}
|
||||
|
||||
let extra = {}
|
||||
try {
|
||||
if (record.extra) {
|
||||
extra = JSON.parse(record.extra)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
// 构造Channel对象
|
||||
const channelData = {
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
description: record.description,
|
||||
adapterType: record.adapterType,
|
||||
type: record.type,
|
||||
weight: Number(record.weight),
|
||||
priority: Number(record.priority),
|
||||
status: record.status,
|
||||
disabledReason: record.disabledReason,
|
||||
models,
|
||||
options,
|
||||
statistics,
|
||||
uploader,
|
||||
cloudId: record.cloudId,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
md5: record.md5,
|
||||
embedded: Boolean(record.embedded),
|
||||
...extra
|
||||
}
|
||||
|
||||
return new Channel(channelData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个渠道
|
||||
* @param {string} key 渠道ID
|
||||
* @returns {Promise<import('chaite').Channel>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const channel = this._recordToChannel(row)
|
||||
resolve(channel)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存渠道
|
||||
* @param {string} id 渠道ID
|
||||
* @param {import('chaite').Channel} channel 渠道对象
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, channel) {
|
||||
await this.ensureInitialized()
|
||||
if (!id) {
|
||||
id = generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!channel.createdAt) {
|
||||
channel.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
channel.updatedAt = new Date().toISOString()
|
||||
// 转换为数据库记录
|
||||
const record = this._channelToRecord(channel)
|
||||
record.id = id // 确保ID是指定的ID
|
||||
|
||||
// 构建插入或更新SQL
|
||||
const fields = Object.keys(record)
|
||||
const placeholders = fields.map(() => '?').join(', ')
|
||||
const updates = fields.map(field => `${field} = ?`).join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(', ')})
|
||||
VALUES (${placeholders})
|
||||
ON CONFLICT(id) DO UPDATE SET ${updates}`,
|
||||
[...values, ...duplicateValues],
|
||||
function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除渠道
|
||||
* @param {string} key 渠道ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有渠道
|
||||
* @returns {Promise<import('chaite').Channel[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const channels = rows.map(row => this._recordToChannel(row)).filter(Boolean)
|
||||
resolve(channels)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选渠道
|
||||
* @param {Record<string, unknown>} filter 筛选条件
|
||||
* @returns {Promise<import('chaite').Channel[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有筛选条件,返回所有
|
||||
if (!filter || Object.keys(filter).length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL字段直接过滤
|
||||
const directFields = ['id', 'name', 'description', 'adapterType', 'type', 'status', 'cloudId']
|
||||
const numericFields = ['weight', 'priority']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraFilters = {}
|
||||
let hasExtraFilters = false
|
||||
|
||||
// 区分数据库字段和额外字段
|
||||
for (const key in filter) {
|
||||
const value = filter[key]
|
||||
|
||||
// 如果是直接支持的字段,构建SQL条件
|
||||
if (directFields.includes(key)) {
|
||||
sqlFilters.push(`${key} = ?`)
|
||||
sqlParams.push(value)
|
||||
} else if (numericFields.includes(key)) {
|
||||
// 数值型字段
|
||||
sqlFilters.push(`${key} = ?`)
|
||||
sqlParams.push(Number(value))
|
||||
} else if (key === 'embedded') {
|
||||
// embedded 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('embedded = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else if (key === 'models' && typeof value === 'string') {
|
||||
// models字段需要特殊处理,判断是否包含某模型
|
||||
// 注意:这种方式仅适用于单个模型的查询,不适用于完全匹配数组
|
||||
sqlFilters.push('models LIKE ?')
|
||||
sqlParams.push(`%${value}%`)
|
||||
} else {
|
||||
// 其他字段需要在结果中进一步过滤
|
||||
extraFilters[key] = value
|
||||
hasExtraFilters = true
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let channels = rows.map(row => this._recordToChannel(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的额外<E9A29D><E5A496><EFBFBD>段
|
||||
if (hasExtraFilters) {
|
||||
channels = channels.filter(channel => {
|
||||
for (const key in extraFilters) {
|
||||
if (channel[key] !== extraFilters[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(channels)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条件筛选渠道
|
||||
* @param {Array<{ field: string; values: unknown[]; }>} query
|
||||
* @returns {Promise<import('chaite').Channel[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有查询条件,返回所有
|
||||
if (!query || query.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL IN子句来优化查询
|
||||
const directFields = ['id', 'name', 'description', 'adapterType', 'type', 'status', 'cloudId']
|
||||
const numericFields = ['weight', 'priority']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraQueries = []
|
||||
|
||||
// 处理每个查询条件
|
||||
for (const { field, values } of query) {
|
||||
if (values.length === 0) continue
|
||||
|
||||
// 如果是直接支持的字段,使用SQL IN子句
|
||||
if (directFields.includes(field)) {
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
sqlFilters.push(`${field} IN (${placeholders})`)
|
||||
sqlParams.push(...values)
|
||||
} else if (numericFields.includes(field)) {
|
||||
// 数值型字段
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
sqlFilters.push(`${field} IN (${placeholders})`)
|
||||
sqlParams.push(...values.map(v => Number(v)))
|
||||
} else if (field === 'embedded') {
|
||||
// embedded 字段需要特殊处理
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`embedded IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else if (field === 'models') {
|
||||
// models字段需要特殊处理,判断是否包含某模型
|
||||
// 由于无法直接使用IN查询JSON字段,这里使用OR和LIKE的组合
|
||||
const modelFilters = values.map(() => 'models LIKE ?').join(' OR ')
|
||||
sqlFilters.push(`(${modelFilters})`)
|
||||
values.forEach(value => {
|
||||
sqlParams.push(`%${value}%`)
|
||||
})
|
||||
} else {
|
||||
// 其他字段在内存中过滤
|
||||
extraQueries.push({ field, values })
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let channels = rows.map(row => this._recordToChannel(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的条件
|
||||
if (extraQueries.length > 0) {
|
||||
channels = channels.filter(channel => {
|
||||
for (const { field, values } of extraQueries) {
|
||||
if (!values.includes(channel[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(channels)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空表中所有数据
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
523
models/chaite/storage/sqlite/chat_preset_storage.js
Normal file
523
models/chaite/storage/sqlite/chat_preset_storage.js
Normal file
|
|
@ -0,0 +1,523 @@
|
|||
import { ChaiteStorage, ChatPreset } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { generateId } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ChatPreset>}
|
||||
*/
|
||||
export class SQLiteChatPresetStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'SQLiteChatPresetStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'chat_presets'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建 ChatPreset 表,将主要属性分列存储
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
prefix TEXT NOT NULL,
|
||||
local INTEGER DEFAULT 1,
|
||||
namespace TEXT,
|
||||
sendMessageOption TEXT NOT NULL,
|
||||
cloudId INTEGER,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT,
|
||||
md5 TEXT,
|
||||
embedded INTEGER DEFAULT 0,
|
||||
uploader TEXT,
|
||||
extraData TEXT
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建索引提高查询性能
|
||||
const promises = [
|
||||
new Promise((resolve, reject) => {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_prefix ON ${this.tableName} (prefix)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}),
|
||||
new Promise((resolve, reject) => {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_name ON ${this.tableName} (name)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
]
|
||||
|
||||
Promise.all(promises)
|
||||
.then(() => {
|
||||
this.initialized = true
|
||||
resolve()
|
||||
})
|
||||
.catch(reject)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保<EFBFBD><EFBFBD><EFBFBD>据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 ChatPreset 对象转换为数据库记录
|
||||
* @param {import('chaite').ChatPreset} preset
|
||||
* @returns {Object} 数据库记录
|
||||
*/
|
||||
_presetToRecord (preset) {
|
||||
// 提取主要字段
|
||||
const {
|
||||
id, name, description, prefix, local, namespace,
|
||||
sendMessageOption, cloudId, createdAt, updatedAt, md5,
|
||||
embedded, uploader, ...rest
|
||||
} = preset
|
||||
|
||||
return {
|
||||
id: id || '',
|
||||
name: name || '',
|
||||
description: description || '',
|
||||
prefix: prefix || '',
|
||||
local: local === false ? 0 : 1,
|
||||
namespace: namespace || null,
|
||||
sendMessageOption: JSON.stringify(sendMessageOption || {}),
|
||||
cloudId: cloudId || null,
|
||||
createdAt: createdAt || '',
|
||||
updatedAt: updatedAt || '',
|
||||
md5: md5 || '',
|
||||
embedded: embedded ? 1 : 0,
|
||||
uploader: uploader ? JSON.stringify(uploader) : null,
|
||||
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数<EFBFBD><EFBFBD><EFBFBD>库记录转换为 ChatPreset 对象
|
||||
* @param {Object} record 数据库记录
|
||||
* @returns {import('chaite').ChatPreset} ChatPreset 对象
|
||||
*/
|
||||
_recordToPreset (record) {
|
||||
if (!record) return null
|
||||
|
||||
// 解析 JSON 字<><E5AD97>
|
||||
let sendMessageOption = {}
|
||||
try {
|
||||
if (record.sendMessageOption) {
|
||||
sendMessageOption = JSON.parse(record.sendMessageOption)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
let uploader = null
|
||||
try {
|
||||
if (record.uploader) {
|
||||
uploader = JSON.parse(record.uploader)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用 null
|
||||
}
|
||||
|
||||
let extraData = {}
|
||||
try {
|
||||
if (record.extraData) {
|
||||
extraData = JSON.parse(record.extraData)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
// 构造 ChatPreset 对象
|
||||
const presetData = {
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
description: record.description,
|
||||
prefix: record.prefix,
|
||||
local: Boolean(record.local),
|
||||
namespace: record.namespace,
|
||||
sendMessageOption,
|
||||
cloudId: record.cloudId,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
md5: record.md5,
|
||||
embedded: Boolean(record.embedded),
|
||||
uploader,
|
||||
...extraData
|
||||
}
|
||||
|
||||
return new ChatPreset(presetData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个聊天预设
|
||||
* @param {string} key 预设ID
|
||||
* @returns {Promise<import('chaite').ChatPreset>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const preset = this._recordToPreset(row)
|
||||
resolve(preset)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存聊天预设
|
||||
* @param {string} id 预设ID
|
||||
* @param {import('chaite').ChatPreset} preset 预设对象
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, preset) {
|
||||
await this.ensureInitialized()
|
||||
if (!id) {
|
||||
id = generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!preset.createdAt) {
|
||||
preset.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
preset.updatedAt = new Date().toISOString()
|
||||
// 转换为数据库记录
|
||||
const record = this._presetToRecord(preset)
|
||||
record.id = id // 确保ID是指定的ID
|
||||
|
||||
// 构建插入或更新SQL
|
||||
const fields = Object.keys(record)
|
||||
const placeholders = fields.map(() => '?').join(', ')
|
||||
const updates = fields.map(field => `${field} = ?`).join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(', ')})
|
||||
VALUES (${placeholders})
|
||||
ON CONFLICT(id) DO UPDATE SET ${updates}`,
|
||||
[...values, ...duplicateValues],
|
||||
function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除聊天预设
|
||||
* @param {string} key 预设ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有聊天预设
|
||||
* @returns {Promise<import('chaite').ChatPreset[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const presets = rows.map(row => this._recordToPreset(row)).filter(Boolean)
|
||||
resolve(presets)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选聊天预设
|
||||
* @param {Record<string, unknown>} filter 筛选条件
|
||||
* @returns {Promise<import('chaite').ChatPreset[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有筛选条件,返回所有
|
||||
if (!filter || Object.keys(filter).length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL字段直接过滤
|
||||
const directFields = ['id', 'name', 'description', 'prefix', 'namespace', 'cloudId']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraFilters = {}
|
||||
let hasExtraFilters = false
|
||||
|
||||
// 区分数据库字段和额外字段
|
||||
for (const key in filter) {
|
||||
const value = filter[key]
|
||||
|
||||
// 如果是直接支持的字段,构建SQL条件
|
||||
if (directFields.includes(key)) {
|
||||
sqlFilters.push(`${key} = ?`)
|
||||
sqlParams.push(value)
|
||||
} else if (key === 'local') {
|
||||
// local 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('local = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else if (key === 'embedded') {
|
||||
// embedded 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('embedded = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else {
|
||||
// 其他字段需要在结果中进一步过滤
|
||||
extraFilters[key] = value
|
||||
hasExtraFilters = true
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let presets = rows.map(row => this._recordToPreset(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的额外字段
|
||||
if (hasExtraFilters) {
|
||||
presets = presets.filter(preset => {
|
||||
for (const key in extraFilters) {
|
||||
const filterValue = extraFilters[key]
|
||||
|
||||
// 处理 sendMessageOption 字段的深层过滤
|
||||
if (key.startsWith('sendMessageOption.')) {
|
||||
const optionKey = key.split('.')[1]
|
||||
if (preset.sendMessageOption && preset.sendMessageOption[optionKey] !== filterValue) {
|
||||
return false
|
||||
}
|
||||
} else if (preset[key] !== filterValue) {
|
||||
// 其他字段直接比较
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(presets)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条件筛选聊天预设
|
||||
* @param {Array<{ field: string; values: unknown[]; }>} query
|
||||
* @returns {Promise<import('chaite').ChatPreset[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有查询条件,返回所有
|
||||
if (!query || query.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL IN子句来优化查询
|
||||
const directFields = ['id', 'name', 'description', 'prefix', 'namespace', 'cloudId']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraQueries = []
|
||||
|
||||
// 处理每个查询条件
|
||||
for (const { field, values } of query) {
|
||||
if (values.length === 0) continue
|
||||
|
||||
// 如果是直接支持的字段,使用SQL IN子句
|
||||
if (directFields.includes(field)) {
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
sqlFilters.push(`${field} IN (${placeholders})`)
|
||||
sqlParams.push(...values)
|
||||
} else if (field === 'local') {
|
||||
// local 字段需要特殊处理
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`local IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else if (field === 'embedded') {
|
||||
// embedded 字段需要特殊处理
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`embedded IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else {
|
||||
// 其他字段在内存中过滤
|
||||
extraQueries.push({ field, values })
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let presets = rows.map(row => this._recordToPreset(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的条件
|
||||
if (extraQueries.length > 0) {
|
||||
presets = presets.filter(preset => {
|
||||
for (const { field, values } of extraQueries) {
|
||||
// 处<><E5A484><EFBFBD> sendMessageOption 字段的深层过滤
|
||||
if (field.startsWith('sendMessageOption.')) {
|
||||
const optionKey = field.split('.')[1]
|
||||
const presetValue = preset.sendMessageOption?.[optionKey]
|
||||
if (!values.includes(presetValue)) {
|
||||
return false
|
||||
}
|
||||
} else if (!values.includes(preset[field])) {
|
||||
// 其他字段直接比较
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(presets)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据前缀获取聊天预设
|
||||
* @param {string} prefix 前缀
|
||||
* @returns {Promise<import('chaite').ChatPreset | null>}
|
||||
*/
|
||||
async getPresetByPrefix (prefix) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE prefix = ?`, [prefix], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const preset = this._recordToPreset(row)
|
||||
resolve(preset)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空表中所有数据
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
596
models/chaite/storage/sqlite/history_manager.js
Normal file
596
models/chaite/storage/sqlite/history_manager.js
Normal file
|
|
@ -0,0 +1,596 @@
|
|||
import { AbstractHistoryManager } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import crypto from 'crypto'
|
||||
|
||||
export class SQLiteHistoryManager extends AbstractHistoryManager {
|
||||
/**
|
||||
*
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
* @param {string} imagesDir 图片存储目录,默认为数据库同级的 images 目录
|
||||
*/
|
||||
constructor (dbPath, imagesDir) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.imagesDir = imagesDir || path.join(path.dirname(dbPath), 'images')
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'history'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
// 确保图片目录存在
|
||||
if (!fs.existsSync(this.imagesDir)) {
|
||||
fs.mkdirSync(this.imagesDir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建 history 表
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
parentId TEXT,
|
||||
conversationId TEXT,
|
||||
role TEXT,
|
||||
messageData TEXT,
|
||||
createdAt TEXT
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建索引,加速查询
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_conversation ON ${this.tableName} (conversationId)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_parent ON ${this.tableName} (parentId)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
this.initialized = true
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保数据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算文本的md5值
|
||||
* @param {string} text
|
||||
* @returns {string}
|
||||
*/
|
||||
_getMd5 (text) {
|
||||
return crypto.createHash('md5').update(text).digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为base64编码的图片
|
||||
* @param {string} str
|
||||
* @returns {boolean}
|
||||
*/
|
||||
_isBase64Image (str) {
|
||||
if (!str || typeof str !== 'string') {
|
||||
return false
|
||||
}
|
||||
|
||||
// 处理带前缀的 base64 格式
|
||||
if (str.startsWith('data:image/')) {
|
||||
return true
|
||||
}
|
||||
|
||||
// 处理纯 base64 字符串
|
||||
// base64 编码只会包含字母、数字、+、/,以及末尾可能有 = 或 == 用于填充
|
||||
return /^[A-Za-z0-9+/]+={0,2}$/.test(str)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从base64提取图片的mime类型,或使用默认类型
|
||||
* @param {string} base64
|
||||
* @param {string} defaultMimeType 默认 MIME 类型
|
||||
* @returns {string}
|
||||
*/
|
||||
_getMimeTypeFromBase64 (base64, defaultMimeType = 'image/jpeg') {
|
||||
if (base64 && base64.startsWith('data:image/')) {
|
||||
const match = base64.match(/^data:(image\/[a-zA-Z+]+);base64,/)
|
||||
if (match) {
|
||||
return match[1]
|
||||
}
|
||||
}
|
||||
return defaultMimeType // 对于纯 base64 字符串,使用默认类型
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片扩展名
|
||||
* @param {string} mimeType
|
||||
* @returns {string}
|
||||
*/
|
||||
_getExtensionFromMimeType (mimeType) {
|
||||
const map = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/gif': '.gif',
|
||||
'image/webp': '.webp',
|
||||
'image/svg+xml': '.svg'
|
||||
}
|
||||
return map[mimeType] || '.png'
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理消息中的图片内容,将base64图片保存到本地文件
|
||||
* @param {object} message
|
||||
* @returns {object} 处理后的消息对象
|
||||
*/
|
||||
_processMessageImages (message) {
|
||||
if (!message.content || !Array.isArray(message.content)) {
|
||||
return message
|
||||
}
|
||||
|
||||
// 深拷贝避免修改原对象
|
||||
const processedMessage = JSON.parse(JSON.stringify(message))
|
||||
|
||||
processedMessage.content = processedMessage.content.map(item => {
|
||||
if (item.type === 'image' && item.image) {
|
||||
// 检查是否是base64图片数据
|
||||
if (this._isBase64Image(item.image)) {
|
||||
let base64Data = item.image
|
||||
let mimeType = item.mimeType || 'image/jpeg' // 使用项目指定的 MIME 类型或默认值
|
||||
|
||||
// 如果是data:image格式,提取纯base64部分
|
||||
if (base64Data.startsWith('data:')) {
|
||||
const parts = base64Data.split(',')
|
||||
if (parts.length > 1) {
|
||||
base64Data = parts[1]
|
||||
// 更新 MIME 类型
|
||||
mimeType = this._getMimeTypeFromBase64(item.image, mimeType)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// 计算MD5
|
||||
const md5 = this._getMd5(base64Data)
|
||||
const ext = this._getExtensionFromMimeType(mimeType)
|
||||
const filePath = path.join(this.imagesDir, `${md5}${ext}`)
|
||||
|
||||
// 如果文件不存在,则保存
|
||||
if (!fs.existsSync(filePath)) {
|
||||
fs.writeFileSync(filePath, Buffer.from(base64Data, 'base64'))
|
||||
}
|
||||
|
||||
// 替换为引用格式: $image:md5:ext
|
||||
item.image = `$image:${md5}:${ext}`
|
||||
item._type = mimeType // 保存原始类型
|
||||
} catch (error) {
|
||||
console.error('保存图片失败:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
return item
|
||||
})
|
||||
|
||||
return processedMessage
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复消息中的图片引用,转换回base64
|
||||
* @param {object} message
|
||||
* @returns {object} 处理后的消息对象
|
||||
*/
|
||||
_restoreMessageImages (message) {
|
||||
if (!message || !message.content || !Array.isArray(message.content)) {
|
||||
return message
|
||||
}
|
||||
|
||||
// 深拷贝避免修改原对象
|
||||
const restoredMessage = JSON.parse(JSON.stringify(message))
|
||||
|
||||
// 标记是否需要添加[图片]文本
|
||||
let needImageText = true
|
||||
let hasRemovedImage = false
|
||||
|
||||
restoredMessage.content = restoredMessage.content.filter((item, index) => {
|
||||
if (item.type === 'image' && item.image && typeof item.image === 'string') {
|
||||
// 检查是否是图片引用格式
|
||||
const match = item.image.match(/^\$image:([a-f0-9]+):(\.[a-z]+)$/)
|
||||
if (match) {
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const [_, md5, ext] = match
|
||||
const filePath = path.join(this.imagesDir, `${md5}${ext}`)
|
||||
|
||||
// 检查文件是否存在
|
||||
if (fs.existsSync(filePath)) {
|
||||
try {
|
||||
// 读取文件并转换为base64
|
||||
const imageBuffer = fs.readFileSync(filePath)
|
||||
item.image = imageBuffer.toString('base64')
|
||||
return true
|
||||
} catch (error) {
|
||||
console.error('读取图片文件失败:', filePath, error)
|
||||
hasRemovedImage = true
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
// 文件不存在,删除这个image元素
|
||||
hasRemovedImage = true
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.type === 'text') {
|
||||
needImageText = false
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
// 如果移除了图片且没有文本内容,添加[图片]提示
|
||||
if (hasRemovedImage) {
|
||||
if (restoredMessage.content.length === 0) {
|
||||
restoredMessage.content.push({
|
||||
type: 'text',
|
||||
text: '[图片]'
|
||||
})
|
||||
} else if (needImageText) {
|
||||
// 查找第一个文本元素
|
||||
const textIndex = restoredMessage.content.findIndex(item => item.type === 'text')
|
||||
if (textIndex !== -1) {
|
||||
restoredMessage.content[textIndex].text = `[图片] ${restoredMessage.content[textIndex].text}`
|
||||
} else {
|
||||
// 如果没有文本元素,添加一个
|
||||
restoredMessage.content.unshift({
|
||||
type: 'text',
|
||||
text: '[图片]'
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return restoredMessage
|
||||
}
|
||||
|
||||
/**
|
||||
* 将消息对象转换为数据库记录
|
||||
* @param {import('chaite').HistoryMessage} message
|
||||
* @param {string} conversationId
|
||||
* @returns {Object} 数据库记录
|
||||
*/
|
||||
_messageToRecord (message, conversationId) {
|
||||
// 处理图片,将base64图片保存到本地文件
|
||||
const processedMessage = this._processMessageImages(message)
|
||||
|
||||
// 将 content 和 toolCalls 等转为 JSON
|
||||
const { id, parentId, role } = processedMessage
|
||||
const messageData = JSON.stringify(processedMessage)
|
||||
|
||||
return {
|
||||
id: id || '',
|
||||
parentId: parentId || null,
|
||||
conversationId: conversationId || '',
|
||||
role: role || '',
|
||||
messageData,
|
||||
createdAt: new Date().toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据库记录转换为消息对象
|
||||
* @param {Object} record 数据库记录
|
||||
* @returns {import('chaite').HistoryMessage} 消息对象
|
||||
*/
|
||||
_recordToMessage (record) {
|
||||
if (!record) return null
|
||||
|
||||
try {
|
||||
// 解析存储的消息数据
|
||||
const message = JSON.parse(record.messageData)
|
||||
|
||||
// 恢复图片引用为base64
|
||||
return this._restoreMessageImages(message)
|
||||
} catch (e) {
|
||||
// 解析失败,尝试构造最小结构
|
||||
return {
|
||||
id: record.id,
|
||||
parentId: record.parentId,
|
||||
role: record.role,
|
||||
conversationId: record.conversationId,
|
||||
content: []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存历史消息
|
||||
* @param {import('chaite').HistoryMessage} message 消息对象
|
||||
* @param {string} conversationId 会话ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async saveHistory (message, conversationId) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
const record = this._messageToRecord(message, conversationId)
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 检查消息是否已存在
|
||||
if (message.id) {
|
||||
this.db.get(`SELECT id FROM ${this.tableName} WHERE id = ?`, [message.id], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
if (row) {
|
||||
// 消息已存在,更新
|
||||
const fields = Object.keys(record)
|
||||
const updates = fields.map(field => `${field} = ?`).join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
|
||||
this.db.run(`UPDATE ${this.tableName} SET ${updates} WHERE id = ?`, [...values, message.id], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
} else {
|
||||
// 消息不存在,插入
|
||||
this._insertMessage(record, resolve, reject)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// 没有ID,直接插入
|
||||
this._insertMessage(record, resolve, reject)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 内部方法:插入消息记录
|
||||
* @private
|
||||
*/
|
||||
_insertMessage (record, resolve, reject) {
|
||||
const fields = Object.keys(record)
|
||||
const placeholders = fields.map(() => '?').join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(', ')}) VALUES (${placeholders})`,
|
||||
values,
|
||||
function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取历史消息
|
||||
* @param {string} messageId 消息ID
|
||||
* @param {string} conversationId 会话ID
|
||||
* @returns {Promise<import('chaite').HistoryMessage[]>}
|
||||
*/
|
||||
async getHistory (messageId, conversationId) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
if (messageId) {
|
||||
return this._getMessageChain(messageId)
|
||||
} else if (conversationId) {
|
||||
return this._getConversationMessages(conversationId)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取消息链(从指定消息追溯到根消息)
|
||||
* @private
|
||||
*/
|
||||
async _getMessageChain (messageId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const messages = []
|
||||
const getMessageById = (id) => {
|
||||
if (!id) {
|
||||
resolve(messages)
|
||||
return
|
||||
}
|
||||
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [id], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
if (!row) {
|
||||
resolve(messages)
|
||||
return
|
||||
}
|
||||
|
||||
const message = this._recordToMessage(row)
|
||||
messages.unshift(message) // 将消息添加到数组开头
|
||||
|
||||
getMessageById(row.parentId) // 递归获取父消息
|
||||
})
|
||||
}
|
||||
|
||||
getMessageById(messageId)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取会话中的所有消息
|
||||
* @private
|
||||
*/
|
||||
async _getConversationMessages (conversationId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName} WHERE conversationId = ? ORDER BY createdAt`, [conversationId], (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const messages = rows.map(row => this._recordToMessage(row)).filter(Boolean)
|
||||
resolve(messages)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除会话
|
||||
* @param {string} conversationId 会话ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async deleteConversation (conversationId) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE conversationId = ?`, [conversationId], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单条历史消息
|
||||
* @param {string} messageId 消息ID
|
||||
* @param {string} conversationId 会话ID
|
||||
* @returns {Promise<import('chaite').HistoryMessage | null>}
|
||||
*/
|
||||
async getOneHistory (messageId, conversationId) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const conditions = []
|
||||
const params = []
|
||||
|
||||
if (messageId) {
|
||||
conditions.push('id = ?')
|
||||
params.push(messageId)
|
||||
}
|
||||
|
||||
if (conversationId) {
|
||||
conditions.push('conversationId = ?')
|
||||
params.push(conversationId)
|
||||
}
|
||||
|
||||
if (conditions.length === 0) {
|
||||
return resolve(null)
|
||||
}
|
||||
|
||||
const whereClause = conditions.join(' AND ')
|
||||
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE ${whereClause} LIMIT 1`, params, (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
resolve(this._recordToMessage(row))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理未引用的图片文件
|
||||
* @returns {Promise<{deleted: number, total: number}>}
|
||||
*/
|
||||
async cleanupUnusedImages () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 获取所有消息数据
|
||||
this.db.all(`SELECT messageData FROM ${this.tableName}`, async (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
try {
|
||||
// 从数据库中提取所有图片引用
|
||||
const usedImageRefs = new Set()
|
||||
rows.forEach(row => {
|
||||
try {
|
||||
const message = JSON.parse(row.messageData)
|
||||
if (message.content && Array.isArray(message.content)) {
|
||||
message.content.forEach(item => {
|
||||
if (item.type === 'image' && typeof item.image === 'string') {
|
||||
const match = item.image.match(/^\$image:([a-f0-9]+):(\.[a-z]+)$/)
|
||||
if (match) {
|
||||
usedImageRefs.add(`${match[1]}${match[2]}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略解析错误
|
||||
}
|
||||
})
|
||||
|
||||
// 获取图片目录中的所有文件
|
||||
const files = fs.readdirSync(this.imagesDir)
|
||||
|
||||
// 删除未引用的图片
|
||||
let deletedCount = 0
|
||||
for (const file of files) {
|
||||
if (!usedImageRefs.has(file)) {
|
||||
fs.unlinkSync(path.join(this.imagesDir, file))
|
||||
deletedCount++
|
||||
}
|
||||
}
|
||||
|
||||
resolve({
|
||||
deleted: deletedCount,
|
||||
total: files.length
|
||||
})
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
192
models/chaite/storage/sqlite/migrate.js
Normal file
192
models/chaite/storage/sqlite/migrate.js
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import path from 'path'
|
||||
import { dataDir } from '../../../../utils/common.js'
|
||||
import { SQLiteChannelStorage } from './channel_storage.js'
|
||||
import { LowDBChannelStorage } from '../lowdb/channel_storage.js'
|
||||
import { SQLiteChatPresetStorage } from './chat_preset_storage.js'
|
||||
import { LowDBChatPresetsStorage } from '../lowdb/chat_preset_storage.js'
|
||||
import { SQLiteToolsStorage } from './tools_storage.js'
|
||||
import { LowDBToolsStorage } from '../lowdb/tools_storage.js'
|
||||
import { SQLiteProcessorsStorage } from './processors_storage.js'
|
||||
import { LowDBProcessorsStorage } from '../lowdb/processors_storage.js'
|
||||
import { SQLiteUserStateStorage } from './user_state_storage.js'
|
||||
import { LowDBUserStateStorage } from '../lowdb/user_state_storage.js'
|
||||
import fs from 'fs'
|
||||
|
||||
export async function checkMigrate () {
|
||||
logger.debug('检查是否需要从 LowDB 迁移数据到 SQLite...')
|
||||
|
||||
try {
|
||||
// 导入所需的模块
|
||||
const { default: ChatGPTStorage } = await import('../lowdb/storage.js')
|
||||
await ChatGPTStorage.init()
|
||||
const { ChatGPTHistoryStorage } = await import('../lowdb/storage.js')
|
||||
await ChatGPTHistoryStorage.init()
|
||||
|
||||
const dbPath = path.join(dataDir, 'data.db')
|
||||
|
||||
// 删除所有id为空的行
|
||||
logger.debug('开始修复id为空的数据行...')
|
||||
const collectionsToClean = ['channel', 'chat_presets', 'tools', 'processors']
|
||||
for (const collectionName of collectionsToClean) {
|
||||
try {
|
||||
const collection = ChatGPTStorage.collection(collectionName)
|
||||
const allItems = await collection.findAll()
|
||||
const invalidItems = allItems.filter(item => !item.id)
|
||||
|
||||
if (invalidItems.length > 0) {
|
||||
logger.info(`在${collectionName}中发现${invalidItems.length}条id为空的数据,正在修复...`)
|
||||
|
||||
for (const item of invalidItems) {
|
||||
// 生成一个新的唯一ID
|
||||
const newId = `generated_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
||||
// 更新时间戳
|
||||
const now = new Date().toISOString()
|
||||
|
||||
// 更新项目
|
||||
item.id = newId
|
||||
item.createdAt = now
|
||||
item.updatedAt = now
|
||||
|
||||
// 保存更新后的项目
|
||||
await collection.set(newId, item)
|
||||
|
||||
// 移除旧的无ID项
|
||||
await collection.remove(item)
|
||||
}
|
||||
|
||||
logger.info(`已成功修复${collectionName}中的${invalidItems.length}条无效数据`)
|
||||
} else {
|
||||
logger.debug(`${collectionName}中没有发现id为空的数据`)
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`修复${collectionName}中id为空的数据时出错:`, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 定义要检查的存储对
|
||||
const storagePairs = [
|
||||
{
|
||||
name: '渠道',
|
||||
lowdbStorageClass: LowDBChannelStorage,
|
||||
sqliteStorageClass: SQLiteChannelStorage,
|
||||
collection: 'channel'
|
||||
},
|
||||
{
|
||||
name: '预设',
|
||||
lowdbStorageClass: LowDBChatPresetsStorage,
|
||||
sqliteStorageClass: SQLiteChatPresetStorage,
|
||||
collection: 'chat_presets'
|
||||
},
|
||||
{
|
||||
name: '工具',
|
||||
lowdbStorageClass: LowDBToolsStorage,
|
||||
sqliteStorageClass: SQLiteToolsStorage,
|
||||
collection: 'tools'
|
||||
},
|
||||
{
|
||||
name: '处理器',
|
||||
lowdbStorageClass: LowDBProcessorsStorage,
|
||||
sqliteStorageClass: SQLiteProcessorsStorage,
|
||||
collection: 'processors'
|
||||
},
|
||||
{
|
||||
name: '用户状态',
|
||||
lowdbStorageClass: LowDBUserStateStorage,
|
||||
sqliteStorageClass: SQLiteUserStateStorage,
|
||||
collection: 'userState',
|
||||
isSpecial: true
|
||||
}
|
||||
]
|
||||
|
||||
// 检查是否有任何数据需要迁移
|
||||
const needMigrate = await Promise.all(storagePairs.map(async pair => {
|
||||
if (pair.isSpecial) {
|
||||
// 用户状态特殊处理
|
||||
const collection = ChatGPTStorage.collection(pair.collection)
|
||||
const items = await collection.findAll()
|
||||
return items.length > 0
|
||||
} else {
|
||||
// 标准集合处理
|
||||
const collection = ChatGPTStorage.collection(pair.collection)
|
||||
const items = await collection.findAll()
|
||||
return items.length > 0
|
||||
}
|
||||
})).then(results => results.some(result => result))
|
||||
|
||||
if (!needMigrate) {
|
||||
logger.debug('LowDB 存储为空,无需迁移')
|
||||
return
|
||||
}
|
||||
|
||||
// 检查 SQLite 中是否已有数据
|
||||
const testStorage = new SQLiteChannelStorage(dbPath)
|
||||
await testStorage.initialize()
|
||||
const channels = await testStorage.listItems()
|
||||
|
||||
if (channels.length > 0) {
|
||||
logger.debug('SQLite 存储已有数据,跳过迁移')
|
||||
await testStorage.close()
|
||||
return
|
||||
}
|
||||
await testStorage.close()
|
||||
|
||||
logger.info('开始从 LowDB 迁移数据到 SQLite...')
|
||||
|
||||
// 迁移每种数据
|
||||
for (const pair of storagePairs) {
|
||||
const collection = ChatGPTStorage.collection(pair.collection)
|
||||
const items = await collection.findAll()
|
||||
|
||||
if (items.length > 0) {
|
||||
logger.info(`迁移${pair.name}数据...`)
|
||||
// eslint-disable-next-line new-cap
|
||||
const sqliteStorage = new pair.sqliteStorageClass(dbPath)
|
||||
await sqliteStorage.initialize()
|
||||
|
||||
for (const item of items) {
|
||||
await sqliteStorage.setItem(item.id, item)
|
||||
}
|
||||
|
||||
logger.info(`迁移了 ${items.length} 个${pair.name}`)
|
||||
await sqliteStorage.close()
|
||||
}
|
||||
}
|
||||
|
||||
// 迁移完成后,备份并清空 LowDB 数据
|
||||
const backupDir = path.join(dataDir, 'backup')
|
||||
if (!fs.existsSync(backupDir)) {
|
||||
fs.mkdirSync(backupDir, { recursive: true })
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
|
||||
|
||||
// 备份并清空<E6B885><E7A9BA>数据
|
||||
if (fs.existsSync(ChatGPTStorage.filePath)) {
|
||||
fs.copyFileSync(
|
||||
ChatGPTStorage.filePath,
|
||||
path.join(backupDir, `storage-backup-${timestamp}.json`)
|
||||
)
|
||||
// 清空数据但保留文件结构
|
||||
for (const pair of storagePairs) {
|
||||
if (!pair.collection) continue
|
||||
await ChatGPTStorage.collection(pair.collection).deleteAll()
|
||||
}
|
||||
}
|
||||
|
||||
// 备份并清空历史数据
|
||||
if (fs.existsSync(ChatGPTHistoryStorage.filePath)) {
|
||||
fs.copyFileSync(
|
||||
ChatGPTHistoryStorage.filePath,
|
||||
path.join(backupDir, `history-backup-${timestamp}.json`)
|
||||
)
|
||||
// 清空历史数据
|
||||
for (const collectionName of ChatGPTHistoryStorage.listCollections()) {
|
||||
await ChatGPTHistoryStorage.collection(collectionName).deleteAll()
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug(`迁移完成,原数据已备份至 ${backupDir} 目录`)
|
||||
} catch (error) {
|
||||
logger.error('数据迁移过程中发生错误:', error)
|
||||
}
|
||||
}
|
||||
440
models/chaite/storage/sqlite/processors_storage.js
Normal file
440
models/chaite/storage/sqlite/processors_storage.js
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
import { ChaiteStorage, ProcessorDTO } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { generateId } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ProcessorDTO>}
|
||||
*/
|
||||
export class SQLiteProcessorsStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'SQLiteProcessorsStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'processors'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保<E7A1AE><E4BF9D>录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建处理器表,将主要属性分列存储
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
type TEXT NOT NULL,
|
||||
code TEXT,
|
||||
cloudId INTEGER,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT,
|
||||
md5 TEXT,
|
||||
embedded INTEGER DEFAULT 0,
|
||||
uploader TEXT,
|
||||
extraData TEXT
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建索引
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_type ON ${this.tableName} (type)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
this.initialized = true
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保数据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 ProcessorDTO 对象转换为数据库记录
|
||||
* @param {import('chaite').ProcessorDTO} processor
|
||||
* @returns {Object} 数据库记录
|
||||
*/
|
||||
_processorToRecord (processor) {
|
||||
// 提取主要字段
|
||||
const {
|
||||
id, name, description, type, code, cloudId,
|
||||
createdAt, updatedAt, md5, embedded, uploader, ...rest
|
||||
} = processor
|
||||
|
||||
return {
|
||||
id: id || '',
|
||||
name: name || '',
|
||||
description: description || '',
|
||||
type: type || '', // 'pre' 或 'post'
|
||||
code: code || '',
|
||||
cloudId: cloudId || null,
|
||||
createdAt: createdAt || '',
|
||||
updatedAt: updatedAt || '',
|
||||
md5: md5 || '',
|
||||
embedded: embedded ? 1 : 0,
|
||||
uploader: uploader ? JSON.stringify(uploader) : null,
|
||||
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据库记录转换为 ProcessorDTO 对象
|
||||
* @param {Object} record 数据库记录
|
||||
* @returns {import('chaite').ProcessorDTO} ProcessorDTO 对象
|
||||
*/
|
||||
_recordToProcessor (record) {
|
||||
if (!record) return null
|
||||
|
||||
// 解析 JSON 字段
|
||||
let uploader = null
|
||||
try {
|
||||
if (record.uploader) {
|
||||
uploader = JSON.parse(record.uploader)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用 null
|
||||
}
|
||||
|
||||
let extraData = {}
|
||||
try {
|
||||
if (record.extraData) {
|
||||
extraData = JSON.parse(record.extraData)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
// 构造 ProcessorDTO 对象
|
||||
const processorData = {
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
description: record.description,
|
||||
type: record.type, // 'pre' 或 'post'
|
||||
code: record.code,
|
||||
cloudId: record.cloudId,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
md5: record.md5,
|
||||
embedded: Boolean(record.embedded),
|
||||
uploader,
|
||||
...extraData
|
||||
}
|
||||
|
||||
return new ProcessorDTO(processorData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个处理器
|
||||
* @param {string} key 处理器ID
|
||||
* @returns {Promise<import('chaite').ProcessorDTO>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const processor = this._recordToProcessor(row)
|
||||
resolve(processor)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存处理器
|
||||
* @param {string} id 处理器ID
|
||||
* @param {import('chaite').ProcessorDTO} processor 处理器对象
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, processor) {
|
||||
await this.ensureInitialized()
|
||||
if (!id) {
|
||||
id = generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!processor.createdAt) {
|
||||
processor.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
processor.updatedAt = new Date().toISOString()
|
||||
// 转换为数据库记录
|
||||
const record = this._processorToRecord(processor)
|
||||
record.id = id // 确保ID是指定的ID
|
||||
|
||||
// 构建插入或更新SQL
|
||||
const fields = Object.keys(record)
|
||||
const placeholders = fields.map(() => '?').join(', ')
|
||||
const updates = fields.map(field => `${field} = ?`).join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(', ')})
|
||||
VALUES (${placeholders})
|
||||
ON CONFLICT(id) DO UPDATE SET ${updates}`,
|
||||
[...values, ...duplicateValues],
|
||||
function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除处<EFBFBD><EFBFBD><EFBFBD>器
|
||||
* @param {string} key 处理器ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有处理器
|
||||
* @returns {Promise<import('chaite').ProcessorDTO[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const processors = rows.map(row => this._recordToProcessor(row)).filter(Boolean)
|
||||
resolve(processors)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选处理器
|
||||
* @param {Record<string, unknown>} filter 筛选条件
|
||||
* @returns {Promise<import('chaite').ProcessorDTO[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有筛选条件,返回所有
|
||||
if (!filter || Object.keys(filter).length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL字段直接过滤
|
||||
const directFields = ['id', 'name', 'description', 'type', 'cloudId']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraFilters = {}
|
||||
let hasExtraFilters = false
|
||||
|
||||
// 区分数据库字段和额外字段
|
||||
for (const key in filter) {
|
||||
const value = filter[key]
|
||||
|
||||
// 如果是直接支持的字段,构建SQL条件
|
||||
if (directFields.includes(key)) {
|
||||
sqlFilters.push(`${key} = ?`)
|
||||
sqlParams.push(value)
|
||||
} else if (key === 'embedded') {
|
||||
// embedded 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('embedded = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else {
|
||||
// 其他字段需要在结果中进一步过滤
|
||||
extraFilters[key] = value
|
||||
hasExtraFilters = true
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let processors = rows.map(row => this._recordToProcessor(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的额外字段
|
||||
if (hasExtraFilters) {
|
||||
processors = processors.filter(processor => {
|
||||
for (const key in extraFilters) {
|
||||
if (processor[key] !== extraFilters[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(processors)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条<EFBFBD><EFBFBD>筛选处理器
|
||||
* @param {Array<{ field: string; values: unknown[]; }>} query
|
||||
* @returns {Promise<import('chaite').ProcessorDTO[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有查询条件,返回所有
|
||||
if (!query || query.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL IN子句来优化查询
|
||||
const directFields = ['id', 'name', 'description', 'type', 'cloudId']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraQueries = []
|
||||
|
||||
// 处理每个查询条件
|
||||
for (const { field, values } of query) {
|
||||
if (values.length === 0) continue
|
||||
|
||||
// 如果是直接支持的字段,使用SQL IN子句
|
||||
if (directFields.includes(field)) {
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
sqlFilters.push(`${field} IN (${placeholders})`)
|
||||
sqlParams.push(...values)
|
||||
} else if (field === 'embedded') {
|
||||
// embedded 字段需要特殊处理
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`embedded IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else {
|
||||
// 其他字段在内存中过滤
|
||||
extraQueries.push({ field, values })
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let processors = rows.map(row => this._recordToProcessor(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的条件
|
||||
if (extraQueries.length > 0) {
|
||||
processors = processors.filter(processor => {
|
||||
for (const { field, values } of extraQueries) {
|
||||
if (!values.includes(processor[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(processors)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空表中所有数据
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
569
models/chaite/storage/sqlite/tool_groups_storage.js
Normal file
569
models/chaite/storage/sqlite/tool_groups_storage.js
Normal file
|
|
@ -0,0 +1,569 @@
|
|||
import { ChaiteStorage } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { generateId } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ToolsGroupDTO>}
|
||||
*/
|
||||
export class SQLiteToolsGroupStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'SQLiteToolsGroupStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'tools_groups'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) return reject(err)
|
||||
|
||||
try {
|
||||
// 首先检查表是否存在
|
||||
const tableExists = await this.checkTableExists()
|
||||
|
||||
if (tableExists) {
|
||||
// 如果表存在,检查并迁移旧结构
|
||||
await this.migrateTableIfNeeded()
|
||||
} else {
|
||||
// 如果表不存在,创建新表
|
||||
await this.createTable()
|
||||
}
|
||||
|
||||
// 确保索引存在
|
||||
await this.ensureIndex()
|
||||
|
||||
this.initialized = true
|
||||
resolve()
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查表是否存在
|
||||
*/
|
||||
async checkTableExists () {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(
|
||||
'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=?',
|
||||
[this.tableName],
|
||||
(err, row) => {
|
||||
if (err) return reject(err)
|
||||
resolve(!!row)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新表
|
||||
*/
|
||||
async createTable () {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
toolIds TEXT NOT NULL,
|
||||
isDefault INTEGER DEFAULT 0,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT
|
||||
)`, (err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保索引存在
|
||||
*/
|
||||
async ensureIndex () {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_groups_name ON ${this.tableName} (name)`, (err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并迁移表结构
|
||||
*/
|
||||
async migrateTableIfNeeded () {
|
||||
// 检查表结构
|
||||
const columns = await this.getTableColumns()
|
||||
|
||||
// 检查是否有旧版本的结构(有tools字段而不是toolIds)
|
||||
const hasOldStructure = columns.includes('tools') && !columns.includes('toolIds')
|
||||
const needsDefaultColumn = !columns.includes('isDefault')
|
||||
|
||||
if (hasOldStructure || needsDefaultColumn) {
|
||||
console.log(`检测到旧表结构,开始迁移 ${this.tableName} 表...`)
|
||||
|
||||
// 备份所有数据
|
||||
const allData = await this.backupData()
|
||||
|
||||
// 重命名旧表
|
||||
await this.renameTable(`${this.tableName}_old`)
|
||||
|
||||
// 创建新表
|
||||
await this.createTable()
|
||||
await this.ensureIndex()
|
||||
|
||||
// 恢复数据到新表
|
||||
if (allData.length > 0) {
|
||||
await this.restoreData(allData, hasOldStructure)
|
||||
}
|
||||
|
||||
// 删除旧表
|
||||
await this.dropTable(`${this.tableName}_old`)
|
||||
|
||||
console.log(`表 ${this.tableName} 迁移完成,共迁移 ${allData.length} 条数据`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取表的所有列名
|
||||
*/
|
||||
async getTableColumns () {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`PRAGMA table_info(${this.tableName})`, (err, rows) => {
|
||||
if (err) return reject(err)
|
||||
|
||||
const columns = rows.map(row => row.name)
|
||||
resolve(columns)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 备份表数据
|
||||
*/
|
||||
async backupData () {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) return reject(err)
|
||||
resolve(rows)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 重命名表
|
||||
*/
|
||||
async renameTable (newName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`ALTER TABLE ${this.tableName} RENAME TO ${newName}`, (err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除表
|
||||
*/
|
||||
async dropTable (tableName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DROP TABLE IF EXISTS ${tableName}`, (err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复数据到新表
|
||||
*/
|
||||
async restoreData (data, hasOldStructure) {
|
||||
const promises = data.map(row => {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 处理数据转换
|
||||
const newRow = { ...row }
|
||||
|
||||
if (hasOldStructure && row.tools) {
|
||||
try {
|
||||
// 从旧的tools结构提取toolIds
|
||||
const tools = JSON.parse(row.tools)
|
||||
newRow.toolIds = JSON.stringify(tools.map(t => t.id || t))
|
||||
delete newRow.tools
|
||||
} catch (e) {
|
||||
console.error(`解析工具组数据错误: ${row.id}`, e)
|
||||
newRow.toolIds = JSON.stringify([])
|
||||
delete newRow.tools
|
||||
}
|
||||
}
|
||||
|
||||
// 添加isDefault字段
|
||||
if (newRow.isDefault === undefined) {
|
||||
newRow.isDefault = 0
|
||||
}
|
||||
|
||||
// 添加时间戳
|
||||
if (!newRow.createdAt) {
|
||||
newRow.createdAt = new Date().toISOString()
|
||||
}
|
||||
if (!newRow.updatedAt) {
|
||||
newRow.updatedAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
const fields = Object.keys(newRow)
|
||||
const placeholders = fields.map(() => '?').join(',')
|
||||
const values = fields.map(field => newRow[field])
|
||||
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(',')}) VALUES (${placeholders})`,
|
||||
values,
|
||||
(err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
return Promise.all(promises)
|
||||
}
|
||||
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取工具组
|
||||
* @param {string} key 工具组ID
|
||||
*/
|
||||
async getItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
|
||||
if (err) return reject(err)
|
||||
|
||||
if (!row) return resolve(null)
|
||||
|
||||
try {
|
||||
const toolsGroup = {
|
||||
...row,
|
||||
toolIds: JSON.parse(row.toolIds),
|
||||
isDefault: Boolean(row.isDefault)
|
||||
}
|
||||
resolve(toolsGroup)
|
||||
} catch (e) {
|
||||
console.error(`解析工具组数据错误: ${key}`, e)
|
||||
resolve({
|
||||
...row,
|
||||
toolIds: [],
|
||||
isDefault: Boolean(row.isDefault)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存工具组
|
||||
* @param {string} id 工具组ID
|
||||
* @param {Object} data 工具组数据
|
||||
*/
|
||||
async setItem (id, data) {
|
||||
await this.ensureInitialized()
|
||||
if (!id) {
|
||||
id = generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!data.createdAt) {
|
||||
data.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
data.updatedAt = new Date().toISOString()
|
||||
// 提取工具组数据
|
||||
const { name, description, toolIds, isDefault } = data
|
||||
const updatedAt = new Date().toISOString()
|
||||
|
||||
// 将工具ID列表序列化为JSON字符串
|
||||
const toolIdsJson = JSON.stringify(toolIds || [])
|
||||
const isDefaultValue = isDefault ? 1 : 0
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 检查工具组是否已存在
|
||||
this.db.get(`SELECT id FROM ${this.tableName} WHERE id = ?`, [id], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
if (row) {
|
||||
// 更新现有工具组
|
||||
this.db.run(
|
||||
`UPDATE ${this.tableName} SET name = ?, description = ?, toolIds = ?, isDefault = ?, updatedAt = ? WHERE id = ?`,
|
||||
[name, description, toolIdsJson, isDefaultValue, updatedAt, id],
|
||||
(err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// 插入新工具组
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (id, name, description, toolIds, isDefault, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
[id, name, description, toolIdsJson, isDefaultValue, data.createdAt, updatedAt],
|
||||
(err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除工具组
|
||||
* @param {string} key 工具组ID
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有工具组
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const toolsGroups = rows.map(row => {
|
||||
try {
|
||||
return {
|
||||
...row,
|
||||
toolIds: JSON.parse(row.toolIds),
|
||||
isDefault: Boolean(row.isDefault)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`解析工具组数据错误: ${row.id}`, e)
|
||||
return {
|
||||
...row,
|
||||
toolIds: [],
|
||||
isDefault: Boolean(row.isDefault)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
resolve(toolsGroups)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选工具组
|
||||
* @param {Record<string, unknown>} filter 筛选条件
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
if (!filter || Object.keys(filter).length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
const directFields = ['id', 'name', 'description']
|
||||
const conditions = []
|
||||
const params = []
|
||||
|
||||
for (const key in filter) {
|
||||
if (directFields.includes(key)) {
|
||||
conditions.push(`${key} = ?`)
|
||||
params.push(filter[key])
|
||||
} else if (key === 'isDefault') {
|
||||
conditions.push('isDefault = ?')
|
||||
params.push(filter[key] ? 1 : 0)
|
||||
}
|
||||
}
|
||||
|
||||
const sql = conditions.length > 0
|
||||
? `SELECT * FROM ${this.tableName} WHERE ${conditions.join(' AND ')}`
|
||||
: `SELECT * FROM ${this.tableName}`
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, params, (err, rows) => {
|
||||
if (err) return reject(err)
|
||||
|
||||
const toolsGroups = rows.map(row => {
|
||||
try {
|
||||
const group = {
|
||||
...row,
|
||||
toolIds: JSON.parse(row.toolIds || '[]'),
|
||||
isDefault: Boolean(row.isDefault)
|
||||
}
|
||||
|
||||
// 过滤其他字段
|
||||
for (const key in filter) {
|
||||
if (!directFields.includes(key) &&
|
||||
key !== 'isDefault' &&
|
||||
JSON.stringify(group[key]) !== JSON.stringify(filter[key])) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return group
|
||||
} catch (e) {
|
||||
console.error(`解析工具组数据错误: ${row.id}`, e)
|
||||
return null
|
||||
}
|
||||
}).filter(Boolean)
|
||||
|
||||
resolve(toolsGroups)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条件筛选工具组
|
||||
* @param {Array<{field: string, values: unknown[]}>} query IN查询条件
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
if (!query || query.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
const directFields = ['id', 'name', 'description']
|
||||
const conditions = []
|
||||
const params = []
|
||||
const memoryQueries = []
|
||||
|
||||
for (const item of query) {
|
||||
if (directFields.includes(item.field) && Array.isArray(item.values) && item.values.length > 0) {
|
||||
const placeholders = item.values.map(() => '?').join(',')
|
||||
conditions.push(`${item.field} IN (${placeholders})`)
|
||||
params.push(...item.values)
|
||||
} else if (item.field === 'isDefault' && Array.isArray(item.values) && item.values.length > 0) {
|
||||
const boolValues = item.values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(',')
|
||||
conditions.push(`isDefault IN (${placeholders})`)
|
||||
params.push(...boolValues)
|
||||
} else if (item.values.length > 0) {
|
||||
memoryQueries.push(item)
|
||||
}
|
||||
}
|
||||
|
||||
const sql = conditions.length > 0
|
||||
? `SELECT * FROM ${this.tableName} WHERE ${conditions.join(' AND ')}`
|
||||
: `SELECT * FROM ${this.tableName}`
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, params, (err, rows) => {
|
||||
if (err) return reject(err)
|
||||
|
||||
let toolsGroups = rows.map(row => {
|
||||
try {
|
||||
return {
|
||||
...row,
|
||||
toolIds: JSON.parse(row.toolIds || '[]'),
|
||||
isDefault: Boolean(row.isDefault)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`解析工具组数据错误: ${row.id}`, e)
|
||||
return null
|
||||
}
|
||||
}).filter(Boolean)
|
||||
|
||||
// 内存中过滤其它字段
|
||||
if (memoryQueries.length > 0) {
|
||||
toolsGroups = toolsGroups.filter(group => {
|
||||
for (const { field, values } of memoryQueries) {
|
||||
// 对于toolIds字段做特殊处理
|
||||
if (field === 'toolIds') {
|
||||
const hasMatch = values.some(toolId => group.toolIds.includes(toolId))
|
||||
if (!hasMatch) return false
|
||||
} else if (!values.includes(group[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(toolsGroups)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有工具组
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) return reject(err)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
467
models/chaite/storage/sqlite/tools_storage.js
Normal file
467
models/chaite/storage/sqlite/tools_storage.js
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
import { ChaiteStorage, ToolDTO } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { generateId } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').ToolDTO>}
|
||||
*/
|
||||
export class SQLiteToolsStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'SQLiteToolsStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'tools'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建工具表,将主要属性分列存储
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
modelType TEXT,
|
||||
code TEXT,
|
||||
cloudId INTEGER,
|
||||
embedded INTEGER,
|
||||
uploader TEXT,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT,
|
||||
md5 TEXT,
|
||||
status TEXT,
|
||||
permission TEXT,
|
||||
extraData TEXT -- 存储其他额外数据的JSON
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
// 创建索引以提高查询性能
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_name ON ${this.tableName} (name)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_status ON ${this.tableName} (status)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_tools_permission ON ${this.tableName} (permission)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = true
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保数据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 ToolDTO 对象转换为数据库记录
|
||||
* @param {import('chaite').ToolDTO} tool
|
||||
* @returns {Object} 数据库记录
|
||||
*/
|
||||
_toolToRecord (tool) {
|
||||
// 提取主要字段,剩余的放入extraData
|
||||
const {
|
||||
id, name, description, modelType, code, cloudId,
|
||||
embedded, uploader, createdAt, updatedAt, md5,
|
||||
status, permission, ...rest
|
||||
} = tool
|
||||
|
||||
// 序列化上传者对象
|
||||
const uploaderStr = uploader ? JSON.stringify(uploader) : null
|
||||
|
||||
return {
|
||||
id: id || '',
|
||||
name: name || '',
|
||||
description: description || '',
|
||||
modelType: modelType || '',
|
||||
code: code || null,
|
||||
cloudId: cloudId || null,
|
||||
embedded: embedded ? 1 : 0,
|
||||
uploader: uploaderStr,
|
||||
createdAt: createdAt || '',
|
||||
updatedAt: updatedAt || '',
|
||||
md5: md5 || '',
|
||||
status: status || 'enabled',
|
||||
permission: permission || 'public',
|
||||
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据库记录转换为 ToolDTO 对象
|
||||
* @param {Object} record 数据库记录
|
||||
* @returns {import('chaite').ToolDTO} ToolDTO对象
|
||||
*/
|
||||
_recordToTool (record) {
|
||||
// 若记录不存在则返回null
|
||||
if (!record) return null
|
||||
|
||||
// 解析上传者
|
||||
let uploader = null
|
||||
try {
|
||||
if (record.uploader) {
|
||||
uploader = JSON.parse(record.uploader)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用null
|
||||
}
|
||||
|
||||
// 解析额外数据
|
||||
let extraData = {}
|
||||
try {
|
||||
if (record.extraData) {
|
||||
extraData = JSON.parse(record.extraData)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
// 构造基本对象
|
||||
const toolData = {
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
description: record.description,
|
||||
modelType: record.modelType,
|
||||
code: record.code,
|
||||
cloudId: record.cloudId,
|
||||
embedded: Boolean(record.embedded),
|
||||
uploader,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
md5: record.md5,
|
||||
status: record.status,
|
||||
permission: record.permission,
|
||||
...extraData
|
||||
}
|
||||
|
||||
return new ToolDTO(toolData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个工具
|
||||
* @param {string} key 工具ID
|
||||
* @returns {Promise<import('chaite').ToolDTO>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const tool = this._recordToTool(row)
|
||||
resolve(tool)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存工具
|
||||
* @param {string} id 工具ID
|
||||
* @param {import('chaite').ToolDTO} tool 工具对象
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, tool) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
if (!id) {
|
||||
id = generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!tool.createdAt) {
|
||||
tool.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
tool.updatedAt = new Date().toISOString()
|
||||
|
||||
// 转换为数据库记录
|
||||
const record = this._toolToRecord(tool)
|
||||
record.id = id // 确保ID是指定的ID
|
||||
|
||||
// 构建插入或更新SQL
|
||||
const fields = Object.keys(record)
|
||||
const placeholders = fields.map(() => '?').join(', ')
|
||||
const updates = fields.map(field => `${field} = ?`).join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(', ')})
|
||||
VALUES (${placeholders})
|
||||
ON CONFLICT(id) DO UPDATE SET ${updates}`,
|
||||
[...values, ...duplicateValues],
|
||||
function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除工具
|
||||
* @param {string} key 工具ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有工具
|
||||
* @returns {Promise<import('chaite').ToolDTO[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const tools = rows.map(row => this._recordToTool(row)).filter(Boolean)
|
||||
resolve(tools)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选工具(直接使用SQL查询,避免全表扫描)
|
||||
* @param {Record<string, unknown>} filter 筛选条件
|
||||
* @returns {Promise<import('chaite').ToolDTO[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有筛选条件,返回所有
|
||||
if (!filter || Object.keys(filter).length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL字段直接过滤
|
||||
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraFilters = {}
|
||||
let hasExtraFilters = false
|
||||
|
||||
// 区分数据库字段和额外字段
|
||||
for (const key in filter) {
|
||||
const value = filter[key]
|
||||
|
||||
// 如果是直接支持的字段,构建SQL条件
|
||||
if (directFields.includes(key)) {
|
||||
sqlFilters.push(`${key} = ?`)
|
||||
sqlParams.push(value)
|
||||
} else if (key === 'embedded') {
|
||||
// embedded 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('embedded = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else {
|
||||
// 其他字段需要在结果中进一步过滤
|
||||
extraFilters[key] = value
|
||||
hasExtraFilters = true
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let tools = rows.map(row => this._recordToTool(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的额外字段
|
||||
if (hasExtraFilters) {
|
||||
tools = tools.filter(tool => {
|
||||
for (const key in extraFilters) {
|
||||
if (tool[key] !== extraFilters[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(tools)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条件筛选工具
|
||||
* @param {Array<{ field: string; values: unknown[]; }>} query
|
||||
* @returns {Promise<import('chaite').ToolDTO[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有查询条件,返回所有
|
||||
if (!query || query.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL IN子句来优化查询
|
||||
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraQueries = []
|
||||
|
||||
// 处理每个查询条件
|
||||
for (const { field, values } of query) {
|
||||
if (values.length === 0) continue
|
||||
|
||||
// 如果是直接支持的字段,使用SQL IN子句
|
||||
if (directFields.includes(field)) {
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
sqlFilters.push(`${field} IN (${placeholders})`)
|
||||
sqlParams.push(...values)
|
||||
// embedded 字段需要特殊处理
|
||||
} else if (field === 'embedded') {
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`embedded IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else {
|
||||
// 其他字段在内存中过滤
|
||||
extraQueries.push({ field, values })
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let tools = rows.map(row => this._recordToTool(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的条件
|
||||
if (extraQueries.length > 0) {
|
||||
tools = tools.filter(tool => {
|
||||
for (const { field, values } of extraQueries) {
|
||||
if (!values.includes(tool[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(tools)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空表中所有数据
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
474
models/chaite/storage/sqlite/trigger_storage.js
Normal file
474
models/chaite/storage/sqlite/trigger_storage.js
Normal file
|
|
@ -0,0 +1,474 @@
|
|||
import { ChaiteStorage, TriggerDTO } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { generateId } from '../../../../utils/common.js'
|
||||
|
||||
/**
|
||||
* @extends {ChaiteStorage<import('chaite').TriggerDTO>}
|
||||
*/
|
||||
export class SQLiteTriggerStorage extends ChaiteStorage {
|
||||
getName () {
|
||||
return 'SQLiteTriggerStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'triggers'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库连接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建触发器表,将主要属性分列存储
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
modelType TEXT,
|
||||
code TEXT,
|
||||
cloudId INTEGER,
|
||||
embedded INTEGER,
|
||||
uploader TEXT,
|
||||
createdAt TEXT,
|
||||
updatedAt TEXT,
|
||||
md5 TEXT,
|
||||
status TEXT,
|
||||
permission TEXT,
|
||||
isOneTime INTEGER,
|
||||
extraData TEXT -- 存储其他额外数据的JSON
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
// 创建索引以提高查询性能
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_triggers_name ON ${this.tableName} (name)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_triggers_status ON ${this.tableName} (status)`, (err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = true
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保数据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 TriggerDTO 对象转换为数据库记录
|
||||
* @param {import('chaite').TriggerDTO} trigger
|
||||
* @returns {Object} 数据库记录
|
||||
*/
|
||||
_triggerToRecord (trigger) {
|
||||
// 提取主要字段,剩余的放入extraData
|
||||
const {
|
||||
id, name, description, modelType, code, cloudId,
|
||||
embedded, uploader, createdAt, updatedAt, md5,
|
||||
status, permission, isOneTime, ...rest
|
||||
} = trigger
|
||||
|
||||
// 序列化上传者对象
|
||||
const uploaderStr = uploader ? JSON.stringify(uploader) : null
|
||||
|
||||
return {
|
||||
id: id || '',
|
||||
name: name || '',
|
||||
description: description || '',
|
||||
modelType: modelType || 'executable',
|
||||
code: code || null,
|
||||
cloudId: cloudId || null,
|
||||
embedded: embedded ? 1 : 0,
|
||||
uploader: uploaderStr,
|
||||
createdAt: createdAt || '',
|
||||
updatedAt: updatedAt || '',
|
||||
md5: md5 || '',
|
||||
status: status || 'enabled',
|
||||
permission: permission || 'public',
|
||||
isOneTime: isOneTime ? 1 : 0,
|
||||
extraData: Object.keys(rest).length > 0 ? JSON.stringify(rest) : null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据库记录转换为 TriggerDTO 对象
|
||||
* @param {Object} record 数据库记录
|
||||
* @returns {import('chaite').TriggerDTO} TriggerDTO对象
|
||||
*/
|
||||
_recordToTrigger (record) {
|
||||
// 若记录不存在则返回null
|
||||
if (!record) return null
|
||||
|
||||
// 解析上传者
|
||||
let uploader = null
|
||||
try {
|
||||
if (record.uploader) {
|
||||
uploader = JSON.parse(record.uploader)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用null
|
||||
}
|
||||
|
||||
// 解析额外数据
|
||||
let extraData = {}
|
||||
try {
|
||||
if (record.extraData) {
|
||||
extraData = JSON.parse(record.extraData)
|
||||
}
|
||||
} catch (e) {
|
||||
// 解析错误,使用空对象
|
||||
}
|
||||
|
||||
// 构造基本对象
|
||||
const triggerData = {
|
||||
id: record.id,
|
||||
name: record.name,
|
||||
description: record.description,
|
||||
modelType: record.modelType,
|
||||
code: record.code,
|
||||
cloudId: record.cloudId,
|
||||
embedded: Boolean(record.embedded),
|
||||
uploader,
|
||||
createdAt: record.createdAt,
|
||||
updatedAt: record.updatedAt,
|
||||
md5: record.md5,
|
||||
status: record.status,
|
||||
permission: record.permission,
|
||||
isOneTime: Boolean(record.isOneTime),
|
||||
...extraData
|
||||
}
|
||||
|
||||
return new TriggerDTO(triggerData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单个触发器
|
||||
* @param {string} key 触发器ID
|
||||
* @returns {Promise<import('chaite').TriggerDTO>}
|
||||
*/
|
||||
async getItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE id = ?`, [key], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const trigger = this._recordToTrigger(row)
|
||||
resolve(trigger)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存触发器
|
||||
* @param {string} id 触发器ID
|
||||
* @param {import('chaite').TriggerDTO} trigger 触发器对象
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async setItem (id, trigger) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
if (!id) {
|
||||
id = generateId()
|
||||
}
|
||||
|
||||
// 加上时间戳
|
||||
if (!trigger.createdAt) {
|
||||
trigger.createdAt = new Date().toISOString()
|
||||
}
|
||||
|
||||
trigger.updatedAt = new Date().toISOString()
|
||||
|
||||
// 转换为数据库记录
|
||||
const record = this._triggerToRecord(trigger)
|
||||
record.id = id // 确保ID是指定的ID
|
||||
|
||||
// 构建插入或更新SQL
|
||||
const fields = Object.keys(record)
|
||||
const placeholders = fields.map(() => '?').join(', ')
|
||||
const updates = fields.map(field => `${field} = ?`).join(', ')
|
||||
const values = fields.map(field => record[field])
|
||||
const duplicateValues = [...values] // 用于ON CONFLICT时的更新
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName} (${fields.join(', ')})
|
||||
VALUES (${placeholders})
|
||||
ON CONFLICT(id) DO UPDATE SET ${updates}`,
|
||||
[...values, ...duplicateValues],
|
||||
function (err) {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(id)
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除触发器
|
||||
* @param {string} key 触发器ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (key) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE id = ?`, [key], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有触发器
|
||||
* @returns {Promise<import('chaite').TriggerDTO[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const triggers = rows.map(row => this._recordToTrigger(row)).filter(Boolean)
|
||||
resolve(triggers)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件筛选触发器
|
||||
* @param {Record<string, unknown>} filter 筛选条件
|
||||
* @returns {Promise<import('chaite').TriggerDTO[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有筛选条件,返回所有
|
||||
if (!filter || Object.keys(filter).length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL字段直接过滤
|
||||
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraFilters = {}
|
||||
let hasExtraFilters = false
|
||||
|
||||
// 区分数据库字段和额外字段
|
||||
for (const key in filter) {
|
||||
const value = filter[key]
|
||||
|
||||
// 如果是直接支持的字段,构建SQL条件
|
||||
if (directFields.includes(key)) {
|
||||
sqlFilters.push(`${key} = ?`)
|
||||
sqlParams.push(value)
|
||||
} else if (key === 'embedded') {
|
||||
// embedded 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('embedded = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else if (key === 'isOneTime') {
|
||||
// isOneTime 字段需要特殊处理为 0/1
|
||||
sqlFilters.push('isOneTime = ?')
|
||||
sqlParams.push(value ? 1 : 0)
|
||||
} else {
|
||||
// 其他字段需要在结果中进一步过滤
|
||||
extraFilters[key] = value
|
||||
hasExtraFilters = true
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let triggers = rows.map(row => this._recordToTrigger(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的额外字段
|
||||
if (hasExtraFilters) {
|
||||
triggers = triggers.filter(trigger => {
|
||||
for (const key in extraFilters) {
|
||||
if (trigger[key] !== extraFilters[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(triggers)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN条件筛选触发器
|
||||
* @param {Array<{ field: string; values: unknown[]; }>} query
|
||||
* @returns {Promise<import('chaite').TriggerDTO[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 如果没有查询条<E8AFA2><E69DA1><EFBFBD>,返回所有
|
||||
if (!query || query.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 尝试使用SQL IN子句来优化查询
|
||||
const directFields = ['id', 'name', 'description', 'modelType', 'cloudId', 'status', 'permission']
|
||||
const sqlFilters = []
|
||||
const sqlParams = []
|
||||
const extraQueries = []
|
||||
|
||||
// 处理每个查询条件
|
||||
for (const { field, values } of query) {
|
||||
if (values.length === 0) continue
|
||||
|
||||
// 如果是直接支持的字段,使用SQL IN子句
|
||||
if (directFields.includes(field)) {
|
||||
const placeholders = values.map(() => '?').join(', ')
|
||||
sqlFilters.push(`${field} IN (${placeholders})`)
|
||||
sqlParams.push(...values)
|
||||
} else if (field === 'embedded') {
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`embedded IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else if (field === 'isOneTime') {
|
||||
const boolValues = values.map(v => v ? 1 : 0)
|
||||
const placeholders = boolValues.map(() => '?').join(', ')
|
||||
sqlFilters.push(`isOneTime IN (${placeholders})`)
|
||||
sqlParams.push(...boolValues)
|
||||
} else {
|
||||
// 其他字段在内存中过滤
|
||||
extraQueries.push({ field, values })
|
||||
}
|
||||
}
|
||||
|
||||
// 构建SQL查询
|
||||
let sql = `SELECT * FROM ${this.tableName}`
|
||||
if (sqlFilters.length > 0) {
|
||||
sql += ` WHERE ${sqlFilters.join(' AND ')}`
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(sql, sqlParams, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
let triggers = rows.map(row => this._recordToTrigger(row)).filter(Boolean)
|
||||
|
||||
// 如果有需要在内存中过滤的条件
|
||||
if (extraQueries.length > 0) {
|
||||
triggers = triggers.filter(trigger => {
|
||||
for (const { field, values } of extraQueries) {
|
||||
if (!values.includes(trigger[field])) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
resolve(triggers)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空表中所有数据
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) return Promise.resolve()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export default SQLiteTriggerStorage
|
||||
388
models/chaite/storage/sqlite/user_state_storage.js
Normal file
388
models/chaite/storage/sqlite/user_state_storage.js
Normal file
|
|
@ -0,0 +1,388 @@
|
|||
import { ChaiteStorage } from 'chaite'
|
||||
import sqlite3 from 'sqlite3'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
/**
|
||||
* 基于SQLite的用户状态存储实现
|
||||
* @extends {ChaiteStorage<import('chaite').UserState>}
|
||||
*/
|
||||
export class SQLiteUserStateStorage extends ChaiteStorage {
|
||||
/**
|
||||
* 构造函数
|
||||
* @param {string} dbPath 数据库文件路径
|
||||
*/
|
||||
constructor (dbPath) {
|
||||
super()
|
||||
this.dbPath = dbPath
|
||||
this.db = null
|
||||
this.initialized = false
|
||||
this.tableName = 'user_states'
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化数据库<EFBFBD><EFBFBD>接和表结构
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initialize () {
|
||||
if (this.initialized) return
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 确保目录存在
|
||||
const dir = path.dirname(this.dbPath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
|
||||
this.db = new sqlite3.Database(this.dbPath, async (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建用户状态表
|
||||
this.db.run(`CREATE TABLE IF NOT EXISTS ${this.tableName} (
|
||||
id TEXT PRIMARY KEY,
|
||||
userId TEXT NOT NULL,
|
||||
nickname TEXT,
|
||||
card TEXT,
|
||||
conversations TEXT NOT NULL,
|
||||
settings TEXT NOT NULL,
|
||||
current TEXT NOT NULL,
|
||||
updatedAt INTEGER
|
||||
)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
// 创建索引以加快查询
|
||||
this.db.run(`CREATE INDEX IF NOT EXISTS idx_${this.tableName}_userId ON ${this.tableName} (userId)`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
this.initialized = true
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保数据库已初始化
|
||||
*/
|
||||
async ensureInitialized () {
|
||||
if (!this.initialized) {
|
||||
await this.initialize()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户状态
|
||||
* @param {string} userId 用户ID
|
||||
* @returns {Promise<import('chaite').UserState|null>}
|
||||
*/
|
||||
async getItem (userId) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.get(`SELECT * FROM ${this.tableName} WHERE userId = ?`, [userId], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
if (!row) {
|
||||
return resolve(null)
|
||||
}
|
||||
|
||||
try {
|
||||
const userState = {
|
||||
userId: row.userId,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
conversations: JSON.parse(row.conversations),
|
||||
settings: JSON.parse(row.settings),
|
||||
current: JSON.parse(row.current)
|
||||
}
|
||||
resolve(userState)
|
||||
} catch (e) {
|
||||
console.error(`解析用户状态数据错误: ${userId}`, e)
|
||||
resolve(null)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存用户状态
|
||||
* @param {string} userId 用户ID
|
||||
* @param {import('chaite').UserState} userState 用户状态数据
|
||||
* @returns {Promise<string>} 返回用户ID
|
||||
*/
|
||||
async setItem (userId, userState) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 提取用户状态数据
|
||||
const { nickname, card, conversations, settings, current } = userState
|
||||
const updatedAt = Date.now()
|
||||
|
||||
// 序列化数据
|
||||
const conversationsJson = JSON.stringify(conversations || [])
|
||||
const settingsJson = JSON.stringify(settings || {})
|
||||
const currentJson = JSON.stringify(current || {})
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// 检查用户状态是否已存在
|
||||
this.db.get(`SELECT userId FROM ${this.tableName} WHERE userId = ?`, [userId], (err, row) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
if (row) {
|
||||
// 更新现有用户状态
|
||||
this.db.run(
|
||||
`UPDATE ${this.tableName} SET
|
||||
nickname = ?,
|
||||
card = ?,
|
||||
conversations = ?,
|
||||
settings = ?,
|
||||
current = ?,
|
||||
updatedAt = ?
|
||||
WHERE userId = ?`,
|
||||
[nickname, card, conversationsJson, settingsJson, currentJson, updatedAt, userId],
|
||||
(err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(userId)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
// 插入新用户状态
|
||||
this.db.run(
|
||||
`INSERT INTO ${this.tableName}
|
||||
(id, userId, nickname, card, conversations, settings, current, updatedAt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[crypto.randomUUID(), userId, nickname, card, conversationsJson, settingsJson, currentJson, updatedAt],
|
||||
(err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve(userId)
|
||||
}
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除用户状态
|
||||
* @param {string} userId 用户ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async removeItem (userId) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName} WHERE userId = ?`, [userId], (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有用户状态
|
||||
* @returns {Promise<import('chaite').UserState[]>}
|
||||
*/
|
||||
async listItems () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName}`, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const userStates = rows.map(row => {
|
||||
try {
|
||||
return {
|
||||
userId: row.userId,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
conversations: JSON.parse(row.conversations),
|
||||
settings: JSON.parse(row.settings),
|
||||
current: JSON.parse(row.current)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`解析用户状态数据错误: ${row.userId}`, e)
|
||||
return null
|
||||
}
|
||||
}).filter(Boolean)
|
||||
|
||||
resolve(userStates)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据过滤条件查询用户状态
|
||||
* @param {Record<string, unknown>} filter 过滤条件
|
||||
* @returns {Promise<import('chaite').UserState[]>}
|
||||
*/
|
||||
async listItemsByEqFilter (filter) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
// 只支持userId、nickname、card的过滤
|
||||
const supportedFilters = ['userId', 'nickname', 'card']
|
||||
const conditions = []
|
||||
const params = []
|
||||
|
||||
for (const key of supportedFilters) {
|
||||
if (filter[key] !== undefined) {
|
||||
conditions.push(`${key} = ?`)
|
||||
params.push(filter[key])
|
||||
}
|
||||
}
|
||||
|
||||
if (conditions.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
const whereClause = conditions.join(' AND ')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName} WHERE ${whereClause}`, params, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const userStates = rows.map(row => {
|
||||
try {
|
||||
return {
|
||||
userId: row.userId,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
conversations: JSON.parse(row.conversations),
|
||||
settings: JSON.parse(row.settings),
|
||||
current: JSON.parse(row.current)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`解析用户状态数据错误: ${row.userId}`, e)
|
||||
return null
|
||||
}
|
||||
}).filter(Boolean)
|
||||
|
||||
resolve(userStates)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据IN查询条件查询用户状<EFBFBD><EFBFBD>
|
||||
* @param {Array<{field: string, values: unknown[]}>} query IN查询条件
|
||||
* @returns {Promise<import('chaite').UserState[]>}
|
||||
*/
|
||||
async listItemsByInQuery (query) {
|
||||
await this.ensureInitialized()
|
||||
|
||||
if (!query || !query.length) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
// 只支持userId、nickname、card的过滤
|
||||
const supportedFields = ['userId', 'nickname', 'card']
|
||||
const conditions = []
|
||||
const params = []
|
||||
|
||||
for (const item of query) {
|
||||
if (supportedFields.includes(item.field) && Array.isArray(item.values) && item.values.length > 0) {
|
||||
const placeholders = item.values.map(() => '?').join(',')
|
||||
conditions.push(`${item.field} IN (${placeholders})`)
|
||||
params.push(...item.values)
|
||||
}
|
||||
}
|
||||
|
||||
if (conditions.length === 0) {
|
||||
return this.listItems()
|
||||
}
|
||||
|
||||
const whereClause = conditions.join(' AND ')
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.all(`SELECT * FROM ${this.tableName} WHERE ${whereClause}`, params, (err, rows) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
|
||||
const userStates = rows.map(row => {
|
||||
try {
|
||||
return {
|
||||
userId: row.userId,
|
||||
nickname: row.nickname,
|
||||
card: row.card,
|
||||
conversations: JSON.parse(row.conversations),
|
||||
settings: JSON.parse(row.settings),
|
||||
current: JSON.parse(row.current)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`解析用户状态数据错误: ${row.userId}`, e)
|
||||
return null
|
||||
}
|
||||
}).filter(Boolean)
|
||||
|
||||
resolve(userStates)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有用户状态
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async clear () {
|
||||
await this.ensureInitialized()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.run(`DELETE FROM ${this.tableName}`, (err) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取存储名称
|
||||
* @returns {string}
|
||||
*/
|
||||
getName () {
|
||||
return 'SQLiteUserStateStorage'
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭数据库连接
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async close () {
|
||||
if (!this.db) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.close(err => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
} else {
|
||||
this.initialized = false
|
||||
this.db = null
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
12
models/chaite/user_mode_selector.js
Normal file
12
models/chaite/user_mode_selector.js
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { AbstractUserModeSelector } from 'chaite'
|
||||
|
||||
export class ChatGPTUserModeSelector extends AbstractUserModeSelector {
|
||||
/**
|
||||
* 根据e判断当前要使用的预设,非常灵活。
|
||||
* @param e
|
||||
* @returns {Promise<import('chaite').ChatPreset>}
|
||||
*/
|
||||
getChatPreset (e) {
|
||||
// todo
|
||||
}
|
||||
}
|
||||
84
models/chaite/vector_database.js
Normal file
84
models/chaite/vector_database.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { LocalIndex } from 'vectra'
|
||||
import { md5 } from '../../utils/common.js'
|
||||
|
||||
/**
|
||||
* 基于Vectra实现的简单向量数据库,作为默认实现
|
||||
* @implements { import('chaite').VectorDatabase }
|
||||
*/
|
||||
export class VectraVectorDatabase {
|
||||
constructor (indexFile) {
|
||||
this.index = new LocalIndex(indexFile)
|
||||
}
|
||||
|
||||
async init () {
|
||||
if (!(await this.index.isIndexCreated())) {
|
||||
await this.index.createIndex()
|
||||
}
|
||||
}
|
||||
|
||||
async addVector (vector, text) {
|
||||
const id = md5(text)
|
||||
await this.index.insertItem({
|
||||
vector,
|
||||
id,
|
||||
metadata: { text }
|
||||
})
|
||||
return id
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param vectors
|
||||
* @param texts
|
||||
* @returns {Promise<string[]>}
|
||||
*/
|
||||
async addVectors (vectors, texts) {
|
||||
return await Promise.all(vectors.map((v, i) => this.addVector(v, texts[i])))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param queryVector
|
||||
* @param k
|
||||
* @returns {Promise<Array<{ id: string, score: number, text: string }>>}
|
||||
*/
|
||||
async search (queryVector, k) {
|
||||
const results = await this.index.queryItems(queryVector, k)
|
||||
return results.map(r => ({ id: r.item.id, score: r.score, text: r.item.metadata.text }))
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param id
|
||||
* @returns {Promise<{ vector: number[], text: string } | null>}
|
||||
*/
|
||||
async getVector (id) {
|
||||
const result = await this.index.getItem(id)
|
||||
return {
|
||||
vector: result.vector,
|
||||
text: result.metadata.text
|
||||
}
|
||||
}
|
||||
|
||||
async deleteVector (id) {
|
||||
await this.index.deleteItem(id)
|
||||
return true
|
||||
}
|
||||
|
||||
async updateVector (id, newVector, newText) {
|
||||
await this.index.upsertItem({
|
||||
id,
|
||||
vector: newVector,
|
||||
metadata: { text: newText }
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
async count () {
|
||||
return (await this.index.getIndexStats()).items
|
||||
}
|
||||
|
||||
async clear () {
|
||||
await this.index.deleteIndex()
|
||||
}
|
||||
}
|
||||
89
models/chaite/vectorizer.js
Normal file
89
models/chaite/vectorizer.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import { Chaite, ChaiteContext, GeminiClient, OpenAIClient } from 'chaite'
|
||||
|
||||
async function getIClientByChannel (channel) {
|
||||
await channel.ready()
|
||||
const baseLogger = global.logger || console
|
||||
if (channel.options?.setLogger) {
|
||||
channel.options.setLogger(baseLogger)
|
||||
}
|
||||
const context = new ChaiteContext(baseLogger)
|
||||
context.setChaite(Chaite.getInstance())
|
||||
switch (channel.adapterType) {
|
||||
case 'openai':
|
||||
return new OpenAIClient(channel.options, context)
|
||||
case 'gemini':
|
||||
return new GeminiClient(channel.options, context)
|
||||
case 'claude':
|
||||
throw new Error('claude does not support embedding')
|
||||
default:
|
||||
throw new Error(`Unsupported adapter ${channel.adapterType}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveChannelForModel (model) {
|
||||
const manager = Chaite.getInstance().getChannelsManager()
|
||||
const channels = await manager.getChannelByModel(model)
|
||||
if (channels.length === 0) {
|
||||
throw new Error('No channel found for model: ' + model)
|
||||
}
|
||||
return channels[0]
|
||||
}
|
||||
|
||||
export async function getClientForModel (model) {
|
||||
const channel = await resolveChannelForModel(model)
|
||||
const client = await getIClientByChannel(channel)
|
||||
return { client, channel }
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个基于Chaite渠道的向量器
|
||||
* @param {string} model
|
||||
* @param {number} dimensions
|
||||
* @returns {{ textToVector: (text: string) => Promise<number[]>, batchTextToVector: (texts: string[]) => Promise<number[][]> }}
|
||||
*/
|
||||
export function createChaiteVectorizer (model, dimensions) {
|
||||
return {
|
||||
async textToVector (text) {
|
||||
const { client } = await getClientForModel(model)
|
||||
const options = { model }
|
||||
if (Number.isFinite(dimensions) && dimensions > 0) {
|
||||
options.dimensions = dimensions
|
||||
}
|
||||
const result = await client.getEmbedding(text, options)
|
||||
return result.embeddings[0]
|
||||
},
|
||||
async batchTextToVector (texts) {
|
||||
const manager = Chaite.getInstance().getChannelsManager()
|
||||
const channels = await manager.getChannelsByModel(model, texts.length)
|
||||
if (channels.length === 0) {
|
||||
throw new Error('No channel found for model: ' + model)
|
||||
}
|
||||
const clients = await Promise.all(channels.map(({ channel }) => getIClientByChannel(channel)))
|
||||
const results = []
|
||||
let startIndex = 0
|
||||
for (let i = 0; i < channels.length; i++) {
|
||||
const { quantity } = channels[i]
|
||||
const slice = texts.slice(startIndex, startIndex + quantity)
|
||||
const options = { model }
|
||||
if (Number.isFinite(dimensions) && dimensions > 0) {
|
||||
options.dimensions = dimensions
|
||||
}
|
||||
const embeddings = await clients[i].getEmbedding(slice, options)
|
||||
results.push(...embeddings.embeddings)
|
||||
startIndex += quantity
|
||||
}
|
||||
return results
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function embedTexts (texts, model, dimensions) {
|
||||
if (!texts || texts.length === 0) {
|
||||
return []
|
||||
}
|
||||
const vectorizer = createChaiteVectorizer(model, dimensions)
|
||||
if (texts.length === 1) {
|
||||
return [await vectorizer.textToVector(texts[0])]
|
||||
}
|
||||
return await vectorizer.batchTextToVector(texts)
|
||||
}
|
||||
633
models/memory/collector.js
Normal file
633
models/memory/collector.js
Normal file
|
|
@ -0,0 +1,633 @@
|
|||
import * as crypto from 'node:crypto'
|
||||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { extractGroupFacts } from './extractor.js'
|
||||
import { memoryService } from './service.js'
|
||||
import { getBotFramework } from '../../utils/bot.js'
|
||||
import { ICQQGroupContextCollector, TRSSGroupContextCollector } from '../../utils/group.js'
|
||||
import { groupHistoryCursorStore } from './groupHistoryCursorStore.js'
|
||||
|
||||
const DEFAULT_MAX_WINDOW = 300 // seconds
|
||||
const DEFAULT_HISTORY_BATCH = 120
|
||||
const MAX_RECENT_IDS = 200
|
||||
|
||||
function nowSeconds () {
|
||||
return Math.floor(Date.now() / 1000)
|
||||
}
|
||||
|
||||
function normaliseGroupId (groupId) {
|
||||
return groupId === null || groupId === undefined ? null : String(groupId)
|
||||
}
|
||||
|
||||
function shouldIgnoreMessage (e) {
|
||||
if (!e || !e.message) {
|
||||
return true
|
||||
}
|
||||
if (e.sender?.user_id && e.sender.user_id === e.bot?.uin) {
|
||||
return true
|
||||
}
|
||||
if (e.isPrivate) {
|
||||
return true
|
||||
}
|
||||
const text = e.msg?.trim()
|
||||
if (!text) {
|
||||
return true
|
||||
}
|
||||
if (text.startsWith('#')) {
|
||||
return true
|
||||
}
|
||||
const prefix = ChatGPTConfig.basic?.togglePrefix
|
||||
if (prefix && text.startsWith(prefix)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function extractPlainText (e) {
|
||||
if (e.msg) {
|
||||
return e.msg.trim()
|
||||
}
|
||||
if (Array.isArray(e.message)) {
|
||||
return e.message
|
||||
.filter(item => item.type === 'text')
|
||||
.map(item => item.text || '')
|
||||
.join('')
|
||||
.trim()
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function extractHistoryText (chat) {
|
||||
if (!chat) {
|
||||
return ''
|
||||
}
|
||||
if (typeof chat.raw_message === 'string') {
|
||||
const trimmed = chat.raw_message.trim()
|
||||
if (trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
if (typeof chat.msg === 'string') {
|
||||
const trimmed = chat.msg.trim()
|
||||
if (trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
if (Array.isArray(chat.message)) {
|
||||
const merged = chat.message
|
||||
.filter(item => item && item.type === 'text')
|
||||
.map(item => item.text || '')
|
||||
.join('')
|
||||
.trim()
|
||||
if (merged) {
|
||||
return merged
|
||||
}
|
||||
}
|
||||
if (typeof chat.text === 'string') {
|
||||
const trimmed = chat.text.trim()
|
||||
if (trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function toPositiveInt (value, fallback = 0) {
|
||||
const num = Number(value)
|
||||
if (Number.isFinite(num) && num > 0) {
|
||||
return Math.floor(num)
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
function normalizeTimestamp (value) {
|
||||
if (value === null || value === undefined) {
|
||||
return 0
|
||||
}
|
||||
const num = Number(value)
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
return 0
|
||||
}
|
||||
if (num > 1e12) {
|
||||
return Math.floor(num)
|
||||
}
|
||||
return Math.floor(num * 1000)
|
||||
}
|
||||
|
||||
function resolveMessageIdCandidate (source) {
|
||||
if (!source) {
|
||||
return ''
|
||||
}
|
||||
const candidates = [
|
||||
source.message_id,
|
||||
source.messageId,
|
||||
source.msg_id,
|
||||
source.seq,
|
||||
source.messageSeq,
|
||||
source.id
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (candidate || candidate === 0) {
|
||||
const str = String(candidate).trim()
|
||||
if (str) {
|
||||
return str
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function resolveUserId (source) {
|
||||
if (!source) {
|
||||
return ''
|
||||
}
|
||||
const candidates = [
|
||||
source.user_id,
|
||||
source.uid,
|
||||
source.userId,
|
||||
source.uin,
|
||||
source.id,
|
||||
source.qq
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (candidate || candidate === 0) {
|
||||
const str = String(candidate).trim()
|
||||
if (str) {
|
||||
return str
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function resolveNickname (source) {
|
||||
if (!source) {
|
||||
return ''
|
||||
}
|
||||
const candidates = [
|
||||
source.card,
|
||||
source.nickname,
|
||||
source.name,
|
||||
source.remark
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string') {
|
||||
const trimmed = candidate.trim()
|
||||
if (trimmed) {
|
||||
return trimmed
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export class GroupMessageCollector {
|
||||
constructor () {
|
||||
this.buffers = new Map()
|
||||
this.processing = new Set()
|
||||
this.groupStates = new Map()
|
||||
this.lastPollAt = 0
|
||||
this.polling = false
|
||||
this.selfIds = null
|
||||
}
|
||||
|
||||
get groupConfig () {
|
||||
return ChatGPTConfig.memory?.group || {}
|
||||
}
|
||||
|
||||
get historyBatchSize () {
|
||||
const config = this.groupConfig
|
||||
const configured = toPositiveInt(config.historyBatchSize, 0)
|
||||
if (configured > 0) {
|
||||
return configured
|
||||
}
|
||||
const minCount = toPositiveInt(config.minMessageCount, 80)
|
||||
return Math.max(minCount, DEFAULT_HISTORY_BATCH)
|
||||
}
|
||||
|
||||
get historyPollIntervalMs () {
|
||||
const config = this.groupConfig
|
||||
const configured = Number(config.historyPollInterval)
|
||||
if (Number.isFinite(configured) && configured > 0) {
|
||||
return Math.floor(configured) * 1000
|
||||
}
|
||||
if (configured === 0) {
|
||||
return 0
|
||||
}
|
||||
const fallbackSeconds = Math.max(toPositiveInt(config.maxMessageWindow, DEFAULT_MAX_WINDOW), DEFAULT_MAX_WINDOW)
|
||||
return fallbackSeconds * 1000
|
||||
}
|
||||
|
||||
async tickHistoryPolling (force = false) {
|
||||
const intervalMs = this.historyPollIntervalMs
|
||||
if (intervalMs <= 0) {
|
||||
return
|
||||
}
|
||||
if (!force) {
|
||||
const now = Date.now()
|
||||
if (this.lastPollAt && (now - this.lastPollAt) < intervalMs) {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
this.refreshSelfIds()
|
||||
}
|
||||
await this.runHistoryPoll()
|
||||
}
|
||||
|
||||
async runHistoryPoll () {
|
||||
if (this.polling) {
|
||||
return
|
||||
}
|
||||
this.polling = true
|
||||
try {
|
||||
logger.info('[Memory] start group history poll')
|
||||
await this.pollGroupHistories()
|
||||
} catch (err) {
|
||||
logger.error('[Memory] group history poll execution failed:', err)
|
||||
} finally {
|
||||
this.lastPollAt = Date.now()
|
||||
this.polling = false
|
||||
}
|
||||
}
|
||||
|
||||
async pollGroupHistories () {
|
||||
const config = this.groupConfig
|
||||
if (!config.enable) {
|
||||
return
|
||||
}
|
||||
const groupIds = (config.enabledGroups || [])
|
||||
.map(normaliseGroupId)
|
||||
.filter(Boolean)
|
||||
if (groupIds.length === 0) {
|
||||
return
|
||||
}
|
||||
this.refreshSelfIds()
|
||||
const framework = getBotFramework()
|
||||
for (const groupId of groupIds) {
|
||||
if (!memoryService.isGroupMemoryEnabled(groupId)) {
|
||||
continue
|
||||
}
|
||||
const collector = framework === 'trss'
|
||||
? new TRSSGroupContextCollector()
|
||||
: new ICQQGroupContextCollector()
|
||||
try {
|
||||
const added = await this.collectHistoryForGroup(collector, groupId)
|
||||
if (added > 0) {
|
||||
logger.debug(`[Memory] history poll buffered ${added} messages, group=${groupId}`)
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(`[Memory] failed to poll history for group=${groupId}:`, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async collectHistoryForGroup (collector, groupId) {
|
||||
const limit = this.historyBatchSize
|
||||
if (!limit) {
|
||||
return 0
|
||||
}
|
||||
let chats = []
|
||||
try {
|
||||
chats = await collector.collect(undefined, groupId, 0, limit)
|
||||
} catch (err) {
|
||||
logger.warn(`[Memory] failed to collect history for group=${groupId}:`, err)
|
||||
return 0
|
||||
}
|
||||
if (!Array.isArray(chats) || chats.length === 0) {
|
||||
return 0
|
||||
}
|
||||
const messages = []
|
||||
for (const chat of chats) {
|
||||
const payload = this.transformHistoryMessage(groupId, chat)
|
||||
if (payload) {
|
||||
messages.push(payload)
|
||||
}
|
||||
}
|
||||
if (!messages.length) {
|
||||
return 0
|
||||
}
|
||||
messages.sort((a, b) => normalizeTimestamp(a.timestamp) - normalizeTimestamp(b.timestamp))
|
||||
let queued = 0
|
||||
for (const payload of messages) {
|
||||
if (this.queueMessage(groupId, payload)) {
|
||||
queued++
|
||||
}
|
||||
}
|
||||
return queued
|
||||
}
|
||||
|
||||
transformHistoryMessage (groupId, chat) {
|
||||
const text = extractHistoryText(chat)
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
if (text.startsWith('#')) {
|
||||
return null
|
||||
}
|
||||
const prefix = ChatGPTConfig.basic?.togglePrefix
|
||||
if (prefix && text.startsWith(prefix)) {
|
||||
return null
|
||||
}
|
||||
const sender = chat?.sender || {}
|
||||
const userId = resolveUserId(sender) || resolveUserId(chat)
|
||||
if (this.isBotSelfId(userId)) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
message_id: resolveMessageIdCandidate(chat),
|
||||
user_id: userId,
|
||||
nickname: resolveNickname(sender) || resolveNickname(chat),
|
||||
text,
|
||||
timestamp: chat?.time ?? chat?.timestamp ?? chat?.message_time ?? Date.now()
|
||||
}
|
||||
}
|
||||
|
||||
queueMessage (groupId, rawPayload) {
|
||||
if (!rawPayload || !rawPayload.text) {
|
||||
return false
|
||||
}
|
||||
const state = this.getGroupState(groupId)
|
||||
const messageId = this.ensureMessageId(rawPayload)
|
||||
const timestampMs = normalizeTimestamp(rawPayload.timestamp)
|
||||
const buffer = this.getBuffer(groupId)
|
||||
const payload = {
|
||||
message_id: messageId,
|
||||
user_id: rawPayload.user_id ? String(rawPayload.user_id) : '',
|
||||
nickname: rawPayload.nickname ? String(rawPayload.nickname) : '',
|
||||
text: rawPayload.text,
|
||||
timestamp: timestampMs || Date.now()
|
||||
}
|
||||
const messageKey = this.resolveMessageKey(payload, messageId, timestampMs)
|
||||
if (this.shouldSkipMessage(state, timestampMs, messageKey, payload.message_id)) {
|
||||
return false
|
||||
}
|
||||
this.updateGroupState(groupId, state, timestampMs, messageKey, payload.message_id)
|
||||
buffer.messages.push(payload)
|
||||
logger.debug(`[Memory] buffered group message, group=${groupId}, buffer=${buffer.messages.length}`)
|
||||
this.tryTriggerFlush(groupId, buffer)
|
||||
return true
|
||||
}
|
||||
|
||||
ensureMessageId (payload) {
|
||||
const direct = payload?.message_id ? String(payload.message_id).trim() : ''
|
||||
if (direct) {
|
||||
return direct
|
||||
}
|
||||
const fallback = resolveMessageIdCandidate(payload)
|
||||
if (fallback) {
|
||||
return fallback
|
||||
}
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
|
||||
resolveMessageKey (payload, messageId, timestampMs) {
|
||||
if (messageId) {
|
||||
return messageId
|
||||
}
|
||||
const parts = [
|
||||
timestampMs || '',
|
||||
payload?.user_id || '',
|
||||
(payload?.text || '').slice(0, 32)
|
||||
]
|
||||
return parts.filter(Boolean).join(':')
|
||||
}
|
||||
|
||||
getGroupState (groupId) {
|
||||
let state = this.groupStates.get(groupId)
|
||||
if (!state) {
|
||||
const cursor = groupHistoryCursorStore.getCursor(groupId)
|
||||
const lastTimestamp = Number(cursor?.last_timestamp) || 0
|
||||
const lastMessageId = cursor?.last_message_id || null
|
||||
state = {
|
||||
lastTimestamp,
|
||||
lastMessageId,
|
||||
recentIds: new Set()
|
||||
}
|
||||
if (lastMessageId) {
|
||||
state.recentIds.add(lastMessageId)
|
||||
}
|
||||
this.groupStates.set(groupId, state)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
shouldSkipMessage (state, timestampMs, messageKey, messageId) {
|
||||
if (!state) {
|
||||
return false
|
||||
}
|
||||
if (messageId && state.lastMessageId && messageId === state.lastMessageId) {
|
||||
return true
|
||||
}
|
||||
if (timestampMs && timestampMs < state.lastTimestamp) {
|
||||
return true
|
||||
}
|
||||
if (timestampMs && timestampMs === state.lastTimestamp && messageKey && state.recentIds.has(messageKey)) {
|
||||
return true
|
||||
}
|
||||
if (!timestampMs && messageKey && state.recentIds.has(messageKey)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
updateGroupState (groupId, state, timestampMs, messageKey, messageId) {
|
||||
const hasTimestamp = Number.isFinite(timestampMs) && timestampMs > 0
|
||||
if (!hasTimestamp) {
|
||||
if (messageKey) {
|
||||
state.recentIds.add(messageKey)
|
||||
if (state.recentIds.size > MAX_RECENT_IDS) {
|
||||
const ids = Array.from(state.recentIds).slice(-MAX_RECENT_IDS)
|
||||
state.recentIds = new Set(ids)
|
||||
}
|
||||
}
|
||||
if (messageId) {
|
||||
state.lastMessageId = String(messageId)
|
||||
groupHistoryCursorStore.updateCursor(groupId, {
|
||||
lastMessageId: state.lastMessageId,
|
||||
lastTimestamp: state.lastTimestamp || null
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (timestampMs > state.lastTimestamp) {
|
||||
state.lastTimestamp = timestampMs
|
||||
state.recentIds = messageKey ? new Set([messageKey]) : new Set()
|
||||
} else if (timestampMs === state.lastTimestamp && messageKey) {
|
||||
state.recentIds.add(messageKey)
|
||||
if (state.recentIds.size > MAX_RECENT_IDS) {
|
||||
const ids = Array.from(state.recentIds).slice(-MAX_RECENT_IDS)
|
||||
state.recentIds = new Set(ids)
|
||||
}
|
||||
}
|
||||
|
||||
if (messageId) {
|
||||
state.lastMessageId = String(messageId)
|
||||
}
|
||||
|
||||
groupHistoryCursorStore.updateCursor(groupId, {
|
||||
lastMessageId: state.lastMessageId || null,
|
||||
lastTimestamp: state.lastTimestamp || timestampMs
|
||||
})
|
||||
}
|
||||
|
||||
getBuffer (groupId) {
|
||||
let buffer = this.buffers.get(groupId)
|
||||
if (!buffer) {
|
||||
buffer = {
|
||||
messages: [],
|
||||
lastFlushAt: nowSeconds()
|
||||
}
|
||||
this.buffers.set(groupId, buffer)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
||||
tryTriggerFlush (groupId, buffer) {
|
||||
const config = this.groupConfig
|
||||
const minCount = config.minMessageCount || 50
|
||||
const maxWindow = config.maxMessageWindow || DEFAULT_MAX_WINDOW
|
||||
const shouldFlushByCount = buffer.messages.length >= minCount
|
||||
const shouldFlushByTime = buffer.messages.length > 0 && (nowSeconds() - buffer.lastFlushAt) >= maxWindow
|
||||
logger.debug(`[Memory] try trigger flush, group=${groupId}, count=${buffer.messages.length}, lastFlushAt=${buffer.lastFlushAt}, shouldFlushByCount=${shouldFlushByCount}, shouldFlushByTime=${shouldFlushByTime}`)
|
||||
if (shouldFlushByCount || shouldFlushByTime) {
|
||||
logger.info(`[Memory] trigger group fact extraction, group=${groupId}, count=${buffer.messages.length}, reason=${shouldFlushByCount ? 'count' : 'timeout'}`)
|
||||
this.flush(groupId).catch(err => logger.error('Failed to flush group memory:', err))
|
||||
}
|
||||
}
|
||||
|
||||
push (e) {
|
||||
const groupId = normaliseGroupId(e.group_id || e.group?.group_id)
|
||||
if (!memoryService.isGroupMemoryEnabled(groupId)) {
|
||||
return
|
||||
}
|
||||
if (shouldIgnoreMessage(e)) {
|
||||
return
|
||||
}
|
||||
const text = extractPlainText(e)
|
||||
if (!text) {
|
||||
return
|
||||
}
|
||||
this.addSelfId(e.bot?.uin)
|
||||
const messageId = e.message_id || e.seq || crypto.randomUUID()
|
||||
logger.debug(`[Memory] collect group message, group=${groupId}, user=${e.sender?.user_id}, buffer=${(this.buffers.get(groupId)?.messages.length || 0) + 1}`)
|
||||
this.queueMessage(groupId, {
|
||||
message_id: messageId,
|
||||
user_id: String(e.sender?.user_id || ''),
|
||||
nickname: e.sender?.card || e.sender?.nickname || '',
|
||||
text,
|
||||
timestamp: e.time || Date.now()
|
||||
})
|
||||
}
|
||||
|
||||
async flush (groupId) {
|
||||
if (this.processing.has(groupId)) {
|
||||
return
|
||||
}
|
||||
const buffer = this.buffers.get(groupId)
|
||||
if (!buffer || buffer.messages.length === 0) {
|
||||
return
|
||||
}
|
||||
this.processing.add(groupId)
|
||||
try {
|
||||
const messages = buffer.messages
|
||||
this.buffers.set(groupId, {
|
||||
messages: [],
|
||||
lastFlushAt: nowSeconds()
|
||||
})
|
||||
logger.debug(`[Memory] flushing group buffer, group=${groupId}, messages=${messages.length}`)
|
||||
const simplified = messages.map(msg => ({
|
||||
message_id: msg.message_id,
|
||||
user_id: msg.user_id,
|
||||
nickname: msg.nickname,
|
||||
text: msg.text
|
||||
}))
|
||||
const factCandidates = await extractGroupFacts(simplified)
|
||||
if (factCandidates.length === 0) {
|
||||
logger.debug(`[Memory] group fact extraction returned empty, group=${groupId}`)
|
||||
return
|
||||
}
|
||||
const messageMap = new Map(messages.map(msg => [msg.message_id, msg.text]))
|
||||
const enrichedFacts = factCandidates.map(fact => {
|
||||
if (!fact.source_message_ids && fact.sourceMessages) {
|
||||
fact.source_message_ids = fact.sourceMessages
|
||||
}
|
||||
let ids = []
|
||||
if (Array.isArray(fact.source_message_ids)) {
|
||||
ids = fact.source_message_ids.map(id => String(id))
|
||||
} else if (typeof fact.source_message_ids === 'string') {
|
||||
ids = fact.source_message_ids.split(',').map(id => id.trim()).filter(Boolean)
|
||||
}
|
||||
if (!fact.source_messages && ids.length > 0) {
|
||||
const summary = ids
|
||||
.map(id => messageMap.get(id) || '')
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
fact.source_messages = summary
|
||||
}
|
||||
fact.source_message_ids = ids
|
||||
if (!fact.involved_users || !Array.isArray(fact.involved_users)) {
|
||||
fact.involved_users = []
|
||||
} else {
|
||||
fact.involved_users = fact.involved_users.map(id => String(id))
|
||||
}
|
||||
return fact
|
||||
})
|
||||
const saved = await memoryService.saveGroupFacts(groupId, enrichedFacts)
|
||||
logger.info(`[Memory] saved ${saved.length} group facts for group=${groupId}`)
|
||||
} finally {
|
||||
this.processing.delete(groupId)
|
||||
}
|
||||
}
|
||||
|
||||
addSelfId (uin) {
|
||||
if (uin === null || uin === undefined) {
|
||||
return
|
||||
}
|
||||
const str = String(uin)
|
||||
if (!str) {
|
||||
return
|
||||
}
|
||||
if (!this.selfIds) {
|
||||
this.selfIds = new Set()
|
||||
}
|
||||
this.selfIds.add(str)
|
||||
}
|
||||
|
||||
refreshSelfIds () {
|
||||
this.selfIds = this.collectSelfIds()
|
||||
}
|
||||
|
||||
collectSelfIds () {
|
||||
const ids = new Set()
|
||||
try {
|
||||
const botGlobal = global.Bot
|
||||
if (botGlobal?.bots && typeof botGlobal.bots === 'object') {
|
||||
for (const bot of Object.values(botGlobal.bots)) {
|
||||
if (bot?.uin) {
|
||||
ids.add(String(bot.uin))
|
||||
}
|
||||
}
|
||||
}
|
||||
if (botGlobal?.uin) {
|
||||
ids.add(String(botGlobal.uin))
|
||||
}
|
||||
} catch (err) {
|
||||
logger?.debug?.('[Memory] failed to collect bot self ids: %o', err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
isBotSelfId (userId) {
|
||||
if (userId === null || userId === undefined) {
|
||||
return false
|
||||
}
|
||||
const str = String(userId)
|
||||
if (!str) {
|
||||
return false
|
||||
}
|
||||
if (!this.selfIds || this.selfIds.size === 0) {
|
||||
this.refreshSelfIds()
|
||||
}
|
||||
return this.selfIds?.has(str) || false
|
||||
}
|
||||
}
|
||||
755
models/memory/database.js
Normal file
755
models/memory/database.js
Normal file
|
|
@ -0,0 +1,755 @@
|
|||
import Database from 'better-sqlite3'
|
||||
import * as sqliteVec from 'sqlite-vec'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import ChatGPTConfig from '../../config/config.js'
|
||||
|
||||
const META_VECTOR_DIM_KEY = 'group_vec_dimension'
|
||||
const META_VECTOR_MODEL_KEY = 'group_vec_model'
|
||||
const META_GROUP_TOKENIZER_KEY = 'group_memory_tokenizer'
|
||||
const META_USER_TOKENIZER_KEY = 'user_memory_tokenizer'
|
||||
const TOKENIZER_DEFAULT = 'unicode61'
|
||||
const SIMPLE_MATCH_SIMPLE = 'simple_query'
|
||||
const SIMPLE_MATCH_JIEBA = 'jieba_query'
|
||||
const PLUGIN_ROOT = path.resolve('./plugins/chatgpt-plugin')
|
||||
|
||||
let dbInstance = null
|
||||
let cachedVectorDimension = null
|
||||
let cachedVectorModel = null
|
||||
let userMemoryFtsConfig = {
|
||||
tokenizer: TOKENIZER_DEFAULT,
|
||||
matchQuery: null
|
||||
}
|
||||
let groupMemoryFtsConfig = {
|
||||
tokenizer: TOKENIZER_DEFAULT,
|
||||
matchQuery: null
|
||||
}
|
||||
const simpleExtensionState = {
|
||||
requested: false,
|
||||
enabled: false,
|
||||
loaded: false,
|
||||
error: null,
|
||||
libraryPath: '',
|
||||
dictPath: '',
|
||||
tokenizer: TOKENIZER_DEFAULT,
|
||||
matchQuery: null
|
||||
}
|
||||
|
||||
function resolveDbPath () {
|
||||
const relativePath = ChatGPTConfig.memory?.database || 'data/memory.db'
|
||||
return path.resolve('./plugins/chatgpt-plugin', relativePath)
|
||||
}
|
||||
|
||||
export function resolvePluginPath (targetPath) {
|
||||
if (!targetPath) {
|
||||
return ''
|
||||
}
|
||||
if (path.isAbsolute(targetPath)) {
|
||||
return targetPath
|
||||
}
|
||||
return path.resolve(PLUGIN_ROOT, targetPath)
|
||||
}
|
||||
|
||||
export function toPluginRelativePath (absolutePath) {
|
||||
if (!absolutePath) {
|
||||
return ''
|
||||
}
|
||||
return path.relative(PLUGIN_ROOT, absolutePath)
|
||||
}
|
||||
|
||||
function resolvePreferredDimension () {
|
||||
const { memory, llm } = ChatGPTConfig
|
||||
if (memory?.vectorDimensions && memory.vectorDimensions > 0) {
|
||||
return memory.vectorDimensions
|
||||
}
|
||||
if (llm?.dimensions && llm.dimensions > 0) {
|
||||
return llm.dimensions
|
||||
}
|
||||
return 1536
|
||||
}
|
||||
|
||||
function ensureDirectory (filePath) {
|
||||
const dir = path.dirname(filePath)
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
function ensureMetaTable (db) {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS memory_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
function getMetaValue (db, key) {
|
||||
const stmt = db.prepare('SELECT value FROM memory_meta WHERE key = ?')
|
||||
const row = stmt.get(key)
|
||||
return row ? row.value : null
|
||||
}
|
||||
|
||||
function setMetaValue (db, key, value) {
|
||||
db.prepare(`
|
||||
INSERT INTO memory_meta (key, value)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
||||
`).run(key, value)
|
||||
}
|
||||
|
||||
function resetSimpleState (overrides = {}) {
|
||||
simpleExtensionState.loaded = false
|
||||
simpleExtensionState.error = null
|
||||
simpleExtensionState.tokenizer = TOKENIZER_DEFAULT
|
||||
simpleExtensionState.matchQuery = null
|
||||
Object.assign(simpleExtensionState, overrides)
|
||||
userMemoryFtsConfig = {
|
||||
tokenizer: TOKENIZER_DEFAULT,
|
||||
matchQuery: null
|
||||
}
|
||||
groupMemoryFtsConfig = {
|
||||
tokenizer: TOKENIZER_DEFAULT,
|
||||
matchQuery: null
|
||||
}
|
||||
}
|
||||
|
||||
function sanitiseRawFtsInput (input) {
|
||||
if (!input) {
|
||||
return ''
|
||||
}
|
||||
const trimmed = String(input).trim()
|
||||
if (!trimmed) {
|
||||
return ''
|
||||
}
|
||||
const replaced = trimmed
|
||||
.replace(/["'`]+/g, ' ')
|
||||
.replace(/\u3000/g, ' ')
|
||||
.replace(/[^\p{L}\p{N}\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF\u1100-\u11FF\s]+/gu, ' ')
|
||||
const collapsed = replaced.replace(/\s+/g, ' ').trim()
|
||||
return collapsed || trimmed
|
||||
}
|
||||
|
||||
function isSimpleLibraryFile (filename) {
|
||||
return /(^libsimple.*\.(so|dylib|dll)$)|(^simple\.(so|dylib|dll)$)/i.test(filename)
|
||||
}
|
||||
|
||||
function findSimpleLibrary (startDir) {
|
||||
const stack = [startDir]
|
||||
while (stack.length > 0) {
|
||||
const dir = stack.pop()
|
||||
if (!dir || !fs.existsSync(dir)) {
|
||||
continue
|
||||
}
|
||||
const entries = fs.readdirSync(dir, { withFileTypes: true })
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
stack.push(fullPath)
|
||||
} else if (entry.isFile() && isSimpleLibraryFile(entry.name)) {
|
||||
return fullPath
|
||||
}
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function locateDictPathNear (filePath) {
|
||||
if (!filePath) {
|
||||
return ''
|
||||
}
|
||||
let currentDir = path.dirname(filePath)
|
||||
for (let depth = 0; depth < 5 && currentDir && currentDir !== path.dirname(currentDir); depth++) {
|
||||
const dictCandidate = path.join(currentDir, 'dict')
|
||||
if (fs.existsSync(dictCandidate) && fs.statSync(dictCandidate).isDirectory()) {
|
||||
return dictCandidate
|
||||
}
|
||||
currentDir = path.dirname(currentDir)
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function discoverSimplePaths () {
|
||||
const searchRoots = [
|
||||
path.join(PLUGIN_ROOT, 'resources/simple'),
|
||||
path.join(PLUGIN_ROOT, 'resources'),
|
||||
path.join(PLUGIN_ROOT, 'lib/simple'),
|
||||
PLUGIN_ROOT
|
||||
]
|
||||
for (const root of searchRoots) {
|
||||
if (!root || !fs.existsSync(root)) {
|
||||
continue
|
||||
}
|
||||
const lib = findSimpleLibrary(root)
|
||||
if (lib) {
|
||||
const dictCandidate = locateDictPathNear(lib)
|
||||
return {
|
||||
libraryPath: toPluginRelativePath(lib) || lib,
|
||||
dictPath: dictCandidate ? (toPluginRelativePath(dictCandidate) || dictCandidate) : ''
|
||||
}
|
||||
}
|
||||
}
|
||||
return { libraryPath: '', dictPath: '' }
|
||||
}
|
||||
|
||||
function applySimpleExtension (db) {
|
||||
const config = ChatGPTConfig.memory?.extensions?.simple || {}
|
||||
simpleExtensionState.requested = Boolean(config.enable)
|
||||
simpleExtensionState.enabled = Boolean(config.enable)
|
||||
simpleExtensionState.libraryPath = config.libraryPath || ''
|
||||
simpleExtensionState.dictPath = config.dictPath || ''
|
||||
if (!config.enable) {
|
||||
logger?.debug?.('[Memory] simple tokenizer disabled via config')
|
||||
resetSimpleState({ requested: false, enabled: false })
|
||||
return
|
||||
}
|
||||
if (!simpleExtensionState.libraryPath) {
|
||||
const detected = discoverSimplePaths()
|
||||
if (detected.libraryPath) {
|
||||
simpleExtensionState.libraryPath = detected.libraryPath
|
||||
simpleExtensionState.dictPath = detected.dictPath
|
||||
config.libraryPath = detected.libraryPath
|
||||
if (detected.dictPath) {
|
||||
config.dictPath = detected.dictPath
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolvedLibraryPath = resolvePluginPath(config.libraryPath)
|
||||
if (!resolvedLibraryPath || !fs.existsSync(resolvedLibraryPath)) {
|
||||
logger?.warn?.('[Memory] simple tokenizer library missing:', resolvedLibraryPath || '(empty path)')
|
||||
resetSimpleState({
|
||||
requested: true,
|
||||
enabled: true,
|
||||
error: `Simple extension library not found at ${resolvedLibraryPath || '(empty path)'}`
|
||||
})
|
||||
return
|
||||
}
|
||||
try {
|
||||
logger?.info?.('[Memory] loading simple tokenizer extension from', resolvedLibraryPath)
|
||||
db.loadExtension(resolvedLibraryPath)
|
||||
if (config.useJieba) {
|
||||
const resolvedDict = resolvePluginPath(config.dictPath)
|
||||
if (resolvedDict && fs.existsSync(resolvedDict)) {
|
||||
try {
|
||||
logger?.debug?.('[Memory] configuring simple tokenizer jieba dict:', resolvedDict)
|
||||
db.prepare('select jieba_dict(?)').get(resolvedDict)
|
||||
} catch (err) {
|
||||
logger?.warn?.('Failed to register jieba dict for simple extension:', err)
|
||||
}
|
||||
} else {
|
||||
logger?.warn?.('Simple extension jieba dict path missing:', resolvedDict)
|
||||
}
|
||||
}
|
||||
const tokenizer = config.useJieba ? 'simple_jieba' : 'simple'
|
||||
const matchQuery = config.useJieba ? SIMPLE_MATCH_JIEBA : SIMPLE_MATCH_SIMPLE
|
||||
simpleExtensionState.loaded = true
|
||||
simpleExtensionState.error = null
|
||||
simpleExtensionState.tokenizer = tokenizer
|
||||
simpleExtensionState.matchQuery = matchQuery
|
||||
logger?.info?.('[Memory] simple tokenizer initialised, tokenizer=%s, matchQuery=%s', tokenizer, matchQuery)
|
||||
userMemoryFtsConfig = {
|
||||
tokenizer,
|
||||
matchQuery
|
||||
}
|
||||
groupMemoryFtsConfig = {
|
||||
tokenizer,
|
||||
matchQuery
|
||||
}
|
||||
return
|
||||
} catch (error) {
|
||||
logger?.error?.('Failed to load simple extension:', error)
|
||||
resetSimpleState({
|
||||
requested: true,
|
||||
enabled: true,
|
||||
error: `Failed to load simple extension: ${error?.message || error}`
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function loadSimpleExtensionForCleanup (db) {
|
||||
if (!ChatGPTConfig.memory.extensions) {
|
||||
ChatGPTConfig.memory.extensions = {}
|
||||
}
|
||||
if (!ChatGPTConfig.memory.extensions.simple) {
|
||||
ChatGPTConfig.memory.extensions.simple = {
|
||||
enable: false,
|
||||
libraryPath: '',
|
||||
dictPath: '',
|
||||
useJieba: false
|
||||
}
|
||||
}
|
||||
const config = ChatGPTConfig.memory.extensions.simple
|
||||
let libraryPath = config.libraryPath || ''
|
||||
let dictPath = config.dictPath || ''
|
||||
if (!libraryPath) {
|
||||
const detected = discoverSimplePaths()
|
||||
libraryPath = detected.libraryPath
|
||||
if (detected.dictPath && !dictPath) {
|
||||
dictPath = detected.dictPath
|
||||
}
|
||||
if (libraryPath) {
|
||||
ChatGPTConfig.memory.extensions.simple = ChatGPTConfig.memory.extensions.simple || {}
|
||||
ChatGPTConfig.memory.extensions.simple.libraryPath = libraryPath
|
||||
if (dictPath) {
|
||||
ChatGPTConfig.memory.extensions.simple.dictPath = dictPath
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolvedLibraryPath = resolvePluginPath(libraryPath)
|
||||
if (!resolvedLibraryPath || !fs.existsSync(resolvedLibraryPath)) {
|
||||
logger?.warn?.('[Memory] cleanup requires simple extension but library missing:', resolvedLibraryPath || '(empty path)')
|
||||
return false
|
||||
}
|
||||
try {
|
||||
logger?.info?.('[Memory] temporarily loading simple extension for cleanup tasks')
|
||||
db.loadExtension(resolvedLibraryPath)
|
||||
const useJieba = Boolean(config.useJieba)
|
||||
if (useJieba) {
|
||||
const resolvedDict = resolvePluginPath(dictPath)
|
||||
if (resolvedDict && fs.existsSync(resolvedDict)) {
|
||||
try {
|
||||
db.prepare('select jieba_dict(?)').get(resolvedDict)
|
||||
} catch (err) {
|
||||
logger?.warn?.('Failed to set jieba dict during cleanup:', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
} catch (error) {
|
||||
logger?.error?.('Failed to load simple extension for cleanup:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function ensureGroupFactsTable (db) {
|
||||
ensureMetaTable(db)
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS group_facts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id TEXT NOT NULL,
|
||||
fact TEXT NOT NULL,
|
||||
topic TEXT,
|
||||
importance REAL DEFAULT 0.5,
|
||||
source_message_ids TEXT,
|
||||
source_messages TEXT,
|
||||
involved_users TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_group_facts_unique
|
||||
ON group_facts(group_id, fact)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_group_facts_group
|
||||
ON group_facts(group_id, importance DESC, created_at DESC)
|
||||
`)
|
||||
ensureGroupFactsFtsTable(db)
|
||||
}
|
||||
|
||||
function ensureGroupHistoryCursorTable (db) {
|
||||
ensureMetaTable(db)
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS group_history_cursor (
|
||||
group_id TEXT PRIMARY KEY,
|
||||
last_message_id TEXT,
|
||||
last_timestamp INTEGER
|
||||
)
|
||||
`)
|
||||
}
|
||||
|
||||
function ensureUserMemoryTable (db) {
|
||||
ensureMetaTable(db)
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS user_memory (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
group_id TEXT,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
importance REAL DEFAULT 0.5,
|
||||
source_message_id TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now')),
|
||||
updated_at TEXT DEFAULT (datetime('now'))
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_memory_key
|
||||
ON user_memory(user_id, coalesce(group_id, ''), key)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_user_memory_group
|
||||
ON user_memory(group_id)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_user_memory_user
|
||||
ON user_memory(user_id)
|
||||
`)
|
||||
ensureUserMemoryFtsTable(db)
|
||||
}
|
||||
|
||||
function dropGroupFactsFtsArtifacts (db) {
|
||||
try {
|
||||
db.exec(`
|
||||
DROP TRIGGER IF EXISTS group_facts_ai;
|
||||
DROP TRIGGER IF EXISTS group_facts_ad;
|
||||
DROP TRIGGER IF EXISTS group_facts_au;
|
||||
DROP TABLE IF EXISTS group_facts_fts;
|
||||
`)
|
||||
} catch (err) {
|
||||
if (String(err?.message || '').includes('no such tokenizer')) {
|
||||
const loaded = loadSimpleExtensionForCleanup(db)
|
||||
if (loaded) {
|
||||
db.exec(`
|
||||
DROP TRIGGER IF EXISTS group_facts_ai;
|
||||
DROP TRIGGER IF EXISTS group_facts_ad;
|
||||
DROP TRIGGER IF EXISTS group_facts_au;
|
||||
DROP TABLE IF EXISTS group_facts_fts;
|
||||
`)
|
||||
} else {
|
||||
logger?.warn?.('[Memory] Falling back to raw schema cleanup for group_facts_fts')
|
||||
try {
|
||||
db.exec('PRAGMA writable_schema = ON;')
|
||||
db.exec(`DELETE FROM sqlite_master WHERE name IN ('group_facts_ai','group_facts_ad','group_facts_au','group_facts_fts');`)
|
||||
} finally {
|
||||
db.exec('PRAGMA writable_schema = OFF;')
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createGroupFactsFts (db, tokenizer) {
|
||||
logger?.info?.('[Memory] creating group_facts_fts with tokenizer=%s', tokenizer)
|
||||
db.exec(`
|
||||
CREATE VIRTUAL TABLE group_facts_fts
|
||||
USING fts5(
|
||||
fact,
|
||||
topic,
|
||||
content = 'group_facts',
|
||||
content_rowid = 'id',
|
||||
tokenize = '${tokenizer}'
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TRIGGER group_facts_ai AFTER INSERT ON group_facts BEGIN
|
||||
INSERT INTO group_facts_fts(rowid, fact, topic)
|
||||
VALUES (new.id, new.fact, coalesce(new.topic, ''));
|
||||
END;
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TRIGGER group_facts_ad AFTER DELETE ON group_facts BEGIN
|
||||
INSERT INTO group_facts_fts(group_facts_fts, rowid, fact, topic)
|
||||
VALUES ('delete', old.id, old.fact, coalesce(old.topic, ''));
|
||||
END;
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TRIGGER group_facts_au AFTER UPDATE ON group_facts BEGIN
|
||||
INSERT INTO group_facts_fts(group_facts_fts, rowid, fact, topic)
|
||||
VALUES ('delete', old.id, old.fact, coalesce(old.topic, ''));
|
||||
INSERT INTO group_facts_fts(rowid, fact, topic)
|
||||
VALUES (new.id, new.fact, coalesce(new.topic, ''));
|
||||
END;
|
||||
`)
|
||||
try {
|
||||
db.exec(`INSERT INTO group_facts_fts(group_facts_fts) VALUES ('rebuild')`)
|
||||
} catch (err) {
|
||||
logger?.debug?.('Group facts FTS rebuild skipped:', err?.message || err)
|
||||
}
|
||||
}
|
||||
|
||||
function ensureGroupFactsFtsTable (db) {
|
||||
const desiredTokenizer = groupMemoryFtsConfig.tokenizer || TOKENIZER_DEFAULT
|
||||
const storedTokenizer = getMetaValue(db, META_GROUP_TOKENIZER_KEY)
|
||||
const tableExists = db.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'group_facts_fts'
|
||||
`).get()
|
||||
if (storedTokenizer && storedTokenizer !== desiredTokenizer) {
|
||||
dropGroupFactsFtsArtifacts(db)
|
||||
} else if (!storedTokenizer && tableExists) {
|
||||
// Unknown tokenizer, drop to ensure consistency.
|
||||
dropGroupFactsFtsArtifacts(db)
|
||||
}
|
||||
const existsAfterDrop = db.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'group_facts_fts'
|
||||
`).get()
|
||||
if (!existsAfterDrop) {
|
||||
createGroupFactsFts(db, desiredTokenizer)
|
||||
setMetaValue(db, META_GROUP_TOKENIZER_KEY, desiredTokenizer)
|
||||
logger?.info?.('[Memory] group facts FTS initialised with tokenizer=%s', desiredTokenizer)
|
||||
}
|
||||
}
|
||||
|
||||
function dropUserMemoryFtsArtifacts (db) {
|
||||
try {
|
||||
db.exec(`
|
||||
DROP TRIGGER IF EXISTS user_memory_ai;
|
||||
DROP TRIGGER IF EXISTS user_memory_ad;
|
||||
DROP TRIGGER IF EXISTS user_memory_au;
|
||||
DROP TABLE IF EXISTS user_memory_fts;
|
||||
`)
|
||||
} catch (err) {
|
||||
if (String(err?.message || '').includes('no such tokenizer')) {
|
||||
const loaded = loadSimpleExtensionForCleanup(db)
|
||||
if (loaded) {
|
||||
db.exec(`
|
||||
DROP TRIGGER IF EXISTS user_memory_ai;
|
||||
DROP TRIGGER IF EXISTS user_memory_ad;
|
||||
DROP TRIGGER IF EXISTS user_memory_au;
|
||||
DROP TABLE IF EXISTS user_memory_fts;
|
||||
`)
|
||||
} else {
|
||||
logger?.warn?.('[Memory] Falling back to raw schema cleanup for user_memory_fts')
|
||||
try {
|
||||
db.exec('PRAGMA writable_schema = ON;')
|
||||
db.exec(`DELETE FROM sqlite_master WHERE name IN ('user_memory_ai','user_memory_ad','user_memory_au','user_memory_fts');`)
|
||||
} finally {
|
||||
db.exec('PRAGMA writable_schema = OFF;')
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createUserMemoryFts (db, tokenizer) {
|
||||
logger?.info?.('[Memory] creating user_memory_fts with tokenizer=%s', tokenizer)
|
||||
db.exec(`
|
||||
CREATE VIRTUAL TABLE user_memory_fts
|
||||
USING fts5(
|
||||
value,
|
||||
content = 'user_memory',
|
||||
content_rowid = 'id',
|
||||
tokenize = '${tokenizer}'
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TRIGGER user_memory_ai AFTER INSERT ON user_memory BEGIN
|
||||
INSERT INTO user_memory_fts(rowid, value)
|
||||
VALUES (new.id, new.value);
|
||||
END;
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TRIGGER user_memory_ad AFTER DELETE ON user_memory BEGIN
|
||||
INSERT INTO user_memory_fts(user_memory_fts, rowid, value)
|
||||
VALUES ('delete', old.id, old.value);
|
||||
END;
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TRIGGER user_memory_au AFTER UPDATE ON user_memory BEGIN
|
||||
INSERT INTO user_memory_fts(user_memory_fts, rowid, value)
|
||||
VALUES ('delete', old.id, old.value);
|
||||
INSERT INTO user_memory_fts(rowid, value)
|
||||
VALUES (new.id, new.value);
|
||||
END;
|
||||
`)
|
||||
try {
|
||||
db.exec(`INSERT INTO user_memory_fts(user_memory_fts) VALUES ('rebuild')`)
|
||||
} catch (err) {
|
||||
logger?.debug?.('User memory FTS rebuild skipped:', err?.message || err)
|
||||
}
|
||||
}
|
||||
|
||||
function ensureUserMemoryFtsTable (db) {
|
||||
const desiredTokenizer = userMemoryFtsConfig.tokenizer || TOKENIZER_DEFAULT
|
||||
const storedTokenizer = getMetaValue(db, META_USER_TOKENIZER_KEY)
|
||||
const tableExists = db.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'user_memory_fts'
|
||||
`).get()
|
||||
if (storedTokenizer && storedTokenizer !== desiredTokenizer) {
|
||||
dropUserMemoryFtsArtifacts(db)
|
||||
} else if (!storedTokenizer && tableExists) {
|
||||
dropUserMemoryFtsArtifacts(db)
|
||||
}
|
||||
const existsAfterDrop = db.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'user_memory_fts'
|
||||
`).get()
|
||||
if (!existsAfterDrop) {
|
||||
createUserMemoryFts(db, desiredTokenizer)
|
||||
setMetaValue(db, META_USER_TOKENIZER_KEY, desiredTokenizer)
|
||||
logger?.info?.('[Memory] user memory FTS initialised with tokenizer=%s', desiredTokenizer)
|
||||
}
|
||||
}
|
||||
|
||||
function createVectorTable (db, dimension) {
|
||||
if (!dimension || dimension <= 0) {
|
||||
throw new Error(`Invalid vector dimension for table creation: ${dimension}`)
|
||||
}
|
||||
db.exec(`CREATE VIRTUAL TABLE vec_group_facts USING vec0(embedding float[${dimension}])`)
|
||||
}
|
||||
|
||||
function ensureVectorTable (db) {
|
||||
ensureMetaTable(db)
|
||||
if (cachedVectorDimension !== null) {
|
||||
return cachedVectorDimension
|
||||
}
|
||||
const preferredDimension = resolvePreferredDimension()
|
||||
const stored = getMetaValue(db, META_VECTOR_DIM_KEY)
|
||||
const storedModel = getMetaValue(db, META_VECTOR_MODEL_KEY)
|
||||
const currentModel = ChatGPTConfig.llm?.embeddingModel || ''
|
||||
const tableExists = Boolean(db.prepare(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'vec_group_facts'
|
||||
`).get())
|
||||
|
||||
const parseDimension = value => {
|
||||
if (!value && value !== 0) return 0
|
||||
const parsed = parseInt(String(value), 10)
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
|
||||
}
|
||||
|
||||
const storedDimension = parseDimension(stored)
|
||||
let dimension = storedDimension
|
||||
let tablePresent = tableExists
|
||||
|
||||
let needsTableReset = false
|
||||
if (tableExists && storedDimension <= 0) {
|
||||
needsTableReset = true
|
||||
}
|
||||
|
||||
if (needsTableReset && tableExists) {
|
||||
try {
|
||||
db.exec('DROP TABLE IF EXISTS vec_group_facts')
|
||||
tablePresent = false
|
||||
dimension = 0
|
||||
} catch (err) {
|
||||
logger?.warn?.('[Memory] failed to drop vec_group_facts during dimension change:', err)
|
||||
}
|
||||
}
|
||||
|
||||
if (!tablePresent) {
|
||||
if (dimension <= 0) {
|
||||
dimension = parseDimension(preferredDimension)
|
||||
}
|
||||
if (dimension > 0) {
|
||||
try {
|
||||
createVectorTable(db, dimension)
|
||||
tablePresent = true
|
||||
setMetaValue(db, META_VECTOR_MODEL_KEY, currentModel)
|
||||
setMetaValue(db, META_VECTOR_DIM_KEY, String(dimension))
|
||||
cachedVectorDimension = dimension
|
||||
cachedVectorModel = currentModel
|
||||
return cachedVectorDimension
|
||||
} catch (err) {
|
||||
logger?.error?.('[Memory] failed to (re)create vec_group_facts table:', err)
|
||||
dimension = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (tablePresent && storedDimension > 0) {
|
||||
cachedVectorDimension = storedDimension
|
||||
cachedVectorModel = storedModel || currentModel
|
||||
return cachedVectorDimension
|
||||
}
|
||||
|
||||
// At this point we failed to determine a valid dimension, set metadata to 0 to avoid loops.
|
||||
setMetaValue(db, META_VECTOR_MODEL_KEY, currentModel)
|
||||
setMetaValue(db, META_VECTOR_DIM_KEY, '0')
|
||||
cachedVectorDimension = 0
|
||||
cachedVectorModel = currentModel
|
||||
return cachedVectorDimension
|
||||
}
|
||||
export function resetVectorTableDimension (dimension) {
|
||||
if (!Number.isFinite(dimension) || dimension <= 0) {
|
||||
throw new Error(`Invalid vector dimension: ${dimension}`)
|
||||
}
|
||||
const db = getMemoryDatabase()
|
||||
try {
|
||||
db.exec('DROP TABLE IF EXISTS vec_group_facts')
|
||||
} catch (err) {
|
||||
logger?.warn?.('[Memory] failed to drop vec_group_facts:', err)
|
||||
}
|
||||
createVectorTable(db, dimension)
|
||||
setMetaValue(db, META_VECTOR_DIM_KEY, dimension.toString())
|
||||
const model = ChatGPTConfig.llm?.embeddingModel || ''
|
||||
setMetaValue(db, META_VECTOR_MODEL_KEY, model)
|
||||
cachedVectorDimension = dimension
|
||||
cachedVectorModel = model
|
||||
}
|
||||
|
||||
function migrate (db) {
|
||||
ensureGroupFactsTable(db)
|
||||
ensureGroupHistoryCursorTable(db)
|
||||
ensureUserMemoryTable(db)
|
||||
ensureVectorTable(db)
|
||||
}
|
||||
|
||||
export function getUserMemoryFtsConfig () {
|
||||
return { ...userMemoryFtsConfig }
|
||||
}
|
||||
|
||||
export function getGroupMemoryFtsConfig () {
|
||||
return { ...groupMemoryFtsConfig }
|
||||
}
|
||||
|
||||
export function getSimpleExtensionState () {
|
||||
return { ...simpleExtensionState }
|
||||
}
|
||||
|
||||
export function sanitiseFtsQueryInput (query, ftsConfig) {
|
||||
if (!query) {
|
||||
return ''
|
||||
}
|
||||
if (ftsConfig?.matchQuery) {
|
||||
return String(query).trim()
|
||||
}
|
||||
return sanitiseRawFtsInput(query)
|
||||
}
|
||||
|
||||
export function getMemoryDatabase () {
|
||||
if (dbInstance) {
|
||||
return dbInstance
|
||||
}
|
||||
const dbPath = resolveDbPath()
|
||||
ensureDirectory(dbPath)
|
||||
logger?.info?.('[Memory] opening memory database at %s', dbPath)
|
||||
dbInstance = new Database(dbPath)
|
||||
sqliteVec.load(dbInstance)
|
||||
resetSimpleState({
|
||||
requested: false,
|
||||
enabled: false
|
||||
})
|
||||
applySimpleExtension(dbInstance)
|
||||
migrate(dbInstance)
|
||||
logger?.info?.('[Memory] memory database init completed (simple loaded=%s)', simpleExtensionState.loaded)
|
||||
return dbInstance
|
||||
}
|
||||
|
||||
export function getVectorDimension () {
|
||||
const currentModel = ChatGPTConfig.llm?.embeddingModel || ''
|
||||
if (cachedVectorModel && cachedVectorModel !== currentModel) {
|
||||
cachedVectorDimension = null
|
||||
cachedVectorModel = null
|
||||
}
|
||||
if (cachedVectorDimension !== null) {
|
||||
return cachedVectorDimension
|
||||
}
|
||||
const db = getMemoryDatabase()
|
||||
return ensureVectorTable(db)
|
||||
}
|
||||
|
||||
export function resetCachedDimension () {
|
||||
cachedVectorDimension = null
|
||||
cachedVectorModel = null
|
||||
}
|
||||
|
||||
export function resetMemoryDatabaseInstance () {
|
||||
if (dbInstance) {
|
||||
try {
|
||||
dbInstance.close()
|
||||
} catch (error) {
|
||||
console.warn('Failed to close memory database:', error)
|
||||
}
|
||||
}
|
||||
dbInstance = null
|
||||
cachedVectorDimension = null
|
||||
cachedVectorModel = null
|
||||
}
|
||||
306
models/memory/extractor.js
Normal file
306
models/memory/extractor.js
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
import { SendMessageOption, Chaite } from 'chaite'
|
||||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { getClientForModel } from '../chaite/vectorizer.js'
|
||||
|
||||
function collectTextFromResponse (response) {
|
||||
if (!response?.contents) {
|
||||
return ''
|
||||
}
|
||||
return response.contents
|
||||
.filter(content => content.type === 'text')
|
||||
.map(content => content.text || '')
|
||||
.join('\n')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function parseJSON (text) {
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
const trimmed = text.trim()
|
||||
const codeBlockMatch = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)
|
||||
const payload = codeBlockMatch ? codeBlockMatch[1] : trimmed
|
||||
try {
|
||||
return JSON.parse(payload)
|
||||
} catch (err) {
|
||||
logger.warn('Failed to parse JSON from memory extractor response:', text)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function formatEntry (entry) {
|
||||
let str = ''
|
||||
try {
|
||||
if (typeof entry === 'string') {
|
||||
str = entry
|
||||
} else {
|
||||
str = JSON.stringify(entry)
|
||||
}
|
||||
} catch (err) {
|
||||
str = String(entry)
|
||||
}
|
||||
const limit = 200
|
||||
return str.length > limit ? str.slice(0, limit) + '…' : str
|
||||
}
|
||||
|
||||
function injectMessagesIntoTemplate (template, body) {
|
||||
if (!template || typeof template !== 'string') {
|
||||
return body
|
||||
}
|
||||
const placeholders = ['${messages}', '{messages}', '{{messages}}']
|
||||
let result = template
|
||||
let replaced = false
|
||||
for (const placeholder of placeholders) {
|
||||
if (result.includes(placeholder)) {
|
||||
result = result.split(placeholder).join(body)
|
||||
replaced = true
|
||||
}
|
||||
}
|
||||
if (!replaced) {
|
||||
const trimmed = result.trim()
|
||||
if (!trimmed) {
|
||||
return body
|
||||
}
|
||||
if (/\n\s*$/.test(result)) {
|
||||
return `${result}${body}`
|
||||
}
|
||||
return `${result}\n${body}`
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
async function resolvePresetSendMessageOption (presetId, scope) {
|
||||
if (!presetId) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const chaite = Chaite.getInstance?.()
|
||||
if (!chaite) {
|
||||
logger.warn(`[Memory] ${scope} extraction preset ${presetId} configured but Chaite is not initialized`)
|
||||
return null
|
||||
}
|
||||
const presetManager = chaite.getChatPresetManager?.()
|
||||
if (!presetManager) {
|
||||
logger.warn(`[Memory] ${scope} extraction preset ${presetId} configured but preset manager unavailable`)
|
||||
return null
|
||||
}
|
||||
const preset = await presetManager.getInstance(presetId)
|
||||
if (!preset) {
|
||||
logger.warn(`[Memory] ${scope} extraction preset ${presetId} not found`)
|
||||
return null
|
||||
}
|
||||
logger.debug(`[Memory] using ${scope} extraction preset ${presetId}`)
|
||||
return {
|
||||
preset,
|
||||
sendMessageOption: JSON.parse(JSON.stringify(preset.sendMessageOption || {}))
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`[Memory] failed to load ${scope} extraction preset ${presetId}:`, err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function resolveGroupExtractionPrompts (presetSendMessageOption) {
|
||||
const config = ChatGPTConfig.memory?.group || {}
|
||||
const system = config.extractionSystemPrompt || presetSendMessageOption?.systemOverride || `You are a knowledge extraction assistant that specialises in summarising long-term facts from group chat transcripts.
|
||||
Read the provided conversation and identify statements that should be stored as long-term knowledge for the group.
|
||||
Return a JSON array. Each element must contain:
|
||||
{
|
||||
"fact": 事实内容,必须完整包含事件的各个要素而不能是简单的短语(比如谁参与了事件、做了什么事情、背景时间是什么)(同一件事情尽可能整合为同一条而非拆分,以便利于检索),
|
||||
"topic": 主题关键词,字符串,如 "活动"、"成员信息",
|
||||
"importance": 一个介于0和1之间的小数,数值越大表示越重要,
|
||||
"source_message_ids": 原始消息ID数组,
|
||||
"source_messages": 对应原始消息的简要摘录或合并文本,
|
||||
"involved_users": 出现或相关的用户ID数组
|
||||
}
|
||||
Only include meaningful, verifiable group-specific information that is useful for future conversations. Do not record incomplete information. Do not include general knowledge or unrelated facts. Do not wrap the JSON array in code fences.`
|
||||
const userTemplate = config.extractionUserPrompt || `以下是群聊中的一些消息,请根据系统说明提取值得长期记忆的事实,以JSON数组形式返回,不要输出额外说明。
|
||||
|
||||
\${messages}`
|
||||
return { system, userTemplate }
|
||||
}
|
||||
|
||||
function buildGroupUserPrompt (messages, template) {
|
||||
const joined = messages.map(msg => {
|
||||
const sender = msg.nickname || msg.user_id || '未知用户'
|
||||
return `${sender}: ${msg.text}`
|
||||
}).join('\n')
|
||||
return injectMessagesIntoTemplate(template, joined)
|
||||
}
|
||||
|
||||
function buildExistingMemorySection (existingMemories = []) {
|
||||
if (!existingMemories || existingMemories.length === 0) {
|
||||
return '当前没有任何已知的长期记忆。'
|
||||
}
|
||||
const lines = existingMemories.map((item, idx) => `${idx + 1}. ${item}`)
|
||||
return `以下是关于用户的已知长期记忆,请在提取新记忆时参考,避免重复已有事实,并在信息变更时更新描述:\n${lines.join('\n')}`
|
||||
}
|
||||
|
||||
function resolveUserExtractionPrompts (existingMemories = [], presetSendMessageOption) {
|
||||
const config = ChatGPTConfig.memory?.user || {}
|
||||
const systemTemplate = config.extractionSystemPrompt || presetSendMessageOption?.systemOverride || `You are an assistant that extracts long-term personal preferences or persona details about a user.
|
||||
Given a conversation snippet between the user and the bot, identify durable information such as preferences, nicknames, roles, speaking style, habits, or other facts that remain valid over time.
|
||||
Return a JSON array of **strings**, and nothing else, without any other characters including \`\`\` or \`\`\`json. Each string must be a short sentence (in the same language as the conversation) describing one piece of long-term memory. Do not include keys, JSON objects, or additional metadata. Ignore temporary topics or uncertain information.`
|
||||
const userTemplate = config.extractionUserPrompt || `下面是用户与机器人的对话,请根据系统提示提取可长期记忆的个人信息。
|
||||
|
||||
\${messages}`
|
||||
return {
|
||||
system: `${systemTemplate}
|
||||
|
||||
${buildExistingMemorySection(existingMemories)}`,
|
||||
userTemplate
|
||||
}
|
||||
}
|
||||
|
||||
function buildUserPrompt (messages, template) {
|
||||
const body = messages.map(msg => {
|
||||
const prefix = msg.role === 'assistant' ? '机器人' : (msg.nickname || msg.user_id || '用户')
|
||||
return `${prefix}: ${msg.text}`
|
||||
}).join('\n')
|
||||
return injectMessagesIntoTemplate(template, body)
|
||||
}
|
||||
|
||||
async function callModel ({ prompt, systemPrompt, model, maxToken = 4096, temperature = 0.2, sendMessageOption }) {
|
||||
const options = sendMessageOption
|
||||
? JSON.parse(JSON.stringify(sendMessageOption))
|
||||
: {}
|
||||
options.model = model || options.model
|
||||
if (!options.model) {
|
||||
throw new Error('No model available for memory extraction call')
|
||||
}
|
||||
const resolvedModel = options.model
|
||||
const { client } = await getClientForModel(resolvedModel)
|
||||
const response = await client.sendMessage({
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: prompt
|
||||
}
|
||||
]
|
||||
}, SendMessageOption.create({
|
||||
...options,
|
||||
model: options.model,
|
||||
temperature: options.temperature ?? temperature,
|
||||
maxToken: options.maxToken ?? maxToken,
|
||||
systemOverride: systemPrompt ?? options.systemOverride,
|
||||
disableHistoryRead: true,
|
||||
disableHistorySave: true,
|
||||
stream: false
|
||||
}))
|
||||
return collectTextFromResponse(response)
|
||||
}
|
||||
|
||||
function resolveGroupExtractionModel (presetSendMessageOption) {
|
||||
const config = ChatGPTConfig.memory?.group
|
||||
if (config?.extractionModel) {
|
||||
return config.extractionModel
|
||||
}
|
||||
if (presetSendMessageOption?.model) {
|
||||
return presetSendMessageOption.model
|
||||
}
|
||||
if (ChatGPTConfig.llm?.defaultModel) {
|
||||
return ChatGPTConfig.llm.defaultModel
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function resolveUserExtractionModel (presetSendMessageOption) {
|
||||
const config = ChatGPTConfig.memory?.user
|
||||
if (config?.extractionModel) {
|
||||
return config.extractionModel
|
||||
}
|
||||
if (presetSendMessageOption?.model) {
|
||||
return presetSendMessageOption.model
|
||||
}
|
||||
if (ChatGPTConfig.llm?.defaultModel) {
|
||||
return ChatGPTConfig.llm.defaultModel
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
export async function extractGroupFacts (messages) {
|
||||
if (!messages || messages.length === 0) {
|
||||
return []
|
||||
}
|
||||
const groupConfig = ChatGPTConfig.memory?.group || {}
|
||||
const presetInfo = await resolvePresetSendMessageOption(groupConfig.extractionPresetId, 'group')
|
||||
const presetOptions = presetInfo?.sendMessageOption
|
||||
const model = resolveGroupExtractionModel(presetOptions)
|
||||
if (!model) {
|
||||
logger.warn('No model configured for group memory extraction')
|
||||
return []
|
||||
}
|
||||
try {
|
||||
const prompts = resolveGroupExtractionPrompts(presetOptions)
|
||||
logger.debug(`[Memory] start group fact extraction, messages=${messages.length}, model=${model}${presetInfo?.preset ? `, preset=${presetInfo.preset.id}` : ''}`)
|
||||
const text = await callModel({
|
||||
prompt: buildGroupUserPrompt(messages, prompts.userTemplate),
|
||||
systemPrompt: prompts.system,
|
||||
model,
|
||||
sendMessageOption: presetOptions
|
||||
})
|
||||
const parsed = parseJSON(text)
|
||||
if (Array.isArray(parsed)) {
|
||||
logger.info(`[Memory] extracted ${parsed.length} group facts`)
|
||||
parsed.slice(0, 10).forEach((item, idx) => {
|
||||
logger.debug(`[Memory] group fact[${idx}] ${formatEntry(item)}`)
|
||||
})
|
||||
return parsed
|
||||
}
|
||||
logger.debug('[Memory] group fact extraction returned non-array content')
|
||||
return []
|
||||
} catch (err) {
|
||||
logger.error('Failed to extract group facts:', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export async function extractUserMemories (messages, existingMemories = []) {
|
||||
if (!messages || messages.length === 0) {
|
||||
return []
|
||||
}
|
||||
const userConfig = ChatGPTConfig.memory?.user || {}
|
||||
const presetInfo = await resolvePresetSendMessageOption(userConfig.extractionPresetId, 'user')
|
||||
const presetOptions = presetInfo?.sendMessageOption
|
||||
const model = resolveUserExtractionModel(presetOptions)
|
||||
if (!model) {
|
||||
logger.warn('No model configured for user memory extraction')
|
||||
return []
|
||||
}
|
||||
try {
|
||||
const prompts = resolveUserExtractionPrompts(existingMemories, presetOptions)
|
||||
logger.debug(`[Memory] start user memory extraction, snippets=${messages.length}, existing=${existingMemories.length}, model=${model}${presetInfo?.preset ? `, preset=${presetInfo.preset.id}` : ''}`)
|
||||
const text = await callModel({
|
||||
prompt: buildUserPrompt(messages, prompts.userTemplate),
|
||||
systemPrompt: prompts.system,
|
||||
model,
|
||||
sendMessageOption: presetOptions
|
||||
})
|
||||
const parsed = parseJSON(text)
|
||||
if (Array.isArray(parsed)) {
|
||||
const sentences = parsed.map(item => {
|
||||
if (typeof item === 'string') {
|
||||
return item.trim()
|
||||
}
|
||||
if (item && typeof item === 'object') {
|
||||
const possible = item.sentence || item.text || item.value || item.fact
|
||||
if (possible) {
|
||||
return String(possible).trim()
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}).filter(Boolean)
|
||||
logger.info(`[Memory] extracted ${sentences.length} user memories`)
|
||||
sentences.slice(0, 10).forEach((item, idx) => {
|
||||
logger.debug(`[Memory] user memory[${idx}] ${formatEntry(item)}`)
|
||||
})
|
||||
return sentences
|
||||
}
|
||||
logger.debug('[Memory] user memory extraction returned non-array content')
|
||||
return []
|
||||
} catch (err) {
|
||||
logger.error('Failed to extract user memories:', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
61
models/memory/groupHistoryCursorStore.js
Normal file
61
models/memory/groupHistoryCursorStore.js
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { getMemoryDatabase } from './database.js'
|
||||
|
||||
function normaliseGroupId (groupId) {
|
||||
if (groupId === null || groupId === undefined) {
|
||||
return null
|
||||
}
|
||||
const str = String(groupId).trim()
|
||||
return str || null
|
||||
}
|
||||
|
||||
export class GroupHistoryCursorStore {
|
||||
constructor (db = getMemoryDatabase()) {
|
||||
this.resetDatabase(db)
|
||||
}
|
||||
|
||||
resetDatabase (db = getMemoryDatabase()) {
|
||||
this.db = db
|
||||
this.selectStmt = this.db.prepare(`
|
||||
SELECT last_message_id, last_timestamp
|
||||
FROM group_history_cursor
|
||||
WHERE group_id = ?
|
||||
`)
|
||||
this.upsertStmt = this.db.prepare(`
|
||||
INSERT INTO group_history_cursor (group_id, last_message_id, last_timestamp)
|
||||
VALUES (@group_id, @last_message_id, @last_timestamp)
|
||||
ON CONFLICT(group_id) DO UPDATE SET
|
||||
last_message_id = excluded.last_message_id,
|
||||
last_timestamp = excluded.last_timestamp
|
||||
`)
|
||||
}
|
||||
|
||||
ensureDb () {
|
||||
if (!this.db || this.db.open === false) {
|
||||
logger?.debug?.('[Memory] refreshing group history cursor database connection')
|
||||
this.resetDatabase()
|
||||
}
|
||||
return this.db
|
||||
}
|
||||
|
||||
getCursor (groupId) {
|
||||
const gid = normaliseGroupId(groupId)
|
||||
if (!gid) return null
|
||||
this.ensureDb()
|
||||
return this.selectStmt.get(gid) || null
|
||||
}
|
||||
|
||||
updateCursor (groupId, { lastMessageId = null, lastTimestamp = null } = {}) {
|
||||
const gid = normaliseGroupId(groupId)
|
||||
if (!gid) return false
|
||||
this.ensureDb()
|
||||
const payload = {
|
||||
group_id: gid,
|
||||
last_message_id: lastMessageId ? String(lastMessageId) : null,
|
||||
last_timestamp: (typeof lastTimestamp === 'number' && Number.isFinite(lastTimestamp)) ? Math.floor(lastTimestamp) : null
|
||||
}
|
||||
this.upsertStmt.run(payload)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
export const groupHistoryCursorStore = new GroupHistoryCursorStore()
|
||||
515
models/memory/groupMemoryStore.js
Normal file
515
models/memory/groupMemoryStore.js
Normal file
|
|
@ -0,0 +1,515 @@
|
|||
import { getMemoryDatabase, getVectorDimension, getGroupMemoryFtsConfig, resetVectorTableDimension, sanitiseFtsQueryInput } from './database.js'
|
||||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { embedTexts } from '../chaite/vectorizer.js'
|
||||
|
||||
function toJSONString (value) {
|
||||
if (!value) {
|
||||
return '[]'
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
return typeof value === 'string' ? value : JSON.stringify(value)
|
||||
}
|
||||
|
||||
function toVectorBuffer (vector) {
|
||||
if (!vector) {
|
||||
return null
|
||||
}
|
||||
if (vector instanceof Float32Array) {
|
||||
return Buffer.from(vector.buffer)
|
||||
}
|
||||
if (ArrayBuffer.isView(vector)) {
|
||||
return Buffer.from(new Float32Array(vector).buffer)
|
||||
}
|
||||
return Buffer.from(new Float32Array(vector).buffer)
|
||||
}
|
||||
|
||||
function normaliseEmbeddingVector (vector) {
|
||||
if (!vector) {
|
||||
return null
|
||||
}
|
||||
if (Array.isArray(vector)) {
|
||||
return vector
|
||||
}
|
||||
if (ArrayBuffer.isView(vector)) {
|
||||
return Array.from(vector)
|
||||
}
|
||||
if (typeof vector === 'object') {
|
||||
if (Array.isArray(vector.embedding)) {
|
||||
return vector.embedding
|
||||
}
|
||||
if (ArrayBuffer.isView(vector.embedding)) {
|
||||
return Array.from(vector.embedding)
|
||||
}
|
||||
if (Array.isArray(vector.vector)) {
|
||||
return vector.vector
|
||||
}
|
||||
if (ArrayBuffer.isView(vector.vector)) {
|
||||
return Array.from(vector.vector)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function normaliseGroupId (groupId) {
|
||||
return groupId === null || groupId === undefined ? null : String(groupId)
|
||||
}
|
||||
|
||||
export class GroupMemoryStore {
|
||||
constructor (db = getMemoryDatabase()) {
|
||||
this.resetDatabase(db)
|
||||
}
|
||||
|
||||
resetDatabase (db = getMemoryDatabase()) {
|
||||
this.db = db
|
||||
this.insertFactStmt = this.db.prepare(`
|
||||
INSERT INTO group_facts (group_id, fact, topic, importance, source_message_ids, source_messages, involved_users)
|
||||
VALUES (@group_id, @fact, @topic, @importance, @source_message_ids, @source_messages, @involved_users)
|
||||
ON CONFLICT(group_id, fact) DO UPDATE SET
|
||||
topic = excluded.topic,
|
||||
importance = excluded.importance,
|
||||
source_message_ids = excluded.source_message_ids,
|
||||
source_messages = excluded.source_messages,
|
||||
involved_users = excluded.involved_users,
|
||||
created_at = CASE
|
||||
WHEN excluded.importance > group_facts.importance THEN datetime('now')
|
||||
ELSE group_facts.created_at
|
||||
END
|
||||
`)
|
||||
this.prepareVectorStatements()
|
||||
this.loadFactByIdStmt = this.db.prepare('SELECT * FROM group_facts WHERE id = ?')
|
||||
}
|
||||
|
||||
prepareVectorStatements () {
|
||||
try {
|
||||
this.deleteVecStmt = this.db.prepare('DELETE FROM vec_group_facts WHERE rowid = ?')
|
||||
this.insertVecStmt = this.db.prepare('INSERT INTO vec_group_facts(rowid, embedding) VALUES (?, ?)')
|
||||
} catch (err) {
|
||||
this.deleteVecStmt = null
|
||||
this.insertVecStmt = null
|
||||
logger?.debug?.('[Memory] vector table not ready, postpone statement preparation')
|
||||
}
|
||||
}
|
||||
|
||||
ensureDb () {
|
||||
if (!this.db || this.db.open === false) {
|
||||
logger?.debug?.('[Memory] refreshing group memory database connection')
|
||||
this.resetDatabase()
|
||||
}
|
||||
return this.db
|
||||
}
|
||||
|
||||
get embeddingModel () {
|
||||
return ChatGPTConfig.llm?.embeddingModel || ''
|
||||
}
|
||||
|
||||
get retrievalMode () {
|
||||
const mode = ChatGPTConfig.memory?.group?.retrievalMode || 'hybrid'
|
||||
const lowered = String(mode).toLowerCase()
|
||||
if (['vector', 'keyword', 'hybrid'].includes(lowered)) {
|
||||
return lowered
|
||||
}
|
||||
return 'hybrid'
|
||||
}
|
||||
|
||||
get hybridPrefer () {
|
||||
const prefer = ChatGPTConfig.memory?.group?.hybridPrefer || 'vector-first'
|
||||
return prefer === 'keyword-first' ? 'keyword-first' : 'vector-first'
|
||||
}
|
||||
|
||||
isVectorEnabled () {
|
||||
return Boolean(this.embeddingModel)
|
||||
}
|
||||
|
||||
get vectorDistanceThreshold () {
|
||||
const value = Number(ChatGPTConfig.memory?.group?.vectorMaxDistance)
|
||||
if (Number.isFinite(value) && value > 0) {
|
||||
return value
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
get bm25Threshold () {
|
||||
const value = Number(ChatGPTConfig.memory?.group?.textMaxBm25Score)
|
||||
if (Number.isFinite(value) && value > 0) {
|
||||
return value
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async saveFacts (groupId, facts) {
|
||||
if (!facts || facts.length === 0) {
|
||||
return []
|
||||
}
|
||||
this.ensureDb()
|
||||
const normGroupId = normaliseGroupId(groupId)
|
||||
const filteredFacts = facts
|
||||
.map(f => {
|
||||
const rawFact = typeof f.fact === 'string' ? f.fact : (Array.isArray(f.fact) ? f.fact.join(' ') : String(f.fact || ''))
|
||||
const rawTopic = typeof f.topic === 'string' ? f.topic : (f.topic === undefined || f.topic === null ? '' : String(f.topic))
|
||||
const rawSourceMessages = f.source_messages ?? f.sourceMessages ?? ''
|
||||
const sourceMessages = Array.isArray(rawSourceMessages)
|
||||
? rawSourceMessages.map(item => (item === null || item === undefined) ? '' : String(item)).filter(Boolean).join('\n')
|
||||
: (typeof rawSourceMessages === 'string' ? rawSourceMessages : String(rawSourceMessages || ''))
|
||||
return {
|
||||
fact: rawFact.trim(),
|
||||
topic: rawTopic.trim(),
|
||||
importance: typeof f.importance === 'number' ? f.importance : Number(f.importance) || 0.5,
|
||||
source_message_ids: toJSONString(f.source_message_ids || f.sourceMessages),
|
||||
source_messages: sourceMessages,
|
||||
involved_users: toJSONString(f.involved_users || f.involvedUsers || [])
|
||||
}
|
||||
})
|
||||
.filter(item => item.fact)
|
||||
|
||||
if (filteredFacts.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
let vectors = []
|
||||
let tableDimension = getVectorDimension() || 0
|
||||
const configuredDimension = Number(ChatGPTConfig.llm?.dimensions || 0)
|
||||
if (this.isVectorEnabled()) {
|
||||
try {
|
||||
const preferredDimension = configuredDimension > 0
|
||||
? configuredDimension
|
||||
: (tableDimension > 0 ? tableDimension : undefined)
|
||||
vectors = await embedTexts(filteredFacts.map(f => f.fact), this.embeddingModel, preferredDimension)
|
||||
vectors = vectors.map(normaliseEmbeddingVector)
|
||||
const mismatchVector = vectors.find(vec => {
|
||||
if (!vec) return false
|
||||
if (Array.isArray(vec)) return vec.length > 0
|
||||
if (ArrayBuffer.isView(vec) && typeof vec.length === 'number') {
|
||||
return vec.length > 0
|
||||
}
|
||||
return false
|
||||
})
|
||||
const actualDimension = mismatchVector ? mismatchVector.length : 0
|
||||
if (actualDimension && actualDimension !== tableDimension) {
|
||||
const expectedDimension = tableDimension || preferredDimension || configuredDimension || 'unknown'
|
||||
logger.warn(`[Memory] embedding dimension mismatch, expected=${expectedDimension}, actual=${actualDimension}. Recreating vector table.`)
|
||||
try {
|
||||
resetVectorTableDimension(actualDimension)
|
||||
this.prepareVectorStatements()
|
||||
tableDimension = actualDimension
|
||||
} catch (resetErr) {
|
||||
logger.error('Failed to reset vector table dimension:', resetErr)
|
||||
vectors = []
|
||||
}
|
||||
} else if (actualDimension && tableDimension <= 0) {
|
||||
try {
|
||||
resetVectorTableDimension(actualDimension)
|
||||
this.prepareVectorStatements()
|
||||
tableDimension = actualDimension
|
||||
} catch (resetErr) {
|
||||
logger.error('Failed to initialise vector table dimension:', resetErr)
|
||||
vectors = []
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error('Failed to embed group facts:', err)
|
||||
vectors = []
|
||||
}
|
||||
}
|
||||
|
||||
const transaction = this.db.transaction((items, vectorList) => {
|
||||
const saved = []
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const payload = {
|
||||
group_id: normGroupId,
|
||||
...items[i]
|
||||
}
|
||||
const info = this.insertFactStmt.run(payload)
|
||||
let factId = Number(info.lastInsertRowid)
|
||||
if (!factId) {
|
||||
const existing = this.db.prepare('SELECT id FROM group_facts WHERE group_id = ? AND fact = ?').get(normGroupId, payload.fact)
|
||||
factId = existing?.id
|
||||
}
|
||||
factId = Number.parseInt(String(factId ?? ''), 10)
|
||||
if (!Number.isSafeInteger(factId)) {
|
||||
logger.warn('[Memory] skip fact vector upsert due to invalid fact id', factId)
|
||||
continue
|
||||
}
|
||||
if (!factId) {
|
||||
continue
|
||||
}
|
||||
if (Array.isArray(vectorList) && vectorList[i]) {
|
||||
if (!this.deleteVecStmt || !this.insertVecStmt) {
|
||||
this.prepareVectorStatements()
|
||||
}
|
||||
if (!this.deleteVecStmt || !this.insertVecStmt) {
|
||||
logger.warn('[Memory] vector table unavailable, skip vector upsert')
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const vector = normaliseEmbeddingVector(vectorList[i])
|
||||
if (!vector) {
|
||||
continue
|
||||
}
|
||||
let embeddingArray
|
||||
if (ArrayBuffer.isView(vector)) {
|
||||
if (vector instanceof Float32Array) {
|
||||
embeddingArray = vector
|
||||
} else {
|
||||
embeddingArray = new Float32Array(vector.length)
|
||||
for (let idx = 0; idx < vector.length; idx++) {
|
||||
embeddingArray[idx] = Number(vector[idx])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
embeddingArray = Float32Array.from(vector)
|
||||
}
|
||||
const rowId = BigInt(factId)
|
||||
logger.debug(`[Memory] upserting vector for fact ${factId}, rowIdType=${typeof rowId}`)
|
||||
this.deleteVecStmt.run(rowId)
|
||||
this.insertVecStmt.run(rowId, embeddingArray)
|
||||
} catch (error) {
|
||||
logger.error(`Failed to upsert vector for fact ${factId}:`, error)
|
||||
}
|
||||
}
|
||||
saved.push(this.loadFactByIdStmt.get(factId))
|
||||
}
|
||||
return saved
|
||||
})
|
||||
|
||||
return transaction(filteredFacts, vectors)
|
||||
}
|
||||
|
||||
listFacts (groupId, limit = 50, offset = 0) {
|
||||
return this.db.prepare(`
|
||||
SELECT * FROM group_facts
|
||||
WHERE group_id = ?
|
||||
ORDER BY importance DESC, created_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`).all(normaliseGroupId(groupId), limit, offset)
|
||||
}
|
||||
|
||||
deleteFact (groupId, factId) {
|
||||
this.ensureDb()
|
||||
const normGroupId = normaliseGroupId(groupId)
|
||||
const fact = this.db.prepare('SELECT id FROM group_facts WHERE id = ? AND group_id = ?').get(factId, normGroupId)
|
||||
if (!fact) {
|
||||
return false
|
||||
}
|
||||
this.db.prepare('DELETE FROM group_facts WHERE id = ?').run(factId)
|
||||
try {
|
||||
this.deleteVecStmt.run(BigInt(factId))
|
||||
} catch (err) {
|
||||
logger?.warn?.(`[Memory] failed to delete vector for fact ${factId}:`, err)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async vectorSearch (groupId, queryText, limit) {
|
||||
this.ensureDb()
|
||||
if (!this.isVectorEnabled()) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
let tableDimension = getVectorDimension() || 0
|
||||
if (!tableDimension || tableDimension <= 0) {
|
||||
logger.debug('[Memory] vector table dimension unavailable, attempting to infer from embedding')
|
||||
}
|
||||
const requestedDimension = tableDimension > 0 ? tableDimension : undefined
|
||||
const [embedding] = await embedTexts([queryText], this.embeddingModel, requestedDimension)
|
||||
if (!embedding) {
|
||||
return []
|
||||
}
|
||||
const embeddingVector = ArrayBuffer.isView(embedding) ? embedding : Float32Array.from(embedding)
|
||||
const actualDimension = embeddingVector.length
|
||||
if (!actualDimension) {
|
||||
logger.debug('[Memory] vector search skipped: empty embedding returned')
|
||||
return []
|
||||
}
|
||||
if (tableDimension > 0 && actualDimension !== tableDimension) {
|
||||
logger.warn(`[Memory] vector dimension mismatch detected during search, table=${tableDimension}, embedding=${actualDimension}. Rebuilding vector table.`)
|
||||
try {
|
||||
resetVectorTableDimension(actualDimension)
|
||||
this.prepareVectorStatements()
|
||||
tableDimension = actualDimension
|
||||
} catch (resetErr) {
|
||||
logger.error('Failed to reset vector table dimension during search:', resetErr)
|
||||
return []
|
||||
}
|
||||
logger.info('[Memory] vector table rebuilt; old vectors must be regenerated before vector search can return results')
|
||||
return []
|
||||
} else if (tableDimension <= 0 && actualDimension > 0) {
|
||||
try {
|
||||
resetVectorTableDimension(actualDimension)
|
||||
this.prepareVectorStatements()
|
||||
tableDimension = actualDimension
|
||||
} catch (resetErr) {
|
||||
logger.error('Failed to initialise vector table dimension during search:', resetErr)
|
||||
return []
|
||||
}
|
||||
}
|
||||
const rows = this.db.prepare(`
|
||||
SELECT gf.*, vec_group_facts.distance AS distance
|
||||
FROM vec_group_facts
|
||||
JOIN group_facts gf ON gf.id = vec_group_facts.rowid
|
||||
WHERE gf.group_id = ?
|
||||
AND vec_group_facts.embedding MATCH ?
|
||||
AND vec_group_facts.k = ${limit}
|
||||
ORDER BY distance ASC
|
||||
`).all(groupId, embeddingVector)
|
||||
const threshold = this.vectorDistanceThreshold
|
||||
if (!threshold) {
|
||||
return rows
|
||||
}
|
||||
return rows.filter(row => typeof row?.distance === 'number' && row.distance <= threshold)
|
||||
} catch (err) {
|
||||
logger.warn('Vector search failed for group memory:', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
textSearch (groupId, queryText, limit) {
|
||||
this.ensureDb()
|
||||
if (!queryText || !queryText.trim()) {
|
||||
return []
|
||||
}
|
||||
const originalQuery = queryText.trim()
|
||||
const ftsConfig = getGroupMemoryFtsConfig()
|
||||
const matchQueryParam = sanitiseFtsQueryInput(originalQuery, ftsConfig)
|
||||
const results = []
|
||||
const seen = new Set()
|
||||
if (matchQueryParam) {
|
||||
const matchExpression = ftsConfig.matchQuery ? `${ftsConfig.matchQuery}(?)` : '?'
|
||||
try {
|
||||
const rows = this.db.prepare(`
|
||||
SELECT gf.*, bm25(group_facts_fts) AS bm25_score
|
||||
FROM group_facts_fts
|
||||
JOIN group_facts gf ON gf.id = group_facts_fts.rowid
|
||||
WHERE gf.group_id = ?
|
||||
AND group_facts_fts MATCH ${matchExpression}
|
||||
ORDER BY bm25_score ASC
|
||||
LIMIT ?
|
||||
`).all(groupId, matchQueryParam, limit)
|
||||
for (const row of rows) {
|
||||
const bm25Threshold = this.bm25Threshold
|
||||
if (bm25Threshold) {
|
||||
const score = Number(row?.bm25_score)
|
||||
if (!Number.isFinite(score) || score > bm25Threshold) {
|
||||
continue
|
||||
}
|
||||
row.bm25_score = score
|
||||
}
|
||||
if (row && !seen.has(row.id)) {
|
||||
results.push(row)
|
||||
seen.add(row.id)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Text search failed for group memory:', err)
|
||||
}
|
||||
} else {
|
||||
logger.debug('[Memory] group memory text search skipped MATCH due to empty query after sanitisation')
|
||||
}
|
||||
|
||||
if (results.length < limit) {
|
||||
try {
|
||||
const likeRows = this.db.prepare(`
|
||||
SELECT *
|
||||
FROM group_facts
|
||||
WHERE group_id = ?
|
||||
AND instr(fact, ?) > 0
|
||||
ORDER BY importance DESC, created_at DESC
|
||||
LIMIT ?
|
||||
`).all(groupId, originalQuery, Math.max(limit * 2, limit))
|
||||
for (const row of likeRows) {
|
||||
if (row && !seen.has(row.id)) {
|
||||
results.push(row)
|
||||
seen.add(row.id)
|
||||
if (results.length >= limit) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('LIKE fallback failed for group memory:', err)
|
||||
}
|
||||
}
|
||||
|
||||
return results.slice(0, limit)
|
||||
}
|
||||
|
||||
importanceFallback (groupId, limit, minImportance, excludeIds = []) {
|
||||
this.ensureDb()
|
||||
const ids = excludeIds.filter(Boolean)
|
||||
const notInClause = ids.length ? `AND id NOT IN (${ids.map(() => '?').join(',')})` : ''
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM group_facts
|
||||
WHERE group_id = ?
|
||||
AND importance >= ?
|
||||
${notInClause}
|
||||
ORDER BY importance DESC, created_at DESC
|
||||
LIMIT ?
|
||||
`)
|
||||
const params = [groupId, minImportance]
|
||||
if (ids.length) {
|
||||
params.push(...ids)
|
||||
}
|
||||
params.push(limit)
|
||||
return stmt.all(...params)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取相关群记忆,支持向量/文本/混合检索
|
||||
* @param {string} groupId
|
||||
* @param {string} queryText
|
||||
* @param {{ limit?: number, minImportance?: number }} options
|
||||
* @returns {Promise<Array<{fact: string, topic: string, importance: number, created_at: string}>>}
|
||||
*/
|
||||
async queryRelevantFacts (groupId, queryText, options = {}) {
|
||||
const { limit = 5, minImportance = 0 } = options
|
||||
const normGroupId = normaliseGroupId(groupId)
|
||||
if (!queryText) {
|
||||
return this.listFacts(normGroupId, limit)
|
||||
}
|
||||
|
||||
const mode = this.retrievalMode
|
||||
const combined = []
|
||||
const seen = new Set()
|
||||
const append = rows => {
|
||||
for (const row of rows) {
|
||||
if (!row || seen.has(row.id)) {
|
||||
continue
|
||||
}
|
||||
combined.push(row)
|
||||
seen.add(row.id)
|
||||
if (combined.length >= limit) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const preferVector = this.hybridPrefer !== 'keyword-first'
|
||||
|
||||
if (mode === 'vector' || mode === 'hybrid') {
|
||||
const vectorRows = await this.vectorSearch(normGroupId, queryText, limit)
|
||||
if (mode === 'vector') {
|
||||
append(vectorRows)
|
||||
} else if (preferVector) {
|
||||
append(vectorRows)
|
||||
if (combined.length < limit) {
|
||||
append(this.textSearch(normGroupId, queryText, limit))
|
||||
}
|
||||
} else {
|
||||
append(this.textSearch(normGroupId, queryText, limit))
|
||||
if (combined.length < limit) {
|
||||
append(vectorRows)
|
||||
}
|
||||
}
|
||||
} else if (mode === 'keyword') {
|
||||
append(this.textSearch(normGroupId, queryText, limit))
|
||||
}
|
||||
|
||||
if (combined.length < limit) {
|
||||
const fallback = this.importanceFallback(normGroupId, limit - combined.length, minImportance, Array.from(seen))
|
||||
append(fallback)
|
||||
}
|
||||
|
||||
return combined.slice(0, limit)
|
||||
}
|
||||
}
|
||||
128
models/memory/prompt.js
Normal file
128
models/memory/prompt.js
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { memoryService } from './service.js'
|
||||
|
||||
function renderTemplate (template, context = {}) {
|
||||
if (!template) {
|
||||
return ''
|
||||
}
|
||||
return template.replace(/\$\{(\w+)\}/g, (_, key) => {
|
||||
const value = context[key]
|
||||
return value === undefined || value === null ? '' : String(value)
|
||||
})
|
||||
}
|
||||
|
||||
function formatUserMemories (memories, config) {
|
||||
if (!memories.length) {
|
||||
return ''
|
||||
}
|
||||
const headerTemplate = config.promptHeader ?? '# 用户画像'
|
||||
const itemTemplate = config.promptItemTemplate ?? '- ${value}'
|
||||
const footerTemplate = config.promptFooter ?? ''
|
||||
const segments = []
|
||||
const header = renderTemplate(headerTemplate, { count: memories.length })
|
||||
if (header) {
|
||||
segments.push(header)
|
||||
}
|
||||
memories.forEach((item, index) => {
|
||||
const timestamp = item.updated_at || item.created_at || ''
|
||||
const timeSuffix = timestamp ? `(记录时间:${timestamp})` : ''
|
||||
const context = {
|
||||
index,
|
||||
order: index + 1,
|
||||
value: item.value || '',
|
||||
importance: item.importance ?? '',
|
||||
sourceMessageId: item.source_message_id || '',
|
||||
sourceId: item.source_message_id || '',
|
||||
groupId: item.group_id || '',
|
||||
createdAt: item.created_at || '',
|
||||
updatedAt: item.updated_at || '',
|
||||
timestamp,
|
||||
time: timestamp,
|
||||
timeSuffix
|
||||
}
|
||||
const line = renderTemplate(itemTemplate, context)
|
||||
if (line) {
|
||||
segments.push(line)
|
||||
}
|
||||
})
|
||||
const footer = renderTemplate(footerTemplate, { count: memories.length })
|
||||
if (footer) {
|
||||
segments.push(footer)
|
||||
}
|
||||
return segments.join('\n')
|
||||
}
|
||||
|
||||
function formatGroupFacts (facts, config) {
|
||||
if (!facts.length) {
|
||||
return ''
|
||||
}
|
||||
const headerTemplate = config.promptHeader ?? '# 群聊长期记忆'
|
||||
const itemTemplate = config.promptItemTemplate ?? '- ${fact}${topicSuffix}'
|
||||
const footerTemplate = config.promptFooter ?? ''
|
||||
const segments = []
|
||||
const header = renderTemplate(headerTemplate, { count: facts.length })
|
||||
if (header) {
|
||||
segments.push(header)
|
||||
}
|
||||
facts.forEach((item, index) => {
|
||||
const topicSuffix = item.topic ? `(${item.topic})` : ''
|
||||
const timestamp = item.updated_at || item.created_at || ''
|
||||
const timeSuffix = timestamp ? `(记录时间:${timestamp})` : ''
|
||||
const context = {
|
||||
index,
|
||||
order: index + 1,
|
||||
fact: item.fact || '',
|
||||
topic: item.topic || '',
|
||||
topicSuffix,
|
||||
importance: item.importance ?? '',
|
||||
createdAt: item.created_at || '',
|
||||
updatedAt: item.updated_at || '',
|
||||
timestamp,
|
||||
time: timestamp,
|
||||
timeSuffix,
|
||||
distance: item.distance ?? '',
|
||||
bm25: item.bm25_score ?? '',
|
||||
sourceMessages: item.source_messages || '',
|
||||
sourceMessageIds: item.source_message_ids || ''
|
||||
}
|
||||
const line = renderTemplate(itemTemplate, context)
|
||||
if (line) {
|
||||
segments.push(line)
|
||||
}
|
||||
})
|
||||
const footer = renderTemplate(footerTemplate, { count: facts.length })
|
||||
if (footer) {
|
||||
segments.push(footer)
|
||||
}
|
||||
return segments.join('\n')
|
||||
}
|
||||
|
||||
export async function buildMemoryPrompt ({ userId, groupId, queryText }) {
|
||||
const segments = []
|
||||
const userConfig = ChatGPTConfig.memory?.user || {}
|
||||
const groupConfig = ChatGPTConfig.memory?.group || {}
|
||||
if (memoryService.isUserMemoryEnabled(userId)) {
|
||||
const totalLimit = userConfig.maxItemsPerInjection || 5
|
||||
const searchLimit = Math.min(userConfig.maxRelevantItemsPerQuery || totalLimit, totalLimit)
|
||||
const userMemories = memoryService.queryUserMemories(userId, groupId, queryText, {
|
||||
totalLimit,
|
||||
searchLimit,
|
||||
minImportance: userConfig.minImportanceForInjection ?? 0
|
||||
})
|
||||
const userSegment = formatUserMemories(userMemories, userConfig)
|
||||
if (userSegment) {
|
||||
segments.push(userSegment)
|
||||
}
|
||||
}
|
||||
if (groupId && memoryService.isGroupMemoryEnabled(groupId)) {
|
||||
const facts = await memoryService.queryGroupFacts(groupId, queryText, {
|
||||
limit: groupConfig.maxFactsPerInjection || 5,
|
||||
minImportance: groupConfig.minImportanceForInjection || 0
|
||||
})
|
||||
const groupSegment = formatGroupFacts(facts, groupConfig)
|
||||
if (groupSegment) {
|
||||
segments.push(groupSegment)
|
||||
}
|
||||
}
|
||||
return segments.join('\n\n').trim()
|
||||
}
|
||||
726
models/memory/router.js
Normal file
726
models/memory/router.js
Normal file
|
|
@ -0,0 +1,726 @@
|
|||
import express from 'express'
|
||||
import fs from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import https from 'https'
|
||||
import { pipeline } from 'stream'
|
||||
import { promisify } from 'util'
|
||||
let AdmZip
|
||||
try {
|
||||
AdmZip = (await import('adm-zip')).default
|
||||
} catch (e) {
|
||||
logger.warn('Failed to load AdmZip, maybe you need to install it manually:', e)
|
||||
}
|
||||
import { execSync } from "child_process"
|
||||
import {
|
||||
Chaite,
|
||||
ChaiteResponse,
|
||||
FrontEndAuthHandler
|
||||
} from 'chaite'
|
||||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { memoryService } from './service.js'
|
||||
import {
|
||||
resetCachedDimension,
|
||||
resetMemoryDatabaseInstance,
|
||||
getSimpleExtensionState,
|
||||
resolvePluginPath,
|
||||
toPluginRelativePath,
|
||||
resetVectorTableDimension
|
||||
} from './database.js'
|
||||
|
||||
const streamPipeline = promisify(pipeline)
|
||||
|
||||
const SIMPLE_DOWNLOAD_BASE_URL = 'https://github.com/wangfenjin/simple/releases/latest/download'
|
||||
const SIMPLE_ASSET_MAP = {
|
||||
'linux-x64': 'libsimple-linux-ubuntu-latest.zip',
|
||||
'linux-arm64': 'libsimple-linux-ubuntu-24.04-arm.zip',
|
||||
'linux-arm': 'libsimple-linux-ubuntu-24.04-arm.zip',
|
||||
'darwin-x64': 'libsimple-osx-x64.zip',
|
||||
'darwin-arm64': 'libsimple-osx-x64.zip',
|
||||
'win32-x64': 'libsimple-windows-x64.zip',
|
||||
'win32-ia32': 'libsimple-windows-x86.zip',
|
||||
'win32-arm64': 'libsimple-windows-arm64.zip'
|
||||
}
|
||||
const DEFAULT_SIMPLE_INSTALL_DIR = 'resources/simple'
|
||||
|
||||
export function authenticateMemoryRequest (req, res, next) {
|
||||
const bearer = req.header('Authorization') || ''
|
||||
const token = bearer.replace(/^Bearer\s+/i, '').trim()
|
||||
if (!token) {
|
||||
res.status(401).json({ message: 'Access denied, token missing' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const authKey = Chaite.getInstance()?.getGlobalConfig()?.getAuthKey()
|
||||
if (authKey && FrontEndAuthHandler.validateJWT(authKey, token)) {
|
||||
next()
|
||||
return
|
||||
}
|
||||
res.status(401).json({ message: 'Invalid token' })
|
||||
} catch (error) {
|
||||
res.status(401).json({ message: 'Invalid token format' })
|
||||
}
|
||||
}
|
||||
|
||||
function parsePositiveInt (value, fallback) {
|
||||
const num = Number(value)
|
||||
return Number.isInteger(num) && num >= 0 ? num : fallback
|
||||
}
|
||||
|
||||
function parseNumber (value, fallback) {
|
||||
const num = Number(value)
|
||||
return Number.isFinite(num) ? num : fallback
|
||||
}
|
||||
|
||||
function toStringArray (value) {
|
||||
if (!Array.isArray(value)) {
|
||||
return []
|
||||
}
|
||||
return value
|
||||
.map(item => {
|
||||
if (item === undefined || item === null) {
|
||||
return null
|
||||
}
|
||||
return String(item).trim()
|
||||
})
|
||||
.filter(item => item)
|
||||
}
|
||||
|
||||
function parseOptionalStringParam (value) {
|
||||
if (Array.isArray(value)) {
|
||||
value = value[0]
|
||||
}
|
||||
if (value === undefined || value === null) {
|
||||
return null
|
||||
}
|
||||
const trimmed = String(value).trim()
|
||||
if (!trimmed || trimmed.toLowerCase() === 'null' || trimmed.toLowerCase() === 'undefined') {
|
||||
return null
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function detectAssetKey (platform, arch) {
|
||||
const normalizedArch = arch === 'arm64' ? 'arm64' : (arch === 'arm' ? 'arm' : (arch === 'ia32' ? 'ia32' : 'x64'))
|
||||
const key = `${platform}-${normalizedArch}`
|
||||
if (SIMPLE_ASSET_MAP[key]) {
|
||||
return key
|
||||
}
|
||||
if (platform === 'darwin' && SIMPLE_ASSET_MAP['darwin-x64']) {
|
||||
return 'darwin-x64'
|
||||
}
|
||||
if (platform === 'linux' && SIMPLE_ASSET_MAP['linux-x64']) {
|
||||
return 'linux-x64'
|
||||
}
|
||||
if (platform === 'win32' && SIMPLE_ASSET_MAP['win32-x64']) {
|
||||
return 'win32-x64'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function resolveSimpleAsset (requestedKey, requestedAsset) {
|
||||
if (requestedAsset) {
|
||||
return {
|
||||
key: requestedKey || 'custom',
|
||||
asset: requestedAsset
|
||||
}
|
||||
}
|
||||
if (requestedKey && SIMPLE_ASSET_MAP[requestedKey]) {
|
||||
return {
|
||||
key: requestedKey,
|
||||
asset: SIMPLE_ASSET_MAP[requestedKey]
|
||||
}
|
||||
}
|
||||
const autoKey = detectAssetKey(process.platform, process.arch)
|
||||
if (autoKey && SIMPLE_ASSET_MAP[autoKey]) {
|
||||
return { key: autoKey, asset: SIMPLE_ASSET_MAP[autoKey] }
|
||||
}
|
||||
return { key: null, asset: null }
|
||||
}
|
||||
|
||||
function ensureDirectoryExists (dirPath) {
|
||||
if (!fs.existsSync(dirPath)) {
|
||||
fs.mkdirSync(dirPath, { recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadToFile (url, destination, redirectCount = 0) {
|
||||
if (redirectCount > 5) {
|
||||
throw new Error('Too many redirects while downloading extension')
|
||||
}
|
||||
await new Promise((resolve, reject) => {
|
||||
const request = https.get(url, {
|
||||
headers: {
|
||||
'User-Agent': 'chatgpt-plugin-memory-extension-downloader'
|
||||
}
|
||||
}, async res => {
|
||||
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
res.resume()
|
||||
try {
|
||||
await downloadToFile(res.headers.location, destination, redirectCount + 1)
|
||||
resolve()
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
reject(new Error(`Failed to download extension: HTTP ${res.statusCode}`))
|
||||
res.resume()
|
||||
return
|
||||
}
|
||||
const fileStream = fs.createWriteStream(destination)
|
||||
streamPipeline(res, fileStream).then(resolve).catch(reject)
|
||||
})
|
||||
request.on('error', error => reject(error))
|
||||
})
|
||||
}
|
||||
|
||||
function removeDirectoryIfExists (dirPath) {
|
||||
if (fs.existsSync(dirPath)) {
|
||||
fs.rmSync(dirPath, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function findLibraryFile (rootDir) {
|
||||
const entries = fs.readdirSync(rootDir, { withFileTypes: true })
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(rootDir, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
const found = findLibraryFile(fullPath)
|
||||
if (found) {
|
||||
return found
|
||||
}
|
||||
} else if (/simple\.(so|dylib|dll)$/i.test(entry.name) || /^libsimple/i.test(entry.name)) {
|
||||
return fullPath
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function findDictDirectory (rootDir) {
|
||||
const directDictPath = path.join(rootDir, 'dict')
|
||||
if (fs.existsSync(directDictPath) && fs.statSync(directDictPath).isDirectory()) {
|
||||
return directDictPath
|
||||
}
|
||||
const entries = fs.readdirSync(rootDir, { withFileTypes: true })
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory()) {
|
||||
const match = findDictDirectory(path.join(rootDir, entry.name))
|
||||
if (match) {
|
||||
return match
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function downloadSimpleExtensionArchive ({ assetKey, assetName, targetDir }) {
|
||||
if (!assetName) {
|
||||
throw new Error('Simple extension asset name is required.')
|
||||
}
|
||||
const downloadUrl = `${SIMPLE_DOWNLOAD_BASE_URL}/${assetName}`
|
||||
const tempFile = path.join(os.tmpdir(), `libsimple-${Date.now()}-${Math.random().toString(16).slice(2)}.zip`)
|
||||
ensureDirectoryExists(path.dirname(tempFile))
|
||||
await downloadToFile(downloadUrl, tempFile)
|
||||
removeDirectoryIfExists(targetDir)
|
||||
ensureDirectoryExists(targetDir)
|
||||
if (AdmZip) {
|
||||
try {
|
||||
const zip = new AdmZip(tempFile)
|
||||
zip.extractAllTo(targetDir, true)
|
||||
} finally {
|
||||
if (fs.existsSync(tempFile)) {
|
||||
fs.unlinkSync(tempFile)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 尝试使用 unzip 命令解压
|
||||
try {
|
||||
execSync(`unzip "${tempFile}" -d "${targetDir}"`, { stdio: 'inherit' })
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to extract zip file: ${error.message}. Please install adm-zip manually: pnpm i`)
|
||||
} finally {
|
||||
if (fs.existsSync(tempFile)) {
|
||||
fs.unlinkSync(tempFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const libraryFile = findLibraryFile(targetDir)
|
||||
if (!libraryFile) {
|
||||
throw new Error('Downloaded extension package does not contain libsimple library.')
|
||||
}
|
||||
const dictDir = findDictDirectory(targetDir)
|
||||
if (!ChatGPTConfig.memory.extensions) {
|
||||
ChatGPTConfig.memory.extensions = {}
|
||||
}
|
||||
if (!ChatGPTConfig.memory.extensions.simple) {
|
||||
ChatGPTConfig.memory.extensions.simple = {
|
||||
enable: false,
|
||||
libraryPath: '',
|
||||
dictPath: '',
|
||||
useJieba: false
|
||||
}
|
||||
}
|
||||
const relativeLibraryPath = toPluginRelativePath(libraryFile)
|
||||
const relativeDictPath = dictDir ? toPluginRelativePath(dictDir) : ''
|
||||
ChatGPTConfig.memory.extensions.simple.libraryPath = relativeLibraryPath
|
||||
ChatGPTConfig.memory.extensions.simple.dictPath = relativeDictPath
|
||||
return {
|
||||
assetKey,
|
||||
assetName,
|
||||
installDir: toPluginRelativePath(targetDir),
|
||||
libraryPath: relativeLibraryPath,
|
||||
dictPath: ChatGPTConfig.memory.extensions.simple.dictPath
|
||||
}
|
||||
}
|
||||
|
||||
function updateMemoryConfig (payload = {}) {
|
||||
const current = ChatGPTConfig.memory || {}
|
||||
const previousDatabase = current.database
|
||||
const previousDimension = current.vectorDimensions
|
||||
|
||||
const nextConfig = {
|
||||
...current,
|
||||
group: {
|
||||
...(current.group || {})
|
||||
},
|
||||
user: {
|
||||
...(current.user || {})
|
||||
},
|
||||
extensions: {
|
||||
...(current.extensions || {}),
|
||||
simple: {
|
||||
...(current.extensions?.simple || {})
|
||||
}
|
||||
}
|
||||
}
|
||||
const previousSimpleConfig = JSON.stringify(current.extensions?.simple || {})
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(payload, 'database') && typeof payload.database === 'string') {
|
||||
nextConfig.database = payload.database.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(payload, 'vectorDimensions')) {
|
||||
const dimension = parsePositiveInt(payload.vectorDimensions, current.vectorDimensions || 1536)
|
||||
if (dimension > 0) {
|
||||
nextConfig.vectorDimensions = dimension
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.group && typeof payload.group === 'object') {
|
||||
const incomingGroup = payload.group
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'enable')) {
|
||||
nextConfig.group.enable = Boolean(incomingGroup.enable)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'enabledGroups')) {
|
||||
nextConfig.group.enabledGroups = toStringArray(incomingGroup.enabledGroups)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'extractionModel') && typeof incomingGroup.extractionModel === 'string') {
|
||||
nextConfig.group.extractionModel = incomingGroup.extractionModel.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'extractionPresetId') && typeof incomingGroup.extractionPresetId === 'string') {
|
||||
nextConfig.group.extractionPresetId = incomingGroup.extractionPresetId.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'minMessageCount')) {
|
||||
nextConfig.group.minMessageCount = parsePositiveInt(incomingGroup.minMessageCount, nextConfig.group.minMessageCount || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'maxMessageWindow')) {
|
||||
nextConfig.group.maxMessageWindow = parsePositiveInt(incomingGroup.maxMessageWindow, nextConfig.group.maxMessageWindow || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'retrievalMode')) {
|
||||
const mode = String(incomingGroup.retrievalMode || '').toLowerCase()
|
||||
if (['vector', 'keyword', 'hybrid'].includes(mode)) {
|
||||
nextConfig.group.retrievalMode = mode
|
||||
}
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'hybridPrefer')) {
|
||||
const prefer = String(incomingGroup.hybridPrefer || '').toLowerCase()
|
||||
if (prefer === 'keyword-first') {
|
||||
nextConfig.group.hybridPrefer = 'keyword-first'
|
||||
} else if (prefer === 'vector-first') {
|
||||
nextConfig.group.hybridPrefer = 'vector-first'
|
||||
}
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'historyPollInterval')) {
|
||||
nextConfig.group.historyPollInterval = parsePositiveInt(incomingGroup.historyPollInterval,
|
||||
nextConfig.group.historyPollInterval || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'historyBatchSize')) {
|
||||
nextConfig.group.historyBatchSize = parsePositiveInt(incomingGroup.historyBatchSize,
|
||||
nextConfig.group.historyBatchSize || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'promptHeader') && typeof incomingGroup.promptHeader === 'string') {
|
||||
nextConfig.group.promptHeader = incomingGroup.promptHeader
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'promptItemTemplate') && typeof incomingGroup.promptItemTemplate === 'string') {
|
||||
nextConfig.group.promptItemTemplate = incomingGroup.promptItemTemplate
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'promptFooter') && typeof incomingGroup.promptFooter === 'string') {
|
||||
nextConfig.group.promptFooter = incomingGroup.promptFooter
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'vectorMaxDistance')) {
|
||||
const distance = parseNumber(incomingGroup.vectorMaxDistance,
|
||||
nextConfig.group.vectorMaxDistance ?? 0)
|
||||
nextConfig.group.vectorMaxDistance = distance
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'textMaxBm25Score')) {
|
||||
const bm25 = parseNumber(incomingGroup.textMaxBm25Score,
|
||||
nextConfig.group.textMaxBm25Score ?? 0)
|
||||
nextConfig.group.textMaxBm25Score = bm25
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'maxFactsPerInjection')) {
|
||||
nextConfig.group.maxFactsPerInjection = parsePositiveInt(incomingGroup.maxFactsPerInjection,
|
||||
nextConfig.group.maxFactsPerInjection || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingGroup, 'minImportanceForInjection')) {
|
||||
const importance = parseNumber(incomingGroup.minImportanceForInjection,
|
||||
nextConfig.group.minImportanceForInjection ?? 0)
|
||||
nextConfig.group.minImportanceForInjection = importance
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.user && typeof payload.user === 'object') {
|
||||
const incomingUser = payload.user
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'enable')) {
|
||||
nextConfig.user.enable = Boolean(incomingUser.enable)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'whitelist')) {
|
||||
nextConfig.user.whitelist = toStringArray(incomingUser.whitelist)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'blacklist')) {
|
||||
nextConfig.user.blacklist = toStringArray(incomingUser.blacklist)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'extractionModel') && typeof incomingUser.extractionModel === 'string') {
|
||||
nextConfig.user.extractionModel = incomingUser.extractionModel.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'extractionPresetId') && typeof incomingUser.extractionPresetId === 'string') {
|
||||
nextConfig.user.extractionPresetId = incomingUser.extractionPresetId.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'maxItemsPerInjection')) {
|
||||
nextConfig.user.maxItemsPerInjection = parsePositiveInt(incomingUser.maxItemsPerInjection,
|
||||
nextConfig.user.maxItemsPerInjection || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'maxRelevantItemsPerQuery')) {
|
||||
nextConfig.user.maxRelevantItemsPerQuery = parsePositiveInt(incomingUser.maxRelevantItemsPerQuery,
|
||||
nextConfig.user.maxRelevantItemsPerQuery || 0)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'minImportanceForInjection')) {
|
||||
const importance = parseNumber(incomingUser.minImportanceForInjection,
|
||||
nextConfig.user.minImportanceForInjection ?? 0)
|
||||
nextConfig.user.minImportanceForInjection = importance
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'promptHeader') && typeof incomingUser.promptHeader === 'string') {
|
||||
nextConfig.user.promptHeader = incomingUser.promptHeader
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'promptItemTemplate') && typeof incomingUser.promptItemTemplate === 'string') {
|
||||
nextConfig.user.promptItemTemplate = incomingUser.promptItemTemplate
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingUser, 'promptFooter') && typeof incomingUser.promptFooter === 'string') {
|
||||
nextConfig.user.promptFooter = incomingUser.promptFooter
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.extensions && typeof payload.extensions === 'object' && !Array.isArray(payload.extensions)) {
|
||||
const incomingExtensions = payload.extensions
|
||||
if (incomingExtensions.simple && typeof incomingExtensions.simple === 'object' && !Array.isArray(incomingExtensions.simple)) {
|
||||
const incomingSimple = incomingExtensions.simple
|
||||
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'enable')) {
|
||||
nextConfig.extensions.simple.enable = Boolean(incomingSimple.enable)
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'libraryPath') && typeof incomingSimple.libraryPath === 'string') {
|
||||
nextConfig.extensions.simple.libraryPath = incomingSimple.libraryPath.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'dictPath') && typeof incomingSimple.dictPath === 'string') {
|
||||
nextConfig.extensions.simple.dictPath = incomingSimple.dictPath.trim()
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(incomingSimple, 'useJieba')) {
|
||||
nextConfig.extensions.simple.useJieba = Boolean(incomingSimple.useJieba)
|
||||
}
|
||||
} else if (Object.prototype.hasOwnProperty.call(incomingExtensions, 'simple')) {
|
||||
logger.warn('[Memory] Unexpected value for extensions.simple, ignoring:', incomingExtensions.simple)
|
||||
}
|
||||
}
|
||||
|
||||
ChatGPTConfig.memory.database = nextConfig.database
|
||||
ChatGPTConfig.memory.vectorDimensions = nextConfig.vectorDimensions
|
||||
if (!ChatGPTConfig.memory.group) ChatGPTConfig.memory.group = {}
|
||||
if (!ChatGPTConfig.memory.user) ChatGPTConfig.memory.user = {}
|
||||
if (!ChatGPTConfig.memory.extensions) ChatGPTConfig.memory.extensions = {}
|
||||
if (!ChatGPTConfig.memory.extensions.simple) {
|
||||
ChatGPTConfig.memory.extensions.simple = {
|
||||
enable: false,
|
||||
libraryPath: '',
|
||||
dictPath: '',
|
||||
useJieba: false
|
||||
}
|
||||
}
|
||||
Object.assign(ChatGPTConfig.memory.group, nextConfig.group)
|
||||
Object.assign(ChatGPTConfig.memory.user, nextConfig.user)
|
||||
Object.assign(ChatGPTConfig.memory.extensions.simple, nextConfig.extensions.simple)
|
||||
|
||||
if (nextConfig.vectorDimensions !== previousDimension) {
|
||||
resetCachedDimension()
|
||||
const targetDimension = Number(nextConfig.vectorDimensions)
|
||||
if (Number.isFinite(targetDimension) && targetDimension > 0) {
|
||||
try {
|
||||
resetVectorTableDimension(targetDimension)
|
||||
} catch (err) {
|
||||
logger?.error?.('[Memory] failed to apply vector dimension change:', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
const currentSimpleConfig = JSON.stringify(ChatGPTConfig.memory.extensions?.simple || {})
|
||||
|
||||
if (nextConfig.database !== previousDatabase) {
|
||||
resetMemoryDatabaseInstance()
|
||||
} else if (currentSimpleConfig !== previousSimpleConfig) {
|
||||
resetMemoryDatabaseInstance()
|
||||
}
|
||||
|
||||
if (typeof ChatGPTConfig._triggerSave === 'function') {
|
||||
ChatGPTConfig._triggerSave('memory')
|
||||
}
|
||||
|
||||
return ChatGPTConfig.memory
|
||||
}
|
||||
|
||||
export const MemoryRouter = (() => {
|
||||
const router = express.Router()
|
||||
|
||||
router.get('/config', (_req, res) => {
|
||||
res.status(200).json(ChaiteResponse.ok(ChatGPTConfig.memory))
|
||||
})
|
||||
|
||||
router.post('/config', (req, res) => {
|
||||
try {
|
||||
const updated = updateMemoryConfig(req.body || {})
|
||||
res.status(200).json(ChaiteResponse.ok(updated))
|
||||
} catch (error) {
|
||||
logger.error('Failed to update memory config:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to update memory config'))
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/group/:groupId/facts', (req, res) => {
|
||||
const { groupId } = req.params
|
||||
const limit = parsePositiveInt(req.query.limit, 50)
|
||||
const offset = parsePositiveInt(req.query.offset, 0)
|
||||
try {
|
||||
const facts = memoryService.listGroupFacts(groupId, limit, offset)
|
||||
res.status(200).json(ChaiteResponse.ok(facts))
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch group facts:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to fetch group facts'))
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/extensions/simple/status', (_req, res) => {
|
||||
try {
|
||||
logger?.debug?.('[Memory] simple extension status requested')
|
||||
const state = getSimpleExtensionState()
|
||||
const simpleConfig = ChatGPTConfig.memory?.extensions?.simple || {}
|
||||
const libraryPath = simpleConfig.libraryPath || state.libraryPath || ''
|
||||
const dictPath = simpleConfig.dictPath || state.dictPath || ''
|
||||
const resolvedLibraryPath = libraryPath ? resolvePluginPath(libraryPath) : ''
|
||||
const resolvedDictPath = dictPath ? resolvePluginPath(dictPath) : ''
|
||||
res.status(200).json(ChaiteResponse.ok({
|
||||
...state,
|
||||
enabled: Boolean(simpleConfig.enable),
|
||||
libraryPath,
|
||||
dictPath,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
resolvedLibraryPath,
|
||||
libraryExists: resolvedLibraryPath ? fs.existsSync(resolvedLibraryPath) : false,
|
||||
resolvedDictPath,
|
||||
dictExists: resolvedDictPath ? fs.existsSync(resolvedDictPath) : false
|
||||
}))
|
||||
} catch (error) {
|
||||
logger.error('Failed to read simple extension status:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to read simple extension status'))
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/extensions/simple/download', async (req, res) => {
|
||||
const { assetKey, assetName, installDir } = req.body || {}
|
||||
try {
|
||||
const resolvedAsset = resolveSimpleAsset(assetKey, assetName)
|
||||
if (!resolvedAsset.asset) {
|
||||
res.status(400).json(ChaiteResponse.fail(null, '无法确定当前平台的扩展文件,请手动指定 assetName。'))
|
||||
return
|
||||
}
|
||||
logger?.info?.('[Memory] downloading simple extension asset=%s (key=%s)', resolvedAsset.asset, resolvedAsset.key)
|
||||
const targetRelativeDir = installDir || path.join(DEFAULT_SIMPLE_INSTALL_DIR, resolvedAsset.key || 'downloaded')
|
||||
const targetDir = resolvePluginPath(targetRelativeDir)
|
||||
const result = await downloadSimpleExtensionArchive({
|
||||
assetKey: resolvedAsset.key || assetKey || 'custom',
|
||||
assetName: resolvedAsset.asset,
|
||||
targetDir
|
||||
})
|
||||
resetMemoryDatabaseInstance()
|
||||
logger?.info?.('[Memory] simple extension downloaded and memory DB scheduled for reload')
|
||||
res.status(200).json(ChaiteResponse.ok({
|
||||
...result,
|
||||
assetName: resolvedAsset.asset,
|
||||
assetKey: resolvedAsset.key || assetKey || 'custom'
|
||||
}))
|
||||
} catch (error) {
|
||||
logger.error('Failed to download simple extension:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, error?.message || 'Failed to download simple extension'))
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/group/:groupId/facts', async (req, res) => {
|
||||
const { groupId } = req.params
|
||||
const facts = Array.isArray(req.body?.facts) ? req.body.facts : []
|
||||
if (facts.length === 0) {
|
||||
res.status(400).json(ChaiteResponse.fail(null, 'facts is required'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const saved = await memoryService.saveGroupFacts(groupId, facts)
|
||||
res.status(200).json(ChaiteResponse.ok(saved))
|
||||
} catch (error) {
|
||||
logger.error('Failed to save group facts:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to save group facts'))
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/group/:groupId/query', async (req, res) => {
|
||||
const { groupId } = req.params
|
||||
const { query, limit, minImportance } = req.body || {}
|
||||
if (!query || typeof query !== 'string') {
|
||||
res.status(400).json(ChaiteResponse.fail(null, 'query is required'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const facts = await memoryService.queryGroupFacts(groupId, query, {
|
||||
limit: parsePositiveInt(limit, undefined),
|
||||
minImportance: minImportance !== undefined ? parseNumber(minImportance, undefined) : undefined
|
||||
})
|
||||
res.status(200).json(ChaiteResponse.ok(facts))
|
||||
} catch (error) {
|
||||
logger.error('Failed to query group memory:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to query group memory'))
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/group/:groupId/facts/:factId', (req, res) => {
|
||||
const { groupId, factId } = req.params
|
||||
try {
|
||||
const removed = memoryService.deleteGroupFact(groupId, factId)
|
||||
if (!removed) {
|
||||
res.status(404).json(ChaiteResponse.fail(null, 'Fact not found'))
|
||||
return
|
||||
}
|
||||
res.status(200).json(ChaiteResponse.ok({ removed }))
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete group fact:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to delete group fact'))
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/user/memories', (req, res) => {
|
||||
const userId = parseOptionalStringParam(req.query.userId)
|
||||
const groupId = parseOptionalStringParam(req.query.groupId)
|
||||
const limit = parsePositiveInt(req.query.limit, 50)
|
||||
const offset = parsePositiveInt(req.query.offset, 0)
|
||||
try {
|
||||
const memories = memoryService.listUserMemories(userId, groupId, limit, offset)
|
||||
res.status(200).json(ChaiteResponse.ok(memories))
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch user memories:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to fetch user memories'))
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/user/:userId/memories', (req, res) => {
|
||||
const { userId } = req.params
|
||||
const groupId = req.query.groupId ?? null
|
||||
const limit = parsePositiveInt(req.query.limit, 50)
|
||||
const offset = parsePositiveInt(req.query.offset, 0)
|
||||
try {
|
||||
const memories = memoryService.listUserMemories(userId, groupId, limit, offset)
|
||||
res.status(200).json(ChaiteResponse.ok(memories))
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch user memories:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to fetch user memories'))
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/user/:userId/query', (req, res) => {
|
||||
const { userId } = req.params
|
||||
const groupId = req.body?.groupId ?? req.query.groupId ?? null
|
||||
const query = req.body?.query
|
||||
const totalLimit = parsePositiveInt(req.body?.totalLimit, undefined)
|
||||
const searchLimit = parsePositiveInt(req.body?.searchLimit, undefined)
|
||||
const minImportance = req.body?.minImportance !== undefined
|
||||
? parseNumber(req.body.minImportance, undefined)
|
||||
: undefined
|
||||
if (!query || typeof query !== 'string') {
|
||||
res.status(400).json(ChaiteResponse.fail(null, 'query is required'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const memories = memoryService.queryUserMemories(userId, groupId, query, {
|
||||
totalLimit,
|
||||
searchLimit,
|
||||
minImportance
|
||||
})
|
||||
res.status(200).json(ChaiteResponse.ok(memories))
|
||||
} catch (error) {
|
||||
logger.error('Failed to query user memory:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to query user memory'))
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/user/:userId/memories', (req, res) => {
|
||||
const { userId } = req.params
|
||||
const groupId = req.body?.groupId ?? null
|
||||
const memories = Array.isArray(req.body?.memories) ? req.body.memories : []
|
||||
if (memories.length === 0) {
|
||||
res.status(400).json(ChaiteResponse.fail(null, 'memories is required'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const updated = memoryService.upsertUserMemories(userId, groupId, memories)
|
||||
res.status(200).json(ChaiteResponse.ok({ updated }))
|
||||
} catch (error) {
|
||||
logger.error('Failed to upsert user memories:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to upsert user memories'))
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/user/:userId/memories/:memoryId', (req, res) => {
|
||||
const { userId, memoryId } = req.params
|
||||
try {
|
||||
const removed = memoryService.deleteUserMemory(memoryId, userId)
|
||||
if (!removed) {
|
||||
res.status(404).json(ChaiteResponse.fail(null, 'Memory not found'))
|
||||
return
|
||||
}
|
||||
res.status(200).json(ChaiteResponse.ok({ removed }))
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete user memory:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to delete user memory'))
|
||||
}
|
||||
})
|
||||
|
||||
router.delete('/memories/:memoryId', (req, res) => {
|
||||
const { memoryId } = req.params
|
||||
try {
|
||||
const removed = memoryService.deleteUserMemory(memoryId)
|
||||
if (!removed) {
|
||||
res.status(404).json(ChaiteResponse.fail(null, 'Memory not found'))
|
||||
return
|
||||
}
|
||||
res.status(200).json(ChaiteResponse.ok({ removed }))
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete memory:', error)
|
||||
res.status(500).json(ChaiteResponse.fail(null, 'Failed to delete memory'))
|
||||
}
|
||||
})
|
||||
|
||||
return router
|
||||
})()
|
||||
194
models/memory/service.js
Normal file
194
models/memory/service.js
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
import ChatGPTConfig from '../../config/config.js'
|
||||
import { getMemoryDatabase } from './database.js'
|
||||
import { GroupMemoryStore } from './groupMemoryStore.js'
|
||||
import { UserMemoryStore } from './userMemoryStore.js'
|
||||
|
||||
function normaliseId (id) {
|
||||
if (id === null || id === undefined) {
|
||||
return ''
|
||||
}
|
||||
return String(id)
|
||||
}
|
||||
|
||||
function formatEntry (entry) {
|
||||
let str = ''
|
||||
try {
|
||||
str = JSON.stringify(entry)
|
||||
} catch (err) {
|
||||
str = String(entry)
|
||||
}
|
||||
const limit = 200
|
||||
return str.length > limit ? str.slice(0, limit) + '…' : str
|
||||
}
|
||||
|
||||
function normalisePersonalMemory (entry) {
|
||||
if (!entry) return null
|
||||
let text = ''
|
||||
let importance = typeof entry?.importance === 'number' ? entry.importance : 0.6
|
||||
let sourceId = entry?.source_message_id ? String(entry.source_message_id) : null
|
||||
if (typeof entry === 'string') {
|
||||
text = entry.trim()
|
||||
} else if (typeof entry === 'object') {
|
||||
const value = entry.value || entry.text || entry.fact || entry.sentence
|
||||
if (Array.isArray(value)) {
|
||||
text = value.join(', ').trim()
|
||||
} else if (value) {
|
||||
text = String(value).trim()
|
||||
}
|
||||
if (entry.importance !== undefined) {
|
||||
importance = Number(entry.importance)
|
||||
}
|
||||
if (entry.source_message_id) {
|
||||
sourceId = String(entry.source_message_id)
|
||||
}
|
||||
}
|
||||
if (!text) {
|
||||
return null
|
||||
}
|
||||
if (Number.isNaN(importance) || importance <= 0) {
|
||||
importance = 0.6
|
||||
}
|
||||
return { text, importance, sourceId }
|
||||
}
|
||||
|
||||
class MemoryService {
|
||||
constructor () {
|
||||
const db = getMemoryDatabase()
|
||||
this.groupStore = new GroupMemoryStore(db)
|
||||
this.userStore = new UserMemoryStore(db)
|
||||
}
|
||||
|
||||
isGroupMemoryEnabled (groupId) {
|
||||
const config = ChatGPTConfig.memory?.group
|
||||
if (!config?.enable) {
|
||||
return false
|
||||
}
|
||||
const enabledGroups = (config.enabledGroups || []).map(normaliseId)
|
||||
if (enabledGroups.length === 0) {
|
||||
return false
|
||||
}
|
||||
return enabledGroups.includes(normaliseId(groupId))
|
||||
}
|
||||
|
||||
isUserMemoryEnabled (userId) {
|
||||
const config = ChatGPTConfig.memory?.user
|
||||
if (!config?.enable) {
|
||||
return false
|
||||
}
|
||||
const uid = normaliseId(userId)
|
||||
const whitelist = (config.whitelist || []).map(normaliseId).filter(Boolean)
|
||||
const blacklist = (config.blacklist || []).map(normaliseId).filter(Boolean)
|
||||
if (whitelist.length > 0) {
|
||||
return whitelist.includes(uid)
|
||||
}
|
||||
if (blacklist.length > 0) {
|
||||
return !blacklist.includes(uid)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async saveGroupFacts (groupId, facts) {
|
||||
if (!this.isGroupMemoryEnabled(groupId)) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
const saved = await this.groupStore.saveFacts(groupId, facts)
|
||||
if (saved.length > 0) {
|
||||
logger.info(`[Memory] group=${groupId} stored ${saved.length} facts`)
|
||||
saved.slice(0, 10).forEach((item, idx) => {
|
||||
logger.debug(`[Memory] group stored fact[${idx}] ${formatEntry(item)}`)
|
||||
})
|
||||
}
|
||||
return saved
|
||||
} catch (err) {
|
||||
logger.error('Failed to save group facts:', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
async queryGroupFacts (groupId, queryText, options = {}) {
|
||||
if (!this.isGroupMemoryEnabled(groupId)) {
|
||||
return []
|
||||
}
|
||||
const { maxFactsPerInjection = 5, minImportanceForInjection = 0 } = ChatGPTConfig.memory?.group || {}
|
||||
const limit = options.limit || maxFactsPerInjection
|
||||
const minImportance = options.minImportance ?? minImportanceForInjection
|
||||
try {
|
||||
return await this.groupStore.queryRelevantFacts(groupId, queryText, { limit, minImportance })
|
||||
} catch (err) {
|
||||
logger.error('Failed to query group memory:', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
listGroupFacts (groupId, limit = 50, offset = 0) {
|
||||
return this.groupStore.listFacts(groupId, limit, offset)
|
||||
}
|
||||
|
||||
deleteGroupFact (groupId, factId) {
|
||||
return this.groupStore.deleteFact(groupId, factId)
|
||||
}
|
||||
|
||||
upsertUserMemories (userId, groupId, memories) {
|
||||
if (!this.isUserMemoryEnabled(userId)) {
|
||||
return 0
|
||||
}
|
||||
try {
|
||||
const prepared = (memories || [])
|
||||
.map(normalisePersonalMemory)
|
||||
.filter(item => item && item.text)
|
||||
.map(item => ({
|
||||
value: item.text,
|
||||
importance: item.importance,
|
||||
source_message_id: item.sourceId
|
||||
}))
|
||||
if (prepared.length === 0) {
|
||||
return 0
|
||||
}
|
||||
const changed = this.userStore.upsertMemories(userId, groupId, prepared)
|
||||
if (changed > 0) {
|
||||
logger.info(`[Memory] user=${userId} updated ${changed} personal memories${groupId ? ` in group=${groupId}` : ''}`)
|
||||
prepared.slice(0, 10).forEach((item, idx) => {
|
||||
logger.debug(`[Memory] user memory upsert[${idx}] ${formatEntry(item)}`)
|
||||
})
|
||||
}
|
||||
return changed
|
||||
} catch (err) {
|
||||
logger.error('Failed to upsert user memories:', err)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
queryUserMemories (userId, groupId = null, queryText = '', options = {}) {
|
||||
if (!this.isUserMemoryEnabled(userId)) {
|
||||
return []
|
||||
}
|
||||
const userConfig = ChatGPTConfig.memory?.user || {}
|
||||
const totalLimit = options.totalLimit ?? userConfig.maxItemsPerInjection ?? 5
|
||||
const searchLimit = options.searchLimit ?? userConfig.maxRelevantItemsPerQuery ?? totalLimit
|
||||
const minImportance = options.minImportance ?? userConfig.minImportanceForInjection ?? 0
|
||||
if (!totalLimit || totalLimit <= 0) {
|
||||
return []
|
||||
}
|
||||
try {
|
||||
return this.userStore.queryMemories(userId, groupId, queryText, {
|
||||
limit: searchLimit,
|
||||
fallbackLimit: totalLimit,
|
||||
minImportance
|
||||
})
|
||||
} catch (err) {
|
||||
logger.error('Failed to query user memories:', err)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
listUserMemories (userId, groupId = null, limit = 50, offset = 0) {
|
||||
return this.userStore.listUserMemories(userId, groupId, limit, offset)
|
||||
}
|
||||
|
||||
deleteUserMemory (memoryId, userId = null) {
|
||||
return this.userStore.deleteMemoryById(memoryId, userId)
|
||||
}
|
||||
}
|
||||
|
||||
export const memoryService = new MemoryService()
|
||||
129
models/memory/userMemoryManager.js
Normal file
129
models/memory/userMemoryManager.js
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import { Chaite } from 'chaite'
|
||||
import * as crypto from 'node:crypto'
|
||||
import { extractUserMemories } from './extractor.js'
|
||||
import { memoryService } from './service.js'
|
||||
|
||||
const USER_MEMORY_CONTEXT_LIMIT = 6
|
||||
|
||||
export function extractTextFromContents (contents) {
|
||||
if (!Array.isArray(contents)) {
|
||||
return ''
|
||||
}
|
||||
return contents
|
||||
.filter(item => item && item.type === 'text')
|
||||
.map(item => item.text || '')
|
||||
.join('\n')
|
||||
.trim()
|
||||
}
|
||||
|
||||
export function extractTextFromUserMessage (userMessage) {
|
||||
if (!userMessage?.content) {
|
||||
return ''
|
||||
}
|
||||
return userMessage.content
|
||||
.filter(item => item.type === 'text')
|
||||
.map(item => item.text || '')
|
||||
.join('\n')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function normaliseMemoriesInput (memories, sourceId) {
|
||||
return (memories || []).map(mem => {
|
||||
if (typeof mem === 'string') {
|
||||
return {
|
||||
value: mem,
|
||||
source_message_id: sourceId
|
||||
}
|
||||
}
|
||||
if (mem && typeof mem === 'object') {
|
||||
const cloned = { ...mem }
|
||||
if (!cloned.source_message_id && sourceId) {
|
||||
cloned.source_message_id = sourceId
|
||||
}
|
||||
if (!cloned.value && cloned.fact) {
|
||||
cloned.value = cloned.fact
|
||||
}
|
||||
if (!cloned.value && cloned.text) {
|
||||
cloned.value = cloned.text
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
return {
|
||||
value: String(mem),
|
||||
source_message_id: sourceId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function processUserMemory ({ event, userMessage, userText, conversationId, assistantContents, assistantMessageId }) {
|
||||
const e = event
|
||||
if (!memoryService.isUserMemoryEnabled(e.sender.user_id)) {
|
||||
return
|
||||
}
|
||||
const snippets = []
|
||||
const userMessageId = e.message_id || e.seq || userMessage?.id || crypto.randomUUID()
|
||||
const senderName = e.sender?.card || e.sender?.nickname || String(e.sender?.user_id || '')
|
||||
|
||||
try {
|
||||
const historyManager = Chaite.getInstance()?.getHistoryManager?.()
|
||||
if (historyManager && conversationId) {
|
||||
const history = await historyManager.getHistory(null, conversationId)
|
||||
const filtered = (history || [])
|
||||
.filter(msg => ['user', 'assistant'].includes(msg.role))
|
||||
.map(msg => ({
|
||||
role: msg.role,
|
||||
text: extractTextFromContents(msg.content),
|
||||
nickname: msg.role === 'user' ? senderName : '机器人',
|
||||
message_id: msg.id
|
||||
}))
|
||||
.filter(item => item.text)
|
||||
if (filtered.length > 0) {
|
||||
const limited = filtered.slice(-USER_MEMORY_CONTEXT_LIMIT * 2)
|
||||
snippets.push(...limited)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn('Failed to collect user memory context:', err)
|
||||
}
|
||||
|
||||
if (assistantContents) {
|
||||
const assistantText = extractTextFromContents(assistantContents)
|
||||
if (assistantText) {
|
||||
snippets.push({
|
||||
role: 'assistant',
|
||||
text: assistantText,
|
||||
nickname: '机器人',
|
||||
message_id: assistantMessageId || crypto.randomUUID()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (userText && !snippets.some(item => item.message_id === userMessageId)) {
|
||||
snippets.push({
|
||||
role: 'user',
|
||||
text: userText,
|
||||
nickname: senderName,
|
||||
message_id: userMessageId
|
||||
})
|
||||
}
|
||||
|
||||
if (snippets.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const existingRecords = memoryService.listUserMemories(e.sender.user_id, e.isGroup ? e.group_id : null, 50)
|
||||
const existingTexts = existingRecords.map(record => record.value).filter(Boolean)
|
||||
const memories = await extractUserMemories(snippets, existingTexts)
|
||||
if (!memories || memories.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const enriched = normaliseMemoriesInput(memories, userMessageId)
|
||||
memoryService.upsertUserMemories(
|
||||
e.sender.user_id,
|
||||
e.isGroup ? e.group_id : null,
|
||||
enriched
|
||||
)
|
||||
}
|
||||
|
||||
export { USER_MEMORY_CONTEXT_LIMIT }
|
||||
335
models/memory/userMemoryStore.js
Normal file
335
models/memory/userMemoryStore.js
Normal file
|
|
@ -0,0 +1,335 @@
|
|||
import { getMemoryDatabase, getUserMemoryFtsConfig, sanitiseFtsQueryInput } from './database.js'
|
||||
import { md5 } from '../../utils/common.js'
|
||||
|
||||
function normaliseId (value) {
|
||||
if (value === null || value === undefined) {
|
||||
return null
|
||||
}
|
||||
const str = String(value).trim()
|
||||
if (!str || str.toLowerCase() === 'null' || str.toLowerCase() === 'undefined') {
|
||||
return null
|
||||
}
|
||||
return str
|
||||
}
|
||||
|
||||
function toMemoryPayload (entry) {
|
||||
if (entry === null || entry === undefined) {
|
||||
return null
|
||||
}
|
||||
if (typeof entry === 'string') {
|
||||
const text = entry.trim()
|
||||
return text ? { value: text, importance: 0.5 } : null
|
||||
}
|
||||
if (typeof entry === 'object') {
|
||||
const rawValue = entry.value ?? entry.text ?? entry.fact ?? ''
|
||||
const value = typeof rawValue === 'string' ? rawValue.trim() : String(rawValue || '').trim()
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
const importance = typeof entry.importance === 'number' ? entry.importance : 0.5
|
||||
const sourceId = entry.source_message_id ? String(entry.source_message_id) : null
|
||||
const providedKey = entry.key ? String(entry.key).trim() : ''
|
||||
return {
|
||||
value,
|
||||
importance,
|
||||
source_message_id: sourceId,
|
||||
providedKey
|
||||
}
|
||||
}
|
||||
const value = String(entry).trim()
|
||||
return value ? { value, importance: 0.5 } : null
|
||||
}
|
||||
|
||||
function deriveKey (value, providedKey = '') {
|
||||
const trimmedProvided = providedKey?.trim?.() || ''
|
||||
if (trimmedProvided) {
|
||||
return trimmedProvided
|
||||
}
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
return `fact:${md5(String(value))}`
|
||||
}
|
||||
|
||||
function stripKey (row) {
|
||||
if (!row || typeof row !== 'object') {
|
||||
return row
|
||||
}
|
||||
const { key, ...rest } = row
|
||||
return rest
|
||||
}
|
||||
|
||||
function appendRows (target, rows, seen) {
|
||||
if (!Array.isArray(rows)) {
|
||||
return
|
||||
}
|
||||
for (const row of rows) {
|
||||
if (!row || seen.has(row.id)) {
|
||||
continue
|
||||
}
|
||||
target.push(stripKey(row))
|
||||
seen.add(row.id)
|
||||
}
|
||||
}
|
||||
|
||||
export class UserMemoryStore {
|
||||
constructor (db = getMemoryDatabase()) {
|
||||
this.resetDatabase(db)
|
||||
}
|
||||
|
||||
resetDatabase (db = getMemoryDatabase()) {
|
||||
this.db = db
|
||||
this.upsertStmt = this.db.prepare(`
|
||||
INSERT INTO user_memory (user_id, group_id, key, value, importance, source_message_id, created_at, updated_at)
|
||||
VALUES (@user_id, @group_id, @key, @value, @importance, @source_message_id, datetime('now'), datetime('now'))
|
||||
ON CONFLICT(user_id, coalesce(group_id, ''), key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
importance = excluded.importance,
|
||||
source_message_id = excluded.source_message_id,
|
||||
updated_at = datetime('now')
|
||||
`)
|
||||
}
|
||||
|
||||
ensureDb () {
|
||||
if (!this.db || this.db.open === false) {
|
||||
logger?.debug?.('[Memory] refreshing user memory database connection')
|
||||
this.resetDatabase()
|
||||
}
|
||||
return this.db
|
||||
}
|
||||
|
||||
upsertMemories (userId, groupId, memories) {
|
||||
if (!memories || memories.length === 0) {
|
||||
return 0
|
||||
}
|
||||
this.ensureDb()
|
||||
const normUserId = normaliseId(userId)
|
||||
const normGroupId = normaliseId(groupId)
|
||||
const prepared = (memories || [])
|
||||
.map(toMemoryPayload)
|
||||
.filter(item => item && item.value)
|
||||
.map(item => {
|
||||
const key = deriveKey(item.value, item.providedKey)
|
||||
if (!key) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
user_id: normUserId,
|
||||
group_id: normGroupId,
|
||||
key,
|
||||
value: String(item.value),
|
||||
importance: typeof item.importance === 'number' ? item.importance : 0.5,
|
||||
source_message_id: item.source_message_id ? String(item.source_message_id) : null
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
if (!prepared.length) {
|
||||
return 0
|
||||
}
|
||||
const transaction = this.db.transaction(items => {
|
||||
let changes = 0
|
||||
for (const item of items) {
|
||||
const info = this.upsertStmt.run(item)
|
||||
changes += info.changes
|
||||
}
|
||||
return changes
|
||||
})
|
||||
return transaction(prepared)
|
||||
}
|
||||
|
||||
listUserMemories (userId = null, groupId = null, limit = 50, offset = 0) {
|
||||
this.ensureDb()
|
||||
const normUserId = normaliseId(userId)
|
||||
const normGroupId = normaliseId(groupId)
|
||||
const params = []
|
||||
let query = `
|
||||
SELECT * FROM user_memory
|
||||
WHERE 1 = 1
|
||||
`
|
||||
if (normUserId) {
|
||||
query += ' AND user_id = ?'
|
||||
params.push(normUserId)
|
||||
}
|
||||
if (normGroupId) {
|
||||
if (normUserId) {
|
||||
query += ' AND (group_id = ? OR group_id IS NULL)'
|
||||
} else {
|
||||
query += ' AND group_id = ?'
|
||||
}
|
||||
params.push(normGroupId)
|
||||
}
|
||||
query += `
|
||||
ORDER BY importance DESC, updated_at DESC
|
||||
LIMIT ? OFFSET ?
|
||||
`
|
||||
params.push(limit, offset)
|
||||
const rows = this.db.prepare(query).all(...params)
|
||||
return rows.map(stripKey)
|
||||
}
|
||||
|
||||
deleteMemoryById (memoryId, userId = null) {
|
||||
this.ensureDb()
|
||||
if (userId) {
|
||||
const result = this.db.prepare('DELETE FROM user_memory WHERE id = ? AND user_id = ?').run(memoryId, normaliseId(userId))
|
||||
return result.changes > 0
|
||||
}
|
||||
const result = this.db.prepare('DELETE FROM user_memory WHERE id = ?').run(memoryId)
|
||||
return result.changes > 0
|
||||
}
|
||||
|
||||
listRecentMemories (userId, groupId = null, limit = 50, excludeIds = [], minImportance = 0) {
|
||||
this.ensureDb()
|
||||
const normUserId = normaliseId(userId)
|
||||
const normGroupId = normaliseId(groupId)
|
||||
const filteredExclude = (excludeIds || []).filter(Boolean)
|
||||
const params = [normUserId]
|
||||
let query = `
|
||||
SELECT * FROM user_memory
|
||||
WHERE user_id = ?
|
||||
AND importance >= ?
|
||||
`
|
||||
params.push(minImportance)
|
||||
if (normGroupId) {
|
||||
query += ' AND (group_id = ? OR group_id IS NULL)'
|
||||
params.push(normGroupId)
|
||||
}
|
||||
if (filteredExclude.length) {
|
||||
query += ` AND id NOT IN (${filteredExclude.map(() => '?').join(',')})`
|
||||
params.push(...filteredExclude)
|
||||
}
|
||||
query += `
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT ?
|
||||
`
|
||||
params.push(limit)
|
||||
return this.db.prepare(query).all(...params).map(stripKey)
|
||||
}
|
||||
|
||||
textSearch (userId, groupId = null, queryText, limit = 5, excludeIds = []) {
|
||||
if (!queryText || !queryText.trim()) {
|
||||
return []
|
||||
}
|
||||
this.ensureDb()
|
||||
const normUserId = normaliseId(userId)
|
||||
const normGroupId = normaliseId(groupId)
|
||||
const filteredExclude = (excludeIds || []).filter(Boolean)
|
||||
const originalQuery = queryText.trim()
|
||||
const ftsConfig = getUserMemoryFtsConfig()
|
||||
const matchQueryParam = sanitiseFtsQueryInput(originalQuery, ftsConfig)
|
||||
const results = []
|
||||
const seen = new Set(filteredExclude)
|
||||
if (matchQueryParam) {
|
||||
const matchExpression = ftsConfig.matchQuery ? `${ftsConfig.matchQuery}(?)` : '?'
|
||||
const params = [normUserId, matchQueryParam]
|
||||
let query = `
|
||||
SELECT um.*, bm25(user_memory_fts) AS bm25_score
|
||||
FROM user_memory_fts
|
||||
JOIN user_memory um ON um.id = user_memory_fts.rowid
|
||||
WHERE um.user_id = ?
|
||||
AND user_memory_fts MATCH ${matchExpression}
|
||||
`
|
||||
if (normGroupId) {
|
||||
query += ' AND (um.group_id = ? OR um.group_id IS NULL)'
|
||||
params.push(normGroupId)
|
||||
}
|
||||
if (filteredExclude.length) {
|
||||
query += ` AND um.id NOT IN (${filteredExclude.map(() => '?').join(',')})`
|
||||
params.push(...filteredExclude)
|
||||
}
|
||||
query += `
|
||||
ORDER BY bm25_score ASC, um.updated_at DESC
|
||||
LIMIT ?
|
||||
`
|
||||
params.push(limit)
|
||||
try {
|
||||
const ftsRows = this.db.prepare(query).all(...params)
|
||||
appendRows(results, ftsRows, seen)
|
||||
} catch (err) {
|
||||
logger?.warn?.('User memory text search failed:', err)
|
||||
}
|
||||
} else {
|
||||
logger?.debug?.('[Memory] user memory text search skipped MATCH due to empty query after sanitisation')
|
||||
}
|
||||
|
||||
if (results.length < limit) {
|
||||
const likeParams = [normUserId, originalQuery]
|
||||
let likeQuery = `
|
||||
SELECT um.*
|
||||
FROM user_memory um
|
||||
WHERE um.user_id = ?
|
||||
AND instr(um.value, ?) > 0
|
||||
`
|
||||
if (normGroupId) {
|
||||
likeQuery += ' AND (um.group_id = ? OR um.group_id IS NULL)'
|
||||
likeParams.push(normGroupId)
|
||||
}
|
||||
if (filteredExclude.length) {
|
||||
likeQuery += ` AND um.id NOT IN (${filteredExclude.map(() => '?').join(',')})`
|
||||
likeParams.push(...filteredExclude)
|
||||
}
|
||||
likeQuery += `
|
||||
ORDER BY um.importance DESC, um.updated_at DESC
|
||||
LIMIT ?
|
||||
`
|
||||
likeParams.push(Math.max(limit * 2, limit))
|
||||
try {
|
||||
const likeRows = this.db.prepare(likeQuery).all(...likeParams)
|
||||
appendRows(results, likeRows, seen)
|
||||
} catch (err) {
|
||||
logger?.warn?.('User memory LIKE search failed:', err)
|
||||
}
|
||||
}
|
||||
|
||||
return results.slice(0, limit)
|
||||
}
|
||||
|
||||
queryMemories (userId, groupId = null, queryText = '', options = {}) {
|
||||
const normUserId = normaliseId(userId)
|
||||
if (!normUserId) {
|
||||
return []
|
||||
}
|
||||
this.ensureDb()
|
||||
const {
|
||||
limit = 3,
|
||||
fallbackLimit,
|
||||
minImportance = 0
|
||||
} = options
|
||||
const totalLimit = Math.max(0, fallbackLimit ?? limit ?? 0)
|
||||
if (totalLimit === 0) {
|
||||
return []
|
||||
}
|
||||
const searchLimit = limit > 0 ? Math.min(limit, totalLimit) : totalLimit
|
||||
const results = []
|
||||
const seen = new Set()
|
||||
const append = rows => {
|
||||
for (const row of rows || []) {
|
||||
if (!row || seen.has(row.id)) {
|
||||
continue
|
||||
}
|
||||
results.push(row)
|
||||
seen.add(row.id)
|
||||
if (results.length >= totalLimit) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (queryText && searchLimit > 0) {
|
||||
const searched = this.textSearch(userId, groupId, queryText, searchLimit)
|
||||
append(searched)
|
||||
}
|
||||
|
||||
if (results.length < totalLimit) {
|
||||
const recent = this.listRecentMemories(
|
||||
userId,
|
||||
groupId,
|
||||
Math.max(totalLimit * 2, totalLimit),
|
||||
Array.from(seen),
|
||||
minImportance
|
||||
)
|
||||
append(recent)
|
||||
}
|
||||
|
||||
return results.slice(0, totalLimit)
|
||||
}
|
||||
}
|
||||
35
package.json
35
package.json
|
|
@ -1,26 +1,21 @@
|
|||
{
|
||||
"name": "chatgpt-plugin",
|
||||
"version": "3.0.0",
|
||||
"type": "module",
|
||||
"author": "ikechan8370",
|
||||
"dependencies": {
|
||||
"@waylaidwanderer/chatgpt-api": "^1.30.0",
|
||||
"chatgpt": "^5.1.1",
|
||||
"delay": "^5.0.0",
|
||||
"https-proxy-agent": "5.0.1",
|
||||
"keyv": "^4.5.2",
|
||||
"keyv-file": "^0.2.0",
|
||||
"node-fetch": "^3.3.1",
|
||||
"openai": "^3.2.1",
|
||||
"random": "^4.1.0",
|
||||
"undici": "^5.21.0",
|
||||
"uuid": "^9.0.0",
|
||||
"ws": "^8.13.0"
|
||||
"better-sqlite3": "^9.4.3",
|
||||
"adm-zip": "^0.5.10",
|
||||
"chaite": "^1.8.2",
|
||||
"js-yaml": "^4.1.0",
|
||||
"keyv": "^5.3.1",
|
||||
"keyv-file": "^5.1.2",
|
||||
"lowdb": "^7.0.1",
|
||||
"sqlite-vec": "^0.1.7-alpha.2",
|
||||
"vectra": "^0.9.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"jimp": "^0.22.7",
|
||||
"puppeteer-extra": "^3.3.6",
|
||||
"puppeteer-extra-plugin-recaptcha": "^3.6.8",
|
||||
"puppeteer-extra-plugin-stealth": "^2.11.2",
|
||||
"sharp": "^0.31.3"
|
||||
}
|
||||
}
|
||||
"peerDependencies": {
|
||||
"sqlite3": ">=5.1.6"
|
||||
},
|
||||
"pnpm": {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,270 +0,0 @@
|
|||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
|
@ -1,630 +0,0 @@
|
|||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0udc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0ddc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0vdc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0adc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0wdc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0xdc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0zdc0.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8oxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8oxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8oxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufwj0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufuz0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufwz0bbck.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufvp0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufwp0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufw50bbck.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufvz0b.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkoxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkoxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkoxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgoxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgoxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgoxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsoxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsoxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsoxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
|
@ -1,144 +0,0 @@
|
|||
<!doctype html>
|
||||
<html class="no-js" lang="zxx">
|
||||
|
||||
<head>
|
||||
<!--========= Required meta tags =========-->
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="x-ua-compatible" content="ie=edge">
|
||||
<!--====== CSS Here ======-->
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/static/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/static/css/font-awesome.min.css">
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/static/css/hljs.css">
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/Bing/style.css">
|
||||
|
||||
</head>
|
||||
|
||||
<body class="body-{{style}}">
|
||||
<header class="site-header">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-lg-3 col-4 my-auto">
|
||||
<a href="#" class="site-logo">
|
||||
<img src="{{pluResPath}}content/static/picture/bing.png" alt="LOGO">
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<section class="about-area pt-232">
|
||||
<div class="container">
|
||||
<div class="row justify-content-end">
|
||||
<div class="col-xl-5 col-lg-5 text-right">
|
||||
<div class="section-heading section-heading-{{style}}">
|
||||
<h2>New Bing</h2>
|
||||
{{if cache.file != ''}}
|
||||
<p> {{cache.file}} </p>
|
||||
{{/if}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-xl-12">
|
||||
<div class="hero-content hero-content-{{style}}">
|
||||
<h4>{{senderName}}</h4>
|
||||
</div>
|
||||
<div class="about-content">
|
||||
<p class="markdown_prompt"></p>
|
||||
<span class="height-50"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-xl-12">
|
||||
<div class="hero-content hero-content-{{style}}">
|
||||
{{if style === 'Sydney'}}
|
||||
<h4>Sydney</h4>
|
||||
{{else}}
|
||||
<h4>必应</h4>
|
||||
{{/if}}
|
||||
</div>
|
||||
<div class="about-content">
|
||||
<p class="markdown_content"></p>
|
||||
<span class="height-50"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{if quote}}
|
||||
<div class="row">
|
||||
<div class="col-xl-12">
|
||||
<div class="hero-content hero-content-{{style}}">
|
||||
<h4>引用</h4>
|
||||
</div>
|
||||
<div class="about-content">
|
||||
{{each quotes item}}
|
||||
<p>{{item}}</p>
|
||||
{{/each}}
|
||||
<span class="height-50"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{/if}}
|
||||
{{if cache.file != ''}}
|
||||
<div id="qrcode" class="row justify-content-end"></div>
|
||||
{{/if}}
|
||||
</div>
|
||||
</section>
|
||||
<!-- footer start -->
|
||||
<footer class="site-footer site-footer-{{style}} mt-175">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-2">
|
||||
</div>
|
||||
<div class="col-md-10 my-auto text-right">
|
||||
<div class="copyright-text copyright-text-{{style}}">
|
||||
<p>Response to {{senderName}} Created By Yunzai-Bot and ChatGPT-Plugin {{version}}</a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
<!-- footer end -->
|
||||
|
||||
<!--========= JS Here =========-->
|
||||
<script>
|
||||
MathJax = {
|
||||
tex: {
|
||||
inlineMath: [['$', '$'], ['\\(', '\\)']]
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<script src="{{pluResPath}}content/static/js/jquery-2.2.4.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/jquery.qrcode.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/highlight.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/marked.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/tex-mml-chtml.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/base64.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/main.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/purify.min.js"></script>
|
||||
|
||||
<script>
|
||||
marked.setOptions({
|
||||
renderer: new marked.Renderer(),
|
||||
gfm: true,
|
||||
tables: true,
|
||||
breaks: false,
|
||||
pedantic: false,
|
||||
sanitize: false,
|
||||
smartLists: true,
|
||||
smartypants: false,
|
||||
highlight: function (code,lang) {
|
||||
return hljs.highlightAuto(code,[lang]).value;
|
||||
}
|
||||
});
|
||||
const markdown_content = '{{@ content}}';
|
||||
const html_content = marked.parse(Base64.decode(markdown_content));
|
||||
const markdown_prompt = '{{@ prompt}}';
|
||||
const html_prompt = marked.parse(Base64.decode(markdown_prompt));
|
||||
|
||||
$(".markdown_content").html(DOMPurify.sanitize(html_content));
|
||||
$(".markdown_prompt").html(DOMPurify.sanitize(html_prompt));
|
||||
jQuery('#qrcode').qrcode({width: 128,height: 128,text: "{{cache.cacheUrl}}/{{cache.file}}"});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,270 +0,0 @@
|
|||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex1xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex0xhgciw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3ezqnved7rkgkxtqiqx5eucex6xhg.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5euanx4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eua3x4rhw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Josefin Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/qw3azqnved7rkgkxtqiqx5eudxx4.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
|
@ -1,630 +0,0 @@
|
|||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwyv9hriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0udc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0ddc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0vdc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0adc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0wdc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0xdc1uaw.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem6yags126mizpba-ufuk0zdc0.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukxgudhriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukwiunhriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hmiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hviqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hniqojjg.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hoiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hkiqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hliqojjg.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: italic;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/memnyags126mizpba-ufukw-u9hriqm.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8oxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8oxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8oxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 300;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un_r8ouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufwj0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufuz0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufwz0bbck.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufvp0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufwp0bbck.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufw50bbck.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem8yags126mizpba-ufvz0b.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkoxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkoxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkoxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-unirkouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgoxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgoxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgoxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un7rgouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsox-hpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsovuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsoxuhpoqc.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsouehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsoxehpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsoxohpoqc.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Open Sans';
|
||||
font-style: normal;
|
||||
font-weight: 800;
|
||||
font-display: swap;
|
||||
src: url(../fonts/mem5yags126mizpba-un8rsouuhp.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
<!doctype html>
|
||||
<html class="no-js" lang="zxx">
|
||||
|
||||
<head>
|
||||
<!--========= Required meta tags =========-->
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="x-ua-compatible" content="ie=edge">
|
||||
<!--====== CSS Here ======-->
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/static/css/bootstrap.min.css">
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/static/css/font-awesome.min.css">
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/static/css/hljs.css">
|
||||
<link rel="stylesheet" href="{{pluResPath}}content/ChatGPT/style.css">
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<header class="site-header">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-lg-3 col-4 my-auto">
|
||||
<a href="#" class="site-logo">
|
||||
<img src="{{pluResPath}}content/static/picture/openai.png" alt="LOGO">
|
||||
</a>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<section class="about-area pt-232">
|
||||
<div class="container">
|
||||
<div class="row justify-content-end">
|
||||
<div class="col-xl-5 col-lg-5 text-right">
|
||||
<div class="section-heading">
|
||||
<h2>Open AI</h2>
|
||||
{{if cache.file != ''}}
|
||||
<p> {{cache.file}} </p>
|
||||
{{/if}}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-xl-12">
|
||||
<div class="hero-content">
|
||||
<h4>{{senderName}}</h4>
|
||||
</div>
|
||||
<div class="about-content">
|
||||
<p class="markdown_prompt"></p>
|
||||
<span class="height-50"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-xl-12">
|
||||
<div class="hero-content">
|
||||
<h4>ChatGPT</h4>
|
||||
</div>
|
||||
<div class="about-content">
|
||||
<p class="markdown_content"></p>
|
||||
<span class="height-50"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{{if cache.file != ''}}
|
||||
<div id="qrcode" class="row justify-content-end"></div>
|
||||
{{/if}}
|
||||
</div>
|
||||
</section>
|
||||
<!-- footer start -->
|
||||
<footer class="site-footer mt-175">
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-md-2">
|
||||
</div>
|
||||
<div class="col-md-10 my-auto text-right">
|
||||
<div class="copyright-text">
|
||||
<p>Response to {{senderName}} Created By Yunzai-Bot and ChatGPT-Plugin {{version}}</a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
<!-- footer end -->
|
||||
|
||||
<!--========= JS Here =========-->
|
||||
<script>
|
||||
MathJax = {
|
||||
tex: {
|
||||
inlineMath: [['$', '$'], ['\\(', '\\)']]
|
||||
}
|
||||
};
|
||||
</script>
|
||||
<script src="{{pluResPath}}content/static/js/jquery-2.2.4.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/jquery.qrcode.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/highlight.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/marked.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/tex-mml-chtml.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/base64.min.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/main.js"></script>
|
||||
<script src="{{pluResPath}}content/static/js/purify.min.js"></script>
|
||||
|
||||
<script>
|
||||
marked.setOptions({
|
||||
renderer: new marked.Renderer(),
|
||||
gfm: true,
|
||||
tables: true,
|
||||
breaks: false,
|
||||
pedantic: false,
|
||||
sanitize: false,
|
||||
smartLists: true,
|
||||
smartypants: false,
|
||||
highlight: function (code,lang) {
|
||||
return hljs.highlightAuto(code,[lang]).value;
|
||||
}
|
||||
});
|
||||
const markdown_content = '{{@ content}}';
|
||||
const html_content = marked.parse(Base64.decode(markdown_content));
|
||||
const markdown_prompt = '{{@ prompt}}';
|
||||
const html_prompt = marked.parse(Base64.decode(markdown_prompt));
|
||||
|
||||
$(".markdown_content").html(DOMPurify.sanitize(html_content));
|
||||
$(".markdown_prompt").html(DOMPurify.sanitize(html_prompt));
|
||||
jQuery('#qrcode').qrcode({width: 128,height: 128,text: "{{cache.cacheUrl}}/{{cache.file}}"});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,429 +0,0 @@
|
|||
@charset "UTF-8";
|
||||
/*-----------------------------------------------------------------------------------
|
||||
|
||||
Template Name: Aiden - Creative Portfolio HTML5 Template
|
||||
Template URI: site.com
|
||||
Description: Aiden - Creative Portfolio HTML5 Template
|
||||
Author: Rs_Theme
|
||||
Version: 1.0
|
||||
|
||||
-----------------------------------------------------------------------------------
|
||||
|
||||
CSS INDEX
|
||||
===================
|
||||
01. Theme default css
|
||||
02. header css
|
||||
03. Navigation css
|
||||
04. hero css
|
||||
05. about css
|
||||
06. service css
|
||||
07. work CSS
|
||||
08. testimonial css
|
||||
09. brand css
|
||||
10. blog css
|
||||
11. contact css
|
||||
12. breadcrumb css
|
||||
13. cta css
|
||||
14. contact-page css
|
||||
15. blog-page css
|
||||
16. footer css
|
||||
|
||||
-----------------------------------------------------------------------------------*/
|
||||
/* reset css start */
|
||||
@import url("644b614f82934cd2a7833c108ceb941b.css");
|
||||
@import url("a0020bf6401d4e99884e2be5f5402f24.css");
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Microsoft YaHei", "微软雅黑", "Josefin Sans", sans-serif;
|
||||
font-size: 18px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-weight: 400;
|
||||
position: relative;
|
||||
line-height: 26px;
|
||||
background: #f5feff;
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
ul, ol {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
*:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
button {
|
||||
border: none;
|
||||
-webkit-transition: 0.3s;
|
||||
-o-transition: 0.3s;
|
||||
transition: 0.3s;
|
||||
}
|
||||
|
||||
button:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
a {
|
||||
-webkit-transition: 0.3s;
|
||||
-o-transition: 0.3s;
|
||||
transition: 0.3s;
|
||||
}
|
||||
a:hover {
|
||||
text-decoration: none;
|
||||
color: #242B58;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
p, li, span {
|
||||
color: #242B58;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* reset css end */
|
||||
/* global css start */
|
||||
|
||||
/* global css end */
|
||||
|
||||
.height-50 {
|
||||
height: 40px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.pt-232 {
|
||||
padding-top: 232px;
|
||||
}
|
||||
|
||||
.section-heading {
|
||||
position: relative;
|
||||
}
|
||||
.section-heading h2 {
|
||||
font-size: 42px;
|
||||
line-height: 51px;
|
||||
display: inline-block;
|
||||
position: relative;
|
||||
padding-right: 15px;
|
||||
color: rgb(255 115 0 / 25%);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.section-heading h2 {
|
||||
font-size: 36px;
|
||||
line-height: 45px;
|
||||
}
|
||||
}
|
||||
@media only screen and (min-width: 576px) and (max-width: 767px) {
|
||||
.section-heading h2 {
|
||||
font-size: 42px;
|
||||
line-height: 51px;
|
||||
}
|
||||
}
|
||||
.section-heading h2::after {
|
||||
width: 160px;
|
||||
height: 100px;
|
||||
right: 0px;
|
||||
content: "";
|
||||
position: absolute;
|
||||
bottom: 0px;
|
||||
background: #b8dee094;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
/*--
|
||||
- Margin & Padding
|
||||
-----------------------------------------*/
|
||||
/*-- Margin Top --*/
|
||||
|
||||
/*-- Margin Top --*/
|
||||
|
||||
.mt-175 {
|
||||
margin-top: 175px;
|
||||
}
|
||||
|
||||
/*-- Margin Bottom --*/
|
||||
|
||||
/*-- Margin Left --*/
|
||||
|
||||
/*-- Margin Right --*/
|
||||
|
||||
/*-- Padding Top --*/
|
||||
|
||||
/*-- Padding Bottom --*/
|
||||
|
||||
/*-- Padding Left --*/
|
||||
|
||||
/*-- Padding Right --*/
|
||||
|
||||
/* typography css start */
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
font-weight: 700;
|
||||
color: #242B58;
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
font-family: "Microsoft YaHei", "微软雅黑", "Josefin Sans", sans-serif;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 32px;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
h5 {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
h6 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* typography css end */
|
||||
/*--
|
||||
- Overlay
|
||||
------------------------------------------*/
|
||||
|
||||
/*-- Overlay Color --*/
|
||||
|
||||
/*-- Overlay Opacity --*/
|
||||
|
||||
/* Heder css start*/
|
||||
.site-header {
|
||||
margin-top: 15px;
|
||||
padding: 25px 0px;
|
||||
position: absolute;
|
||||
width: 100%;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* Navigation css */
|
||||
|
||||
/* form css start */
|
||||
label {
|
||||
font-size: fsize("14px");
|
||||
}
|
||||
|
||||
input:not([type=radio]),
|
||||
textarea {
|
||||
padding: 10px 20px;
|
||||
border-radius: 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
-ms-border-radius: 5px;
|
||||
-o-border-radius: 5px;
|
||||
background-color: transparent;
|
||||
font-size: fsize("14px") !important;
|
||||
}
|
||||
input:not([type=radio])::-webkit-input-placeholder,
|
||||
textarea::-webkit-input-placeholder {
|
||||
color: #c9c9c9 !important;
|
||||
opacity: 1;
|
||||
}
|
||||
input:not([type=radio])::-moz-placeholder,
|
||||
textarea::-moz-placeholder {
|
||||
color: #c9c9c9 !important;
|
||||
opacity: 1;
|
||||
}
|
||||
input:not([type=radio]):-ms-input-placeholder,
|
||||
textarea:-ms-input-placeholder {
|
||||
color: #c9c9c9 !important;
|
||||
opacity: 1;
|
||||
}
|
||||
input:not([type=radio]):-moz-placeholder,
|
||||
textarea:-moz-placeholder {
|
||||
color: #c9c9c9 !important;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
select {
|
||||
padding: 8px 10px;
|
||||
cursor: pointer;
|
||||
color: #242B58;
|
||||
background-color: transparent;
|
||||
border-radius: 0;
|
||||
-webkit-border-radius: 0;
|
||||
-moz-border-radius: 0;
|
||||
-ms-border-radius: 0;
|
||||
-o-border-radius: 0;
|
||||
}
|
||||
|
||||
textarea {
|
||||
min-height: 100px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
input[type=radio],
|
||||
input[type=range],
|
||||
input[type=checkbox] {
|
||||
height: auto !important;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* form css end */
|
||||
/* hero area css*/
|
||||
|
||||
.hero-content {
|
||||
position: relative;
|
||||
margin-top: 30px;
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
.hero-content h4 {
|
||||
position: relative;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
color: #12152f;
|
||||
padding-left: 65px;
|
||||
line-height: 29px;
|
||||
}
|
||||
@media (max-width: 1199px) {
|
||||
.hero-content h4 {
|
||||
font-size: 18px;
|
||||
line-height: 23px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.hero-content h4 {
|
||||
font-size: 16px;
|
||||
line-height: 21px;
|
||||
}
|
||||
}
|
||||
.hero-content h4::after {
|
||||
width: 50px;
|
||||
height: 2px;
|
||||
background: #5beeb1;
|
||||
left: 0px;
|
||||
top: 50%;
|
||||
-webkit-transition: translateY(-50%);
|
||||
-o-transition: translateY(-50%);
|
||||
transition: translateY(-50%);
|
||||
content: "";
|
||||
position: absolute;
|
||||
}
|
||||
.hero-content h1 {
|
||||
margin-top: 20px;
|
||||
font-size: 82px;
|
||||
line-height: 99px;
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
margin-bottom: 30px;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
}
|
||||
@media (max-width: 1650px) {
|
||||
.hero-content h1 {
|
||||
font-size: 70px;
|
||||
line-height: 87px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 1199px) {
|
||||
.hero-content h1 {
|
||||
font-size: 45px;
|
||||
line-height: 62px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.hero-content h1 {
|
||||
font-size: 30px;
|
||||
line-height: 47px;
|
||||
}
|
||||
}
|
||||
@media only screen and (min-width: 576px) and (max-width: 767px) {
|
||||
.hero-content h1 {
|
||||
font-size: 45px;
|
||||
line-height: 62px;
|
||||
}
|
||||
}
|
||||
.hero-content h1 span {
|
||||
font-weight: 300;
|
||||
display: block;
|
||||
color: #ffffff;
|
||||
}
|
||||
.hero-content p {
|
||||
color: #B0B0B2;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
/* About css */
|
||||
.about-area {
|
||||
position: relative;
|
||||
padding-top: 40px;
|
||||
}
|
||||
|
||||
.about-content h6 {
|
||||
color: #12152f;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 24px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.about-content h2 {
|
||||
color: #12152f;
|
||||
font-size: 28px;
|
||||
}
|
||||
.about-content p {
|
||||
color: #12152f;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
/* skill cass */
|
||||
|
||||
/* service css*/
|
||||
|
||||
/* work css */
|
||||
|
||||
/* testimonial css */
|
||||
|
||||
/* brand css */
|
||||
|
||||
/* blog css */
|
||||
|
||||
/* contact css */
|
||||
|
||||
/* breadcrumb css */
|
||||
|
||||
/* cta css */
|
||||
|
||||
/* contact page css */
|
||||
|
||||
/* blog page css */
|
||||
|
||||
/* single blog page css */
|
||||
|
||||
/* comment css */
|
||||
|
||||
/*Footer css*/
|
||||
.site-footer {
|
||||
border-top: 1px solid #00ff8c;
|
||||
padding: 30px 0px;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.copyright-text {
|
||||
text-align: center;
|
||||
margin-top: 20px;
|
||||
}
|
||||
}
|
||||
.copyright-text p {
|
||||
color: #17b874;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +0,0 @@
|
|||
.fa{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}@keyframes fa-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}@font-face{font-family:"Font Awesome 5 Brands";font-style:normal;font-weight:normal;font-display:auto;src:url(../fonts/fa-brands-400.eot);src:url(../fonts/fa-brands-400.eot) format("embedded-opentype"),url(../fonts/fa-brands-400.woff2) format("woff2"),url(../fonts/fa-brands-400.woff) format("woff"),url(../fonts/fa-brands-400.ttf) format("truetype"),url(../fonts/fa-brands-400.svg#fontawesome) format("svg")}@font-face{font-family:"Font Awesome 5 Pro";font-style:normal;font-weight:300;font-display:auto;src:url(../fonts/fa-light-300.eot);src:url(../fonts/fa-light-300.eot) format("embedded-opentype"),url(../fonts/fa-light-300.woff2) format("woff2"),url(../fonts/fa-light-300.woff) format("woff"),url(../fonts/fa-light-300.ttf) format("truetype"),url(../fonts/fa-light-300.svg#fontawesome) format("svg")}@font-face{font-family:"Font Awesome 5 Pro";font-style:normal;font-weight:400;font-display:auto;src:url(../fonts/fa-regular-400.eot);src:url(../fonts/fa-regular-400.eot) format("embedded-opentype"),url(../fonts/fa-regular-400.woff2) format("woff2"),url(../fonts/fa-regular-400.woff) format("woff"),url(../fonts/fa-regular-400.ttf) format("truetype"),url(../fonts/fa-regular-400.svg#fontawesome) format("svg")}@font-face{font-family:"Font Awesome 5 Pro";font-style:normal;font-weight:900;font-display:auto;src:url(../fonts/fa-solid-900.eot);src:url(../fonts/fa-solid-900.eot) format("embedded-opentype"),url(../fonts/fa-solid-900.woff2) format("woff2"),url(../fonts/fa-solid-900.woff) format("woff"),url(../fonts/fa-solid-900.ttf) format("truetype"),url(../fonts/fa-solid-900.svg#fontawesome) format("svg")}.fa{font-family:"Font Awesome 5 Pro";font-weight:900}
|
||||
|
|
@ -1,108 +0,0 @@
|
|||
/*!
|
||||
Theme: Default
|
||||
Description: Original highlight.js style
|
||||
Author: (c) Ivan Sagalaev <maniac@softwaremaniacs.org>
|
||||
Maintainer: @highlightjs/core-team
|
||||
Website: https://highlightjs.org/
|
||||
License: see project LICENSE
|
||||
Touched: 2021
|
||||
*/
|
||||
pre {
|
||||
white-space: pre-wrap; /* 允许换行 */
|
||||
word-wrap: break-word; /* 允许在单词内换行 */
|
||||
max-width: 100%; /* 最大宽度为父容器的宽度 */
|
||||
overflow: auto; /* 添加滚动条 */
|
||||
}
|
||||
|
||||
pre code.hljs {
|
||||
display: block;
|
||||
overflow-x: auto;
|
||||
padding: 1em
|
||||
}
|
||||
|
||||
code.hljs {
|
||||
padding: 3px 5px
|
||||
}
|
||||
|
||||
.hljs {
|
||||
background: #f3f3f3;
|
||||
color: #444
|
||||
}
|
||||
|
||||
.hljs-comment {
|
||||
color: #697070
|
||||
}
|
||||
|
||||
.hljs-punctuation,
|
||||
.hljs-tag {
|
||||
color: #444a
|
||||
}
|
||||
|
||||
.hljs-tag .hljs-attr,
|
||||
.hljs-tag .hljs-name {
|
||||
color: #444
|
||||
}
|
||||
|
||||
.hljs-attribute,
|
||||
.hljs-doctag,
|
||||
.hljs-keyword,
|
||||
.hljs-meta .hljs-keyword,
|
||||
.hljs-name,
|
||||
.hljs-selector-tag {
|
||||
font-weight: 700
|
||||
}
|
||||
|
||||
.hljs-deletion,
|
||||
.hljs-number,
|
||||
.hljs-quote,
|
||||
.hljs-selector-class,
|
||||
.hljs-selector-id,
|
||||
.hljs-string,
|
||||
.hljs-template-tag,
|
||||
.hljs-type {
|
||||
color: #800
|
||||
}
|
||||
|
||||
.hljs-section,
|
||||
.hljs-title {
|
||||
color: #800;
|
||||
font-weight: 700
|
||||
}
|
||||
|
||||
.hljs-link,
|
||||
.hljs-operator,
|
||||
.hljs-regexp,
|
||||
.hljs-selector-attr,
|
||||
.hljs-selector-pseudo,
|
||||
.hljs-symbol,
|
||||
.hljs-template-variable,
|
||||
.hljs-variable {
|
||||
color: #ab5656
|
||||
}
|
||||
|
||||
.hljs-literal {
|
||||
color: #695
|
||||
}
|
||||
|
||||
.hljs-addition,
|
||||
.hljs-built_in,
|
||||
.hljs-bullet,
|
||||
.hljs-code {
|
||||
color: #397300
|
||||
}
|
||||
|
||||
.hljs-meta {
|
||||
color: #1f7199
|
||||
}
|
||||
|
||||
.hljs-meta .hljs-string {
|
||||
color: #38a
|
||||
}
|
||||
|
||||
.hljs-emphasis {
|
||||
font-style: italic
|
||||
}
|
||||
|
||||
.hljs-strong {
|
||||
font-weight: 700
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue