Spaces:
Paused
Paused
Upload 13 files
Browse filesFiles changed (9)
- data/tasks.jsonAdded
- executor.js+228-26
- logger.js+1-1
- package-lock.json+49
- package.json+5-2
- server.js+38-4
- test-api.jsAdded+81
- test-token-rotation.jsAdded+42
- token-consumer.html+38-8
1 unmodified line23456752 unmodified lines6061626364656667686970717216 unmodified lines89909192939495969711 unmodified lines1091101111121131141151161179 unmodified lines12712812913013113213322 unmodified lines15615715815916016116216316416516616713 unmodified lines1811821831841851867 unmodified lines19419519619719819920020120220320420520641 unmodified lines24824925025125225325425525625713 unmodified lines27127227327427527627727827947 unmodified lines32732832933033133256 unmodified lines3893903913923933943953964 unmodified lines4014024034044054064074084094104114124134144154164174184194204218 unmodified lines4304314324334344354365 unmodified lines44244344444544644744844945045145245345424 unmodified lines4794804814824834841 unmodified line48648748848949049149238 unmodified lines5315325335345355364 unmodified lines5415425435445455465 unmodified lines5525535545555565577 unmodified lines5655665675685695704 unmodified lines57557657757857958058158258358 unmodified lines6426436446451 unmodified lineconst http = require('http');const log = require('./logger');function buildUrl(baseUrl, endpoint) {let url = baseUrl.trim().replace(/\/ $/, '');if (!url) throw new Error('Base URL 不能为空');52 unmodified linesconst isHttps = urlObj.protocol === 'https:';const lib = isHttps ? https : http;const reqOptions = {hostname: urlObj.hostname,port: urlObj.port || (isHttps ? 443 : 80),path: urlObj.pathname + urlObj.search,method: options.method || 'GET',headers: options.headers || {},timeout};const req = lib.request(reqOptions, (res) => {16 unmodified linestry {log.debug('Fetching models from:', baseUrl);const url = buildUrl(baseUrl, '/models');const resp = await makeRequest(url, {method: 'GET',headers: { 'Authorization': 'Bearer ' + token }});const data = JSON.parse(resp.body);if (resp.status !== 200) {11 unmodified lines}}async function requestOnce(config, signal) {const { prompt, tag, marker } = buildUserPrompt(config.usr, config.randOn, config.markerLen);const body = {model: config.model,messages: [9 unmodified linesconst resp = await makeRequest(url, {method: 'POST',headers: {'Authorization': 'Bearer ' + config.token,'Content-Type': 'application/json'}}, JSON.stringify(body), config.timeout);22 unmodified lines}const content = data?.choices?.[0]?.message?.content || '';const usage = usageWithFallback(data?.usage, prompt, config.sys, content);return { content, usage, finish_reason: data?.choices?.[0]?.finish_reason, tag, marker, prompt };}async function streamRequest(config, onChunk, signal) {const { prompt, tag, marker } = buildUserPrompt(config.usr, config.randOn, config.markerLen);const body = {13 unmodified linesconst isHttps = urlObj.protocol === 'https:';const lib = isHttps ? https : http;return new Promise((resolve, reject) => {// Check if already aborted before startingif (signal?.aborted) {7 unmodified linespath: urlObj.pathname,method: 'POST',headers: {'Authorization': 'Bearer ' + config.token,'Content-Type': 'application/json'},timeout: config.timeout || 60000};let fullContent = '';let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };let finishReason = null;let aborted = false;41 unmodified linesconst json = JSON.parse(payload);if (json.error) throw new Error(json.error.message);const delta = json.choices?.[0]?.delta?.content;if (delta) {fullContent += delta;if (onChunk) onChunk(delta, fullContent);}if (json.usage) usage = json.usage;13 unmodified linesres.on('end', () => {cleanup();const finalUsage = usageWithFallback(usage, prompt, config.sys, fullContent);resolve({content: fullContent,usage: finalUsage,finish_reason: finishReason,tag,47 unmodified linesthis.notifyTimer = null;this.notifyInterval = 500; // ms between notifications (increased for high concurrency)// Load from saved progress or initialize freshif (savedProgress) {this.stats = savedProgress.stats || {56 unmodified linesthread: threadId,loop: i,status: 'running',startTime: Date.now(),message: ''};this.threadLogs[threadId] = threadLog;4 unmodified linesconst result = this.config.streamOn? await streamRequest({ ...this.config, markerLen: this.markerLen },(delta, full) => {threadLog.status = 'streaming';threadLog.content = full;// notifyUpdate already throttled, so this is finethis.notifyUpdate();},this.controller.signal): await requestOnce({ ...this.config, markerLen: this.markerLen },this.controller.signal);this.stats.completed++;this.stats.success++;this.stats.promptTokens += result.usage.prompt_tokens;this.stats.completionTokens += result.usage.completion_tokens;this.stats.totalTokens += result.usage.total_tokens;8 unmodified lineslog.info('Task', this.taskId, 'reached token limit:', this.stats.totalTokens);} else {threadLog.status = 'success';threadLog.content = result.content?.slice(-500);}// Adjust marker for ratio5 unmodified linesif (this.config.randOn) {const diff = liveRatio - this.ratio.target;if (Math.abs(diff) >= 0.02) {const step = Math.max(1, Math.round(Math.abs(diff) * 50));if (diff < 0) this.markerLen = Math.min(4000, this.markerLen + step);else this.markerLen = Math.max(0, this.markerLen - step);}this.ratio.markerLen = this.markerLen;}} catch (e) {const isAborted = e.message === 'Aborted' || e.name === 'AbortError';24 unmodified lineslog.debug('Thread', threadId, 'loop', i, 'aborted');}} else {this.stats.failed++;threadLog.status = 'error';threadLog.error = e.message || '请求失败';1 unmodified line}}threadLog.endTime = Date.now();this.notifyUpdate(true); // Force update after each request completes// Wait between loops (not after the last loop)38 unmodified lines}this.notifyUpdate();// Run workers in parallelconst workers = [];4 unmodified linesawait Promise.all(workers);this.running = false;log.info('TaskExecutor finished:', this.taskId, 'success:', this.stats.success, 'failed:', this.stats.failed, 'tokens:', this.stats.totalTokens);this.notifyUpdate(true); // Force final update5 unmodified linesif (!this.running || this.paused) return;log.info('TaskExecutor pausing:', this.taskId);this.paused = true;if (this.startTime) {this.elapsedBefore += Date.now() - this.startTime;this.startTime = null;7 unmodified linesif (!this.running || !this.paused) return;log.info('TaskExecutor resuming:', this.taskId);this.paused = false;// Create new AbortController for resumed executionthis.controller = new AbortController();this.startTime = Date.now();4 unmodified lineslog.info('TaskExecutor stopping:', this.taskId);this.stopped = true;this.paused = false;this.controller.abort();}getStatus() {let elapsed = this.elapsedBefore;if (this.startTime && !this.paused) {58 unmodified lines}}module.exports = { TaskExecutor, fetchModels };1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818252 unmodified lines13513613713813914014114214314414514614714814915016 unmodified lines16716816917017117217317417517617717817918011 unmodified lines1921931941951961971981992002012022032042052062072082099 unmodified lines21922022122222322422522 unmodified lines24824925025125225325425525625725825926013 unmodified lines2742752762772782792802812822832842852862872887 unmodified lines29629729829930030130230330430530630730830931031141 unmodified lines35335435535635735835936036136236336436536636736836937037137237337437513 unmodified lines38939039139239339439539639739847 unmodified lines44644744844945045145245345445545656 unmodified lines5135145155165175185195204 unmodified lines5255265275285295305315325335345355365375385395405415425435445455465475488 unmodified lines5575585595605615625635645655665675685695705715 unmodified lines57757857958058158258358458558658758858959059159224 unmodified lines6176186196206216226236246256266276286296306316326336346356366376386396406416426436446456461 unmodified line64864965065165265338 unmodified lines6926936946956966976986997004 unmodified lines7057067077087097107115 unmodified lines7177187197207217227237 unmodified lines7317327337347357367377384 unmodified lines74374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478558 unmodified lines8448458468471 unmodified lineconst http = require('http');const log = require('./logger');const CHERRY_STUDIO_USER_AGENT = 'cherry studio/1.0(secure client)';// 全局 HTTP Agent 配置 - 支持高并发连接复用const httpsAgent = new https.Agent({keepAlive: true, // 启用连接复用maxSockets: 600, // 每个主机最大连接数(略高于线程数)maxFreeSockets: 100, // 空闲连接池大小keepAliveMsecs: 30000, // keepAlive 探测间隔timeout: 10000, // 连接建立超时});const httpAgent = new http.Agent({keepAlive: true,maxSockets: 600,maxFreeSockets: 100,keepAliveMsecs: 30000,timeout: 10000,});// 最大重试次数const MAX_RETRIES = 3;// 停滞自动暂停配置:连续多久没有成功就自动暂停(毫秒)// 默认 1 小时 = 3600000ms,可通过环境变量 STALL_TIMEOUT_MS 配置const STALL_TIMEOUT_MS = Number(process.env.STALL_TIMEOUT_MS) || 3600000;// 判断是否是可重试的网络错误(TLS 握手失败、连接重置等)function isRetryableError(err) {if (!err) return false;const msg = err.message || '';const code = err.code || '';// TLS 握手错误if (msg.includes('TLS') || msg.includes('socket disconnected before secure')) return true;// 连接相关错误if (['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND', 'EHOSTUNREACH'].includes(code)) return true;if (msg.includes('ECONNRESET') || msg.includes('ETIMEDOUT') || msg.includes('socket hang up')) return true;return false;}// Max length of content to store in thread logs (for frontend display)const LOG_CONTENT_MAX_LENGTH = 20;// Multiplier for marker length step calculationconst RATIO_STEP_MULTIPLIER = 100;// Token rotation counterconst tokenCounters = new Map();// Get next token from rotation, returns both token and indexfunction getNextToken(config) {// Split tokens by comma and trim whitespaceconst tokens = String(config.token || '').split(',').map(t => t.trim()).filter(Boolean);// If only one token, return it directlyif (tokens.length <= 1) {return { token: tokens[0] || config.token, index: 0, total: tokens.length || 1 };}// Get current counter for this config (using a hash of token string as key)const tokenKey = tokens.join(',');let counter = tokenCounters.get(tokenKey) || 0;// Get current tokenconst index = counter % tokens.length;const token = tokens[index];// Increment countertokenCounters.set(tokenKey, counter + 1);return { token, index, total: tokens.length };}function buildUrl(baseUrl, endpoint) {let url = baseUrl.trim().replace(/\/ $/, '');if (!url) throw new Error('Base URL 不能为空');52 unmodified linesconst isHttps = urlObj.protocol === 'https:';const lib = isHttps ? https : http;const mergedHeaders = { 'User-Agent': CHERRY_STUDIO_USER_AGENT, ...(options.headers || {}) };const reqOptions = {hostname: urlObj.hostname,port: urlObj.port || (isHttps ? 443 : 80),path: urlObj.pathname + urlObj.search,method: options.method || 'GET',headers: mergedHeaders,timeout,agent: isHttps ? httpsAgent : httpAgent};const req = lib.request(reqOptions, (res) => {16 unmodified linestry {log.debug('Fetching models from:', baseUrl);const url = buildUrl(baseUrl, '/models');// Handle token rotation for model fetchingconst tokens = String(token || '').split(',').map(t => t.trim()).filter(Boolean);const useToken = tokens.length > 0 ? tokens[0] : token;const resp = await makeRequest(url, {method: 'GET',headers: { 'Authorization': 'Bearer ' + useToken }});const data = JSON.parse(resp.body);if (resp.status !== 200) {11 unmodified lines}}async function requestOnce(config, signal, threadLog) {const { prompt, tag, marker } = buildUserPrompt(config.usr, config.randOn, config.markerLen);// Get next token from rotationconst { token, index, total } = getNextToken(config);// Record token index in thread logif (threadLog) {threadLog.tokenIndex = index;threadLog.tokenTotal = total;}const body = {model: config.model,messages: [9 unmodified linesconst resp = await makeRequest(url, {method: 'POST',headers: {'Authorization': 'Bearer ' + token,'Content-Type': 'application/json'}}, JSON.stringify(body), config.timeout);22 unmodified lines}const content = data?.choices?.[0]?.message?.content || '';const reasoning = data?.choices?.[0]?.message?.reasoning_content || '';const usage = usageWithFallback(data?.usage, prompt, config.sys, content + reasoning);return { content, reasoning, usage, finish_reason: data?.choices?.[0]?.finish_reason, tag, marker, prompt };}async function streamRequest(config, onChunk, signal, threadLog) {const { prompt, tag, marker } = buildUserPrompt(config.usr, config.randOn, config.markerLen);const body = {13 unmodified linesconst isHttps = urlObj.protocol === 'https:';const lib = isHttps ? https : http;// Get next token from rotationconst { token, index, total } = getNextToken(config);// Record token index in thread logif (threadLog) {threadLog.tokenIndex = index;threadLog.tokenTotal = total;}return new Promise((resolve, reject) => {// Check if already aborted before startingif (signal?.aborted) {7 unmodified linespath: urlObj.pathname,method: 'POST',headers: {'User-Agent': CHERRY_STUDIO_USER_AGENT,'Authorization': 'Bearer ' + token,'Content-Type': 'application/json'},timeout: config.timeout || 60000,agent: isHttps ? httpsAgent : httpAgent};let fullContent = '';let fullReasoning = '';let usage = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };let finishReason = null;let aborted = false;41 unmodified linesconst json = JSON.parse(payload);if (json.error) throw new Error(json.error.message);const delta = json.choices?.[0]?.delta;if (delta?.content) {fullContent += delta.content;}if (delta?.reasoning_content) {fullReasoning += delta.reasoning_content;}// Call onChunk with combined outputif (onChunk && (delta?.content || delta?.reasoning_content)) {let fullOutput = '';if (fullReasoning) {fullOutput += '💭 ' + fullReasoning + '\n---\n';}if (fullContent) {fullOutput += fullContent;}onChunk(delta?.content || delta?.reasoning_content, fullOutput);}if (json.usage) usage = json.usage;13 unmodified linesres.on('end', () => {cleanup();const finalUsage = usageWithFallback(usage, prompt, config.sys, fullContent + fullReasoning);resolve({content: fullContent,reasoning: fullReasoning,usage: finalUsage,finish_reason: finishReason,tag,47 unmodified linesthis.notifyTimer = null;this.notifyInterval = 500; // ms between notifications (increased for high concurrency)// 停滞自动暂停:跟踪最后一次成功时间this.lastSuccessTime = Date.now();this.stallCheckTimer = null;this.stallCheckInterval = 60000; // 每分钟检查一次// Load from saved progress or initialize freshif (savedProgress) {this.stats = savedProgress.stats || {56 unmodified linesthread: threadId,loop: i,status: 'running',message: '',markerLen: this.markerLen};this.threadLogs[threadId] = threadLog;4 unmodified linesconst result = this.config.streamOn? await streamRequest({ ...this.config, markerLen: this.markerLen },(delta, fullOutput) => {threadLog.status = 'streaming';threadLog.content = fullOutput?.slice(-LOG_CONTENT_MAX_LENGTH);// notifyUpdate already throttled, so this is finethis.notifyUpdate();},this.controller.signal,threadLog): await requestOnce({ ...this.config, markerLen: this.markerLen },this.controller.signal,threadLog);this.stats.completed++;this.stats.success++;this.lastSuccessTime = Date.now(); // 更新最后成功时间this.stats.promptTokens += result.usage.prompt_tokens;this.stats.completionTokens += result.usage.completion_tokens;this.stats.totalTokens += result.usage.total_tokens;8 unmodified lineslog.info('Task', this.taskId, 'reached token limit:', this.stats.totalTokens);} else {threadLog.status = 'success';// Combine reasoning and content, then slicelet fullOutput = '';if (result.reasoning) {fullOutput += '💭 ' + result.reasoning + '\n---\n';}if (result.content) {fullOutput += result.content;}threadLog.content = fullOutput.slice(-LOG_CONTENT_MAX_LENGTH);}// Adjust marker for ratio5 unmodified linesif (this.config.randOn) {const diff = liveRatio - this.ratio.target;if (Math.abs(diff) >= 0.02) {const step = Math.max(1, Math.round(Math.abs(diff) * RATIO_STEP_MULTIPLIER));if (diff < 0) this.markerLen = Math.min(100000, this.markerLen + step);else this.markerLen = Math.max(0, this.markerLen - step);}this.ratio.markerLen = this.markerLen;}// Add markerLen info to thread logthreadLog.markerLen = this.markerLen;} catch (e) {const isAborted = e.message === 'Aborted' || e.name === 'AbortError';24 unmodified lineslog.debug('Thread', threadId, 'loop', i, 'aborted');}} else {// 检查是否是可重试的网络错误(TLS 握手失败等)if (isRetryableError(e)) {// 获取或初始化重试计数const retryKey = `${threadId}-${i}`;if (!this._retryCount) this._retryCount = {};this._retryCount[retryKey] = (this._retryCount[retryKey] || 0) + 1;if (this._retryCount[retryKey] <= MAX_RETRIES) {threadLog.status = 'retrying';threadLog.message = `网络错误,重试 ${this._retryCount[retryKey]}/${MAX_RETRIES}...`;log.warn('Thread', threadId, 'loop', i, 'retryable error:', e.message, 'retry', this._retryCount[retryKey]);this.notifyUpdate(true);// 指数退避等待await new Promise(resolve => setTimeout(resolve, 100 * this._retryCount[retryKey]));// 重试当前循环i--;continue;}// 重试次数用尽,清理计数delete this._retryCount[retryKey];}this.stats.failed++;threadLog.status = 'error';threadLog.error = e.message || '请求失败';1 unmodified line}}this.notifyUpdate(true); // Force update after each request completes// Wait between loops (not after the last loop)38 unmodified lines}this.notifyUpdate();// 启动停滞检查定时器this.startStallCheck();// Run workers in parallelconst workers = [];4 unmodified linesawait Promise.all(workers);this.running = false;this.stopStallCheck(); // 停止停滞检查log.info('TaskExecutor finished:', this.taskId, 'success:', this.stats.success, 'failed:', this.stats.failed, 'tokens:', this.stats.totalTokens);this.notifyUpdate(true); // Force final update5 unmodified linesif (!this.running || this.paused) return;log.info('TaskExecutor pausing:', this.taskId);this.paused = true;this.stopStallCheck(); // 停止停滞检查if (this.startTime) {this.elapsedBefore += Date.now() - this.startTime;this.startTime = null;7 unmodified linesif (!this.running || !this.paused) return;log.info('TaskExecutor resuming:', this.taskId);this.paused = false;this.lastSuccessTime = Date.now(); // 重置成功时间this.startStallCheck(); // 重启停滞检查// Create new AbortController for resumed executionthis.controller = new AbortController();this.startTime = Date.now();4 unmodified lineslog.info('TaskExecutor stopping:', this.taskId);this.stopped = true;this.paused = false;this.stopStallCheck(); // 停止停滞检查this.controller.abort();}// 启动停滞检查定时器startStallCheck() {if (this.stallCheckTimer) return;this.lastSuccessTime = Date.now();this.stallCheckTimer = setInterval(() => this.checkStall(), this.stallCheckInterval);}// 停止停滞检查定时器stopStallCheck() {if (this.stallCheckTimer) {clearInterval(this.stallCheckTimer);this.stallCheckTimer = null;}}// 检查是否停滞,如果超时则自动暂停checkStall() {if (this.paused || this.stopped) return;const timeSinceLastSuccess = Date.now() - this.lastSuccessTime;if (timeSinceLastSuccess >= STALL_TIMEOUT_MS) {log.warn('Task', this.taskId, '停滞超时,自动暂停。最后成功时间:', new Date(this.lastSuccessTime).toISOString());this.pause();// 通知前端if (this.onUpdate) {const status = this.getStatus();status.stallAutoPaused = true;status.stallMessage = `连续 ${Math.round(STALL_TIMEOUT_MS / 60000)} 分钟无成功请求,已自动暂停`;this.onUpdate(status);}}}getStatus() {let elapsed = this.elapsedBefore;if (this.startTime && !this.paused) {58 unmodified lines}}module.exports = { TaskExecutor, fetchModels, getNextToken };
1 unmodified line23456781 unmodified line// LOG_LEVEL: debug, info, warn, error, none (default: info)const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3, none: 4 };const currentLevel = LOG_LEVELS[process.env.LOG_LEVEL?.toLowerCase()] ?? LOG_LEVELS.info;const ts = () => new Date().toISOString();1 unmodified line23456781 unmodified line// LOG_LEVEL: debug, info, warn, error, none (default: info)const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3, none: 4 };const currentLevel = LOG_LEVELS[process.env.LOG_LEVEL?.toLowerCase()] ?? LOG_LEVELS.error;const ts = () => new Date().toISOString();
7 unmodified lines8910111213172 unmodified lines186187188189190191702 unmodified lines8948958968978988997 unmodified lines"name": "token-consumer","version": "1.0.0","dependencies": {"cors": "^2.8.5","express": "^4.18.2","uuid": "^9.0.0"172 unmodified lines"fsevents": "~2.3.2"}},"node_modules/content-disposition": {"version": "0.5.4","resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-0.5.4.tgz",702 unmodified lines"node": ">= 0.8"}},"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz",7 unmodified lines891011121314172 unmodified lines187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231702 unmodified lines9349359369379389399409419429439449459469479487 unmodified lines"name": "token-consumer","version": "1.0.0","dependencies": {"compression": "^1.8.1","cors": "^2.8.5","express": "^4.18.2","uuid": "^9.0.0"172 unmodified lines"fsevents": "~2.3.2"}},"node_modules/compressible": {"version": "2.0.18","resolved": "https://registry.npmmirror.com/compressible/-/compressible-2.0.18.tgz","integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==","license": "MIT","dependencies": {"mime-db": ">= 1.43.0 < 2"},"engines": {"node": ">= 0.6"}},"node_modules/compression": {"version": "1.8.1","resolved": "https://registry.npmmirror.com/compression/-/compression-1.8.1.tgz","integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==","license": "MIT","dependencies": {"bytes": "3.1.2","compressible": "~2.0.18","debug": "2.6.9","negotiator": "~0.6.4","on-headers": "~1.1.0","safe-buffer": "5.2.1","vary": "~1.1.2"},"engines": {"node": ">= 0.8.0"}},"node_modules/compression/node_modules/negotiator": {"version": "0.6.4","resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-0.6.4.tgz","integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==","license": "MIT","engines": {"node": ">= 0.6"}},"node_modules/content-disposition": {"version": "0.5.4","resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-0.5.4.tgz",702 unmodified lines"node": ">= 0.8"}},"node_modules/on-headers": {"version": "1.1.0","resolved": "https://registry.npmmirror.com/on-headers/-/on-headers-1.1.0.tgz","integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==","license": "MIT","engines": {"node": ">= 0.8"}},"node_modules/parseurl": {"version": "1.3.3","resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz",
7 unmodified lines891011121314151617187 unmodified lines"dev": "cross-env LOG_LEVEL=debug nodemon server.js"},"nodemonConfig": {"ignore": ["data/*"]},"dependencies": {"express": "^4.18.2","cors": "^2.8.5","uuid": "^9.0.0"},"devDependencies": {7 unmodified lines891011121314151617181920217 unmodified lines"dev": "cross-env LOG_LEVEL=debug nodemon server.js"},"nodemonConfig": {"ignore": ["data/*"]},"dependencies": {"compression": "^1.8.1","cors": "^2.8.5","express": "^4.18.2","uuid": "^9.0.0"},"devDependencies": {
12345678910111213141532 unmodified lines484950515253545559 unmodified lines11511611711811912012138 unmodified lines160161162163164165166167168169303 unmodified lines473474475476477478const express = require('express');const cors = require('cors');const { v4: uuidv4 } = require('uuid');const path = require('path');const os = require('os');const storage = require('./storage');const { TaskExecutor, fetchModels } = require('./executor');const log = require('./logger');const app = express();const PORT = process.env.PORT || 51730;// Auth configurationconst AUTH_USER = process.env.AUTH_USER || 'admin';const AUTH_PASS = process.env.AUTH_PASS || 'admin';32 unmodified lines}// Middlewareapp.use(cors());app.use(express.json());app.use(rateLimiter);// HTTP Basic Auth middleware for /api routes59 unmodified linessys: config.sys || '',usr: config.usr,loop: Math.max(1, Math.min(10000, Number(config.loop) || 10)),threads: Math.max(1, Math.min(200, Number(config.threads) || 3)),max: Math.max(1, Math.min(32768, Number(config.max) || 1024)),temp: Math.max(0, Math.min(2, Number(config.temp) || 1)),timeout: Math.max(5000, Number(config.timeout) || 60000),38 unmodified linesif (!t.stats.total && t.config) {t.stats.total = (t.config.loop || 10) * (t.config.threads || 3);}return {...t,running: executor?.running || false,currentStats: executor?.getStatus() || null};});log.debug('GET /api/tasks, count:', result.length);303 unmodified linesres.sendFile(path.join(__dirname, 'token-consumer.html'));});// Resume running tasks on startupfunction resumeRunningTasks() {const tasks = storage.getAllTasks();1234567891011121314151617181920212223242532 unmodified lines58596061626364656659 unmodified lines12612712812913013113238 unmodified lines171172173174175176177178179180181182183184185186187188189190191192193303 unmodified lines497498499500501502503504505506507508509510511512const express = require('express');const cors = require('cors');const compression = require('compression');const { v4: uuidv4 } = require('uuid');const path = require('path');const os = require('os');const http = require('http');const https = require('https');const storage = require('./storage');const { TaskExecutor, fetchModels } = require('./executor');const log = require('./logger');// 设置全局 HTTP Agent 的最大连接数,支持高并发http.globalAgent.maxSockets = 1000;https.globalAgent.maxSockets = 1000;const app = express();const PORT = process.env.PORT || 51730;// Configurationconst MAX_THREADS = 1000;// Auth configurationconst AUTH_USER = process.env.AUTH_USER || 'admin';const AUTH_PASS = process.env.AUTH_PASS || 'admin';32 unmodified lines}// Middlewareapp.use(compression());app.use(cors());app.use(express.json({ limit: '50mb' }));app.use(rateLimiter);// HTTP Basic Auth middleware for /api routes59 unmodified linessys: config.sys || '',usr: config.usr,loop: Math.max(1, Math.min(10000, Number(config.loop) || 10)),threads: Math.max(1, Math.min(MAX_THREADS, Number(config.threads) || 3)),max: Math.max(1, Math.min(32768, Number(config.max) || 1024)),temp: Math.max(0, Math.min(2, Number(config.temp) || 1)),timeout: Math.max(5000, Number(config.timeout) || 60000),38 unmodified linesif (!t.stats.total && t.config) {t.stats.total = (t.config.loop || 10) * (t.config.threads || 3);}const status = executor?.getStatus() || null;// Remove threadLogs and threadProgress from list view to reduce payloadif (status) {delete status.threadLogs;delete status.threadProgress;}// Create shallow copy and remove threadLogs/threadProgress from progressconst taskCopy = { ...t };if (taskCopy.progress) {taskCopy.progress = { ...taskCopy.progress };delete taskCopy.progress.threadLogs;delete taskCopy.progress.threadProgress;}return {...taskCopy,running: executor?.running || false,currentStats: status};});log.debug('GET /api/tasks, count:', result.length);303 unmodified linesres.sendFile(path.join(__dirname, 'token-consumer.html'));});// Global error handler - must be after all routesapp.use((err, req, res, next) => {log.error('Unhandled error:', err.message);// Ensure JSON response for API routesif (req.path.startsWith('/api')) {return res.status(500).json({ error: err.message || '服务器内部错误' });}res.status(500).send('服务器内部错误');});// Resume running tasks on startupfunction resumeRunningTasks() {const tasks = storage.getAllTasks();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081const https = require('https');
const BASE_URL = 'https://s2a.bbx.qzz.io';const TOKEN = 'sk-b2ff52c85b4a654733d25bd7fc85f52d70fe7900613ae681a070b5e5ed880e47';
function testRequest(headers) { return new Promise((resolve, reject) => { const urlObj = new URL('/v1/models', BASE_URL); const options = { hostname: urlObj.hostname, port: 443, path: urlObj.pathname, method: 'GET', headers: { 'Authorization': 'Bearer ' + TOKEN, ...headers } };
console.log('Testing with headers:', JSON.stringify(headers, null, 2)); const req = https.request(options, (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => { console.log(`Status: ${res.statusCode}`); console.log('Response headers:', res.headers); if (data) { console.log('Response body:', data.slice(0, 500)); } resolve({ status: res.statusCode, headers: res.headers, body: data }); }); });
req.on('error', reject); req.end(); });}
async function runTests() { console.log('=== Test 1: Cherry Studio User-Agent only ==='); await testRequest({ 'User-Agent': 'cherry studio/1.0(secure client)' }); console.log('\n=== Test 2: Modern Chrome browser ==='); await testRequest({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'en-US,en;q=0.9', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'https://chat.openai.com/', 'Origin': 'https://chat.openai.com', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache' }); console.log('\n=== Test 3: More complete browser headers ==='); await testRequest({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Referer': 'https://platform.openai.com/', 'Origin': 'https://platform.openai.com', 'Sec-Ch-Ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"', 'Sec-Ch-Ua-Mobile': '?0', 'Sec-Ch-Ua-Platform': '"Windows"', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-site', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' });}
runTests().catch(console.error);123456789101112131415161718192021222324252627282930313233343536373839404142const { getNextToken } = require('./executor');
// Test token rotationfunction testTokenRotation() { console.log('Testing token rotation...'); // Test with multiple tokens const config = { token: 'token1, token2, token3' }; console.log('Testing with tokens:', config.token); // Get tokens multiple times to test rotation for (let i = 0; i < 10; i++) { const { token, index, total } = getNextToken(config); console.log(`Request ${i+1}: Using token: ${token} (Key: ${index+1}/${total})`); } // Test with single token const singleTokenConfig = { token: 'single-token' }; console.log('\nTesting with single token:', singleTokenConfig.token); for (let i = 0; i < 3; i++) { const { token, index, total } = getNextToken(singleTokenConfig); console.log(`Request ${i+1}: Using token: ${token} (Key: ${index+1}/${total})`); } // Test with empty token const emptyTokenConfig = { token: '' }; console.log('\nTesting with empty token:'); const { token, index, total } = getNextToken(emptyTokenConfig); console.log(`Using token: ${token} (Key: ${index+1}/${total})`);}
testTokenRotation();37 unmodified lines383940414243443 unmodified lines48495051525354183 unmodified lines23823924024124224342 unmodified lines28628728828929029129284 unmodified lines37737837938038138238338438594 unmodified lines48048148248348448591 unmodified lines577578579580581582583183 unmodified lines76776876977077177225 unmodified lines79879980080180280380480580680733 unmodified lines841842843844845846203 unmodified lines10501051105210531054105537 unmodified lines.box label{font-size:11px;color:#64748b;margin-bottom:4px}.box b{display:block;font-size:22px;color:#60a5fa;margin-top:4px}.logs{grid-template-columns:repeat(auto-fill,minmax(280px,1fr))}.log{border:1px solid #334155;border-radius:10px;background:linear-gradient(145deg,#1e293b,#0f172a);padding:10px;transition:all 0.2s}.log.waiting{border-color:#475569}.log.running{border-color:#3b82f6;border-width:2px;box-shadow:0 0 15px rgba(59,130,246,0.3)}.log.success{border-color:#22c55e;box-shadow:0 0 10px rgba(34,197,94,0.2)}3 unmodified lines.log.paused{border-color:#f59e0b;box-shadow:0 0 10px rgba(245,158,11,0.2)}.t{display:flex;justify-content:space-between;font-size:13px;font-weight:600;margin-bottom:6px;color:#e2e8f0}.m{font-size:11px;color:#64748b;margin-bottom:6px}pre{margin:0;background:#0f172a;color:#93c5fd;border-radius:6px;padding:8px;min-height:80px;max-height:180px;overflow:auto;white-space:pre-wrap;word-break:break-word;font-size:11px}pre::-webkit-scrollbar{width:5px;height:5px}pre::-webkit-scrollbar-track{background:#1e293b;border-radius:3px}pre::-webkit-scrollbar-thumb{background:#475569;border-radius:3px}183 unmodified lines<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg><span id="bannerTime">0s</span></div><div class="meta-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>成功 <b id="detailSuccess" style="color:#4ade80">0</b></span>42 unmodified lines</div><div class="g3" style="margin-top:8px"><label>每线程循环次数<input id="loop" type="number" min="1" value="10"></label><label>并发线程数<input id="thr" type="number" min="1" value="3"></label><label>max_tokens<input id="max" type="number" min="1" value="1024"></label><label>temperature<input id="temp" type="number" min="0" max="2" step="0.1" value="1"></label><label>单次超时秒数<input id="to" type="number" min="5" value="600"></label>84 unmodified linesconst saveLocal=d=>{try{localStorage.setItem(LOCAL_KEY,JSON.stringify(d))}catch{}};// API functionsasync function apiGet(url){const r=await fetch(API+url);return r.json()}async function apiPost(url,data){const r=await fetch(API+url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});return r.json()}async function apiDelete(url){const r=await fetch(API+url,{method:'DELETE'});return r.json()}// Load tasksasync function loadTasks(){94 unmodified lines<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg><span>${elapsedStr||'-'}</span></div><div class="meta-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>成功 <b style="color:#4ade80">${stats.success||0}</b></span>91 unmodified linessys:$('sys').value.trim(),usr:$('usr').value.trim(),loop:n($('loop').value,10,1,10000),threads:n($('thr').value,3,1,200),max:n($('max').value,1024,1,32768),temp:n($('temp').value,1,0,2),timeout:n($('to').value,600,5,3600)*1000,183 unmodified lines$('bannerProgress').textContent=`${completed}/${total}`;$('bannerTokens').textContent=`${fmt(totalTokens)}/${fmt(maxTokens)}`;$('bannerTime').textContent=fmtTime(s.elapsed||0);$('detailSuccess').textContent=s.stats?.success||0;$('detailFailed').textContent=s.stats?.failed||0;$('detailAborted').textContent=s.stats?.aborted||0;25 unmodified lines}else if(log.message){displayContent=log.message;}return`<div class="log ${statusClass}"><div class="t"><span>线程 #${id}</span><span>${log.status}</span></div><div class="m">循环:${log.loop||'-'}</div><pre>${displayContent.slice(-500)}</pre></div>`;33 unmodified lines$('detailBadge').className='task-badge '+status;$('detailBadge').textContent=statusText;$('bannerLabel').textContent=statusText;updateButtons(task.running, task.currentStats?.paused, task.stopped);}203 unmodified lines$('bannerProgress').textContent='0/0';$('bannerTokens').textContent='0/0';$('bannerTime').textContent='0s';$('detailSuccess').textContent='0';$('detailFailed').textContent='0';$('detailAborted').textContent='0';37 unmodified lines383940414243443 unmodified lines48495051525354183 unmodified lines23823924024124224324424524624742 unmodified lines29029129229329429529684 unmodified lines38138238338438538638738838939039139239339439539639739839940094 unmodified lines49549649749849950050150250350491 unmodified lines596597598599600601602183 unmodified lines78678778878979079179225 unmodified lines81881982082182282382482582682782882983083183283383483533 unmodified lines869870871872873874875203 unmodified lines107910801081108210831084108537 unmodified lines.box label{font-size:11px;color:#64748b;margin-bottom:4px}.box b{display:block;font-size:22px;color:#60a5fa;margin-top:4px}.logs{grid-template-columns:repeat(auto-fill,minmax(280px,1fr))}.log{border:1px solid #334155;border-radius:10px;background:linear-gradient(145deg,#1e293b,#0f172a);padding:10px;transition:all 0.2s;height:180px;display:flex;flex-direction:column}.log.waiting{border-color:#475569}.log.running{border-color:#3b82f6;border-width:2px;box-shadow:0 0 15px rgba(59,130,246,0.3)}.log.success{border-color:#22c55e;box-shadow:0 0 10px rgba(34,197,94,0.2)}3 unmodified lines.log.paused{border-color:#f59e0b;box-shadow:0 0 10px rgba(245,158,11,0.2)}.t{display:flex;justify-content:space-between;font-size:13px;font-weight:600;margin-bottom:6px;color:#e2e8f0}.m{font-size:11px;color:#64748b;margin-bottom:6px}pre{margin:0;background:#0f172a;color:#93c5fd;border-radius:6px;padding:8px;flex:1;overflow:auto;white-space:pre-wrap;word-break:break-word;font-size:11px}pre::-webkit-scrollbar{width:5px;height:5px}pre::-webkit-scrollbar-track{background:#1e293b;border-radius:3px}pre::-webkit-scrollbar-thumb{background:#475569;border-radius:3px}183 unmodified lines<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg><span id="bannerTime">0s</span></div><div class="meta-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg><span>线程 <b id="detailThreads">0</b></span></div><div class="meta-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>成功 <b id="detailSuccess" style="color:#4ade80">0</b></span>42 unmodified lines</div><div class="g3" style="margin-top:8px"><label>每线程循环次数<input id="loop" type="number" min="1" value="10"></label><label>并发线程数<input id="thr" type="number" min="1" max="1000" value="3"></label><label>max_tokens<input id="max" type="number" min="1" value="1024"></label><label>temperature<input id="temp" type="number" min="0" max="2" step="0.1" value="1"></label><label>单次超时秒数<input id="to" type="number" min="5" value="600"></label>84 unmodified linesconst saveLocal=d=>{try{localStorage.setItem(LOCAL_KEY,JSON.stringify(d))}catch{}};// API functionsasync function apiRequest(url,options={}){const r=await fetch(API+url,options);const ct=r.headers.get('content-type')||'';if(!ct.includes('application/json')){const text=await r.text();throw new Error(r.status===401?'需要认证,请刷新页面重新登录':'服务器返回非JSON响应: '+text.slice(0,100));}const data=await r.json();if(!r.ok)throw new Error(data.error||'请求失败');return data;}async function apiGet(url){return apiRequest(url)}async function apiPost(url,data){return apiRequest(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)})}async function apiDelete(url){return apiRequest(url,{method:'DELETE'})}// Load tasksasync function loadTasks(){94 unmodified lines<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg><span>${elapsedStr||'-'}</span></div><div class="meta-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg><span>线程 <b>${t.config?.threads||0}</b></span></div><div class="meta-item"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>成功 <b style="color:#4ade80">${stats.success||0}</b></span>91 unmodified linessys:$('sys').value.trim(),usr:$('usr').value.trim(),loop:n($('loop').value,10,1,10000),threads:n($('thr').value,3,1,1000),max:n($('max').value,1024,1,32768),temp:n($('temp').value,1,0,2),timeout:n($('to').value,600,5,3600)*1000,183 unmodified lines$('bannerProgress').textContent=`${completed}/${total}`;$('bannerTokens').textContent=`${fmt(totalTokens)}/${fmt(maxTokens)}`;$('bannerTime').textContent=fmtTime(s.elapsed||0);$('detailThreads').textContent=$('thr').value||0;$('detailSuccess').textContent=s.stats?.success||0;$('detailFailed').textContent=s.stats?.failed||0;$('detailAborted').textContent=s.stats?.aborted||0;25 unmodified lines}else if(log.message){displayContent=log.message;}// Build info linelet infoLine=`循环:${log.loop||'-'}`;if(log.markerLen!==undefined){infoLine+=` | 标记:${log.markerLen}`;}if(log.tokenTotal!==undefined && log.tokenTotal>1){infoLine+=` | Key:${log.tokenIndex+1}/${log.tokenTotal}`;}return`<div class="log ${statusClass}"><div class="t"><span>线程 #${id}</span><span>${log.status}</span></div><div class="m">${infoLine}</div><pre>${displayContent.slice(-500)}</pre></div>`;33 unmodified lines$('detailBadge').className='task-badge '+status;$('detailBadge').textContent=statusText;$('bannerLabel').textContent=statusText;$('detailThreads').textContent=$('thr').value||0;updateButtons(task.running, task.currentStats?.paused, task.stopped);}203 unmodified lines$('bannerProgress').textContent='0/0';$('bannerTokens').textContent='0/0';$('bannerTime').textContent='0s';$('detailThreads').textContent=$('thr').value||'0';$('detailSuccess').textContent='0';$('detailFailed').textContent='0';$('detailAborted').textContent='0';
data/tasks.jsonAdded
executor.js+228-26
logger.js+1-1
package-lock.json+49
package.json+5-2
server.js+38-4
test-api.jsAdded+81
test-token-rotation.jsAdded+42
token-consumer.html+38-8