-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·2476 lines (2322 loc) · 120 KB
/
Copy pathserver.js
File metadata and controls
executable file
·2476 lines (2322 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* OpenAI-compatible API server wrapping DeepSeek Web API
* Supports BOTH streaming (SSE) and non-streaming modes
* Includes tool calling: injects tool definitions into system prompt,
* parses LLM text responses for TOOL_CALL patterns, returns OpenAI tool_calls format.
*
* Per-agent sessions: each unique `user` field gets its own DeepSeek web session.
* Auto-reset: sessions reset when message chain reaches 100 messages or age > 2 hours.
* Listens on 127.0.0.1:9655 by default (HOST is configurable)
*/
const http = require('http');
const fs = require('fs');
const os = require('os');
const path = require('path');
const readline = require('readline');
const crypto = require('crypto');
const { spawnSync } = require('child_process');
const { solvePOW } = require('./lib/pow');
// Per-DeepSeek-request network timeout. Plain fetch() has NO default timeout, so a
// stalled upstream would hang the inbound request (and pin the account) forever.
const DS_FETCH_TIMEOUT_MS = Number(process.env.DEEPSEEK_FETCH_TIMEOUT_MS || 60000);
function dsFetch(url, options = {}, timeoutMs = DS_FETCH_TIMEOUT_MS) {
return fetch(url, { ...options, signal: options.signal || AbortSignal.timeout(timeoutMs) });
}
const SERVER_HOST = os.hostname(); // Dynamic hostname detection
const SERVER_PUBLIC_IP = (() => {
try {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) return iface.address;
}
}
} catch (e) {}
return 'localhost';
})();
const FORGETMEAI_WATERMARK = 't.me/forgetmeai';
const PORT = Number(process.env.PORT || 9655);
const HOST = process.env.HOST || '127.0.0.1';
function loadProxyApiKey(env = process.env) {
if (env.PROXY_API_KEY) return String(env.PROXY_API_KEY);
const secretPath = String(env.PROXY_API_KEY_FILE || '').trim();
if (!secretPath) return '';
try {
return fs.readFileSync(secretPath, 'utf8').trim();
} catch (error) {
// A missing optional secret is equivalent to an unset key. Container
// deployments set REQUIRE_PROXY_API_KEY=1 and fail closed in main().
if (error.code === 'ENOENT') return '';
throw new Error(`Could not read PROXY_API_KEY_FILE (${secretPath}): ${error.message}`);
}
}
function requireProxyApiKey(key, required) {
if (required && !key) {
throw new Error('PROXY_API_KEY is required. Set PROXY_API_KEY or mount a secret and set PROXY_API_KEY_FILE.');
}
}
const PROXY_API_KEY = loadProxyApiKey();
const PROXY_CORS_ORIGINS = new Set(String(process.env.PROXY_CORS_ORIGINS || '')
.split(',')
.map(value => normalizeOrigin(value))
.filter(Boolean));
function formatWatermark(prefix = 'ForgetMeAI') { return `${prefix}: ${FORGETMEAI_WATERMARK}`; }
function printBanner() {
console.log(`
███████ ██████ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
█████ ██████ █████ █████ ██ ██ █████ █████ █████ █████
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
FreeDeepseekAPI — API-прокси для DeepSeek Web Chat
${formatWatermark()}
`);
}
function prompt(question) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans); }));
}
function isTruthy(value) { return typeof value === 'string' && ['1','true','yes','on'].includes(value.trim().toLowerCase()); }
function isProxyAuthorized(authorization, expectedKey = PROXY_API_KEY) {
if (!expectedKey) return true;
if (typeof authorization !== 'string' || !authorization.startsWith('Bearer ')) return false;
const supplied = Buffer.from(authorization.slice('Bearer '.length), 'utf8');
const expected = Buffer.from(String(expectedKey), 'utf8');
return supplied.length === expected.length && crypto.timingSafeEqual(supplied, expected);
}
function isLoopbackHost(host) {
const normalized = String(host || '').trim().toLowerCase().replace(/^\[|\]$/g, '');
return normalized === '127.0.0.1'
|| normalized === '::1'
|| normalized === '::ffff:127.0.0.1'
|| normalized === 'localhost';
}
function normalizeOrigin(origin) {
const value = String(origin || '').trim().replace(/\/+$/, '');
if (!value) return '';
try {
const parsed = new URL(value);
return parsed.origin === 'null' ? value : parsed.origin;
} catch (e) {
return value;
}
}
function isBrowserOriginAllowed(origin, allowedOrigins = PROXY_CORS_ORIGINS) {
if (!origin) return true; // curl, SDKs, and other non-browser clients
const normalized = normalizeOrigin(origin);
if (allowedOrigins.has(normalized)) return true;
try {
const parsed = new URL(normalized);
return (parsed.protocol === 'http:' || parsed.protocol === 'https:')
&& isLoopbackHost(parsed.hostname);
} catch (e) {
return false;
}
}
const CONTEXT_COMPACTED_HEADER = 'X-FreeDeepseek-Context-Compacted';
function setCorsResponseHeaders(res) {
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Expose-Headers', CONTEXT_COMPACTED_HEADER);
}
function markContextCompacted(res) {
res.setHeader(CONTEXT_COMPACTED_HEADER, 'true');
}
// === Per-Agent Session Store ===
const sessions = new Map(); // keyed by agent ID (from `user` field)
const MAX_HISTORY_LENGTH = 15;
const MAX_HISTORY_CHARS = 10000;
const MAX_MESSAGE_DEPTH = 100; // auto-reset after this many messages
const SESSION_TTL_MS = 2 * 60 * 60 * 1000; // 2 hours
// === DeepSeek Web API Config — loaded from external config file ===
const DS_CONFIG_PATH = process.env.DEEPSEEK_AUTH_PATH || path.join(__dirname, 'deepseek-auth.json');
const DEFAULT_ACCOUNT_COOLDOWN_MS = Number(process.env.DEEPSEEK_ACCOUNT_COOLDOWN_MS || 10 * 60 * 1000);
let DS_CONFIG = {};
let dsHeaders = {};
const accounts = [];
let accountRoundRobin = 0;
let inFlight = 0; // concurrent in-flight completions (backpressure cap)
// Overall wall-clock budget for one inbound request (caps the retry/continuation
// loops), max concurrent completions, and the empty-response retry cap.
const REQUEST_DEADLINE_MS = Number(process.env.DEEPSEEK_REQUEST_DEADLINE_MS || 120000);
const MAX_CONCURRENT = Number(process.env.DEEPSEEK_MAX_CONCURRENT || 24);
const configuredEmptyRetries = Number(process.env.DEEPSEEK_MAX_RETRIES);
const MAX_EMPTY_RETRIES = Number.isFinite(configuredEmptyRetries)
? Math.max(0, Math.min(10, Math.floor(configuredEmptyRetries)))
: 2;
const MIN_UPSTREAM_PROMPT_CHARS = 16000;
const configuredPromptChars = Number(process.env.DEEPSEEK_MAX_PROMPT_CHARS);
const MAX_UPSTREAM_PROMPT_CHARS = Number.isFinite(configuredPromptChars)
? Math.max(MIN_UPSTREAM_PROMPT_CHARS, Math.floor(configuredPromptChars))
: 80000;
function buildBaseHeaders(config = DS_CONFIG) {
return {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
"x-client-platform": "web",
"x-client-version": "2.0.0",
"x-client-locale": "ru",
"x-client-timezone-offset": "14400",
"x-app-version": "2.0.0",
"Authorization": `Bearer ${config.token || ''}`,
"x-hif-dliq": config.hif_dliq || '',
"x-hif-leim": config.hif_leim || '',
"Origin": "https://chat.deepseek.com",
"Referer": "https://chat.deepseek.com/",
"Cookie": config.cookie || '',
"Content-Type": "application/json",
};
}
function discoverAuthPaths() {
if (process.env.DEEPSEEK_AUTH_DIR) {
try {
return fs.readdirSync(process.env.DEEPSEEK_AUTH_DIR)
.filter(f => f.endsWith('.json'))
.sort()
.map(f => path.join(process.env.DEEPSEEK_AUTH_DIR, f));
} catch (e) {
console.error(`[DS-API] Could not read DEEPSEEK_AUTH_DIR: ${e.message}`);
return [];
}
}
if (process.env.DEEPSEEK_AUTH_PATH && process.env.DEEPSEEK_AUTH_PATH.includes(',')) {
return process.env.DEEPSEEK_AUTH_PATH.split(',').map(s => s.trim()).filter(Boolean);
}
return [DS_CONFIG_PATH];
}
function loadDeepSeekConfig({ fatal = true } = {}) {
accounts.length = 0;
const paths = discoverAuthPaths();
for (const file of paths) {
try {
const raw = fs.readFileSync(file, 'utf8');
const config = JSON.parse(raw);
const id = `account_${accounts.length + 1}`;
accounts.push({ id, file, config, headers: buildBaseHeaders(config), cooldownUntil: 0, failures: 0, lastUsedAt: 0 });
} catch (e) {
console.error(`[DS-API] Could not load auth config ${file}: ${e.message}`);
}
}
DS_CONFIG = accounts[0]?.config || {};
dsHeaders = accounts[0]?.headers || buildBaseHeaders({});
if (accounts.length > 0) {
console.log(`[DS-API] Loaded ${accounts.length} auth account(s): ${accounts.map(a => a.id).join(', ')}`);
return true;
}
if (fatal) {
console.error(`[DS-API] FATAL: Could not load any auth config. Expected ${paths.join(', ') || DS_CONFIG_PATH}`);
process.exit(1);
}
return false;
}
function hasAuthConfig() { return accounts.some(a => a.config.token && a.config.cookie); }
function accountStatus(account) {
return {
id: account.id,
ready: !!(account.config.token && account.config.cookie),
cooldown: account.cooldownUntil > Date.now(),
cooldown_remaining_sec: Math.max(0, Math.ceil((account.cooldownUntil - Date.now()) / 1000)),
failures: account.failures,
last_used_at: account.lastUsedAt || null,
};
}
function selectAccountForSession(session) {
const now = Date.now();
if (session.accountId) {
const sticky = accounts.find(a => a.id === session.accountId);
if (sticky && sticky.config.token && sticky.config.cookie && sticky.cooldownUntil <= now) return sticky;
// A DeepSeek chat_session belongs to the auth account that created it.
// If that account disappeared, lost credentials, or is cooling down,
// never reuse its session id under a different account.
resetRemoteSession(session);
session.accountId = null;
}
const ready = accounts.filter(a => a.config.token && a.config.cookie && a.cooldownUntil <= now);
if (ready.length === 0) {
const waiting = accounts.filter(a => a.config.token && a.config.cookie).sort((a, b) => a.cooldownUntil - b.cooldownUntil)[0];
if (waiting) {
const waitSec = Math.max(1, Math.ceil((waiting.cooldownUntil - now) / 1000));
// Tagged so the request handler returns 429 + Retry-After instead of a
// generic 500 (integrator backoff keys on the status code, not the text).
const err = new Error(`All DeepSeek auth accounts are cooling down. Retry in ~${waitSec}s or import a fresh account with npm run auth:import.`);
err.status = 429; err.retryAfter = waitSec; err.type = 'rate_limit';
throw err;
}
const noAuth = new Error('No valid DeepSeek auth accounts. Run npm run auth or npm run auth:import.');
noAuth.status = 503; noAuth.type = 'no_auth';
throw noAuth;
}
const account = ready[accountRoundRobin % ready.length];
accountRoundRobin++;
session.accountId = account.id;
return account;
}
// Parse a Retry-After header value into a cooldown duration in ms, or null if
// absent/unparseable. Supports both forms: delta-seconds (e.g. "120") and an
// HTTP-date (e.g. "Wed, 21 Oct 2025 07:28:00 GMT"). Clamped to >= 1s.
function parseRetryAfterMs(retryAfterRaw) {
if (!retryAfterRaw) return null;
const raw = String(retryAfterRaw).trim();
if (/^\d+$/.test(raw)) return Math.max(1000, Number(raw) * 1000);
const t = Date.parse(raw);
if (!Number.isNaN(t)) return Math.max(1000, t - Date.now());
return null;
}
function markAccountFailure(account, status, reason = '', retryAfterRaw = null) {
if (!account) return;
account.failures++;
if ([401, 403, 429].includes(Number(status))) {
// On 429, honor a valid Retry-After header (seconds or HTTP-date) when present;
// otherwise fall back to the fixed env-configured cooldown.
const retryMs = Number(status) === 429 ? parseRetryAfterMs(retryAfterRaw) : null;
const cooldownMs = retryMs != null ? retryMs : DEFAULT_ACCOUNT_COOLDOWN_MS;
account.cooldownUntil = Date.now() + cooldownMs;
console.log(`[account:${account.id}] cooldown for ${Math.round(cooldownMs / 1000)}s after HTTP ${status}${reason ? ` (${reason})` : ''}${retryMs != null ? ' (Retry-After)' : ''}`);
}
}
async function readDeepSeekJsonResponse(resp, label, account) {
const text = await resp.text();
let json = null;
if (text) {
try { json = JSON.parse(text); }
catch (e) {
markAccountFailure(account, resp.status, label);
throw new Error(`DeepSeek returned non-JSON ${label} response (HTTP ${resp.status}). Run npm run doctor. First chars: ${text.substring(0, 120)}`);
}
}
if (!resp.ok) markAccountFailure(account, resp.status, label);
return { json, text };
}
if (require.main === module) {
loadDeepSeekConfig({ fatal: false });
}
function createSession() {
return {
id: null,
parentMessageId: null,
createdAt: null,
messageCount: 0,
accountId: null,
history: [],
lastActivityAt: Date.now(),
};
}
function resetRemoteSession(session) {
const failed = {
failedSessionId: session.id,
failedMessageCount: session.messageCount,
accountId: session.accountId,
};
session.id = null;
session.parentMessageId = null;
session.createdAt = null;
session.messageCount = 0;
// Keep local recovery history and the sticky account assignment. A remote
// chat can be unhealthy without invalidating either of those local hints.
return failed;
}
function prepareSessionForPrompt(session, now = Date.now()) {
if (!session || !session.id) return null;
let reason = null;
if (session.messageCount >= MAX_MESSAGE_DEPTH) reason = 'max_message_depth';
else if (session.createdAt && now - session.createdAt > SESSION_TTL_MS) reason = 'session_ttl';
if (!reason) return null;
return { reason, ...resetRemoteSession(session) };
}
function getOrCreateAgentSession(agentId) {
if (!sessions.has(agentId)) {
sessions.set(agentId, createSession());
}
const session = sessions.get(agentId);
session.lastActivityAt = Date.now();
return session;
}
// Evict idle sessions so the Map (keyed by client IP / user id) can't grow without
// bound on a long-running process. Drops entries untouched for 2× the session TTL.
function sweepIdleSessions(maxIdleMs = SESSION_TTL_MS * 2) {
const now = Date.now();
let removed = 0;
for (const [agentId, session] of sessions) {
if (now - (session.lastActivityAt || 0) > maxIdleMs) { sessions.delete(agentId); removed++; }
}
if (removed) console.log(`[DS-API] swept ${removed} idle session(s); ${sessions.size} remain`);
return removed;
}
// solvePOW() lives in lib/pow (compiled-module cache + WASM-fetch timeout),
// shared with client.js. Called as solvePOW(challenge, wasmUrl).
const MODEL_CONFIGS = {
// DeepSeek Web real model_type: default / UI name: "Быстрый".
// Public model family: DeepSeek-V3.2-Exp chat mode (fast, no visible reasoning).
'deepseek-chat': {
model_type: 'default', thinking_enabled: false, search_enabled: false,
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
capabilities: { reasoning: false, web_search: false, files: true },
supported: true,
},
'deepseek-v3': {
model_type: 'default', thinking_enabled: false, search_enabled: false,
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
capabilities: { reasoning: false, web_search: false, files: true },
supported: true,
},
'deepseek-default': {
model_type: 'default', thinking_enabled: false, search_enabled: false,
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
capabilities: { reasoning: false, web_search: false, files: true },
supported: true,
},
// Same DeepSeek Web default model, but with thinking_enabled=true. UI exposes it as thinking/reasoning mode.
'deepseek-reasoner': {
model_type: 'default', thinking_enabled: true, search_enabled: false,
real_model: 'DeepSeek-V4-Flash thinking mode (DeepSeek Web “Быстрый” + thinking_enabled)',
capabilities: { reasoning: true, web_search: false, files: true },
supported: true,
},
'deepseek-r1': {
model_type: 'default', thinking_enabled: true, search_enabled: false,
real_model: 'DeepSeek-V4-Flash thinking mode; R1-compatible alias, not a separate R1 model_type in current Web API',
capabilities: { reasoning: true, web_search: false, files: true },
supported: true,
},
'deepseek-chat-search': {
model_type: 'default', thinking_enabled: false, search_enabled: true,
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search',
capabilities: { reasoning: false, web_search: true, files: true },
supported: true,
},
'deepseek-default-search': {
model_type: 'default', thinking_enabled: false, search_enabled: true,
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search',
capabilities: { reasoning: false, web_search: true, files: true },
supported: true,
},
'deepseek-reasoner-search': {
model_type: 'default', thinking_enabled: true, search_enabled: true,
real_model: 'DeepSeek-V4-Flash thinking mode + web search',
capabilities: { reasoning: true, web_search: true, files: true },
supported: true,
},
'deepseek-r1-search': {
model_type: 'default', thinking_enabled: true, search_enabled: true,
real_model: 'DeepSeek-V4-Flash thinking mode + web search; R1-compatible alias',
capabilities: { reasoning: true, web_search: true, files: true },
supported: true,
},
// DeepSeek Web UI name: “Эксперт”. Requires current web client headers (x-client-version=2.0.0).
'deepseek-expert': {
model_type: 'expert', thinking_enabled: false, search_enabled: false,
real_model: 'DeepSeek Web “Эксперт” (limited resources)',
capabilities: { reasoning: false, web_search: false, files: false },
supported: true,
},
'deepseek-v4-pro': {
model_type: 'expert', thinking_enabled: true, search_enabled: false,
real_model: 'DeepSeek Web “Эксперт” + thinking mode (exposed as deepseek-v4-pro alias)',
capabilities: { reasoning: true, web_search: false, files: false },
supported: true,
},
'deepseek-expert-search': {
model_type: 'expert', thinking_enabled: false, search_enabled: true,
real_model: 'DeepSeek Web “Эксперт” + search requested, but Expert has search_feature=null in remote config',
capabilities: { reasoning: false, web_search: false, files: false },
supported: false,
unavailable_reason: 'Expert mode is rejected; remote config says search is not available for Expert.',
},
'deepseek-vision': {
model_type: 'vision', thinking_enabled: false, search_enabled: false,
real_model: 'DeepSeek Web “Распознавание” / image understanding beta',
capabilities: { reasoning: false, web_search: false, files: true, vision: true },
supported: false,
unavailable_reason: 'Current Web API returns: Vision is temporarily unavailable (backend_err_by_model).',
},
};
const SUPPORTED_MODEL_IDS = Object.keys(MODEL_CONFIGS).filter(id => MODEL_CONFIGS[id].supported);
const ALL_MODEL_CAPABILITIES = Object.fromEntries(Object.entries(MODEL_CONFIGS).map(([id, cfg]) => [id, {
id,
real_model: cfg.real_model,
model_type: cfg.model_type,
thinking_enabled: cfg.thinking_enabled,
search_enabled: cfg.search_enabled,
capabilities: cfg.capabilities,
supported: cfg.supported,
unavailable_reason: cfg.unavailable_reason || null,
}]));
function isAssistantOutputFragment(fragment) {
return fragment
&& (fragment.type === 'RESPONSE' || fragment.type === 'SEARCH')
&& typeof fragment.content === 'string';
}
function isReasoningFragment(fragment) {
return fragment
&& (fragment.type === 'THINK' || fragment.type === 'REASONING')
&& typeof fragment.content === 'string';
}
function isDeepSeekModelErrorEvent(event) {
return event && event.type === 'error';
}
function createUpstreamHttpError(status, body = '', retryAfter = null) {
const code = Number(status) || 502;
const detail = String(body || '').replace(/\s+/g, ' ').trim().substring(0, 300);
const type = code === 429
? 'rate_limit_error'
: ((code === 401 || code === 403) ? 'authentication_error' : 'upstream_http_error');
const error = new Error(`DeepSeek upstream HTTP ${code}${detail ? `: ${detail}` : ''}`);
error.status = code;
error.type = type;
if (retryAfter) error.retryAfter = retryAfter;
return error;
}
function rebuildFragmentText(fragments) {
const responseText = fragments
.filter(isAssistantOutputFragment)
.map(f => f.content)
.join('');
const thinkText = fragments
.filter(isReasoningFragment)
.map(f => f.content)
.join('');
return { responseText, thinkText };
}
function applyResponsePatchOperations(ops, appendFragments) {
if (!Array.isArray(ops)) return false;
let applied = false;
for (const op of ops) {
if (!op || typeof op !== 'object') continue;
if (op.p === 'fragments' && op.o === 'APPEND' && op.v !== undefined) {
appendFragments(op.v);
applied = true;
}
}
return applied;
}
function resolveModelConfig(model) {
const requested = String(model || 'deepseek-chat').toLowerCase();
return MODEL_CONFIGS[requested] || MODEL_CONFIGS['deepseek-chat'];
}
function isKnownModel(model) { return Object.prototype.hasOwnProperty.call(MODEL_CONFIGS, String(model || '').toLowerCase()); }
function isSupportedModel(model) { return resolveModelConfig(model).supported === true; }
async function askDeepSeekStream(prompt, agentId, model = 'deepseek-default', freshSessionPrompt = prompt) {
const modelCfg = resolveModelConfig(model);
const session = getOrCreateAgentSession(agentId);
const hadRemoteSession = Boolean(session.id);
const account = selectAccountForSession(session);
const dsHeaders = account.headers;
account.lastUsedAt = Date.now();
const agentTag = `[${agentId}/acct:${account.id}]`;
// Normally this rollover is performed before the prompt is built, so local
// recovery history can be injected. Keep this guard for direct callers and
// concurrent requests that may have advanced the same session meanwhile.
const rollover = prepareSessionForPrompt(session);
const accountRotationReset = hadRemoteSession && !session.id;
const recoveredFreshSession = accountRotationReset || Boolean(rollover);
let effectivePrompt = recoveredFreshSession ? freshSessionPrompt : prompt;
if (accountRotationReset) {
console.log(`${agentTag} Account rotation reset the previous remote session; using recovery prompt.`);
}
if (rollover) {
console.log(`${agentTag} Session ${rollover.failedSessionId} reset before upstream call (${rollover.reason}).`);
}
const cr = await dsFetch('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', {
method: 'POST', headers: dsHeaders,
body: JSON.stringify({ target_path: '/api/v0/chat/completion' })
});
const chalText = await cr.text();
if (!cr.ok) {
markAccountFailure(account, cr.status, 'pow challenge');
throw new Error(`DeepSeek auth/network error while creating PoW challenge: HTTP ${cr.status}. Run npm run doctor. If auth expired, run npm run auth or npm run auth:import.`);
}
let chalJson;
try { chalJson = JSON.parse(chalText); }
catch (e) { throw new Error(`DeepSeek returned non-JSON PoW response. Run npm run doctor. First chars: ${chalText.substring(0, 120)}`); }
const challenge = chalJson?.data?.biz_data?.challenge;
if (!challenge) {
throw new Error('DeepSeek PoW response has no data.biz_data.challenge. Auth may be expired, captcha may be required, or DeepSeek changed Web API. Run npm run doctor, then npm run auth.');
}
const answer = await solvePOW(challenge, account.config.wasmUrl);
if (!session.id) {
const sr = await dsFetch('https://chat.deepseek.com/api/v0/chat_session/create', {
method: 'POST', headers: dsHeaders, body: '{}'
});
const { json: sessionData, text: sessionText } = await readDeepSeekJsonResponse(sr, 'session create', account);
const createdSessionId = sessionData?.data?.biz_data?.chat_session?.id || sessionData?.data?.biz_data?.id;
if (!sr.ok || !createdSessionId) {
throw new Error(`Could not create DeepSeek chat session (HTTP ${sr.status}). Auth may be expired/captcha-blocked. Run npm run doctor, then npm run auth. First chars: ${String(sessionText || '').substring(0, 120)}`);
}
session.id = createdSessionId;
session.accountId = account.id;
session.parentMessageId = null;
session.createdAt = Date.now();
session.messageCount = 0;
console.log(`${agentTag} Created new session: ${session.id}`);
} else {
console.log(`${agentTag} Reusing session: ${session.id} (parent: ${session.parentMessageId}, msg#${session.messageCount})`);
}
const powB64 = Buffer.from(JSON.stringify({
algorithm: challenge.algorithm, challenge: challenge.challenge,
salt: challenge.salt, answer: answer,
signature: challenge.signature, target_path: '/api/v0/chat/completion'
})).toString('base64');
const resp = await dsFetch('https://chat.deepseek.com/api/v0/chat/completion', {
method: 'POST',
headers: { ...dsHeaders, 'X-DS-PoW-Response': powB64 },
body: JSON.stringify({
chat_session_id: session.id,
parent_message_id: session.parentMessageId,
model_type: modelCfg.model_type,
prompt: effectivePrompt, ref_file_ids: [],
thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
action: null, preempt: false,
})
});
// If session expired, reset and retry once
if (resp.status !== 200) {
// Pass Retry-After so a 429 honors the server-requested cooldown (#16).
const retryAfter = resp.headers.get('retry-after');
markAccountFailure(account, resp.status, 'completion', retryAfter);
const errText = await resp.text();
console.log(`${agentTag} Session error (${resp.status}): ${errText.substring(0, 100)}`);
if (resp.status === 400 || resp.status === 404 || resp.status === 500) {
console.log(`${agentTag} Session ${session.id} expired. Creating new session...`);
resetRemoteSession(session);
const sr2 = await dsFetch('https://chat.deepseek.com/api/v0/chat_session/create', {
method: 'POST', headers: dsHeaders, body: '{}'
});
const { json: sessionData2, text: sessionText2 } = await readDeepSeekJsonResponse(sr2, 'session recreate', account);
const createdSessionId2 = sessionData2?.data?.biz_data?.chat_session?.id || sessionData2?.data?.biz_data?.id;
if (!sr2.ok || !createdSessionId2) {
throw new Error(`Could not recreate DeepSeek chat session (HTTP ${sr2.status}). Run npm run doctor, then npm run auth. First chars: ${String(sessionText2 || '').substring(0, 120)}`);
}
session.id = createdSessionId2;
session.accountId = account.id;
session.parentMessageId = null;
session.createdAt = Date.now();
console.log(`${agentTag} Created new session: ${session.id}`);
const newPowB64 = Buffer.from(JSON.stringify({
algorithm: challenge.algorithm, challenge: challenge.challenge,
salt: challenge.salt, answer: answer,
signature: challenge.signature, target_path: '/api/v0/chat/completion'
})).toString('base64');
const resp2 = await dsFetch('https://chat.deepseek.com/api/v0/chat/completion', {
method: 'POST',
headers: { ...dsHeaders, 'X-DS-PoW-Response': newPowB64 },
body: JSON.stringify({
chat_session_id: session.id,
parent_message_id: null,
model_type: modelCfg.model_type,
prompt: freshSessionPrompt, ref_file_ids: [],
thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
action: null, preempt: false,
})
});
if (!resp2.ok) {
const retryAfter2 = resp2.headers.get('retry-after');
markAccountFailure(account, resp2.status, 'completion after session recreate', retryAfter2);
const errText2 = await resp2.text();
throw createUpstreamHttpError(resp2.status, errText2, retryAfter2);
}
effectivePrompt = freshSessionPrompt;
return { resp: resp2, agentId, account, promptUsed: effectivePrompt, freshSessionReset: true };
}
// The body was consumed for diagnostics, so returning this Response
// would hand a locked stream to readDeepSeekResponse. Surface a typed
// error instead and retain the real upstream status/Retry-After.
throw createUpstreamHttpError(resp.status, errText, retryAfter);
}
return { resp, agentId, account, promptUsed: effectivePrompt, freshSessionReset: recoveredFreshSession };
}
// === Tool Calling Support ===
const TOOL_SCHEMA_ANNOTATION_KEYS = new Set(['description', 'examples', '$comment', 'title']);
const TOOL_SCHEMA_MAP_KEYS = new Set(['properties', 'patternProperties', '$defs', 'definitions', 'dependentSchemas']);
const TOOL_SCHEMA_ARRAY_KEYS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
const TOOL_SCHEMA_SINGLE_KEYS = new Set([
'additionalItems', 'additionalProperties', 'contains', 'contentSchema', 'else', 'if',
'items', 'not', 'propertyNames', 'then', 'unevaluatedItems', 'unevaluatedProperties',
]);
function compactToolSchema(value) {
if (Array.isArray(value)) return value.map(compactToolSchema);
if (!value || typeof value !== 'object') return value;
const compact = {};
for (const [key, child] of Object.entries(value)) {
// Descriptions/examples dominate large agent tool payloads but do not
// affect argument validation. Traverse only keywords whose values are
// themselves schemas. Literal instance values under const/enum/default
// must remain byte-for-byte equivalent, even when they contain fields
// named "description" or "title".
if (TOOL_SCHEMA_ANNOTATION_KEYS.has(key)) continue;
if (TOOL_SCHEMA_MAP_KEYS.has(key) && child && typeof child === 'object' && !Array.isArray(child)) {
compact[key] = Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, compactToolSchema(schema)]));
} else if (TOOL_SCHEMA_ARRAY_KEYS.has(key) && Array.isArray(child)) {
compact[key] = child.map(compactToolSchema);
} else if (TOOL_SCHEMA_SINGLE_KEYS.has(key)) {
compact[key] = Array.isArray(child) ? child.map(compactToolSchema) : compactToolSchema(child);
} else if (key === 'dependencies' && child && typeof child === 'object' && !Array.isArray(child)) {
compact[key] = Object.fromEntries(Object.entries(child).map(([name, dependency]) => [
name,
Array.isArray(dependency) ? dependency : compactToolSchema(dependency),
]));
} else {
compact[key] = child;
}
}
return compact;
}
function formatToolDefinitions(tools) {
if (!tools || tools.length === 0) return '';
const rawSchemaChars = tools.reduce((total, tool) => {
try { return total + JSON.stringify(tool?.function?.parameters || {}).length; }
catch (e) { return total; }
}, 0);
const compactSchemas = rawSchemaChars > Math.floor(MAX_UPSTREAM_PROMPT_CHARS * 0.4);
let text = '\n\n--- TOOL REQUEST SYSTEM ---\n';
text += 'You are an AI that ONLY REASONS and REQUESTS tool executions. You do NOT run any commands yourself.\n';
text += 'When you need data from the local server, REQUEST exactly one tool call. Prefer strict JSON:\n';
text += '{"tool_call":{"name":"<function_name>","arguments":{...}}}\n\n';
text += 'Legacy format is also accepted: TOOL_CALL: <function_name>\narguments: <JSON arguments>\n\n';
text += 'Your response will be sent to the local gateway, which executes the command and sends the output back in the next message.\n\n';
text += 'RULES:\n';
text += '1. You ONLY output the tool request — you never run anything yourself\n';
text += '2. Do NOT simulate, guess, or fabricate command output — wait for the actual result\n';
text += '3. The tool runs on ' + SERVER_HOST + ' (' + SERVER_PUBLIC_IP + '), the local server — NOT on DeepSeek\n';
text += '4. After the tool executes, the result will be sent to you as a new user/tool message\n';
text += '5. Never add explanation before or after the tool request when requesting a tool\n';
text += '6. Keep arguments compact. Do not include large file contents unless the tool schema requires it.\n\n';
text += 'Available functions:\n';
for (const tool of tools) {
if (tool.type === 'function' && tool.function) {
const fn = tool.function;
text += `\n## ${fn.name}\n`;
const description = String(fn.description || '').replace(/\s+/g, ' ').trim();
text += `${description.length > 500 ? description.substring(0, 497) + '...' : description}\n`;
if (fn.parameters) {
text += `Parameters: ${JSON.stringify(compactSchemas ? compactToolSchema(fn.parameters) : fn.parameters)}\n`;
}
}
}
text += '\n--- END TOOL REQUEST SYSTEM ---\n';
text += '\nREMEMBER: Request tools only with strict JSON or TOOL_CALL legacy format. Never simulate results.';
return text;
}
const MAX_TOOL_MARKUP_CHARS = 256 * 1024;
const MAX_TOOL_ARGUMENT_CHARS = 128 * 1024;
const MAX_TOOL_JSON_CANDIDATES = 32;
const MAX_DSML_PARAMETERS = 128;
const MAX_DSML_STRUCTURAL_TAGS = MAX_DSML_PARAMETERS * 2 + 16;
const MAX_DSML_TAG_CHARS = 2048;
function extractBalancedJsonAt(text, startIndex) {
if (text[startIndex] !== '{') return null;
let braceDepth = 0;
let inString = false;
let escape = false;
for (let i = startIndex; i < text.length; i++) {
const ch = text[i];
if (escape) { escape = false; continue; }
if (ch === '\\' && inString) { escape = true; continue; }
if (ch === '"') { inString = !inString; continue; }
if (!inString) {
if (ch === '{') braceDepth++;
if (ch === '}') {
braceDepth--;
if (braceDepth === 0) return text.substring(startIndex, i + 1);
}
}
}
return null;
}
function extractBalancedJsonObjects(text, maxObjects = MAX_TOOL_JSON_CANDIDATES) {
const objects = [];
let start = -1;
let depth = 0;
let inString = false;
let escape = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (start === -1) {
if (ch === '{') {
start = i;
depth = 1;
inString = false;
escape = false;
}
continue;
}
if (escape) { escape = false; continue; }
if (ch === '\\' && inString) { escape = true; continue; }
if (ch === '"') { inString = !inString; continue; }
if (inString) continue;
if (ch === '{') depth++;
if (ch === '}') {
depth--;
if (depth === 0) {
objects.push(text.substring(start, i + 1));
if (objects.length >= maxObjects) return objects;
start = -1;
}
}
}
return objects;
}
function buildToolCall(name, args = {}) {
const toolName = typeof name === 'string' ? name.trim() : '';
if (!/^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/.test(toolName)) return null;
let parsedArgs = args;
if (typeof parsedArgs === 'string') {
if (parsedArgs.length > MAX_TOOL_ARGUMENT_CHARS) return null;
try { parsedArgs = JSON.parse(parsedArgs); } catch (e) { return null; }
}
if (parsedArgs === null || parsedArgs === undefined) parsedArgs = {};
if (typeof parsedArgs !== 'object' || Array.isArray(parsedArgs)) return null;
let serialized;
try { serialized = JSON.stringify(parsedArgs); } catch (e) { return null; }
if (serialized.length > MAX_TOOL_ARGUMENT_CHARS) return null;
return { name: toolName, arguments: serialized };
}
function coerceToolCallObject(obj, { allowBare = false } = {}) {
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return null;
let candidate = null;
if (Object.prototype.hasOwnProperty.call(obj, 'tool_call')) {
candidate = obj.tool_call;
} else if (Object.prototype.hasOwnProperty.call(obj, 'function_call')) {
candidate = obj.function_call;
} else if (Object.prototype.hasOwnProperty.call(obj, 'tool_calls')) {
if (!Array.isArray(obj.tool_calls) || obj.tool_calls.length !== 1) return null;
candidate = obj.tool_calls[0];
} else if (allowBare) {
candidate = obj;
}
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) return null;
const fn = candidate.function && typeof candidate.function === 'object'
? candidate.function
: candidate;
return buildToolCall(
fn.name ?? candidate.name,
fn.arguments ?? candidate.arguments ?? candidate.input ?? {}
);
}
function parseJsonToolCandidate(raw, label = 'json', options = {}) {
if (!raw) return null;
try {
const parsed = JSON.parse(raw);
const tc = coerceToolCallObject(parsed, options);
if (tc) {
console.log(`[parseToolCall] SUCCESS ${label}: ${tc.name} (args=${tc.arguments.length} chars)`);
return tc;
}
} catch (e) {
console.log(`[parseToolCall] ${label} JSON.parse failed: ${e.message.substring(0, 100)}`);
}
return null;
}
function canonicalizeToolMarkupTag(rawTag) {
let token = String(rawTag || '').trim()
.replace(/|/g, '|')
.replace(/[“”"]/g, '"')
.replace(/[‘’']/g, "'");
let closing = false;
if (token.startsWith('/')) {
closing = true;
token = token.substring(1).trim();
}
token = token.replace(/^\|+\s*DSML\s*\|+\s*/i, '');
if (token.startsWith('/')) {
closing = true;
token = token.substring(1).trim();
}
token = token.replace(/^DSML(?=(?:tool[\s_-]*calls|function[\s_-]*calls|invoke|parameter)\b)/i, '');
if (!closing && /^name\s*=/i.test(token)) return `<direct ${token}>`;
const semantic = token.match(/^(?:(?:[A-Za-z_][\w.-]*):)?(tool[\s_-]*calls|function[\s_-]*calls|invoke|parameter)\b([\s\S]*)$/i);
if (!semantic) return null;
const localName = semantic[1].replace(/[\s_-]/g, '').toLowerCase();
const canonicalName = localName === 'toolcalls' || localName === 'functioncalls'
? 'tool_calls'
: localName;
const attrs = closing ? '' : semantic[2];
return `<${closing ? '/' : ''}${canonicalName}${attrs}>`;
}
function normalizeToolMarkupTags(text) {
const withAsciiAngles = String(text || '').replace(/</g, '<').replace(/>/g, '>');
return withAsciiAngles.replace(/<([^<>]{0,1024})>/g, (whole, rawTag) => {
const canonical = canonicalizeToolMarkupTag(rawTag);
return canonical || whole;
});
}
function decodeDsmlValue(value) {
return String(value || '')
.replace(/"/gi, '"')
.replace(/'/gi, "'")
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/&/gi, '&');
}
function decodeDsmlParameterValue(value) {
const raw = String(value || '');
const cdata = raw.trim().match(/^<!\[CDATA\[([\s\S]*?)\]\]>$/i);
return cdata ? cdata[1] : decodeDsmlValue(raw);
}
function getMarkupAttribute(attrs, attribute) {
const match = String(attrs || '').match(new RegExp(`\\b${attribute}\\s*=\\s*(["'])([^"']+)\\1`, 'i'));
return match ? match[2] : null;
}
function readDsmlTagAt(text, start) {
if (text[start] !== '<') return null;
const prefix = text.substring(start + 1, Math.min(text.length, start + 40)).trimStart();
if (!/^\/?(?:tool_calls|invoke|parameter|direct)\b/i.test(prefix)) return null;
let quote = null;
let end = -1;
const scanEnd = Math.min(text.length, start + MAX_DSML_TAG_CHARS + 1);
for (let i = start + 1; i < scanEnd; i++) {
const ch = text[i];
if (quote) {
if (ch === quote) quote = null;
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
continue;
}
if (ch === '>') {
end = i;
break;
}
}
if (end === -1) return { invalid: true };
let token = text.substring(start + 1, end).trim();
let closing = false;
if (token.startsWith('/')) {
closing = true;
token = token.substring(1).trim();
}
let selfClosing = false;
if (!closing && token.endsWith('/')) {
selfClosing = true;
token = token.substring(0, token.length - 1).trim();
}
const match = token.match(/^(tool_calls|invoke|parameter|direct)\b([\s\S]*)$/i);
if (!match) return null;
return {
name: match[1].toLowerCase(),
attrs: closing ? '' : match[2],
closing,
selfClosing,
start,
end: end + 1,
};
}
function scanDsmlStructuralTags(text) {
const tags = [];
const value = String(text || '');
for (let i = 0; i < value.length;) {
if (value.substring(i, i + 9).toUpperCase() === '<![CDATA[') {
const cdataEnd = value.indexOf(']]>', i + 9);
if (cdataEnd === -1) return null;
i = cdataEnd + 3;
continue;
}
if (value[i] !== '<') {
i++;
continue;
}
const tag = readDsmlTagAt(value, i);
if (!tag) {
i++;
continue;
}
if (tag.invalid) return null;
tags.push(tag);
if (tags.length > MAX_DSML_STRUCTURAL_TAGS) return null;
i = tag.end;
}
return tags;
}
function parseDsmlParameter(attrs, rawBody, args, seenNames) {
const parameterName = getMarkupAttribute(attrs, 'name');
if (!parameterName || !/^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/.test(parameterName) || seenNames.has(parameterName)) return false;
seenNames.add(parameterName);
const stringMode = getMarkupAttribute(attrs, 'string');
const rawValue = decodeDsmlParameterValue(rawBody);
if (rawValue.length > MAX_TOOL_ARGUMENT_CHARS) return false;
let value = rawValue;
if (stringMode && stringMode.toLowerCase() === 'false') {
try { value = JSON.parse(rawValue.trim()); } catch (e) { return false; }
}