7
7
const { createServer : Server , IncomingMessage, ServerResponse} = require ( 'node:http' ) , { createHash : Hash , randomUUID, randomInt, randomBytes} = require ( 'node:crypto' ) , { TransformStream, ReadableStream} = require ( 'node:stream/web' ) , { Readable, Writable} = require ( 'node:stream' ) , { Blob} = require ( 'node:buffer' ) , { existsSync : exists , writeFileSync : write , createWriteStream} = require ( 'node:fs' ) , { join : joinP } = require ( 'node:path' ) , { ClewdSuperfetch : Superfetch , SuperfetchAvailable} = require ( './lib/clewd-superfetch' ) , { AI , fileName, genericFixes, bytesToSize, setTitle, checkResErr, Replacements, Main} = require ( './lib/clewd-utils' ) , ClewdStream = require ( './lib/clewd-stream' ) ;
8
8
9
9
/******************************************************* */
10
- let currentIndex , Firstlogin = true , changeflag = 0 , changetime = 0 , totaltime , uuidOrgArray = [ ] , model , tokens , apiKey ;
10
+ let currentIndex , Firstlogin = true , changeflag = 0 , changetime = 0 , totaltime , invalidtime = 0 , uuidOrgArray = [ ] , model , tokens , apiKey , timestamp = Date . now ( ) ;
11
11
12
12
const events = require ( 'events' ) , CookieChanger = new events . EventEmitter ( ) ;
13
13
require ( 'events' ) . EventEmitter . defaultMaxListeners = 0 ;
14
14
15
15
CookieChanger . on ( 'ChangeCookie' , ( ) => {
16
- changeflag = 0 ;
17
- Proxy && Proxy . close ( ) ;
18
- console . log ( `Changing Cookie...\n` ) ;
19
- Proxy . listen ( Config . Port , Config . Ip , onListen ) ;
20
- Proxy . on ( 'error' , ( err => {
21
- console . error ( 'Proxy error\n%o' , err ) ;
22
- } ) ) ;
16
+ setTimeout ( ( ) => {
17
+ changeflag = 0 ;
18
+ Proxy && Proxy . close ( ) ;
19
+ console . log ( `Changing Cookie...\n` ) ;
20
+ Proxy . listen ( Config . Port , Config . Ip , onListen ) ;
21
+ Proxy . on ( 'error' , ( err => {
22
+ console . error ( 'Proxy error\n%o' , err ) ;
23
+ } ) ) ;
24
+ timestamp = Date . now ( ) ;
25
+ invalidtime += 1 ;
26
+ } , ! Config . rProxy || Config . rProxy === AI . end ( ) ? 15000 + timestamp - Date . now ( ) : 0 ) ;
23
27
} ) ;
24
28
25
29
const convertToType = value => {
@@ -37,10 +41,9 @@ const convertToType = value => {
37
41
const placeholder = Config . padtxt_placeholder || randomBytes ( randomInt ( 5 , 15 ) ) . toString ( 'hex' ) ;
38
42
tokens = countTokens ( content ) ;
39
43
const padding = placeholder . repeat ( Math . floor ( Math . max ( 1000 , Config . Settings . padtxt - tokens ) / countTokens ( placeholder . trim ( ) ) ) ) ;
40
- content = content . includes ( '<|padtxt|>' ) ? content . replace ( / < \| p a d t x t \| > / , padding ) : ! apiKey ? padding + '\n\n\n' + content . trim ( ) : content ;
44
+ content = content . includes ( '<|padtxt|>' ) ? content . replace ( / < \| p a d t x t \| > / gm , padding ) : ! apiKey ? padding + '\n\n\n' + content . trim ( ) : content ;
41
45
return content ;
42
46
} , xmlPlot = ( content , nonsys = false ) => {
43
- const card = content . includes ( '<card>' ) || content . includes ( '<|card|>' ) ;
44
47
//role合并
45
48
const MergeDisable = content . includes ( '<|Merge Disable|>' ) ;
46
49
const MergeHumanDisable = content . includes ( '<|Merge Human Disable|>' ) ;
@@ -94,13 +97,7 @@ const convertToType = value => {
94
97
if ( ! apiKey && segcontentlastIndex >= 2 && segcontentHuman [ segcontentlastIndex ] . includes ( '<|Plain Prompt Enable|>' ) && ! content . includes ( '\n\nPlainPrompt:' ) ) {
95
98
content = segcontentHuman . slice ( 0 , segcontentlastIndex ) . join ( '\n\nHuman:' ) + '\n\nPlainPrompt:' + segcontentHuman . slice ( segcontentlastIndex ) . join ( '\n\nHuman:' ) . replace ( / \n \n H u m a n : * P l a i n P r o m p t : / , '\n\nPlainPrompt:' ) ;
96
99
}
97
- //<card>群组
98
- if ( ! card ) {
99
- return content . replace ( / ( < r e p l y > \n | \n < \/ r e p l y > ) / g, '' ) . replace ( / < c u s t o m n a m e > ( .* ?) < \/ c u s t o m n a m e > / gm, '$1' ) ;
100
- } else {
101
- content = content . replace ( / ( < r e p l y > \n | \n < \/ r e p l y > ) \1* / g, '$1' ) . replace ( / < c u s t o m n a m e > ( .* ?) < \/ c u s t o m n a m e > : / gm, '$1:\n' ) ;
102
- }
103
- //<card>消除空XML tags、两端空白符和多余的\n
100
+ //消除空XML tags、两端空白符和多余的\n
104
101
content = content . replace ( / \s * < \| c u r t a i l \| > \s * / g, '\n' )
105
102
. replace ( / \n < \/ ( c a r d | h i d d e n | M E T A ) > \s + ?< \1> \n / g, '\n' )
106
103
. replace ( / \n < ( \/ ? c a r d | e x a m p l e | h i d d e n | p l o t | M E T A ) > \s + ?< \1> / g, '\n<$1>' )
@@ -138,7 +135,7 @@ let uuidOrg, curPrompt = {}, prevPrompt = {}, prevMessages = [], prevImpersonate
138
135
localtunnel : false ,
139
136
BufferSize : 1 ,
140
137
SystemInterval : 3 ,
141
- rProxy : AI . end ( ) ,
138
+ rProxy : '' ,
142
139
api_rProxy : '' ,
143
140
padtxt_placeholder : '' ,
144
141
PromptExperimentFirst : '' ,
@@ -208,7 +205,7 @@ const updateParams = res => {
208
205
return ;
209
206
}
210
207
try { //
211
- const res = await fetch ( `${ Config . rProxy } /api/organizations/${ uuidOrg } /chat_conversations/${ uuid } ` , {
208
+ const res = await fetch ( `${ Config . rProxy || AI . end ( ) } /api/organizations/${ uuidOrg } /chat_conversations/${ uuid } ` , {
212
209
headers : {
213
210
...AI . hdr ( ) ,
214
211
Cookie : getCookies ( )
@@ -244,13 +241,13 @@ const updateParams = res => {
244
241
}
245
242
try {
246
243
/***************************** */
247
- if ( 'SET YOUR COOKIE HERE' === Config . Cookie || Config . Cookie ?. length < 1 ) {
244
+ if ( 'SET YOUR COOKIE HERE' === Config . Cookie || Config . Cookie ?. length < 1 || ( Config . CookieArray ?. length > 0 && invalidtime >= totaltime ) ) { //if ('SET YOUR COOKIE HERE' === Config.Cookie || Config.Cookie?.length < 1 ) {
248
245
return console . log ( `[33mNo cookie available, apiKey-Only mode enabled.[0m\n` ) ; //throw Error('Set your cookie inside config.js');
249
246
}
250
247
updateCookies ( Config . Cookie . replace ( / ^ ( s e s s i o n K e y = ) ? / , 'sessionKey=' ) ) ; //updateCookies(Config.Cookie);
251
248
//console.log(`[2m${Main}[0m\n[33mhttp://${Config.Ip}:${Config.Port}/v1[0m\n\n${Object.keys(Config.Settings).map((setting => UnknownSettings.includes(setting) ? `??? [31m${setting}: ${Config.Settings[setting]}[0m` : `[1m${setting}:[0m ${ChangedSettings.includes(setting) ? '[33m' : '[36m'}${Config.Settings[setting]}[0m`)).sort().join('\n')}\n`);
252
249
//Config.Settings.Superfetch && SuperfetchAvailable(true);
253
- const accRes = await fetch ( Config . rProxy + '/api/organizations' , {
250
+ const accRes = await fetch ( ( Config . rProxy || AI . end ( ) ) + '/api/organizations' , {
254
251
method : 'GET' ,
255
252
headers : {
256
253
...AI . hdr ( ) ,
@@ -276,7 +273,7 @@ const updateParams = res => {
276
273
setTitle ( 'ok' ) ;
277
274
updateParams ( accRes ) ;
278
275
/**************************** */
279
- const accountRes = await fetch ( Config . rProxy + '/api/auth/current_account' , {
276
+ const accountRes = await fetch ( ( Config . rProxy || AI . end ( ) ) + '/api/auth/current_account' , {
280
277
method : 'GET' ,
281
278
headers : {
282
279
...AI . hdr ( ) ,
@@ -335,7 +332,7 @@ const updateParams = res => {
335
332
if ( 'consumer_restricted_mode' === type || 'consumer_banned' === type ) { //if ('consumer_restricted_mode' === type) {
336
333
return ;
337
334
}
338
- const req = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( `${ Config . rProxy } /api/organizations/${ uuidOrg } /flags/${ type } /dismiss` , {
335
+ const req = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( `${ Config . rProxy || AI . end ( ) } /api/organizations/${ uuidOrg } /flags/${ type } /dismiss` , {
339
336
headers : {
340
337
...AI . hdr ( ) ,
341
338
Cookie : getCookies ( )
@@ -359,7 +356,7 @@ const updateParams = res => {
359
356
return CookieChanger . emit ( 'ChangeCookie' ) ;
360
357
/***************************** */
361
358
}
362
- const convRes = await fetch ( `${ Config . rProxy } /api/organizations/${ uuidOrg } /chat_conversations` , {
359
+ const convRes = await fetch ( `${ Config . rProxy || AI . end ( ) } /api/organizations/${ uuidOrg } /chat_conversations` , {
363
360
method : 'GET' ,
364
361
headers : {
365
362
...AI . hdr ( ) ,
@@ -369,6 +366,7 @@ const updateParams = res => {
369
366
updateParams ( convRes ) ;
370
367
conversations . length > 0 && await Promise . all ( conversations . map ( ( conv => deleteChat ( conv . uuid ) ) ) ) ;
371
368
/***************************** */
369
+ invalidtime = 0 ;
372
370
} catch ( err ) {
373
371
console . error ( '[33mClewd:[0m\n%o' , err ) ;
374
372
Config . CookieArray ?. length > 0 && CookieChanger . emit ( 'ChangeCookie' ) ;
@@ -429,15 +427,20 @@ const updateParams = res => {
429
427
const body = JSON . parse ( Buffer . concat ( buffer ) . toString ( ) ) , temperature = Math . max ( .1 , Math . min ( 1 , body . temperature ) ) ;
430
428
let { messages} = body ;
431
429
/************************* */
432
- apiKey = / (?< = ^ B e a r e r \s * ) s k - a n t - a p i [ \w - ] * (? = \s * ) $ / . exec ( req . headers . authorization ) ;
433
- let api_max_tokens , api_model ;
430
+ apiKey = req . headers . authorization ?. match ( / s k - a n t - a p i \d \d - [ \w - ] { 86 } - [ \w - ] { 6 } A A / g ) ;
431
+ let max_tokens_to_sample , stop_sequences ;
434
432
if ( apiKey ) {
435
- apiKey = apiKey [ 0 ] ;
436
- api_max_tokens = body . max_tokens ;
437
- api_model = body . model ;
438
- if ( ! api_model . includes ( 'claude' ) ) throw Error ( 'Please change to claude model in "External"' ) ;
433
+ stop_sequences = body . stop ;
434
+ max_tokens_to_sample = body . max_tokens ;
435
+ model = body . model ;
436
+ if ( ! model . includes ( 'claude' ) ) throw Error ( 'Please change to claude model in "External"' ) ;
437
+ } else if ( req . headers . authorization . includes ( 'sk-ant-api' ) ) {
438
+ throw Error ( 'apiKey Wrong' ) ;
439
439
} else if ( Config . ProxyPassword != '' && req . headers . authorization != 'Bearer ' + Config . ProxyPassword ) {
440
440
throw Error ( 'ProxyPassword Wrong' ) ;
441
+ } else if ( Config . CookieArray ?. length > 0 && invalidtime >= Config . CookieArray ?. length ) {
442
+ invalidtime = 0 ;
443
+ return CookieChanger . emit ( 'ChangeCookie' ) ;
441
444
}
442
445
/************************* */
443
446
if ( messages ?. length < 1 ) {
@@ -518,7 +521,7 @@ const updateParams = res => {
518
521
const names = Object . keys ( headers ) , values = Object . values ( headers ) ;
519
522
headers = names . map ( ( ( header , idx ) => `${ header } : ${ values [ idx ] } ` ) ) ;
520
523
}
521
- res = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( Config . rProxy + '/api/retry_message' , {
524
+ res = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( ( Config . rProxy || AI . end ( ) ) + '/api/retry_message' , {
522
525
stream : true ,
523
526
signal,
524
527
method : 'POST' ,
@@ -534,7 +537,7 @@ const updateParams = res => {
534
537
fetchAPI = await ( async signal => {
535
538
Conversation . uuid = randomUUID ( ) . toString ( ) ;
536
539
Conversation . depth = 0 ;
537
- const res = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( `${ Config . rProxy } /api/organizations/${ uuidOrg } /chat_conversations` , {
540
+ const res = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( `${ Config . rProxy || AI . end ( ) } /api/organizations/${ uuidOrg } /chat_conversations` , {
538
541
signal,
539
542
headers : {
540
543
...AI . hdr ( ) ,
@@ -643,8 +646,8 @@ const updateParams = res => {
643
646
/******************************** */
644
647
if ( Config . Settings . xmlPlot ) {
645
648
idx > 0 && ( spacing = '\n\n' ) ;
646
- const prefix = message . customname ? message . role + ': <customname> ' + message . name + '</customname> : ' : 'system' !== message . role || message . name ? Replacements [ message . name || message . role ] + ': ' : 'xmlPlot: ' + Replacements [ message . role ] ;
647
- return `${ spacing } ${ prefix } ${ message . customname ? '<reply>\n' + message . content . trim ( ) + '\n</reply>' : message . content } ` ;
649
+ const prefix = message . customname ? message . role + ': ' + message . name + ': ' : 'system' !== message . role || message . name ? Replacements [ message . name || message . role ] + ': ' : 'xmlPlot: ' + Replacements [ message . role ] ;
650
+ return `${ spacing } ${ message . strip ? '' : prefix } ${ message . content } ` ;
648
651
} else {
649
652
/******************************** */
650
653
idx > 0 && ( spacing = systemMessages . includes ( message ) ? '\n' : '\n\n' ) ;
@@ -657,16 +660,16 @@ const updateParams = res => {
657
660
systems
658
661
} ;
659
662
} ) ( messages , type ) ;
660
- console . log ( `${ apiKey ? api_model : model } [[2m${ type } [0m]${ ! retryRegen && systems . length > 0 ? ' ' + systems . join ( ' [33m/[0m ' ) : '' } ` ) ; //console.log(`${model} [[2m${type}[0m]${!retryRegen && systems.length > 0 ? ' ' + systems.join(' [33m/[0m ') : ''}`);
663
+ console . log ( `${ model } [[2m${ type } [0m]${ ! retryRegen && systems . length > 0 ? ' ' + systems . join ( ' [33m/[0m ' ) : '' } ` ) ; //console.log(`${model} [[2m${type}[0m]${!retryRegen && systems.length > 0 ? ' ' + systems.join(' [33m/[0m ') : ''}`);
661
664
'R' !== type || prompt || ( prompt = '...regen...' ) ;
662
665
/******************************** */
663
- prompt = Config . Settings . xmlPlot ? xmlPlot ( prompt , api_model && api_model != 'claude-2.1' ) : apiKey ? `\n\nHuman: ${ genericFixes ( prompt ) } \n\nAssistant: ` : genericFixes ( prompt ) ;
666
+ prompt = Config . Settings . xmlPlot ? xmlPlot ( prompt , model != AI . mdl ( ) ) : apiKey ? `\n\nHuman: ${ genericFixes ( prompt ) } \n\nAssistant: ` : genericFixes ( prompt ) ;
664
667
Config . Settings . FullColon && ( prompt = apiKey
665
668
? prompt . replace ( / ( \n \n A s s i s t a n t | \n \n H u m a n ) : / , function ( match , p1 ) { return p1 === '\n\nHuman' ? match : p1 + ':' } ) . replace ( / ( \n \n A s s i s t a n t | \n \n H u m a n ) : (? ! .* ?\n \n ( A s s i s t a n t | H u m a n ) : ) / s, function ( match , p1 ) { return p1 === '\n\nAssistant' ? match : p1 + ':' } )
666
669
: prompt . replace ( / (?< = \n \n ( H (?: u m a n ) ? | A (?: s s i s t a n t ) ? ) ) : [ ] ? / g, ': ' ) ) ;
667
670
Config . Settings . padtxt && ( prompt = padtxt ( prompt ) ) ;
668
671
/******************************** */
669
- Logger ?. write ( `\n\n-------\n[${ ( new Date ) . toLocaleString ( ) } ]\n####### ${ apiKey ? api_model : model } PROMPT (${ type } ):\n${ prompt } \n--\n####### [Tokens: ${ tokens } ] REPLY:\n` ) ; //Logger?.write(`\n\n-------\n[${(new Date).toLocaleString()}]\n####### PROMPT (${type}):\n${prompt}\n--\n####### REPLY:\n`);
672
+ Logger ?. write ( `\n\n-------\n[${ ( new Date ) . toLocaleString ( ) } ]\n####### ${ model } (${ type } ) ${ tokens } t PROMPT :\n${ prompt } \n--\n####### REPLY:\n` ) ; //Logger?.write(`\n\n-------\n[${(new Date).toLocaleString()}]\n####### PROMPT (${type}):\n${prompt}\n--\n####### REPLY:\n`);
670
673
retryRegen || ( fetchAPI = await ( async ( signal , model , prompt , temperature , type ) => {
671
674
/******************************** */
672
675
if ( apiKey ) {
@@ -675,12 +678,13 @@ const updateParams = res => {
675
678
signal,
676
679
headers : {
677
680
'Content-Type' : 'application/json' ,
678
- 'x-api-key' : apiKey ,
681
+ 'x-api-key' : apiKey [ Math . floor ( Math . random ( ) * apiKey . length ) ] ,
679
682
'anthropic-version' : '2023-06-01'
680
683
} ,
681
684
body : JSON . stringify ( {
682
- model : api_model ,
683
- max_tokens_to_sample : api_max_tokens ,
685
+ ...stop_sequences && { stop_sequences} ,
686
+ model,
687
+ max_tokens_to_sample,
684
688
stream : true ,
685
689
prompt,
686
690
temperature
@@ -723,7 +727,7 @@ const updateParams = res => {
723
727
Accept : 'text/event-stream' ,
724
728
Cookie : getCookies ( )
725
729
} ;
726
- res = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( Config . rProxy + '/api/append_message' , {
730
+ res = await ( Config . Settings . Superfetch ? Superfetch : fetch ) ( ( Config . rProxy || AI . end ( ) ) + '/api/append_message' , {
727
731
stream : true ,
728
732
signal,
729
733
method : 'POST' ,
@@ -779,7 +783,7 @@ const updateParams = res => {
779
783
await deleteChat ( Conversation . uuid ) ;
780
784
/******************************** */
781
785
changeflag += 1 ;
782
- if ( Config . CookieArray ?. length > 0 && ( 429 == fetchAPI ?. status || Config . Cookiecounter && changeflag >= Config . Cookiecounter ) ) {
786
+ if ( Config . CookieArray ?. length > 0 && ( 429 == fetchAPI ?. status || Config . Cookiecounter > 0 && changeflag >= Config . Cookiecounter ) ) {
783
787
changeflag = 0 ;
784
788
CookieChanger . emit ( 'ChangeCookie' ) ;
785
789
}
@@ -856,7 +860,7 @@ const updateParams = res => {
856
860
Config [ key ] = process . env [ key ] ? convertToType ( process . env [ key ] ) : Config [ key ] ;
857
861
}
858
862
}
859
- Config . rProxy = Config . rProxy ? Config . rProxy . replace ( / \/ $ / , '' ) : AI . end ( ) ;
863
+ Config . rProxy = Config . rProxy . replace ( / \/ $ / , '' ) ;
860
864
Config . CookieArray = [ ...new Set ( [ Config . CookieArray ] . join ( '' ) . match ( / ( s e s s i o n K e y = ) ? s k - a n t - s i d 0 1 - [ \w - ] { 86 } - [ \w - ] { 6 } A A / g) ) ] ;
861
865
writeSettings ( Config ) ;
862
866
currentIndex = Config . CookieIndex > 0 ? Config . CookieIndex - 1 : Config . Cookiecounter >= 0 ? Math . floor ( Math . random ( ) * Config . CookieArray . length ) : 0 ;
0 commit comments