forked from ForgetMeAI/FreeDeepseekAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·2075 lines (1940 loc) · 105 KB
/
Copy pathserver.js
File metadata and controls
executable file
·2075 lines (1940 loc) · 105 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');
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;
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;
if (sticky && sticky.cooldownUntil > now) {
// A DeepSeek chat_session belongs to the auth account that created it.
// If that account is rate-limited/expired, do not keep hammering it;
// reset the web session and let a healthy account take over.
session.id = null;
session.parentMessageId = null;
session.createdAt = null;
session.messageCount = 0;
}
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));
throw new Error(`All DeepSeek auth accounts are cooling down. Retry in ~${waitSec}s or import a fresh account with npm run auth:import.`);
}
throw new Error('No valid DeepSeek auth accounts. Run npm run auth or npm run auth:import.');
}
const account = ready[accountRoundRobin % ready.length];
accountRoundRobin++;
session.accountId = account.id;
return account;
}
function markAccountFailure(account, status, reason = '') {
if (!account) return;
account.failures++;
if ([401, 403, 429].includes(Number(status))) {
account.cooldownUntil = Date.now() + DEFAULT_ACCOUNT_COOLDOWN_MS;
console.log(`[account:${account.id}] cooldown for ${Math.round(DEFAULT_ACCOUNT_COOLDOWN_MS / 1000)}s after HTTP ${status}${reason ? ` (${reason})` : ''}`);
}
}
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 };
}
loadDeepSeekConfig({ fatal: false });
function createSession() {
return {
id: null,
parentMessageId: null,
createdAt: null,
messageCount: 0,
accountId: null,
history: [],
};
}
function getOrCreateAgentSession(agentId) {
if (!sessions.has(agentId)) {
sessions.set(agentId, createSession());
}
return sessions.get(agentId);
}
async function solvePOW(challenge, config = DS_CONFIG) {
const resp = await fetch(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 account = selectAccountForSession(session);
const dsHeaders = account.headers;
account.lastUsedAt = Date.now();
const agentTag = `[${agentId}/acct:${account.id}]`;
// 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: 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);
if (!session.id) {
const sr = await fetch('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 fetch('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: 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) {
markAccountFailure(account, resp.status, 'completion');
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: 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 fetch('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: 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 per response. Prefer strict JSON:\n';
text += '{"tool_call":{"name":"<function_name>","arguments":{...}}}\n\n';
text += 'Other accepted formats:\n';
text += '[调用 <function_name>] {"arg1":"value1"}\n';
text +=('[Call <function_name>] {"arg1":"value1"}\n');
text += 'TOOL_CALL: <function_name>\narguments: <JSON arguments>\n\n';
text += 'CRITICAL 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. Do NOT write [Tool Result] blocks — the gateway provides real results\n';
text += '4. Request ONLY ONE tool per response — the gateway will execute it and return the result\n';
text += '5. The tool runs on ' + SERVER_HOST + ' (' + SERVER_PUBLIC_IP + '), the local server — NOT on DeepSeek\n';
text += '6. After the tool executes, the result will be sent to you as a new user/tool message\n';
text += '7. Never add explanation before or after the tool request when requesting a tool\n';
text += '8. 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 ONE tool per response using strict JSON, [调用], [Call], or TOOL_CALL format. Never simulate results. Never write [Tool Result] blocks.';
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;
// Handle {"tool": "Bash", "arguments": {...}} where "tool" is a string
// DeepSeek sometimes uses this format in fenced JSON blocks
if (typeof obj.tool === 'string' && obj.arguments && typeof obj.arguments === 'object') {
const name = obj.tool;
let args = obj.arguments;
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) };
}
const candidate = obj.tool_call || (typeof obj.tool === 'object' ? obj.tool : null) || 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;
}
/**
* Parse DeepSeek XML-style tool calls with <parameter> tags.
* DeepSeek sometimes emits tool calls in this format instead of JSON:
* <tool_call name="Bash">\n{"command":"ls"}\n</tool_call)> (most common)
* <tool_calls>\n<invoke name="Bash">\n<parameter name="command" string="true">ls</parameter>\n</invoke>\n</tool_calls>
* <tool_call}>\n<name>function_name</name>\n<parameter name="param1">value1</parameter>\n</tool_call)>
*
* Also handles variants:
* <function_call}><function>name</function><parameter>...</parameter></function_call)>
* <tool_call}><name>...</name><arguments><arg1>...</arg1></arguments></tool_call)>
*/
function parseXmlToolCall(text) {
if (!text || typeof text !== 'string') return null;
// DeepSeek emits tool calls in XML-ish format. Observed variants:
// <tool_call name="Bash">\n{"command":"ls"}\n</tool_call)> (most common)
// <tool_calls>\n<invoke name="Bash">\n<parameter name="command" string="true">ls</parameter>\n</invoke>\n</tool_calls>
// <tool_call}>\n<name>func</name>\n<parameter name="x">1</parameter>\n</tool_call)>
// <tool_call} (no >, just newline)
// <function_call}><function>name</function>...</function_call)>
// <bash>\n description="List project files"\n command="ls -la"\n</bash> (tag name = tool name)
// The opening tag can have name as attribute OR as child <name>/<invoke> element.
// Arguments can be JSON directly inside, or <parameter>/<arguments> children, or key="value" attribute lines.
// Note: <tool_calls> (plural) wraps <invoke> elements — we extract the FIRST one.
// Step 0: Handle <tagname>key="value"...</tagname> format
// DeepSeek sometimes emits: <bash>\n description="..."\n command="..."\n</bash>
// where the tag name IS the tool name and content has attribute-style key="value" pairs.
// Values can contain embedded quotes — greedy (.*) handles this by matching to the last " on each line.
{
const structuralTags = new Set([
'tool_call', 'function_call', 'tool_calls', 'invoke', 'parameter',
'arguments', 'name', 'function', 'reasoning', 'think', 'scratchpad',
'think_tag', 'reflection', 'plan', 'step', 'output', 'result', 'response',
'code', 'pre', 'div', 'span', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'ul', 'ol', 'li',
'table', 'tr', 'td', 'th', 'a', 'img', 'em', 'strong', 'b', 'i', 'u', 's',
'details', 'summary', 'blockquote', 'sup', 'sub', 'abbr',
]);
const attrTagRe = /<([a-zA-Z_][a-zA-Z0-9_-]*)>([\s\S]*?)<\/\1>/g;
let attrTagMatch;
while ((attrTagMatch = attrTagRe.exec(text)) !== null) {
const tag = attrTagMatch[1];
if (structuralTags.has(tag.toLowerCase())) continue;
// Skip tags that look like HTML/XML structural elements with lowercase names > 10 chars
if (tag.length > 30) continue;
const innerContent = attrTagMatch[2].trim();
if (!innerContent) continue;
// Check if content looks like key="value" attribute pairs (each on its own line or inline)
const args = {};
let attrCount = 0;
const attrLineRe = /^\s*(\w+)\s*=\s*"(.*)"\s*$/gm;
let attrLineMatch;
while ((attrLineMatch = attrLineRe.exec(innerContent)) !== null) {
const key = attrLineMatch[1];
let val = attrLineMatch[2];
// Try to parse as JSON (for numbers, booleans, arrays, objects), fallback to string
try { const parsed = JSON.parse(val); if (typeof parsed !== 'object' || parsed === null) val = parsed; } catch (e) { /* keep as string */ }
args[key] = val;
attrCount++;
}
// Also try key="value" pairs on a single line (e.g. <bash command="ls -la" description="list"/>)
if (attrCount === 0) {
const inlineAttrRe = /(\w+)\s*=\s*"([^"]*)"/g;
let inlineMatch;
while ((inlineMatch = inlineAttrRe.exec(innerContent)) !== null) {
const key = inlineMatch[1];
let val = inlineMatch[2];
try { const parsed = JSON.parse(val); if (typeof parsed !== 'object' || parsed === null) val = parsed; } catch (e) { /* keep as string */ }
args[key] = val;
attrCount++;
}
// Also check the opening tag itself for attributes
if (attrCount === 0) {
const tagFull = text.substring(attrTagMatch.index, attrTagMatch.index + attrTagMatch[0].length);
const openTag = tagFull.substring(0, tagFull.indexOf('>'));
let openAttrMatch;
while ((openAttrMatch = inlineAttrRe.exec(openTag)) !== null) {
const key = openAttrMatch[1];
let val = openAttrMatch[2];
try { const parsed = JSON.parse(val); if (typeof parsed !== 'object' || parsed === null) val = parsed; } catch (e) { /* keep as string */ }
args[key] = val;
attrCount++;
}
}
}
if (attrCount >= 1) {
// Capitalize first letter: bash → Bash, Read → Read
const name = tag.charAt(0).toUpperCase() + tag.slice(1);
console.log(`[parseXmlToolCall] SUCCESS attr-tag: ${name} (${attrCount} params)`);
return { name, arguments: JSON.stringify(args) };
}
}
}
// Step 1: Check for <tool_calls> (plural) wrapper — two sub-formats:
// 1a) <tool_calls><invoke name="Bash"><parameter name="cmd">val</parameter></invoke></tool_calls>
// 1b) <tool_calls><parameter name="command">val</parameter><parameter name="description">val</parameter></tool_calls>
// (no <invoke>, no function name — infer from parameter names)
// Use indexOf-based parsing to handle malformed tags like <tool_calls}> or </tool_calls)>
{
const tcPluralIdx = text.indexOf('<tool_calls');
if (tcPluralIdx !== -1) {
// Find end of opening tag (may be malformed like <tool_calls}>)
let contentStart = -1;
const firstGt = text.indexOf('>', tcPluralIdx + 11);
const firstNewline = text.indexOf('\n', tcPluralIdx + 11);
if (firstGt !== -1 && (firstNewline === -1 || firstGt < firstNewline)) {
contentStart = firstGt + 1;
} else if (firstNewline !== -1) {
contentStart = firstNewline + 1;
}
// Find closing tag (may be malformed)
const closeIdx = text.indexOf('</tool_calls', contentStart > 0 ? contentStart : tcPluralIdx + 12);
if (contentStart > 0 && closeIdx > contentStart) {
const outerInner = text.substring(contentStart, closeIdx);
// Helper: parse <parameter> elements from a string into an args object
function parseParametersFrom(src) {
const args = {};
let searchFrom = 0;
while (true) {
const paramOpen = src.indexOf('<parameter', searchFrom);
if (paramOpen === -1) break;
const paramGt = src.indexOf('>', paramOpen + 10);
const paramClose = src.indexOf('</parameter', paramGt > 0 ? paramGt : paramOpen + 10);
if (paramGt === -1 || paramClose === -1 || paramClose <= paramGt) break;
const paramTag = src.substring(paramOpen, paramGt + 1);
const paramVal = src.substring(paramGt + 1, paramClose).trim();
const pNameIdx = paramTag.indexOf('name=');
if (pNameIdx !== -1) {
const pQuoteStart = paramTag.indexOf('"', pNameIdx) + 1;
const pQuoteEnd = paramTag.indexOf('"', pQuoteStart);
if (pQuoteStart > 0 && pQuoteEnd > pQuoteStart) {
const key = paramTag.substring(pQuoteStart, pQuoteEnd).trim();
let val = paramVal;
try { val = JSON.parse(val); } catch (e) { /* keep as string */ }
args[key] = val;
}
}
searchFrom = paramClose + 11;
}
return args;
}
// Helper: infer tool name from parameter keys
function inferToolName(args) {
const keys = Object.keys(args).map(k => k.toLowerCase());
if (keys.includes('command')) return 'Bash';
if (keys.includes('file_path') && !keys.includes('content') && !keys.includes('write')) return 'Read';
if (keys.includes('file_path') && keys.includes('content')) return 'Write';
if (keys.includes('pattern')) return 'Glob';
if (keys.includes('pattern') && keys.includes('path')) return 'Glob';
if (keys.includes('old_string') || keys.includes('new_string')) return 'Edit';
return null;
}
// 1a: Try <invoke name="...">
const invokeIdx = outerInner.indexOf('<invoke');
if (invokeIdx !== -1) {
const nameAttrIdx = outerInner.indexOf('name=', invokeIdx);
let invokeName = null;
if (nameAttrIdx !== -1 && nameAttrIdx < outerInner.indexOf('>', invokeIdx)) {
const quoteStart = outerInner.indexOf('"', nameAttrIdx) + 1;
const quoteEnd = outerInner.indexOf('"', quoteStart);
if (quoteStart > 0 && quoteEnd > quoteStart) {
invokeName = outerInner.substring(quoteStart, quoteEnd).trim();
}
}
const invokeGtIdx = outerInner.indexOf('>', invokeIdx);
const invokeCloseIdx = outerInner.indexOf('</invoke', invokeGtIdx > 0 ? invokeGtIdx : invokeIdx + 7);
if (invokeName && invokeGtIdx > 0 && invokeCloseIdx > invokeGtIdx) {
const invokeInner = outerInner.substring(invokeGtIdx + 1, invokeCloseIdx);
const args = parseParametersFrom(invokeInner);
console.log(`[parseXmlToolCall] SUCCESS xml-invoke: ${invokeName} (${Object.keys(args).length} params)`);
return { name: invokeName, arguments: JSON.stringify(args) };
}
}
// 1b: No <invoke> — parse <parameter> directly inside <tool_calls>
// Infer tool name from parameter names
const args = parseParametersFrom(outerInner);
if (Object.keys(args).length > 0) {
const inferredName = inferToolName(args);
if (inferredName) {
console.log(`[parseXmlToolCall] SUCCESS xml-plural-infer: ${inferredName} (${Object.keys(args).length} params, inferred from keys)`);
return { name: inferredName, arguments: JSON.stringify(args) };
}
// Has parameters but can't infer name — check for <name> element
const nameMatch = outerInner.match(/<name>([\s\S]*?)<\/name>/i);
if (nameMatch) {
const name = nameMatch[1].trim();
console.log(`[parseXmlToolCall] SUCCESS xml-plural-name: ${name} (${Object.keys(args).length} params)`);
return { name, arguments: JSON.stringify(args) };
}
console.log(`[parseXmlToolCall] <tool_calls> with params but can't infer name: ${Object.keys(args).join(', ')}`);
}
}
}
}
// Step 1c: Bare <parameter> tags without any wrapper
// DeepSeek sometimes emits: <parameter name="file_path">/some/path</parameter>
// with NO <tool_call/tool_calls/invoke> wrapper at all. Infer tool name from parameter keys.
{
const args = {};
let searchFrom = 0;
let paramCount = 0;
while (true) {
const paramOpen = text.indexOf('<parameter', searchFrom);
if (paramOpen === -1) break;
const paramGt = text.indexOf('>', paramOpen + 10);
const paramClose = text.indexOf('</parameter', paramGt > 0 ? paramGt : paramOpen + 10);
if (paramGt === -1 || paramClose === -1 || paramClose <= paramGt) break;
const paramTag = text.substring(paramOpen, paramGt + 1);
const paramVal = text.substring(paramGt + 1, paramClose).trim();
const pNameIdx = paramTag.indexOf('name=');
if (pNameIdx !== -1) {
const pQuoteStart = paramTag.indexOf('"', pNameIdx) + 1;
const pQuoteEnd = paramTag.indexOf('"', pQuoteStart);
if (pQuoteStart > 0 && pQuoteEnd > pQuoteStart) {
const key = paramTag.substring(pQuoteStart, pQuoteEnd).trim();
let val = paramVal;
try { val = JSON.parse(val); } catch (e) { /* keep as string */ }
args[key] = val;
paramCount++;
}
}
searchFrom = paramClose + 11;
}
if (paramCount > 0) {
const keys = Object.keys(args).map(k => k.toLowerCase());
let inferredName = null;
if (keys.includes('command')) inferredName = 'Bash';
else if (keys.includes('file_path') && !keys.includes('content')) inferredName = 'Read';
else if (keys.includes('file_path') && keys.includes('content')) inferredName = 'Write';
else if (keys.includes('pattern')) inferredName = 'Glob';
else if (keys.includes('old_string') || keys.includes('new_string')) inferredName = 'Edit';
if (inferredName) {
console.log(`[parseXmlToolCall] SUCCESS bare-parameter: ${inferredName} (${paramCount} params)`);
return { name: inferredName, arguments: JSON.stringify(args) };
}
}
}
// Step 2: Original <tool_call/function_call> parsing
const tagNames = ['tool_call', 'function_call'];
let tagName = null;
let contentStart = -1;
let openingTag = '';
for (const tn of tagNames) {
const openIdx = text.indexOf('<' + tn);
if (openIdx === -1) continue;
// Skip if it's actually <tool_calls> (plural) — already handled above
if (text[openIdx + tn.length] === 's' || text[openIdx + tn.length] === 'S') continue;
const firstGtIdx = text.indexOf('>', openIdx + tn.length + 1);
const newlineAfterOpen = text.indexOf('\n', openIdx);
if (firstGtIdx !== -1 && (newlineAfterOpen === -1 || firstGtIdx < newlineAfterOpen)) {
tagName = tn;
contentStart = firstGtIdx + 1;
openingTag = text.substring(openIdx, firstGtIdx + 1);
} else {
if (newlineAfterOpen !== -1) {
tagName = tn;
contentStart = newlineAfterOpen + 1;
openingTag = text.substring(openIdx, newlineAfterOpen);
}
}
if (tagName) break;
}
if (!tagName || contentStart === -1) return null;
const closeTag = '</' + tagName;
const closeIdx = text.indexOf(closeTag, contentStart);
if (closeIdx === -1) return null;
const inner = text.substring(contentStart, closeIdx).trim();
// Extract function name — try multiple sources:
let name = null;
// Source 1: name as attribute on opening tag: <tool_call name="Bash">
const nameAttrMatch = openingTag.match(/name\s*=\s*"([^"]*)"/i);
if (nameAttrMatch) {
name = nameAttrMatch[1].trim();
}
// Source 2: <name>...</name> or <function>...</function> child element
if (!name) {
const nameMatch = inner.match(/<(?:name|function)>([\s\S]*?)<\/(?:name|function)>/i);
if (nameMatch) name = nameMatch[1].trim();
}
// Extract arguments — multiple patterns:
const args = {};
let paramCount = 0;
// Pattern 1: JSON object directly inside the tag (most common DeepSeek format)
if (paramCount === 0) {
const jsonIdx = inner.indexOf('{');
if (jsonIdx !== -1) {
const rawJson = extractBalancedJsonAt(inner, jsonIdx);
if (rawJson) {
try {
const parsed = JSON.parse(rawJson);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
Object.assign(args, parsed);
paramCount = Object.keys(args).length;
}
} catch (e) { /* not JSON, try other patterns */ }
}
}
}
// Pattern 2: <parameter name="key">value</parameter> (with or without string="true")
if (paramCount === 0) {
const paramRe = /<parameter\s+name\s*=\s*"([^"]*)"[^>]*>([\s\S]*?)<\/parameter>/gi;
let paramMatch;
while ((paramMatch = paramRe.exec(inner)) !== null) {
const key = paramMatch[1].trim();
let val = paramMatch[2].trim();
try { val = JSON.parse(val); } catch (e) { /* keep as string */ }
args[key] = val;
paramCount++;
}
}
// Pattern 3: <parameter>value</parameter> without name attr (positional)
if (paramCount === 0) {
const posParamRe = /<parameter(?:\s*[^>]*)?>([\s\S]*?)<\/parameter>/gi;
let posIdx = 0;
let paramMatch;
while ((paramMatch = posParamRe.exec(inner)) !== null) {
let val = paramMatch[1].trim();
try { val = JSON.parse(val); } catch (e) { /* keep as string */ }
args[`arg${posIdx}`] = val;
posIdx++;
paramCount++;
}
}
// Pattern 4: <arguments>...</arguments> with nested <key>value</key> or JSON
if (paramCount === 0) {
const argsMatch = inner.match(/<arguments>([\s\S]*?)<\/arguments>/i);
if (argsMatch) {
const argsInner = argsMatch[1];
const jsonInArgs = extractBalancedJsonAt(argsInner, argsInner.indexOf('{'));
if (jsonInArgs) {
try {
const parsed = JSON.parse(jsonInArgs);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
Object.assign(args, parsed);
paramCount = Object.keys(args).length;
}
} catch (e) { /* fallback to XML */ }
}
if (paramCount === 0) {
const kvRe = /<(\w+)>([\s\S]*?)<\/\1>/gi;
let kvMatch;
while ((kvMatch = kvRe.exec(argsInner)) !== null) {
const key = kvMatch[1];
if (key.toLowerCase() === 'name' || key.toLowerCase() === 'function') continue;
let val = kvMatch[2].trim();
try { val = JSON.parse(val); } catch (e) { /* keep as string */ }
args[key] = val;
paramCount++;
}
}
}
}
if (!name) return null;
console.log(`[parseXmlToolCall] SUCCESS xml: ${name} (${Object.keys(args).length} params)`);
return { name, arguments: JSON.stringify(args) };
}
function parseToolCall(text) {
if (!text || (typeof text === 'string' && text.length === 0)) return null;
// NEW: Bracket-style tool calls: [调用 ToolName] {json}, [Call ToolName] {json}, [ToolName] {json}
// DeepSeek sometimes emits tool calls in this format (especially in Chinese):
// [调用 Read] {"file_path": "/some/path"}
// [Call Read] {"file_path": "/some/path"}
// [Read] {"file_path": "/some/path"}
// It may also emit multiple such calls in one response, sometimes with hallucinated [Tool Result] blocks.
// We parse the FIRST valid one as the actual tool call.
{
// Known tool names for direct bracket matching (e.g. [Read], [Bash], [Write])
const knownTools = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', 'MultiEdit',
'TodoRead', 'TodoWrite', 'Task', 'Skill', 'LS', 'WebFetch', 'WebSearch',
'NotebookRead', 'NotebookEdit', 'Complete', 'VLM', 'TTS', 'ASR', 'LLM'];
const knownToolsLower = new Set(knownTools.map(t => t.toLowerCase()));
// Pattern 1: [调用 ToolName] or [Call ToolName] — "调用" (Chinese) or "Call" prefix
const callPrefixRe = /\[(?:调用|Call)\s+([\w-]+)\s*\]\s*(\{[\s\S]*?\})/gi;
let callMatch;
while ((callMatch = callPrefixRe.exec(text)) !== null) {
let name = callMatch[1];
// Capitalize first letter
name = name.charAt(0).toUpperCase() + name.slice(1);
const jsonStr = callMatch[2];
let args;
try { args = JSON.parse(jsonStr); } catch (e) {
// Try extracting balanced JSON
const braceStart = text.indexOf('{', callMatch.index + callMatch[0].indexOf('{'));
const balanced = extractBalancedJsonAt(text, braceStart);
if (balanced) {
try { args = JSON.parse(balanced); } catch (e2) {
console.log(`[parseToolCall] bracket-call JSON parse failed for ${name}: ${e2.message.substring(0, 80)}`);
continue;
}
} else {
console.log(`[parseToolCall] bracket-call JSON parse failed for ${name}: ${e.message.substring(0, 80)}`);
continue;
}
}
if (args && typeof args === 'object' && !Array.isArray(args)) {
console.log(`[parseToolCall] SUCCESS bracket-call: ${name} (args=${JSON.stringify(args).length} chars)`);
return { name, arguments: JSON.stringify(args) };
}
}
// Pattern 2: [ToolName] {json} — direct tool name in brackets (no 调用/Call prefix)