-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·1389 lines (1300 loc) · 69.3 KB
/
server.js
File metadata and controls
executable file
·1389 lines (1300 loc) · 69.3 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 > 50 messages or age > 2 hours.
* Listens on 0.0.0.0:9655
*/
const http = require('http');
const fs = require('fs');
const os = require('os');
const path = require('path');
const readline = require('readline');
const { spawnSync } = require('child_process');
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 || '0.0.0.0';
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()); }
// === 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');
let DS_CONFIG = {};
let BASE_HEADERS = {};
function buildBaseHeaders() {
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 ${DS_CONFIG.token || ''}`,
"x-hif-dliq": DS_CONFIG.hif_dliq || '',
"x-hif-leim": DS_CONFIG.hif_leim || '',
"Origin": "https://chat.deepseek.com",
"Referer": "https://chat.deepseek.com/",
"Cookie": DS_CONFIG.cookie || '',
"Content-Type": "application/json",
};
}
function loadDeepSeekConfig({ fatal = true } = {}) {
try {
const raw = fs.readFileSync(DS_CONFIG_PATH, 'utf8');
DS_CONFIG = JSON.parse(raw);
BASE_HEADERS = buildBaseHeaders();
console.log(`[DS-API] Loaded auth config from ${DS_CONFIG_PATH}`);
return true;
} catch (e) {
DS_CONFIG = {};
BASE_HEADERS = buildBaseHeaders();
if (fatal) {
console.error(`[DS-API] FATAL: Could not load auth config: ${e.message}`);
process.exit(1);
}
return false;
}
}
function hasAuthConfig() { return !!(DS_CONFIG.token && DS_CONFIG.cookie); }
loadDeepSeekConfig({ fatal: false });
function createSession() {
return {
id: null,
parentMessageId: null,
createdAt: null,
messageCount: 0,
history: [],
};
}
function getOrCreateAgentSession(agentId) {
if (!sessions.has(agentId)) {
sessions.set(agentId, createSession());
}
return sessions.get(agentId);
}
async function solvePOW(challenge) {
const resp = await fetch(DS_CONFIG.wasmUrl);
const wasmBytes = await resp.arrayBuffer();
const mod = await WebAssembly.instantiate(wasmBytes, { wbg: {} });
const e = mod.instance.exports;
const encoder = new TextEncoder();
const prefix = challenge.salt + '_' + challenge.expire_at + '_';
const cBytes = encoder.encode(challenge.challenge);
const pBytes = encoder.encode(prefix);
const cP = e.__wbindgen_export_0(cBytes.length, 1) >>> 0;
const pP = e.__wbindgen_export_0(pBytes.length, 1) >>> 0;
new Uint8Array(e.memory.buffer, cP, cBytes.length).set(cBytes);
new Uint8Array(e.memory.buffer, pP, pBytes.length).set(pBytes);
const sp = e.__wbindgen_add_to_stack_pointer(-16);
e.wasm_solve(sp, cP, cBytes.length, pP, pBytes.length, challenge.difficulty);
const dv = new DataView(e.memory.buffer);
const code = dv.getInt32(sp, true);
const ans = dv.getFloat64(sp + 8, true);
e.__wbindgen_add_to_stack_pointer(16);
if (code === 0 || !Number.isFinite(ans) || ans <= 0) throw new Error('POW failed');
return Math.floor(ans);
}
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 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') {
const modelCfg = resolveModelConfig(model);
const session = getOrCreateAgentSession(agentId);
const agentTag = `[${agentId}]`;
// Auto-reset on deep message chain
if (session.id && session.messageCount >= MAX_MESSAGE_DEPTH) {
console.log(`${agentTag} Session ${session.id} hit ${session.messageCount} messages. Auto-resetting.`);
session.id = null;
session.parentMessageId = null;
session.createdAt = null;
session.messageCount = 0;
// History preserved for context injection
}
// Reset expired sessions (DeepSeek web sessions last ~1-2 hours)
if (session.id && session.createdAt && (Date.now() - session.createdAt > SESSION_TTL_MS)) {
console.log(`${agentTag} Session ${session.id} expired (age: ${Math.round((Date.now() - session.createdAt) / 60000)}min). Creating new...`);
session.id = null;
session.parentMessageId = null;
session.createdAt = null;
session.messageCount = 0;
}
const cr = await fetch('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', {
method: 'POST', headers: BASE_HEADERS,
body: JSON.stringify({ target_path: '/api/v0/chat/completion' })
});
const chalJson = JSON.parse(await cr.text());
const challenge = chalJson.data.biz_data.challenge;
const answer = await solvePOW(challenge);
if (!session.id) {
const sr = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', {
method: 'POST', headers: BASE_HEADERS, body: '{}'
});
const sessionData = await sr.json();
session.id = sessionData.data.biz_data.chat_session?.id || sessionData.data.biz_data.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 fetch('https://chat.deepseek.com/api/v0/chat/completion', {
method: 'POST',
headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': powB64 },
body: JSON.stringify({
chat_session_id: session.id,
parent_message_id: session.parentMessageId,
model_type: modelCfg.model_type,
prompt: prompt, 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) {
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...`);
session.id = null;
session.parentMessageId = null;
session.createdAt = null;
session.messageCount = 0;
const sr2 = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', {
method: 'POST', headers: BASE_HEADERS, body: '{}'
});
const sessionData2 = await sr2.json();
session.id = sessionData2.data.biz_data.chat_session?.id || sessionData2.data.biz_data.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 fetch('https://chat.deepseek.com/api/v0/chat/completion', {
method: 'POST',
headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': newPowB64 },
body: JSON.stringify({
chat_session_id: session.id,
parent_message_id: null,
model_type: modelCfg.model_type,
prompt: prompt, ref_file_ids: [],
thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
action: null, preempt: false,
})
});
return { resp: resp2, agentId };
}
}
return { resp, agentId };
}
// === Tool Calling Support ===
function formatToolDefinitions(tools) {
if (!tools || tools.length === 0) return '';
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`;
text += `${fn.description || ''}\n`;
if (fn.parameters) {
text += `Parameters: ${JSON.stringify(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;
}
function extractBalancedJsonAt(text, startIndex) {
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 coerceToolCallObject(obj) {
if (!obj || typeof obj !== 'object') return null;
const candidate = obj.tool_call || obj.tool || obj.function_call || obj;
if (!candidate || typeof candidate !== 'object') return null;
const fn = candidate.function && typeof candidate.function === 'object' ? candidate.function : candidate;
const name = fn.name || candidate.name || obj.name;
let args = fn.arguments ?? candidate.arguments ?? candidate.input ?? obj.arguments ?? obj.input ?? {};
if (!name || typeof name !== 'string') return null;
if (typeof args === 'string') {
try { args = JSON.parse(args); } catch (e) { args = { raw: args }; }
}
if (!args || typeof args !== 'object' || Array.isArray(args)) args = { value: args };
return { name, arguments: JSON.stringify(args) };
}
function parseJsonToolCandidate(raw, label = 'json') {
if (!raw) return null;
try {
const parsed = JSON.parse(raw);
const tc = coerceToolCallObject(parsed);
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 parseToolCall(text) {
if (!text || typeof text !== 'string') return null;
// XML-ish wrappers used by some agent prompts.
const xmlMatch = text.match(/<tool_call[^>]*>([\s\S]*?)<\/tool_call>/i);
if (xmlMatch) {
const inner = xmlMatch[1].trim();
const tc = parseJsonToolCandidate(inner, 'xml');
if (tc) return tc;
}
// Fenced JSON blocks.
const fenceRe = /```(?:json)?\s*([\s\S]*?)```/gi;
let fence;
while ((fence = fenceRe.exec(text)) !== null) {
const tc = parseJsonToolCandidate(fence[1].trim(), 'fenced');
if (tc) return tc;
}
// Legacy TOOL_CALL: name + first balanced JSON object after it.
const match = text.match(/TOOL_CALL:\s*([\w-]+)\s*/i);
if (match) {
const name = match[1];
const afterMatch = text.substring(match.index + match[0].length);
const braceIdx = afterMatch.indexOf('{');
if (braceIdx !== -1) {
const rawJson = extractBalancedJsonAt(afterMatch, braceIdx);
if (rawJson) {
try {
const args = JSON.parse(rawJson);
console.log(`[parseToolCall] SUCCESS legacy: ${name} (args=${rawJson.length} chars)`);
return { name, arguments: JSON.stringify(args) };
} catch (e) {
console.log(`[parseToolCall] legacy JSON.parse failed: ${e.message.substring(0,100)}`);
}
} else {
console.log(`[parseToolCall] TOOL_CALL:${name} found but JSON braces are unbalanced`);
}
} else {
console.log(`[parseToolCall] TOOL_CALL:${name} found but no { after it`);
}
}
// First balanced JSON object in the whole response. Supports:
// {"tool_call":{"name":"...","arguments":{...}}}, {"name":"...","arguments":{...}}, etc.
for (let i = 0; i < text.length; i++) {
if (text[i] !== '{') continue;
const rawJson = extractBalancedJsonAt(text, i);
if (!rawJson) continue;
const tc = parseJsonToolCandidate(rawJson, 'inline');
if (tc) return tc;
}
console.log(`[parseToolCall] No tool call match in ${text.length} chars`);
return null;
}
/**
* Strip surrogate characters and other problematic Unicode from text
* to prevent httpx/urlencode crashes when the gateway sends to Telegram.
*/
function sanitizeContent(text) {
return text.replace(/[\ud800-\udfff]/g, '');
}
function estimateTokens(text) {
return text ? Math.ceil(String(text).length / 4) : 0;
}
function buildUsage(prompt, content, reasoningContent = '') {
const promptTokens = estimateTokens(prompt);
const contentTokens = estimateTokens(content);
const reasoningTokens = estimateTokens(reasoningContent);
const completionTokens = contentTokens + reasoningTokens;
return {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: promptTokens + completionTokens,
completion_tokens_details: {
reasoning_tokens: reasoningTokens
}
};
}
function buildToolCallResponse(toolCall, model = 'deepseek-default', prompt = '', reasoningContent = '') {
const id = 'call_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8);
const message = {
role: 'assistant',
content: null,
tool_calls: [{
id: id,
type: 'function',
function: { name: toolCall.name, arguments: toolCall.arguments }
}]
};
// Do not attach reasoning to tool-call turns. Some agent clients treat any
// reasoning/text payload as a final assistant answer and stop their tool loop.
return {
id: 'ds-' + Date.now(),
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model,
choices: [{
index: 0,
message,
finish_reason: 'tool_calls'
}],
usage: buildUsage(prompt, '', reasoningContent),
watermark: FORGETMEAI_WATERMARK
};
}
function buildTextResponse(content, prompt, model = 'deepseek-default', reasoningContent = '') {
const message = { role: 'assistant', content };
if (reasoningContent) message.reasoning_content = reasoningContent;
return {
id: 'ds-' + Date.now(),
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model,
choices: [{
index: 0,
message,
finish_reason: 'stop'
}],
usage: buildUsage(prompt, content, reasoningContent),
watermark: FORGETMEAI_WATERMARK
};
}
function normalizeMessageContent(content) {
if (content === null || content === undefined) return '';
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content.map(part => {
if (typeof part === 'string') return part;
if (!part || typeof part !== 'object') return '';
if (part.type === 'text' || part.type === 'input_text' || part.type === 'output_text') return part.text || '';
if (part.type === 'tool_result') return `[Tool Result ${part.tool_use_id || ''}]\n${normalizeMessageContent(part.content)}`;
if (part.type === 'image_url') return `[Image: ${part.image_url?.url || ''}]`;
return part.text || part.content || JSON.stringify(part);
}).filter(Boolean).join('\n');
}
return String(content);
}
function normalizeAnthropicTools(tools = []) {
return (tools || []).map(tool => ({
type: 'function',
function: {
name: tool.name,
description: tool.description || '',
parameters: tool.input_schema || tool.parameters || { type: 'object', properties: {} }
}
})).filter(tool => tool.function.name);
}
function normalizeResponsesTools(tools = []) {
return (tools || []).map(tool => {
if (tool.type === 'function' && tool.function) return tool;
if (tool.type === 'function' && tool.name) {
return { type: 'function', function: { name: tool.name, description: tool.description || '', parameters: tool.parameters || { type: 'object', properties: {} } } };
}
return null;
}).filter(Boolean);
}
function normalizeResponsesInput(input) {
if (typeof input === 'string') return [{ role: 'user', content: input }];
if (!Array.isArray(input)) return [];
const messages = [];
for (const item of input) {
if (!item || typeof item !== 'object') continue;
if (item.type === 'message') {
messages.push({ role: item.role || 'user', content: normalizeMessageContent(item.content) });
} else if (item.role) {
messages.push({ role: item.role, content: normalizeMessageContent(item.content) });
} else if (item.type === 'function_call_output') {
messages.push({ role: 'tool', tool_call_id: item.call_id, content: item.output || '' });
} else if (item.type === 'input_text') {
messages.push({ role: 'user', content: item.text || '' });
}
}
return messages;
}
function normalizeApiParams(params, apiMode) {
if (apiMode === 'anthropic') {
const messages = [];
if (params.system) messages.push({ role: 'system', content: normalizeMessageContent(params.system) });
for (const msg of params.messages || []) {
if (msg.role === 'assistant' && Array.isArray(msg.content)) {
const toolUses = msg.content.filter(part => part && part.type === 'tool_use');
const text = normalizeMessageContent(msg.content.filter(part => !part || part.type !== 'tool_use'));
if (text) messages.push({ role: 'assistant', content: text });
for (const tu of toolUses) {
messages.push({ role: 'assistant', content: null, tool_calls: [{ id: tu.id, type: 'function', function: { name: tu.name, arguments: JSON.stringify(tu.input || {}) } }] });
}
} else if (msg.role === 'user' && Array.isArray(msg.content) && msg.content.some(part => part && part.type === 'tool_result')) {
for (const part of msg.content) {
if (part && part.type === 'tool_result') messages.push({ role: 'tool', tool_call_id: part.tool_use_id, content: normalizeMessageContent(part.content) });
else messages.push({ role: 'user', content: normalizeMessageContent(part) });
}
} else {
messages.push({ role: msg.role || 'user', content: normalizeMessageContent(msg.content) });
}
}
return {
...params,
model: params.model || 'deepseek-chat',
messages,
tools: normalizeAnthropicTools(params.tools || []),
stream: params.stream === true,
user: params.metadata?.user_id || params.user,
};
}
if (apiMode === 'responses') {
const messages = normalizeResponsesInput(params.input);
if (params.instructions) messages.unshift({ role: 'system', content: params.instructions });
return {
...params,
model: params.model || 'deepseek-chat',
messages,
tools: normalizeResponsesTools(params.tools || []),
stream: params.stream === true,
user: params.user,
};
}
return params;
}
function safeJsonParseObject(text, fallback = {}) {
try {
const parsed = JSON.parse(text || '{}');
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback;
} catch (e) {
return fallback;
}
}
function toAnthropicResponse(openaiResp) {
const choice = openaiResp.choices[0];
const msg = choice.message || {};
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
const content = [];
if (hasToolCalls) {
for (const tc of msg.tool_calls) {
content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input: safeJsonParseObject(tc.function.arguments) });
}
} else {
content.push({ type: 'text', text: msg.content || '' });
}
const response = {
id: 'msg_' + openaiResp.id,
type: 'message',
role: 'assistant',
model: openaiResp.model,
content,
stop_reason: choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn',
stop_sequence: null,
usage: {
input_tokens: openaiResp.usage?.prompt_tokens || 0,
output_tokens: openaiResp.usage?.completion_tokens || 0,
},
watermark: FORGETMEAI_WATERMARK,
};
if (!hasToolCalls && msg.reasoning_content) response.reasoning_content = msg.reasoning_content;
return response;
}
function writeSse(res, event, data) {
if (event) res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
function sendAnthropicStream(res, openaiResp) {
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
const choice = openaiResp.choices[0];
const msg = choice.message || {};
const message = toAnthropicResponse(openaiResp);
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
writeSse(res, 'message_start', { type: 'message_start', message: { ...message, content: [] } });
// Anthropic-compatible clients expect a tool turn to be made of tool_use
// content blocks. If we emit DeepSeek reasoning as a text block before the
// tool_use block, some agents treat the turn as a normal text answer and do
// not execute the tool. Keep tool streaming clean: tool_use blocks only.
if (hasToolCalls) {
msg.tool_calls.forEach((tc, i) => {
writeSse(res, 'content_block_start', { type: 'content_block_start', index: i, content_block: { type: 'tool_use', id: tc.id, name: tc.function.name, input: {} } });
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: i, delta: { type: 'input_json_delta', partial_json: tc.function.arguments || '{}' } });
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: i });
});
writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: message.usage });
} else {
if (msg.reasoning_content) {
writeSse(res, 'content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: `[reasoning]\n${msg.reasoning_content}\n[/reasoning]\n` } });
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: 0 });
}
const offset = msg.reasoning_content ? 1 : 0;
writeSse(res, 'content_block_start', { type: 'content_block_start', index: offset, content_block: { type: 'text', text: '' } });
const text = msg.content || '';
for (let i = 0; i < text.length; i += 80) {
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: offset, delta: { type: 'text_delta', text: text.substring(i, i + 80) } });
}
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: offset });
writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: message.usage });
}
writeSse(res, 'message_stop', { type: 'message_stop' });
res.end();
}
function toResponsesResponse(openaiResp) {
const choice = openaiResp.choices[0];
const msg = choice.message || {};
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
const output = [];
if (!hasToolCalls && msg.reasoning_content) {
output.push({ id: 'rs_' + Date.now(), type: 'reasoning', summary: [{ type: 'summary_text', text: msg.reasoning_content }] });
}
if (hasToolCalls) {
for (const tc of msg.tool_calls) {
output.push({ type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}' });
}
} else {
output.push({ id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: msg.content || '', annotations: [] }] });
}
return {
id: openaiResp.id.replace(/^ds-/, 'resp_'),
object: 'response',
created_at: openaiResp.created,
status: 'completed',
model: openaiResp.model,
output,
output_text: msg.content || '',
usage: {
input_tokens: openaiResp.usage?.prompt_tokens || 0,
output_tokens: openaiResp.usage?.completion_tokens || 0,
total_tokens: openaiResp.usage?.total_tokens || 0,
output_tokens_details: { reasoning_tokens: openaiResp.usage?.completion_tokens_details?.reasoning_tokens || 0 },
},
watermark: FORGETMEAI_WATERMARK,
};
}
function sendResponsesStream(res, openaiResp) {
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
const response = toResponsesResponse(openaiResp);
const choice = openaiResp.choices[0];
const msg = choice.message || {};
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
writeSse(res, 'response.created', { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } });
writeSse(res, 'response.in_progress', { type: 'response.in_progress', response: { ...response, status: 'in_progress', output: [] } });
let outputIndex = 0;
if (!hasToolCalls && msg.reasoning_content) {
const reasoningItem = { id: 'rs_' + Date.now(), type: 'reasoning', summary: [], status: 'completed' };
writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...reasoningItem, status: 'in_progress' } });
writeSse(res, 'response.reasoning_summary_text.delta', { type: 'response.reasoning_summary_text.delta', output_index: outputIndex, summary_index: 0, delta: msg.reasoning_content });
writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item: { ...reasoningItem, summary: [{ type: 'summary_text', text: msg.reasoning_content }] } });
outputIndex++;
}
if (hasToolCalls) {
msg.tool_calls.forEach((tc) => {
const item = { type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}', status: 'completed' };
writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, arguments: '', status: 'in_progress' } });
writeSse(res, 'response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', output_index: outputIndex, item_id: item.id, delta: item.arguments });
writeSse(res, 'response.function_call_arguments.done', { type: 'response.function_call_arguments.done', output_index: outputIndex, item_id: item.id, arguments: item.arguments });
writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item });
outputIndex++;
});
} else {
const text = msg.content || '';
const item = { id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text, annotations: [] }] };
writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, status: 'in_progress', content: [] } });
writeSse(res, 'response.content_part.added', { type: 'response.content_part.added', output_index: outputIndex, content_index: 0, item_id: item.id, part: { type: 'output_text', text: '', annotations: [] } });
for (let i = 0; i < text.length; i += 80) {
writeSse(res, 'response.output_text.delta', { type: 'response.output_text.delta', output_index: outputIndex, content_index: 0, item_id: item.id, delta: text.substring(i, i + 80) });
}
writeSse(res, 'response.output_text.done', { type: 'response.output_text.done', output_index: outputIndex, content_index: 0, item_id: item.id, text });
writeSse(res, 'response.content_part.done', { type: 'response.content_part.done', output_index: outputIndex, content_index: 0, item_id: item.id, part: item.content[0] });
writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item });
}
writeSse(res, 'response.completed', { type: 'response.completed', response });
res.write('data: [DONE]\n\n');
res.end();
}
function sendOpenAIStream(res, openaiResp) {
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
const choice = openaiResp.choices[0];
const msg = choice.message || {};
const id = openaiResp.id;
const created = openaiResp.created;
const model = openaiResp.model;
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
if (!hasToolCalls && msg.reasoning_content) {
for (let i = 0; i < msg.reasoning_content.length; i += 50) {
const chunk = msg.reasoning_content.substring(i, i + 50);
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { reasoning_content: chunk }, finish_reason: null }] })}\n\n`);
}
}
if (hasToolCalls) {
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { role: 'assistant', content: null, tool_calls: msg.tool_calls }, finish_reason: null }] })}\n\n`);
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] })}\n\ndata: [DONE]\n\n`);
} else {
for (let i = 0; i < (msg.content || '').length; i += 50) {
const chunk = msg.content.substring(i, i + 50);
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }] })}\n\n`);
}
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`);
}
res.end();
}
function storeHistory(agentId, prompt, content, toolCall) {
const session = getOrCreateAgentSession(agentId);
const assistantResponse = toolCall
? `TOOL_CALL: ${toolCall.name}\narguments: ${toolCall.arguments}`
: content;
// Save last 500 chars of the prompt for history context
const shortPrompt = prompt.length > 500 ? '...' + prompt.substring(prompt.length - 500) : prompt;
session.history.push({ user: shortPrompt, assistant: assistantResponse });
while (session.history.length > MAX_HISTORY_LENGTH) session.history.shift();
let historyChars = session.history.reduce((sum, e) => sum + e.user.length + e.assistant.length, 0);
while (historyChars > MAX_HISTORY_CHARS && session.history.length > 1) {
const removed = session.history.shift();
historyChars -= removed.user.length + removed.assistant.length;
}
}
// Extract MEDIA: paths from tool results that contain screenshot paths
function extractScreenshotPaths(messages) {
const paths = [];
const fs = require('fs');
for (const msg of messages) {
if (msg.role === 'tool' && msg.content) {
// Look for screenshot_path or path fields in JSON tool results
// These come DIRECTLY from browser_vision — always the real path
const pngMatch = msg.content.match(/["'](screenshot_path|path)["']\s*:\s*["']([^"']+\.(?:png|jpg|jpeg|webp|gif))["']/i);
if (pngMatch) {
const filePath = pngMatch[2];
if (filePath.startsWith('/') && fs.existsSync(filePath)) {
paths.push(`MEDIA:${filePath}`);
}
}
// Also catch plain MEDIA: tags
const mediaMatch = msg.content.match(/MEDIA:(\S+)/g);
if (mediaMatch) {
for (const tag of mediaMatch) {
const extractedPath = tag.replace(/^MEDIA:/, '');
if (fs.existsSync(extractedPath) && !paths.includes(tag)) {
paths.push(tag);
}
}
}
}
// Check user/assistant messages for paths mentioned in conversation text
// Only include if the file ACTUALLY EXISTS (DeepSeek hallucinates paths)
if ((msg.role === 'user' || msg.role === 'assistant') && msg.content) {
const content = typeof msg.content === 'string' ? msg.content : '';
const pathRegex = /(\/[^\s<>"']+\.(?:png|jpg|jpeg|webp|gif))/gi;
let match;
while ((match = pathRegex.exec(content)) !== null) {
const filePath = match[1];
if (filePath.startsWith('/') && fs.existsSync(filePath) && !paths.includes(`MEDIA:${filePath}`)) {
paths.push(`MEDIA:${filePath}`);
}
}
}
}
return paths;
}
function formatMessages(messages, tools) {
let systemPrompt = '';
for (const msg of messages) {
if (msg.role === 'system' && msg.content) {
systemPrompt += msg.content + '\n';
}
}
systemPrompt += formatToolDefinitions(tools);
// Build full conversation history for DeepSeek's context
let conversation = '';
for (const msg of messages) {
if (msg.role === 'system') continue; // already in systemPrompt
if (msg.role === 'user' && msg.content) {
conversation += `User: ${msg.content}\n\n`;
} else if (msg.role === 'assistant') {
if (msg.tool_calls && msg.tool_calls.length > 0) {
// This was a tool call response from a previous turn
for (const tc of msg.tool_calls) {
conversation += `Assistant: TOOL_CALL: ${tc.function.name}\narguments: ${tc.function.arguments}\n\n`;
}
} else if (msg.content) {
conversation += `Assistant: ${msg.content}\n\n`;
}
} else if (msg.role === 'tool' && msg.content) {
// Tool execution result — send back to DeepSeek as context
const truncated = msg.content.length > 8000
? msg.content.substring(0, 8000) + '\n...[truncated]'
: msg.content;
conversation += `[Tool Result]\n${truncated}\n\n`;
}
}
// The last user message + full conversation context
return { prompt: conversation.trim(), systemPrompt: systemPrompt.trim() };
}
// === HTTP Server ===
const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
// Health check
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', service: 'FreeDeepseekAPI', watermark: FORGETMEAI_WATERMARK, models: SUPPORTED_MODEL_IDS, unsupported_models: Object.keys(MODEL_CONFIGS).filter(id => !MODEL_CONFIGS[id].supported), agents: sessions.size, config_ready: hasAuthConfig() }));
return;
}
// Models: OpenAI-compatible list exposes only aliases verified to work through this proxy.
if (req.method === 'GET' && url.pathname === '/v1/models') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ object: 'list', data: SUPPORTED_MODEL_IDS.map(id => ({ id, object: 'model', created: 1700000000, owned_by: 'deepseek-web', real_model: MODEL_CONFIGS[id].real_model, capabilities: MODEL_CONFIGS[id].capabilities })) }));
return;
}
// Full mapping, including Web models observed but not currently usable through the direct API.
if (req.method === 'GET' && (url.pathname === '/v1/model-capabilities' || url.pathname === '/api/model-capabilities')) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ object: 'model_capabilities', watermark: FORGETMEAI_WATERMARK, data: ALL_MODEL_CAPABILITIES }));
return;
}
// Sessions status
if (req.method === 'GET' && url.pathname === '/v1/sessions') {
const agentList = [];
for (const [agentId, session] of sessions) {
agentList.push({
agent: agentId,
session_id: session.id,
message_count: session.messageCount,
history_size: session.history.length,
age_min: session.createdAt ? Math.round((Date.now() - session.createdAt) / 60000) : 0,
});
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ agents: agentList, total: agentList.length }));
return;
}
// Reset session for a specific agent (or all if no agent specified)
if (req.method === 'POST' && url.pathname === '/reset-session') {
const agentId = url.searchParams.get('agent') || 'default';
if (agentId === 'all') {