-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathdeepseek-web.ts
More file actions
1167 lines (1057 loc) · 42.4 KB
/
Copy pathdeepseek-web.ts
File metadata and controls
1167 lines (1057 loc) · 42.4 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
import { BaseExecutor, type ExecuteInput } from "./base.ts";
import { solveDeepSeekPowAsync } from "../lib/deepseek-pow.ts";
import { type OpenAIToolCall } from "../translator/webTools.ts";
import {
serializeDeepSeekToolPrompt,
parseDeepSeekToolCalls,
buildToolConversationPrompt,
} from "../translator/deepseekWebTools.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
import {
isThinkingModel,
isSearchModel,
formatStreamContent,
appendSearchCitations,
type DeepSeekSearchResult,
} from "./deepseek-web/stream-format.ts";
import {
createFinishOnceGuard,
createFinishedDrainScheduler,
} from "./deepseek-web-done-terminator.ts";
export const DEEPSEEK_WEB_BASE = "https://chat.deepseek.com";
const DEEPSEEK_API_BASE = `${DEEPSEEK_WEB_BASE}/api`;
const COMPLETION_URL = `${DEEPSEEK_API_BASE}/v0/chat/completion`;
// Fingerprint headers the chat.deepseek.com web client sends on every /api/v0/*
// request. Kept in sync with a real captured completion request (client v2.0.0):
// the 2.0.0 web build DROPPED the legacy `X-App-Version` build stamp and ADDED
// `X-Client-Bundle-Id`. Sending the stale `X-App-Version` (and the old 1.8.0
// version) is itself a bot-detection signal, so match the current client exactly.
// NOTE: the live client also sends `x-hif-leim`, a signed client-attestation
// token generated by obfuscated JS. It is intentionally omitted — reproducing it
// requires porting that JS, and it is not currently enforced by the completion
// endpoint. Revisit if requests start failing a client-attestation check.
const FAKE_HEADERS: Record<string, string> = {
Accept: "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
Origin: DEEPSEEK_WEB_BASE,
Referer: `${DEEPSEEK_WEB_BASE}/`,
"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-Bundle-Id": "com.deepseek.chat",
"X-Client-Locale": "en-US",
"X-Client-Platform": "web",
"X-Client-Version": "2.0.0",
};
// ── Types ────────────────────────────────────────────────────────────────
interface PowChallenge {
algorithm: string;
challenge: string;
salt: string;
signature: string;
difficulty: number;
expire_at: number;
expire_after: number;
target_path: string;
}
interface TokenInfo {
accessToken: string;
expiresAt: number;
}
// ── Token cache (keyed by userToken → short-lived access token) ─────────
const tokenCache = new Map<string, TokenInfo>();
const sessionCache = new Map<string, { sessionId: string; createdAt: number }>();
const CACHE_MAX_SIZE = 100;
function evictOldest(cache: Map<string, unknown>): void {
if (cache.size >= CACHE_MAX_SIZE) {
const first = cache.keys().next().value;
if (first) cache.delete(first);
}
}
// ── Helpers ──────────────────────────────────────────────────────────────
export function extractUserToken(credentials: Record<string, unknown>): string | null {
const raw = credentials?.apiKey || credentials?.accessToken;
if (typeof raw !== "string" || raw.length === 0) return null;
// Handle JSON-wrapped tokens (DeepSeek stores token as {"value":"..."})
try {
const parsed = JSON.parse(raw);
if (typeof parsed?.value === "string") return parsed.value;
} catch {
// not JSON, use raw
}
return raw;
}
function errorResponse(status: number, message: string, dsCode?: number): Response {
return new Response(
JSON.stringify({
error: { message, type: "upstream_error", code: dsCode ?? `HTTP_${status}` },
}),
{ status, headers: { "Content-Type": "application/json" } }
);
}
function resolveModelOptions(
model?: string,
bodyObj?: Record<string, unknown>
): {
modelType: string;
thinkingEnabled: boolean;
searchEnabled: boolean;
} {
const m = (model || "").toLowerCase();
const modelType = m.includes("pro") || m.includes("expert") ? "expert" : "default";
const thinkingEnabled =
m.includes("r1") ||
m.includes("think") ||
m.includes("reason") ||
bodyObj?.thinking_enabled === true ||
bodyObj?.thinking === true ||
!!bodyObj?.reasoning_effort;
const searchEnabled =
m.includes("search") ||
bodyObj?.search_enabled === true ||
bodyObj?.search === true ||
bodyObj?.web_search === true;
return { modelType, thinkingEnabled, searchEnabled };
}
function generateFakeCookie(): string {
const ts = Date.now();
const hex = (n: number) =>
Array.from({ length: n }, () => Math.floor(Math.random() * 16).toString(16)).join("");
const uid = () =>
"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
});
return `intercom-HWWAFSESTIME=${ts}; HWWAFSESID=${hex(18)}; Hm_lvt_${uid()}=${Math.floor(ts / 1000)}; _frid=${uid()}`;
}
// ── PoW Solver (DeepSeekHashV1) ─────────────────────────────────────────
async function solvePow(challenge: PowChallenge, signal?: AbortSignal | null): Promise<string> {
const answer = await solveDeepSeekPowAsync(
challenge.algorithm,
challenge.challenge,
challenge.salt,
challenge.difficulty,
challenge.expire_at,
{ signal }
);
if (answer < 0) throw new Error("PoW solver failed");
return Buffer.from(
JSON.stringify({
algorithm: challenge.algorithm,
challenge: challenge.challenge,
salt: challenge.salt,
answer,
signature: challenge.signature,
target_path: challenge.target_path,
})
).toString("base64");
}
// ── SSE Transform (DeepSeek → OpenAI) ───────────────────────────────────
function transformSSE(deepseekStream: ReadableStream, model: string): ReadableStream {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const streamModel = model || "deepseek-web";
const id = `chatcmpl-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const created = Math.floor(Date.now() / 1000);
let emittedRole = false;
let currentPath: "thinking" | "content" | "" = "";
const thinkingModel = isThinkingModel(streamModel);
const searchResults: DeepSeekSearchResult[] = [];
return new ReadableStream(
{
async start(controller) {
const reader = deepseekStream.getReader();
let buffer = "";
const emit = (obj: object) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(obj)}\n\n`));
};
const chunk = (delta: object, finish?: string) => {
emit({
id,
object: "chat.completion.chunk",
created,
model: streamModel,
choices: [{ index: 0, delta, finish_reason: finish ?? null }],
});
};
const ensureRole = () => {
if (!emittedRole) {
emittedRole = true;
chunk({ role: "assistant", content: "" });
}
};
const { finishOnce: finishStream, hasFinished } = createFinishOnceGuard(() => {
const citations = appendSearchCitations(searchResults, streamModel);
if (citations) {
ensureRole();
chunk({ content: `\n\n${citations}` });
}
ensureRole();
chunk({}, "stop");
// OpenAI-compatible clients (SDK, OpenCode) hang without this terminator.
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
});
// Do not close *immediately* on FINISHED — DeepSeek may still send
// search_results afterward. Drain briefly, then always emit
// stop + [DONE] so clients do not hang if the upstream body stays open.
const { scheduleFinishAfterDrain, clearFinishedDrain, isDrainPending } =
createFinishedDrainScheduler(finishStream);
const sendByPath = (raw: string) => {
const text = formatStreamContent(raw, streamModel);
if (!text) return;
ensureRole();
let path = currentPath;
if (!path && thinkingModel) path = "thinking";
else if (!path && isSearchModel(streamModel)) path = "content";
if (path === "thinking") {
chunk({ reasoning_content: text });
} else {
chunk({ content: text });
}
};
const applyFragmentType = (frag: any) => {
const type = String(frag?.type || "").toUpperCase();
if (type === "THINK") currentPath = "thinking";
else if (type === "ANSWER" || type === "RESPONSE") currentPath = "content";
};
const handleFragment = (frag: any, setPathFromType = false) => {
if (setPathFromType) applyFragmentType(frag);
if (typeof frag?.content !== "string" || frag.content.length === 0) return;
if (!setPathFromType) {
const type = String(frag?.type || "").toUpperCase();
if (type === "THINK") currentPath = "thinking";
else if (type === "ANSWER" || type === "RESPONSE") currentPath = "content";
}
sendByPath(frag.content);
};
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ") && !line.startsWith("data:")) continue;
const payload = line.replace(/^data:\s*/, "").trim();
if (payload === "[DONE]") {
finishStream();
return;
}
let data: Record<string, unknown>;
try {
data = JSON.parse(payload);
} catch {
continue;
}
const p = (data as any)?.p;
const o = (data as any)?.o;
const v = (data as any)?.v;
if (v && typeof v === "object" && v.response) {
if (v.response.thinking_enabled === true) currentPath = "thinking";
else if (v.response.thinking_enabled === false) currentPath = "content";
const fragments = v.response.fragments;
if (Array.isArray(fragments)) {
for (const frag of fragments) handleFragment(frag, false);
}
}
if (p === "response/fragments") {
if (Array.isArray(v)) {
for (const frag of v) handleFragment(frag, true);
} else if (v && typeof v === "object") {
handleFragment(v, true);
}
}
if (p === "response" && Array.isArray(v)) {
for (const entry of v) {
if (entry?.p === "response" && entry?.v?.thinking_enabled === true) {
currentPath = "thinking";
}
}
}
if (p === "response/search_status") continue;
if (p === "response/search_results" && Array.isArray(v)) {
if (o !== "BATCH") {
searchResults.length = 0;
searchResults.push(...v);
} else {
for (const op of v) {
const match = String(op?.p || "").match(/^(\d+)\/cite_index$/);
if (match) {
const index = parseInt(match[1], 10);
if (searchResults[index]) searchResults[index].cite_index = op.v;
}
}
}
continue;
}
if (typeof v === "string") {
sendByPath(v);
} else if (Array.isArray(v) && p === "response") {
for (const entry of v) {
if (Array.isArray(entry?.v)) {
const joined = entry.v.map((item: any) => item?.content || "").join("");
if (joined) sendByPath(joined);
}
}
}
if (p === "response/status" && v === "FINISHED") {
scheduleFinishAfterDrain();
continue;
}
// Any other post-FINISHED payload extends the drain window so we
// still capture late search_results before closing.
if (isDrainPending()) {
scheduleFinishAfterDrain();
}
}
}
} catch (err) {
clearFinishedDrain();
if (!hasFinished()) {
controller.error(err);
}
return;
}
finishStream();
},
cancel() {
// Best-effort: cancel upstream reader if the client aborts mid-stream.
// finishStream is not required here — the controller is already cancelled.
},
},
{ highWaterMark: 16384 }
);
}
async function collectSSEContent(
deepseekStream: ReadableStream,
model: string
): Promise<{ content: string; reasoningContent: string }> {
const decoder = new TextDecoder();
const reader = deepseekStream.getReader();
let buffer = "";
let content = "";
let reasoningContent = "";
let currentPath: "thinking" | "content" | "" = "";
const streamModel = model || "deepseek-web";
const thinkingModel = isThinkingModel(streamModel);
const searchResults: DeepSeekSearchResult[] = [];
const appendByPath = (raw: string) => {
const text = formatStreamContent(raw, streamModel);
if (!text) return;
let path = currentPath;
if (!path && thinkingModel) path = "thinking";
else if (!path && isSearchModel(streamModel)) path = "content";
if (path === "thinking") reasoningContent += text;
else content += text;
};
const applyFragmentType = (frag: any) => {
const type = String(frag?.type || "").toUpperCase();
if (type === "THINK") currentPath = "thinking";
else if (type === "ANSWER" || type === "RESPONSE") currentPath = "content";
};
const handleFragment = (frag: any, setPathFromType = false) => {
if (setPathFromType) applyFragmentType(frag);
if (typeof frag?.content !== "string" || frag.content.length === 0) return;
if (!setPathFromType) {
const type = String(frag?.type || "").toUpperCase();
if (type === "THINK") currentPath = "thinking";
else if (type === "ANSWER" || type === "RESPONSE") currentPath = "content";
}
appendByPath(frag.content);
};
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() || "";
for (const line of lines) {
if (!line.startsWith("data: ") && !line.startsWith("data:")) continue;
const payload = line.replace(/^data:\s*/, "").trim();
try {
const data = JSON.parse(payload);
const p = data?.p;
const v = data?.v;
if (v && typeof v === "object" && v.response) {
if (v.response.thinking_enabled === true) currentPath = "thinking";
else if (v.response.thinking_enabled === false) currentPath = "content";
if (Array.isArray(v.response.fragments)) {
for (const frag of v.response.fragments) handleFragment(frag, false);
}
}
if (p === "response/fragments") {
if (Array.isArray(v)) {
for (const frag of v) handleFragment(frag, true);
} else if (v && typeof v === "object") {
handleFragment(v, true);
}
}
if (p === "response" && Array.isArray(v)) {
for (const entry of v) {
if (entry?.p === "response" && entry?.v?.thinking_enabled === true) {
currentPath = "thinking";
}
}
}
if (p === "response/search_status") continue;
if (p === "response/search_results" && Array.isArray(v)) {
if (data?.o !== "BATCH") {
searchResults.length = 0;
searchResults.push(...v);
} else {
for (const op of v) {
const match = String(op?.p || "").match(/^(\d+)\/cite_index$/);
if (match) {
const index = parseInt(match[1], 10);
if (searchResults[index]) searchResults[index].cite_index = op.v;
}
}
}
continue;
}
if (typeof v === "string") {
appendByPath(v);
} else if (Array.isArray(v) && p === "response") {
for (const entry of v) {
if (Array.isArray(entry?.v)) {
const joined = entry.v.map((item: any) => item?.content || "").join("");
if (joined) appendByPath(joined);
}
}
}
} catch {
// skip
}
}
}
const citations = appendSearchCitations(searchResults, streamModel);
if (citations) content += `\n\n${citations}`;
return { content, reasoningContent };
}
// ── Prompt builder (DeepSeek native format, matches Chat2API) ────────────
function extractMessageText(content: unknown): string {
if (Array.isArray(content)) {
return (content as any[])
.filter((item: any) => item.type === "text")
.map((item: any) => item.text)
.join("\n");
}
return String(content || "");
}
// #10527 — with no explicit `historyWindow`, genuinely multi-turn conversations (any
// assistant turn present, or more than one user turn) now auto-replay a bounded
// trajectory instead of only the last user message, so agentic clients that never send
// OpenAI-native `tools[]` (e.g. Cline, which embeds its own XML tool convention) don't
// silently lose the original task after a couple of tool-result turns. This cap keeps
// the auto-replay bounded for very long agent sessions; set `historyWindow` explicitly
// on the connection to raise or lower it.
const DEFAULT_AUTO_HISTORY_WINDOW = 20;
/**
* Build the single prompt string the DeepSeek web API accepts.
*
* The web endpoint (`/api/v0/chat/completion`) takes only a `prompt` string, not a
* `messages` array. For a genuinely single-turn request (one user message, no prior
* assistant turns) we keep the minimal behavior — system prompt(s) + the last user
* message only — which is fine for plain chat and avoids inflating token usage.
*
* For a multi-turn conversation, `historyWindow > 0` stitches the last N non-system
* messages into a role-tagged transcript so agentic multi-turn clients keep context
* across turns (rolling-window memory, #2942). With `historyWindow` unset/`<= 0` we now
* auto-apply a bounded window (`DEFAULT_AUTO_HISTORY_WINDOW`) instead of dropping every
* earlier turn (#10527) — the previous default silently discarded the original task
* after a couple of turns for clients (Cline) that never send `tools[]`. The system
* prompt(s) still lead the prompt and the newest user turn is the last line of the
* transcript.
*/
export function messagesToPrompt(
messages: Array<{ role: string; content: string; tool_call_id?: string; name?: string }>,
historyWindow = 0
): string {
if (messages.length === 0) return "";
const systemParts: string[] = [];
const conversation: Array<{ role: string; text: string }> = [];
const callNameById = new Map<string, string>();
let lastUserContent = "";
for (const m of messages) {
const text = extractMessageText(m.content).trim();
if (m.role === "system") {
if (text) systemParts.push(text);
} else if (m.role === "user" || m.role === "assistant") {
if (text) conversation.push({ role: m.role, text });
if (m.role === "user") lastUserContent = text;
const toolCalls = (m as { tool_calls?: unknown }).tool_calls;
const calls = Array.isArray(toolCalls)
? (toolCalls as Array<{ id?: string; function?: { name?: string } }>)
: [];
for (const c of calls) {
if (c?.id && typeof c.function?.name === "string") callNameById.set(c.id, c.function.name);
}
} else if (m.role === "tool") {
// Tool results have no native slot in deepseek-web's single-prompt format. Without
// this branch they were silently dropped (#4712) — the model never saw the tool
// output and either re-called the tool endlessly or answered "I don't have that
// information". Fold them into the transcript as plain text, mirroring the agentic
// buildToolConversationPrompt() path.
if (text) {
const name = (m.tool_call_id && callNameById.get(m.tool_call_id)) || m.name || "tool";
conversation.push({ role: "tool", text: `(${name}) ${text}` });
}
}
}
const parts: string[] = [];
if (systemParts.length > 0) {
parts.push(systemParts.join("\n\n"));
}
const effectiveWindow =
historyWindow > 0 ? historyWindow : conversation.length > 1 ? DEFAULT_AUTO_HISTORY_WINDOW : 0;
if (effectiveWindow > 0 && conversation.length > 1) {
// Rolling-window transcript of the most recent turns (#2942, auto-applied per
// #10527 when no explicit historyWindow is configured and the conversation is
// genuinely multi-turn).
const recent = conversation.slice(-effectiveWindow);
const transcript = recent
.map((turn) =>
turn.role === "assistant"
? `Assistant: ${turn.text}`
: turn.role === "tool"
? `Tool result ${turn.text}`
: `User: ${turn.text}`
)
.join("\n\n");
parts.push(transcript);
} else if (lastUserContent) {
parts.push(lastUserContent);
}
return parts.join("\n\n").replace(/!\[.*?\]\(.*?\)/g, "");
}
// ── DeepSeek API calls (Bearer token auth, like Chat2API) ───────────────
async function acquireAccessToken(
userToken: string,
signal?: AbortSignal | null,
log?: ExecuteInput["log"]
): Promise<string> {
const cached = tokenCache.get(userToken);
if (cached && cached.expiresAt > Math.floor(Date.now() / 1000)) {
return cached.accessToken;
}
log?.info?.("DEEPSEEK-WEB", "Acquiring access token from /users/current...");
const resp = await fetch(`${DEEPSEEK_API_BASE}/v0/users/current`, {
headers: {
Authorization: `Bearer ${userToken}`,
...FAKE_HEADERS,
},
signal: signal ?? undefined,
});
if (resp.status === 401 || resp.status === 403) {
throw new Error("Token invalid or expired — get a new userToken from DeepSeek localStorage");
}
if (!resp.ok) {
throw new Error(`users/current HTTP ${resp.status}`);
}
const json = await resp.json();
if (json?.code && json.code !== 0) {
const errMsg = json.msg || json?.data?.biz_msg || `error code ${json.code}`;
tokenCache.delete(userToken);
throw new Error(`DeepSeek rejected token: ${errMsg}`);
}
const bizData = json?.data?.biz_data || json?.biz_data;
if (!bizData?.token) {
const errMsg = json?.msg || json?.data?.biz_msg || "Unknown error";
throw new Error(`Failed to acquire token: ${errMsg}`);
}
const accessToken = bizData.token;
evictOldest(tokenCache);
tokenCache.set(userToken, {
accessToken,
expiresAt: Math.floor(Date.now() / 1000) + 3600,
});
log?.info?.("DEEPSEEK-WEB", `Access token acquired (${accessToken.length} chars)`);
return accessToken;
}
function parseDeepSeekErrorPayload(payload: unknown): { code?: number; message: string } | null {
if (!payload || typeof payload !== "object") return null;
const record = payload as Record<string, unknown>;
const codeRaw = record.code;
const code = typeof codeRaw === "number" ? codeRaw : undefined;
const msg = record.msg;
const data = record.data as Record<string, unknown> | undefined;
const bizMsg = data?.biz_msg;
const messageRaw = typeof msg === "string" ? msg : typeof bizMsg === "string" ? bizMsg : "";
if (code !== undefined && code !== 0) {
return { code, message: messageRaw || `DeepSeek error ${code}` };
}
return null;
}
async function createSession(accessToken: string, signal?: AbortSignal | null): Promise<string> {
const resp = await fetch(`${DEEPSEEK_API_BASE}/v0/chat_session/create`, {
method: "POST",
headers: {
...FAKE_HEADERS,
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
Cookie: generateFakeCookie(),
},
body: JSON.stringify({}),
signal: signal ?? undefined,
});
if (!resp.ok) throw new Error(`chat_session/create HTTP ${resp.status}`);
const json = await resp.json();
const bizData = json?.data?.biz_data || json?.biz_data;
const id = bizData?.chat_session?.id;
if (!id) throw new Error(`No session id: code=${json?.code}`);
return id;
}
async function deleteSessionOnDeepSeek(accessToken: string, sessionId: string): Promise<void> {
try {
await fetch(`${DEEPSEEK_API_BASE}/v0/chat_session/delete`, {
method: "POST",
headers: {
...FAKE_HEADERS,
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ chat_session_id: sessionId }),
});
} catch {
// best-effort cleanup
}
}
function wrapStreamWithCleanup(
responseStream: ReadableStream,
cleanup: () => Promise<void>
): ReadableStream {
const reader = responseStream.getReader();
return new ReadableStream({
async pull(controller) {
const { done, value } = await reader.read();
if (done) {
controller.close();
cleanup().catch(() => {});
return;
}
controller.enqueue(value);
},
cancel() {
reader.cancel();
cleanup().catch(() => {});
},
});
}
async function getPowChallenge(
accessToken: string,
signal?: AbortSignal | null
): Promise<PowChallenge> {
const resp = await fetch(`${DEEPSEEK_API_BASE}/v0/chat/create_pow_challenge`, {
method: "POST",
headers: {
...FAKE_HEADERS,
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({ target_path: "/api/v0/chat/completion" }),
signal: signal ?? undefined,
});
if (!resp.ok) throw new Error(`create_pow_challenge HTTP ${resp.status}`);
const json = await resp.json();
const bizData = json?.data?.biz_data || json?.biz_data;
if (!bizData?.challenge?.challenge) throw new Error(`No PoW challenge: code=${json?.code}`);
return bizData.challenge as PowChallenge;
}
// ── Tool-call response builder (#2820) ──────────────────────────────────
/**
* Build the executor result for a tool-translated reply. Emits OpenAI `tool_calls`
* with `finish_reason: "tool_calls"` when tool calls were parsed, otherwise plain
* content. Supports both streaming (synthetic SSE) and non-streaming clients.
*/
function buildToolAwareResult(opts: {
stream: boolean;
clientModel: string;
content: string;
reasoningContent?: string;
toolCalls: OpenAIToolCall[] | null;
reqHeaders: Record<string, string>;
requestPayload: unknown;
}) {
const { stream, clientModel, content, reasoningContent, toolCalls, reqHeaders, requestPayload } =
opts;
const hasCalls = !!toolCalls && toolCalls.length > 0;
const finishReason = hasCalls ? "tool_calls" : "stop";
const id = `chatcmpl-${Date.now()}`;
const created = Math.floor(Date.now() / 1000);
if (stream) {
const encoder = new TextEncoder();
const emit = (
controller: ReadableStreamDefaultController,
delta: object,
finish: string | null
) => {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
id,
object: "chat.completion.chunk",
created,
model: clientModel,
choices: [{ index: 0, delta, finish_reason: finish }],
})}\n\n`
)
);
};
const sse = new ReadableStream({
start(controller) {
emit(controller, { role: "assistant", content: "" }, null);
// Surrounding natural-language text (and reasoning) is emitted before the tool_calls
// so a model reply that interleaves a plan with a call still reaches the client (#7).
if (reasoningContent) emit(controller, { reasoning_content: reasoningContent }, null);
if (content) emit(controller, { content }, null);
if (hasCalls) {
emit(
controller,
{
tool_calls: toolCalls!.map((tc, i) => ({
index: i,
id: tc.id,
type: "function",
function: { name: tc.function.name, arguments: tc.function.arguments },
})),
},
null
);
}
emit(controller, {}, finishReason);
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
});
return {
response: new Response(sse, {
status: 200,
headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" },
}),
url: COMPLETION_URL,
headers: reqHeaders,
transformedBody: requestPayload,
};
}
const message: Record<string, unknown> = { role: "assistant", content: content || "" };
if (reasoningContent) message.reasoning_content = reasoningContent;
if (hasCalls) {
message.tool_calls = toolCalls;
if (!content) message.content = null;
}
const openaiResponse = {
id,
object: "chat.completion",
created,
model: clientModel,
choices: [{ index: 0, message, finish_reason: finishReason }],
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
};
return {
response: new Response(JSON.stringify(openaiResponse), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
url: COMPLETION_URL,
headers: reqHeaders,
transformedBody: requestPayload,
};
}
// ── Executor ─────────────────────────────────────────────────────────────
export class DeepSeekWebExecutor extends BaseExecutor {
constructor() {
super("deepseek-web", { baseUrl: DEEPSEEK_WEB_BASE });
}
async testConnection(
credentials: Record<string, unknown>,
signal?: AbortSignal
): Promise<boolean> {
try {
const userToken = extractUserToken(credentials);
if (!userToken) return false;
const accessToken = await acquireAccessToken(userToken, signal);
return !!accessToken;
} catch {
return false;
}
}
async execute({ model, body, stream, credentials, signal, log }: ExecuteInput) {
const bodyObj = (body || {}) as Record<string, unknown>;
// chat.deepseek.com's web API only accepts {prompt, ref_file_ids,
// thinking_enabled, search_enabled} - no native tools field. Instead of failing
// tool-using requests, translate them (#2820): serialize the OpenAI tools[] into a
// <tool>...</tool> prompt contract on the way in, and parse the model's text reply
// back into OpenAI tool_calls on the way out.
const requestedTools = bodyObj.tools;
const hasTools = Array.isArray(requestedTools) && requestedTools.length > 0;
const toolSystemPrompt = hasTools ? serializeDeepSeekToolPrompt(requestedTools) : "";
const messages = (Array.isArray(bodyObj.messages) ? bodyObj.messages : []) as Array<{
role: string;
content: string;
}>;
const promptMessages = toolSystemPrompt
? [{ role: "system", content: toolSystemPrompt }, ...messages]
: messages;
const rawCreds = credentials as unknown as Record<string, unknown>;
const userToken = extractUserToken(rawCreds);
if (!userToken) {
return {
response: errorResponse(
400,
"Invalid credentials: paste your userToken from DeepSeek localStorage " +
"(DevTools → Application → Local Storage → chat.deepseek.com → userToken)"
),
url: COMPLETION_URL,
headers: {},
transformedBody: body,
};
}
const { modelType, thinkingEnabled, searchEnabled } = resolveModelOptions(
model as string,
bodyObj
);
// Per-connection memory config (#2942). Defaults preserve the legacy
// fresh-session-per-request, last-user-message-only behavior.
const psd = (rawCreds.providerSpecificData ?? {}) as Record<string, unknown>;
const persistSession = psd.persistSession === true;
const historyWindow =
typeof psd.historyWindow === "number" && psd.historyWindow > 0 ? psd.historyWindow : 0;
try {
let t0 = Date.now();
const accessToken = await acquireAccessToken(userToken, signal, log);
log?.info?.("DEEPSEEK-WEB", `Token acquired in ${Date.now() - t0}ms`);
// Tool (agentic) requests replay the whole trajectory — prior tool calls and their
// results — so the model keeps context across turns instead of restarting each time.
// Plain chat keeps the legacy last-user-message / rolling-window behavior.
const prompt = hasTools
? buildToolConversationPrompt(messages, toolSystemPrompt)
: messagesToPrompt(promptMessages, historyWindow);
const refFileIds = Array.isArray(bodyObj.ref_file_ids) ? bodyObj.ref_file_ids : [];
log?.info?.(
"DEEPSEEK-WEB",
`model_type=${modelType}, thinking=${thinkingEnabled}, search=${searchEnabled}, files=${refFileIds.length}, stream=${stream !== false}, persist=${persistSession}, window=${historyWindow}`
);
// One completion attempt against a given session id (fresh PoW per attempt).
const performCompletion = async (sid: string) => {
const powChallenge = await getPowChallenge(accessToken, signal);
const powAnswer = await solvePow(powChallenge, signal);
const reqHeaders: Record<string, string> = {
...FAKE_HEADERS,
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
"X-Ds-Pow-Response": powAnswer,
"X-Client-Timezone-Offset": String(new Date().getTimezoneOffset() * -60),
Cookie: generateFakeCookie(),
};
const requestPayload = {
chat_session_id: sid,
parent_message_id: null,
model_type: modelType,
prompt,
ref_file_ids: refFileIds,
thinking_enabled: thinkingEnabled,
search_enabled: searchEnabled,
preempt: false,
};
const resp = await fetch(COMPLETION_URL, {
method: "POST",
headers: reqHeaders,
body: JSON.stringify(requestPayload),
signal: signal ?? undefined,
});
return { resp, reqHeaders, requestPayload };
};
// Acquire a session. With persistSession we reuse one upstream session per
// userToken (rolling-window memory); otherwise we create a fresh one per
// request (legacy behavior — dodges stale sessions when the user deletes
// chats in the DeepSeek UI). (#2942)
const acquireSession = async (): Promise<{ sessionId: string; reused: boolean }> => {
if (persistSession) {
const cached = sessionCache.get(userToken);
if (cached) return { sessionId: cached.sessionId, reused: true };
const created = await createSession(accessToken, signal);
evictOldest(sessionCache);
sessionCache.set(userToken, { sessionId: created, createdAt: Date.now() });
return { sessionId: created, reused: false };
}
return { sessionId: await createSession(accessToken, signal), reused: false };
};
t0 = Date.now();
let { sessionId, reused: reusedSession } = await acquireSession();
log?.info?.(
"DEEPSEEK-WEB",
`Session ${reusedSession ? "reused" : "created"} in ${Date.now() - t0}ms`
);
t0 = Date.now();
log?.info?.("DEEPSEEK-WEB", `POST ${COMPLETION_URL}`);
let { resp, reqHeaders, requestPayload } = await performCompletion(sessionId);
log?.info?.(
"DEEPSEEK-WEB",
`Completion response in ${Date.now() - t0}ms, status=${resp.status}`
);
// A reused session that fails is likely stale (user deleted the chat in the
// DeepSeek UI). Drop it, create a fresh session, and retry once. (#2942)
if (!resp.ok && persistSession && reusedSession) {
log?.warn?.("DEEPSEEK-WEB", "Reused session failed — retrying with a fresh session");
sessionCache.delete(userToken);
sessionId = await createSession(accessToken, signal);
evictOldest(sessionCache);
sessionCache.set(userToken, { sessionId, createdAt: Date.now() });
reusedSession = false;
({ resp, reqHeaders, requestPayload } = await performCompletion(sessionId));