teralomaniac commited on
Commit
706ee05
1 Parent(s): daae8d5

Upload 11 files

Browse files
Files changed (4) hide show
  1. clewd.js +105 -80
  2. lib/clewd-stream.js +1 -1
  3. lib/clewd-utils.js +1 -1
  4. package.json +1 -1
clewd.js CHANGED
@@ -7,7 +7,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
 
9
  /******************************************************* */
10
- let currentIndex, Firstlogin = true, changeflag = 0, changetime = 0, totaltime, uuidOrgArray = [], model;
11
 
12
  const events = require('events'), CookieChanger = new events.EventEmitter();
13
  require('events').EventEmitter.defaultMaxListeners = 0;
@@ -22,20 +22,21 @@ CookieChanger.on('ChangeCookie', () => {
22
  }));
23
  });
24
 
25
- const CookieCleaner = () => {
 
 
 
 
 
26
  Config.CookieArray = Config.CookieArray.filter(item => item !== Config.Cookie);
27
  !process.env.Cookie && !process.env.CookieArray && writeSettings(Config);
28
  currentIndex = (currentIndex - 1 + Config.CookieArray.length) % Config.CookieArray.length;
29
  }, padtxt = content => {
30
- const {encode} = require('gpt-tokenizer');
31
  const placeholder = Config.padtxt_placeholder || randomBytes(randomInt(5, 15)).toString('hex');
32
- let count = Math.floor(Math.max(1000, Config.Settings.padtxt - encode(content).length) / encode(placeholder).length);
33
- let padding = '';
34
- for (let i = 0; i < count; i++) {
35
- padding += placeholder;
36
- }
37
- content = padding + '\n\n\n' + content;
38
- return content.trim();
39
  }, xmlPlot = content => {
40
  // 检查内容中是否包含"<card>"
41
  const card = content.includes('<card>');
@@ -53,13 +54,14 @@ const CookieCleaner = () => {
53
  const MergeHumanDisable = content.includes('<\!-- Merge Human Disable -->');
54
  const MergeAssistantDisable = content.includes('<\!-- Merge Assistant Disable -->');
55
  if (!MergeDisable) {
56
- if (content.includes('<\!-- Merge System Disable -->') || !card) {
57
  content = content.replace(/(\n\n|^\s*)xmlPlot:\s*/gm, '$1');
58
  }
59
  if (!MergeHumanDisable) {
 
60
  content = content.replace(/(\n\n|^\s*)xmlPlot:/g, '$1Human:');
61
  content = content.replace(/(?:\n\n|^\s*)Human:(.*?(?:\n\nAssistant:|$))/gs, function(match, p1) {return '\n\nHuman:' + p1.replace(/\n\nHuman:\s*/g, '\n\n')});
62
- content = content.replace(/^\s*Human:\s*/, '');
63
  }
64
  if (!MergeAssistantDisable) {
65
  content = content.replace(/\n\nAssistant:(.*?(?:\n\nHuman:|$))/gs, function(match, p1) {return '\n\nAssistant:' + p1.replace(/\n\nAssistant:\s*/g, '\n\n')});
@@ -130,7 +132,7 @@ const CookieCleaner = () => {
130
  content = content.replace(/(?<=(: |\n)<(card|hidden|example|plot|META|EOT)>\n)\s*/g, '');
131
  content = content.replace(/\s*(?=\n<\/(card|hidden|example|plot|META|EOT)>(\n|$))/g, '');
132
  content = content.replace(/(?<=\n)\n(?=\n)/g, '');
133
- return content.trim();
134
  };
135
  /******************************************************* */
136
 
@@ -154,6 +156,7 @@ let uuidOrg, curPrompt = {}, prevPrompt = {}, prevMessages = [], prevImpersonate
154
  BufferSize: 1,
155
  SystemInterval: 3,
156
  rProxy: AI.end(),
 
157
  padtxt_placeholder: '',
158
  PromptExperimentFirst: '',
159
  PromptExperimentNext: '',
@@ -258,6 +261,7 @@ const updateParams = res => {
258
  console.log(`\n※※※Cookie cleanup completed※※※\n\n`);
259
  return process.exit();
260
  }
 
261
  /***************************** */
262
  if ('SET YOUR COOKIE HERE' === Config.Cookie || Config.Cookie?.length < 1) {
263
  throw Error('Set your cookie inside config.js');
@@ -278,8 +282,7 @@ const updateParams = res => {
278
  CookieCleaner();
279
  console.log(`Expired!`);
280
  Config.Cookiecounter < 0 && console.log(`[progress]: ${percentage.toFixed(2)}%\n[length]: ${Config.CookieArray.length}\n`);
281
- CookieChanger.emit('ChangeCookie');
282
- return;
283
  }
284
  /**************************** */
285
  await checkResErr(accRes);
@@ -301,7 +304,7 @@ const updateParams = res => {
301
  }
302
  });
303
  await checkResErr(accountRes);
304
- const accountInfo = (await accountRes.json());
305
  /**************************** */
306
  console.log(Config.CookieArray?.length > 0 ? `(index: ${currentIndex || Config.CookieArray.length}) Logged in %o` : 'Logged in %o', { //console.log('Logged in %o', {
307
  name: accInfo.name?.split('@')?.[0],
@@ -371,11 +374,8 @@ const updateParams = res => {
371
  return CookieChanger.emit('ChangeCookie');
372
  }
373
  }
374
- if (Config.Cookiecounter < 0) {
375
- console.log(`[progress]: ${percentage.toFixed(2)}%\n[length]: ${Config.CookieArray.length}\n`);
376
- return CookieChanger.emit('ChangeCookie');
377
- } else if (Exceededlimit) {
378
- console.log(`Exceeded limit!\n`);
379
  return CookieChanger.emit('ChangeCookie');
380
  /***************************** */
381
  }
@@ -388,6 +388,12 @@ const updateParams = res => {
388
  }), conversations = await convRes.json();
389
  updateParams(convRes);
390
  conversations.length > 0 && await Promise.all(conversations.map((conv => deleteChat(conv.uuid))));
 
 
 
 
 
 
391
  }, writeSettings = async (config, firstRun = false) => {
392
  write(ConfigPath, `/*\n* https://rentry.org/teralomaniac_clewd\n* https://github.com/teralomaniac/clewd\n*/\n\n// SET YOUR COOKIE BELOW\n\nmodule.exports = ${JSON.stringify(config, null, 4)}\n\n/*\n BufferSize\n * How many characters will be buffered before the AI types once\n * lower = less chance of \`PreventImperson\` working properly\n\n ---\n\n SystemInterval\n * How many messages until \`SystemExperiments alternates\`\n\n ---\n\n Other settings\n * https://gitgud.io/ahsk/clewd/#defaults\n * and\n * https://gitgud.io/ahsk/clewd/-/blob/master/CHANGELOG.md\n */`.trim().replace(/((?<!\r)\n|\r(?!\n))/g, '\r\n'));
393
  if (firstRun) {
@@ -408,7 +414,18 @@ const updateParams = res => {
408
  case '/v1/models':
409
  res.json({
410
  data: [ {
411
- id: AI.mdl()
 
 
 
 
 
 
 
 
 
 
 
412
  } ]
413
  });
414
  break;
@@ -416,7 +433,7 @@ const updateParams = res => {
416
  case '/v1/chat/completions':
417
  ((req, res) => {
418
  setTitle('recv...');
419
- let fetchAPI, changer; //let fetchAPI;
420
  const abortControl = new AbortController, {signal} = abortControl;
421
  res.socket.on('close', (async () => {
422
  abortControl.signal.aborted || abortControl.abort();
@@ -431,8 +448,13 @@ const updateParams = res => {
431
  const body = JSON.parse(Buffer.concat(buffer).toString()), temperature = Math.max(.1, Math.min(1, body.temperature));
432
  let {messages} = body;
433
  /************************* */
434
- const authorization = Object.fromEntries(Object.entries(req.headers).map(([key, value]) => [key, value])).authorization;
435
- if (Config.ProxyPassword != '' && authorization != 'Bearer ' + Config.ProxyPassword) {
 
 
 
 
 
436
  throw Error('ProxyPassword Wrong');
437
  }
438
  /************************* */
@@ -491,7 +513,7 @@ const updateParams = res => {
491
  retryRegen = Config.Settings.RetryRegenerate && samePrompt && null != Conversation.uuid;
492
  samePrompt || (prevMessages = JSON.parse(JSON.stringify(messages)));
493
  let type = '';
494
- if (retryRegen) {
495
  type = 'R';
496
  fetchAPI = await (async (signal, model) => {
497
  let res;
@@ -565,16 +587,16 @@ const updateParams = res => {
565
  if (next && !Config.Settings.xmlPlot) { //if (next) {
566
  if ('name' in message && 'name' in next) {
567
  if (message.name === next.name) {
568
- message.content += '\n\n' + next.content; //message.content += '\n' + next.content;
569
  next.merged = true;
570
  }
571
  } else if ('system' !== next.role) {
572
  if (next.role === message.role) {
573
- message.content += '\n\n' + next.content; //message.content += '\n' + next.content;
574
  next.merged = true;
575
  }
576
  } else {
577
- message.content += '\n\n' + next.content; //message.content += '\n' + next.content;
578
  next.merged = true;
579
  }
580
  }
@@ -622,7 +644,7 @@ const updateParams = res => {
622
  message.customname || delete message.name;
623
  }));
624
  let systems = [];
625
- if (![ 'r', 'R' ].includes(type)) {
626
  lastUser.strip = true;
627
  systemMessages.forEach((message => message.discard = message.discard || 'c-c' === type ? !message.jailbreak : !message.jailbreak && !message.main));
628
  systems = systemMessages.filter((message => !message.discard)).map((message => `"${message.content.substring(0, 25).replace(/\n/g, '\\n').trim()}..."`));
@@ -649,25 +671,45 @@ const updateParams = res => {
649
  } //
650
  }));
651
  return {
652
- prompt: prompt.join('').trim(),//genericFixes(prompt.join('')).trim(),
653
  systems
654
  };
655
  })(messages, type);
656
- console.log(`${model} [${type}]${!retryRegen && systems.length > 0 ? ' ' + systems.join(' / ') : ''}`);
657
  'R' !== type || prompt || (prompt = '...regen...');
658
  /******************************** */
659
  prompt = Config.Settings.xmlPlot ? xmlPlot(prompt) : genericFixes(prompt);
660
- Config.Settings.FullColon && (prompt = prompt.replace(/(?<=\n\n(H(?:uman)?|A(?:ssistant)?)):[ ]?/g, ': '));
661
  Config.Settings.padtxt && (prompt = padtxt(prompt));
662
  /******************************** */
663
- Logger?.write(`\n\n-------\n[${(new Date).toLocaleString()}]\n####### PROMPT (${type}):\n${prompt}\n--\n####### REPLY:\n`);
664
  retryRegen || (fetchAPI = await (async (signal, model, prompt, temperature, type) => {
665
- const attachments = [];
666
- if (Config.Settings.PromptExperiments) {
667
  /******************************** */
668
- let splitedprompt = prompt.split('\n\nPlainPrompt:');
669
- prompt = splitedprompt[0];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
670
  /******************************** */
 
 
 
 
671
  attachments.push({
672
  extracted_content: (prompt),
673
  file_name: 'paste.txt', //fileName(),
@@ -675,9 +717,7 @@ const updateParams = res => {
675
  file_type: 'txt' //'text/plain'
676
  });
677
  prompt = 'r' === type ? Config.PromptExperimentFirst : Config.PromptExperimentNext;
678
- /******************************** */
679
- splitedprompt.length > 1 && (prompt = prompt + splitedprompt[1]);
680
- /******************************** */
681
  }
682
  let res;
683
  const body = {
@@ -712,7 +752,13 @@ const updateParams = res => {
712
  })(signal, model, prompt, temperature, type));
713
  const response = Writable.toWeb(res);
714
  clewdStream = new ClewdStream({
715
- config: Config,
 
 
 
 
 
 
716
  version: Main,
717
  minSize: Config.BufferSize,
718
  model,
@@ -721,7 +767,7 @@ const updateParams = res => {
721
  source: fetchAPI
722
  }, Logger);
723
  titleTimer = setInterval((() => setTitle('recv ' + bytesToSize(clewdStream.size))), 300);
724
- Config.Settings.Superfetch ? await Readable.toWeb(fetchAPI.body).pipeThrough(clewdStream).pipeTo(response) : await fetchAPI.body.pipeThrough(clewdStream).pipeTo(response);
725
  } catch (err) {
726
  if ('AbortError' === err.name) {
727
  res.end();
@@ -743,22 +789,18 @@ const updateParams = res => {
743
  prevImpersonated = clewdStream.impersonated;
744
  setTitle('ok ' + bytesToSize(clewdStream.size));
745
  429 == fetchAPI.status ? console.log(`Exceeded limit!\n`) : console.log(`${200 == fetchAPI.status ? '' : ''}${fetchAPI.status}!\n`); //console.log(`${200 == fetchAPI.status ? '' : ''}${fetchAPI.status}!\n`);
 
 
 
 
746
  /******************************** */
747
  changeflag += 1;
748
- if (Config.CookieArray?.length > 0 && (429 == fetchAPI.status || (Config.Cookiecounter && changeflag >= Config.Cookiecounter))) {
749
  changeflag = 0;
750
- changer = true;
751
  }
752
  /******************************** */
753
- clewdStream.empty();
754
  }
755
- /*if (prevImpersonated) {
756
- await deleteChat(Conversation.uuid);
757
- }*/
758
- /******************************** */
759
- await deleteChat(Conversation.uuid);
760
- changer && CookieChanger.emit('ChangeCookie');
761
- /******************************** */
762
  }));
763
  })(req, res);
764
  break;
@@ -819,38 +861,21 @@ const updateParams = res => {
819
  Config.Cookie = 'SET YOUR COOKIE HERE';
820
  writeSettings(Config, true);
821
  }
822
- /***************************** */
823
- function convertToType(value) {
824
- if (value === "true") return true;
825
- if (value === "false") return false;
826
- if (/^\d+$/.test(value)) return parseInt(value);
827
- return value;
828
- }
829
- for (let key in Config) {
830
- if (key === 'Settings') {
831
- for (let setting in Config.Settings) {
832
- Config.Settings[setting] = convertToType(process.env[setting]) ?? Config.Settings[setting];
833
- }
834
- } else {
835
- Config[key] = key === 'CookieArray' ? (process.env[key]?.split(',')?.map(x => x.replace(/[\[\]"\s]/g, '')) ?? Config[key]) : (convertToType(process.env[key]) ?? Config[key]);
836
- }
837
- }
838
- /***************************** */
839
  })();
840
  /***************************** */
841
- !Config.rProxy && (Config.rProxy = AI.end());
842
- Config.rProxy.endsWith('/') && (Config.rProxy = Config.rProxy.slice(0, -1));
843
- let uniqueArr = [], seen = new Set();
844
- for (let Cookie of Config.CookieArray) {
845
- !/^sessionKey=/.test(Cookie) && (Cookie += 'sessionKey=');
846
- if (!seen.has(Cookie)) {
847
- uniqueArr.push(Cookie);
848
- seen.add(Cookie);
849
  }
850
  }
851
- Config.CookieArray = uniqueArr;
 
852
  !process.env.Cookie && !process.env.CookieArray && writeSettings(Config);
853
- currentIndex = Config.CookieIndex > 0 ? Config.CookieIndex - 1 : Config.Cookiecounter >= 0 ? Math.floor(Math.random()*Config.CookieArray.length) : 0;
854
  /***************************** */
855
  Proxy.listen(Config.Port, Config.Ip, onListen);
856
  Proxy.on('error', (err => {
 
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
 
9
  /******************************************************* */
10
+ let currentIndex, Firstlogin = true, changeflag = 0, changetime = 0, totaltime, uuidOrgArray = [], model, tokens, apiKey;
11
 
12
  const events = require('events'), CookieChanger = new events.EventEmitter();
13
  require('events').EventEmitter.defaultMaxListeners = 0;
 
22
  }));
23
  });
24
 
25
+ const convertToType = value => {
26
+ if (value === "true") return true;
27
+ if (value === "false") return false;
28
+ if (/^\d+$/.test(value)) return parseInt(value);
29
+ return value;
30
+ }, CookieCleaner = () => {
31
  Config.CookieArray = Config.CookieArray.filter(item => item !== Config.Cookie);
32
  !process.env.Cookie && !process.env.CookieArray && writeSettings(Config);
33
  currentIndex = (currentIndex - 1 + Config.CookieArray.length) % Config.CookieArray.length;
34
  }, padtxt = content => {
35
+ const {countTokens} = require('@anthropic-ai/tokenizer');
36
  const placeholder = Config.padtxt_placeholder || randomBytes(randomInt(5, 15)).toString('hex');
37
+ tokens = countTokens(content);
38
+ !apiKey && (content = placeholder.repeat(Math.floor(Math.max(1000, Config.Settings.padtxt - tokens) / countTokens(placeholder.trim()))) + '\n\n\n' + content.trim());
39
+ return content;
 
 
 
 
40
  }, xmlPlot = content => {
41
  // 检查内容中是否包含"<card>"
42
  const card = content.includes('<card>');
 
54
  const MergeHumanDisable = content.includes('<\!-- Merge Human Disable -->');
55
  const MergeAssistantDisable = content.includes('<\!-- Merge Assistant Disable -->');
56
  if (!MergeDisable) {
57
+ if (content.includes('<\!-- Merge System Disable -->')) {
58
  content = content.replace(/(\n\n|^\s*)xmlPlot:\s*/gm, '$1');
59
  }
60
  if (!MergeHumanDisable) {
61
+ const Human = /^\s*Human:/.test(content);
62
  content = content.replace(/(\n\n|^\s*)xmlPlot:/g, '$1Human:');
63
  content = content.replace(/(?:\n\n|^\s*)Human:(.*?(?:\n\nAssistant:|$))/gs, function(match, p1) {return '\n\nHuman:' + p1.replace(/\n\nHuman:\s*/g, '\n\n')});
64
+ !apiKey && !Human && (content = content.replace(/^\s*Human:\s*/, ''));
65
  }
66
  if (!MergeAssistantDisable) {
67
  content = content.replace(/\n\nAssistant:(.*?(?:\n\nHuman:|$))/gs, function(match, p1) {return '\n\nAssistant:' + p1.replace(/\n\nAssistant:\s*/g, '\n\n')});
 
132
  content = content.replace(/(?<=(: |\n)<(card|hidden|example|plot|META|EOT)>\n)\s*/g, '');
133
  content = content.replace(/\s*(?=\n<\/(card|hidden|example|plot|META|EOT)>(\n|$))/g, '');
134
  content = content.replace(/(?<=\n)\n(?=\n)/g, '');
135
+ return content.trim().replace(/^\s*Human:/, '\n\nHuman:');
136
  };
137
  /******************************************************* */
138
 
 
156
  BufferSize: 1,
157
  SystemInterval: 3,
158
  rProxy: AI.end(),
159
+ api_rProxy: '',
160
  padtxt_placeholder: '',
161
  PromptExperimentFirst: '',
162
  PromptExperimentNext: '',
 
261
  console.log(`\n※※※Cookie cleanup completed※※※\n\n`);
262
  return process.exit();
263
  }
264
+ try {
265
  /***************************** */
266
  if ('SET YOUR COOKIE HERE' === Config.Cookie || Config.Cookie?.length < 1) {
267
  throw Error('Set your cookie inside config.js');
 
282
  CookieCleaner();
283
  console.log(`Expired!`);
284
  Config.Cookiecounter < 0 && console.log(`[progress]: ${percentage.toFixed(2)}%\n[length]: ${Config.CookieArray.length}\n`);
285
+ return CookieChanger.emit('ChangeCookie');
 
286
  }
287
  /**************************** */
288
  await checkResErr(accRes);
 
304
  }
305
  });
306
  await checkResErr(accountRes);
307
+ const accountInfo = await accountRes.json();
308
  /**************************** */
309
  console.log(Config.CookieArray?.length > 0 ? `(index: ${currentIndex || Config.CookieArray.length}) Logged in %o` : 'Logged in %o', { //console.log('Logged in %o', {
310
  name: accInfo.name?.split('@')?.[0],
 
374
  return CookieChanger.emit('ChangeCookie');
375
  }
376
  }
377
+ if (Config.Cookiecounter < 0 || Exceededlimit) {
378
+ console.log(Config.Cookiecounter < 0 ? `[progress]: ${percentage.toFixed(2)}%\n[length]: ${Config.CookieArray.length}\n` : 'Exceeded limit!\n');
 
 
 
379
  return CookieChanger.emit('ChangeCookie');
380
  /***************************** */
381
  }
 
388
  }), conversations = await convRes.json();
389
  updateParams(convRes);
390
  conversations.length > 0 && await Promise.all(conversations.map((conv => deleteChat(conv.uuid))));
391
+ /***************************** */
392
+ } catch (err) {
393
+ console.error('Clewd:\n%o', err);
394
+ Config.CookieArray?.length > 0 && CookieChanger.emit('ChangeCookie');
395
+ }
396
+ /***************************** */
397
  }, writeSettings = async (config, firstRun = false) => {
398
  write(ConfigPath, `/*\n* https://rentry.org/teralomaniac_clewd\n* https://github.com/teralomaniac/clewd\n*/\n\n// SET YOUR COOKIE BELOW\n\nmodule.exports = ${JSON.stringify(config, null, 4)}\n\n/*\n BufferSize\n * How many characters will be buffered before the AI types once\n * lower = less chance of \`PreventImperson\` working properly\n\n ---\n\n SystemInterval\n * How many messages until \`SystemExperiments alternates\`\n\n ---\n\n Other settings\n * https://gitgud.io/ahsk/clewd/#defaults\n * and\n * https://gitgud.io/ahsk/clewd/-/blob/master/CHANGELOG.md\n */`.trim().replace(/((?<!\r)\n|\r(?!\n))/g, '\r\n'));
399
  if (firstRun) {
 
414
  case '/v1/models':
415
  res.json({
416
  data: [ {
417
+ /***************************** */
418
+ id: 'claude-2.1' },{
419
+ id: 'claude-2.0' },{
420
+ id: 'claude-v1.3' },{
421
+ id: 'claude-v1.3-100k' },{
422
+ id: 'claude-v1.2' },{
423
+ id: 'claude-v1.0' },{
424
+ id: 'claude-instant-1.2' },{
425
+ id: 'claude-instant-v1.1' },{
426
+ id: 'claude-instant-v1.1-100k' },{
427
+ id: 'claude-instant-v1.0' //id: AI.mdl()
428
+ /***************************** */
429
  } ]
430
  });
431
  break;
 
433
  case '/v1/chat/completions':
434
  ((req, res) => {
435
  setTitle('recv...');
436
+ let fetchAPI;
437
  const abortControl = new AbortController, {signal} = abortControl;
438
  res.socket.on('close', (async () => {
439
  abortControl.signal.aborted || abortControl.abort();
 
448
  const body = JSON.parse(Buffer.concat(buffer).toString()), temperature = Math.max(.1, Math.min(1, body.temperature));
449
  let {messages} = body;
450
  /************************* */
451
+ apiKey = /(?<=^Bearer \s*)sk-ant-api[\w-]*(?=\s*)$/.exec(req.headers.authorization);
452
+ let api_max_tokens, api_model;
453
+ if (apiKey) {
454
+ apiKey = apiKey[0];
455
+ api_max_tokens = body.max_tokens;
456
+ api_model = body.model;
457
+ } else if (Config.ProxyPassword != '' && req.headers.authorization != 'Bearer ' + Config.ProxyPassword) {
458
  throw Error('ProxyPassword Wrong');
459
  }
460
  /************************* */
 
513
  retryRegen = Config.Settings.RetryRegenerate && samePrompt && null != Conversation.uuid;
514
  samePrompt || (prevMessages = JSON.parse(JSON.stringify(messages)));
515
  let type = '';
516
+ if (apiKey) { type = 'api'; } else if (retryRegen) { //if (retryRegen) {
517
  type = 'R';
518
  fetchAPI = await (async (signal, model) => {
519
  let res;
 
587
  if (next && !Config.Settings.xmlPlot) { //if (next) {
588
  if ('name' in message && 'name' in next) {
589
  if (message.name === next.name) {
590
+ message.content += '\n' + next.content;
591
  next.merged = true;
592
  }
593
  } else if ('system' !== next.role) {
594
  if (next.role === message.role) {
595
+ message.content += '\n' + next.content;
596
  next.merged = true;
597
  }
598
  } else {
599
+ message.content += '\n' + next.content;
600
  next.merged = true;
601
  }
602
  }
 
644
  message.customname || delete message.name;
645
  }));
646
  let systems = [];
647
+ if (![ 'r', 'R', 'api' ].includes(type)) {
648
  lastUser.strip = true;
649
  systemMessages.forEach((message => message.discard = message.discard || 'c-c' === type ? !message.jailbreak : !message.jailbreak && !message.main));
650
  systems = systemMessages.filter((message => !message.discard)).map((message => `"${message.content.substring(0, 25).replace(/\n/g, '\\n').trim()}..."`));
 
671
  } //
672
  }));
673
  return {
674
+ prompt: prompt.join('').trim(), //genericFixes(prompt.join('')).trim(),
675
  systems
676
  };
677
  })(messages, type);
678
+ console.log(`${apiKey ? api_model : model} [${type}]${!retryRegen && systems.length > 0 ? ' ' + systems.join(' / ') : ''}`); //console.log(`${model} [${type}]${!retryRegen && systems.length > 0 ? ' ' + systems.join(' / ') : ''}`);
679
  'R' !== type || prompt || (prompt = '...regen...');
680
  /******************************** */
681
  prompt = Config.Settings.xmlPlot ? xmlPlot(prompt) : genericFixes(prompt);
682
+ !apiKey && Config.Settings.FullColon && (prompt = prompt.replace(/(?<=\n\n(H(?:uman)?|A(?:ssistant)?)):[ ]?/g, ': '));
683
  Config.Settings.padtxt && (prompt = padtxt(prompt));
684
  /******************************** */
685
+ Logger?.write(`\n\n-------\n[${(new Date).toLocaleString()}]\n####### 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`);
686
  retryRegen || (fetchAPI = await (async (signal, model, prompt, temperature, type) => {
 
 
687
  /******************************** */
688
+ if (apiKey) {
689
+ const res = await fetch(`${Config.api_rProxy ? Config.api_rProxy : 'https://api.anthropic.com'}/v1/complete`, {
690
+ method: 'POST',
691
+ signal,
692
+ headers: {
693
+ 'Content-Type': 'application/json',
694
+ 'x-api-key': apiKey,
695
+ 'anthropic-version': '2023-06-01'
696
+ },
697
+ body: JSON.stringify({
698
+ model: api_model,
699
+ max_tokens_to_sample: api_max_tokens,
700
+ stream: true,
701
+ prompt,
702
+ temperature
703
+ }),
704
+ });
705
+ await checkResErr(res);
706
+ return res;
707
+ }
708
  /******************************** */
709
+ const attachments = [];
710
+ if (Config.Settings.PromptExperiments) {
711
+ let splitedprompt = prompt.split('\n\nPlainPrompt:'); //
712
+ prompt = splitedprompt[0]; //
713
  attachments.push({
714
  extracted_content: (prompt),
715
  file_name: 'paste.txt', //fileName(),
 
717
  file_type: 'txt' //'text/plain'
718
  });
719
  prompt = 'r' === type ? Config.PromptExperimentFirst : Config.PromptExperimentNext;
720
+ splitedprompt.length > 1 && (prompt += splitedprompt[1]); //
 
 
721
  }
722
  let res;
723
  const body = {
 
752
  })(signal, model, prompt, temperature, type));
753
  const response = Writable.toWeb(res);
754
  clewdStream = new ClewdStream({
755
+ config: {
756
+ ...Config,
757
+ Settings: {
758
+ ...Config.Settings,
759
+ Superfetch: apiKey ? false : Config.Settings.Superfetch
760
+ }
761
+ }, //config: Config,
762
  version: Main,
763
  minSize: Config.BufferSize,
764
  model,
 
767
  source: fetchAPI
768
  }, Logger);
769
  titleTimer = setInterval((() => setTitle('recv ' + bytesToSize(clewdStream.size))), 300);
770
+ (!apiKey && Config.Settings.Superfetch) ? await Readable.toWeb(fetchAPI.body).pipeThrough(clewdStream).pipeTo(response) : await fetchAPI.body.pipeThrough(clewdStream).pipeTo(response); //Config.Settings.Superfetch ? await Readable.toWeb(fetchAPI.body).pipeThrough(clewdStream).pipeTo(response) : await fetchAPI.body.pipeThrough(clewdStream).pipeTo(response);
771
  } catch (err) {
772
  if ('AbortError' === err.name) {
773
  res.end();
 
789
  prevImpersonated = clewdStream.impersonated;
790
  setTitle('ok ' + bytesToSize(clewdStream.size));
791
  429 == fetchAPI.status ? console.log(`Exceeded limit!\n`) : console.log(`${200 == fetchAPI.status ? '' : ''}${fetchAPI.status}!\n`); //console.log(`${200 == fetchAPI.status ? '' : ''}${fetchAPI.status}!\n`);
792
+ clewdStream.empty();
793
+ }
794
+ if (!apiKey) { //if (prevImpersonated) {
795
+ await deleteChat(Conversation.uuid);
796
  /******************************** */
797
  changeflag += 1;
798
+ if (Config.CookieArray?.length > 0 && (429 == fetchAPI.status || Config.Cookiecounter && changeflag >= Config.Cookiecounter)) {
799
  changeflag = 0;
800
+ CookieChanger.emit('ChangeCookie');
801
  }
802
  /******************************** */
 
803
  }
 
 
 
 
 
 
 
804
  }));
805
  })(req, res);
806
  break;
 
861
  Config.Cookie = 'SET YOUR COOKIE HERE';
862
  writeSettings(Config, true);
863
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
864
  })();
865
  /***************************** */
866
+ for (let key in Config) {
867
+ if (key === 'Settings') {
868
+ for (let setting in Config.Settings) {
869
+ Config.Settings[setting] = convertToType(process.env[setting]) ?? Config.Settings[setting];
870
+ }
871
+ } else {
872
+ Config[key] = key === 'CookieArray' ? (process.env[key]?.split(',')?.map(x => x.replace(/[\[\]"\s]/g, '')) ?? Config[key]) : (convertToType(process.env[key]) ?? Config[key]);
 
873
  }
874
  }
875
+ Config.rProxy = Config.rProxy.endsWith('/') ? Config.rProxy.slice(0, -1) : Config.rProxy || AI.end();
876
+ Config.CookieArray = [...new Set(Config.CookieArray)];
877
  !process.env.Cookie && !process.env.CookieArray && writeSettings(Config);
878
+ currentIndex = Config.CookieIndex > 0 ? Config.CookieIndex - 1 : Config.Cookiecounter >= 0 ? Math.floor(Math.random() * Config.CookieArray.length) : 0;
879
  /***************************** */
880
  Proxy.listen(Config.Port, Config.Ip, onListen);
881
  Proxy.on('error', (err => {
lib/clewd-stream.js CHANGED
@@ -131,7 +131,7 @@ class ClewdStream extends TransformStream {
131
  } else {
132
  this.#recvLength += Buffer.byteLength(chunk);
133
  }
134
- this.#compRaw += chunk;
135
  const substr = this.#compRaw.split('\n\n'), lastMsg = substr.length - 1;
136
  0 !== substr[lastMsg].length ? this.#compRaw = substr[lastMsg] : this.#compRaw = '';
137
  for (let i = 0; i < lastMsg; i++) {
 
131
  } else {
132
  this.#recvLength += Buffer.byteLength(chunk);
133
  }
134
+ this.#compRaw += chunk.replace(/event: (completion|ping)\s*|\r/gi,''); //this.#compRaw += chunk;
135
  const substr = this.#compRaw.split('\n\n'), lastMsg = substr.length - 1;
136
  0 !== substr[lastMsg].length ? this.#compRaw = substr[lastMsg] : this.#compRaw = '';
137
  for (let i = 0; i < lastMsg; i++) {
lib/clewd-utils.js CHANGED
@@ -5,7 +5,7 @@
5
  'use strict';
6
 
7
  const {randomInt, randomBytes} = require('node:crypto'), {version: Version} = require('../package.json'), Encoder = (new TextDecoder,
8
- new TextEncoder), Main = 'clewd修改版 v' + Version + '(10) by tera', Replacements = {
9
  user: 'Human',
10
  assistant: 'Assistant',
11
  system: '',
 
5
  'use strict';
6
 
7
  const {randomInt, randomBytes} = require('node:crypto'), {version: Version} = require('../package.json'), Encoder = (new TextDecoder,
8
+ new TextEncoder), Main = 'clewd修改版 v' + Version + '(11) by tera', Replacements = {
9
  user: 'Human',
10
  assistant: 'Assistant',
11
  system: '',
package.json CHANGED
@@ -37,6 +37,6 @@
37
  },
38
  "dependencies": {
39
  "localtunnel": "^2.0.2",
40
- "gpt-tokenizer": "^2.1.2"
41
  }
42
  }
 
37
  },
38
  "dependencies": {
39
  "localtunnel": "^2.0.2",
40
+ "@anthropic-ai/tokenizer": "^0.0.4"
41
  }
42
  }