Repository navigation
Expand file tree
/
Copy pathdeepseek.ts
More file actions
501 lines (431 loc) · 15.9 KB
/
Copy pathdeepseek.ts
File metadata and controls
501 lines (431 loc) · 15.9 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
/**
* DeepSeek Adapter
* Implements DeepSeek web API protocol
*
* NOTE: Tool prompt injection is handled by Forwarder.transformRequestForPromptToolUse()
* This adapter only handles message format conversion and API communication
*/
import axios, { AxiosResponse } from 'axios'
import { getDeepSeekHash } from '../../lib/challenge'
import { Account, Provider } from '../store/types'
import { storeManager } from '../store/store'
const DEEPSEEK_API_BASE = 'https://chat.deepseek.com/api'
const FAKE_HEADERS = {
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
Origin: 'https://chat.deepseek.com',
Referer: 'https://chat.deepseek.com/',
'Sec-Ch-Ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"macOS"',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
'X-App-Version': '20241129.1',
'X-Client-Locale': 'zh-CN',
'X-Client-Platform': 'web',
'x-Client-Timezone-Offset': '28800',
'X-Client-Version': '1.8.0',
}
interface TokenInfo {
accessToken: string
refreshToken: string
expiresAt: number
}
interface ChallengeResponse {
algorithm: string
challenge: string
salt: string
difficulty: number
expire_at: number
signature: string
}
interface DeepSeekMessage {
role: 'user' | 'assistant' | 'system' | 'tool'
content: string | null
tool_call_id?: string
tool_calls?: any[]
}
interface ChatCompletionRequest {
model: string
messages: DeepSeekMessage[]
stream?: boolean
temperature?: number
web_search?: boolean
reasoning_effort?: 'low' | 'medium' | 'high'
tools?: any[]
tool_choice?: any
providerSessionId?: string
parentMessageId?: string
}
const tokenCache = new Map<string, TokenInfo>()
const sessionCache = new Map<string, { sessionId: string; createdAt: number }>()
function generateRandomString(length: number, charset: string = 'alphanumeric'): string {
const sets = {
numeric: '0123456789',
alphabetic: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
alphanumeric: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
hex: '0123456789abcdef',
}
const chars = sets[charset as keyof typeof sets] || sets.alphanumeric
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
function uuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0
const v = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
function generateCookie(): string {
const timestamp = Date.now()
return `intercom-HWWAFSESTIME=${timestamp}; HWWAFSESID=${generateRandomString(18, 'hex')}; Hm_lvt_${uuid(false)}=${Math.floor(timestamp / 1000)},${Math.floor(timestamp / 1000)},${Math.floor(timestamp / 1000)}; Hm_lpvt_${uuid(false)}=${Math.floor(timestamp / 1000)}; _frid=${uuid(false)}; _fr_ssid=${uuid(false)}; _fr_pvid=${uuid(false)}`
}
function unixTimestamp(): number {
return Math.floor(Date.now() / 1000)
}
export class DeepSeekAdapter {
private provider: Provider
private account: Account
private token: string
constructor(provider: Provider, account: Account) {
this.provider = provider
this.account = account
console.log('[DeepSeek] Account credentials:', JSON.stringify(account.credentials, null, 2))
this.token = account.credentials.token || account.credentials.apiKey || account.credentials.refreshToken || ''
console.log('[DeepSeek] Using token:', this.token.substring(0, 20) + '...')
}
private async acquireToken(): Promise<string> {
if (!this.token) {
throw new Error('DeepSeek Token not configured, please add Token in account settings')
}
const cached = tokenCache.get(this.token)
if (cached && cached.expiresAt > unixTimestamp()) {
return cached.accessToken
}
console.log('[DeepSeek] Acquiring token...')
const result = await axios.get(`${DEEPSEEK_API_BASE}/v0/users/current`, {
headers: {
Authorization: `Bearer ${this.token}`,
...FAKE_HEADERS,
},
timeout: 15000,
validateStatus: () => true,
})
console.log('[DeepSeek] Token response status:', result.status)
if (result.status === 401 || result.status === 403) {
throw new Error(`Token invalid or expired, please get a new Token`)
}
if (result.status !== 200) {
throw new Error(`Failed to acquire token: HTTP ${result.status}`)
}
// Response structure: { code: 0, data: { biz_code: 0, biz_data: { token: "..." } } }
const bizData = result.data?.data?.biz_data || result.data?.biz_data
if (!bizData?.token) {
const errorMsg = result.data?.msg || result.data?.data?.biz_msg || 'Unknown error'
console.log('[DeepSeek] Token response data:', JSON.stringify(result.data, null, 2))
throw new Error(`Failed to acquire token: ${errorMsg}`)
}
const accessToken = bizData.token
tokenCache.set(this.token, {
accessToken,
refreshToken: this.token,
expiresAt: unixTimestamp() + 3600,
})
console.log('[DeepSeek] Token acquired successfully')
return accessToken
}
private async createSession(): Promise<string> {
const cacheKey = this.account.id
const cached = sessionCache.get(cacheKey)
if (cached && Date.now() - cached.createdAt < 300000) {
return cached.sessionId
}
const token = await this.acquireToken()
const result = await axios.post(
`${DEEPSEEK_API_BASE}/v0/chat_session/create`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
...FAKE_HEADERS,
Cookie: generateCookie(),
},
timeout: 15000,
validateStatus: () => true,
}
)
console.log('[DeepSeek] Create session response:', JSON.stringify(result.data, null, 2))
// Response structure: { code: 0, data: { biz_code: 0, biz_data: { id: "..." } } }
const bizData = result.data?.data?.biz_data || result.data?.biz_data
if (result.status !== 200 || !bizData?.chat_session?.id) {
throw new Error(`Failed to create session: ${result.data?.msg || result.data?.data?.biz_msg || result.status}`)
}
const sessionId = bizData?.chat_session?.id
sessionCache.set(cacheKey, { sessionId, createdAt: Date.now() })
return sessionId
}
async deleteSession(sessionId: string): Promise<boolean> {
try {
const token = await this.acquireToken()
const result = await axios.post(
`${DEEPSEEK_API_BASE}/v0/chat_session/delete`,
{ chat_session_id: sessionId },
{
headers: {
Authorization: `Bearer ${token}`,
...FAKE_HEADERS,
},
timeout: 15000,
validateStatus: () => true,
}
)
console.log('[DeepSeek] Delete session response:', JSON.stringify(result.data, null, 2))
const success = result.status === 200 && result.data?.code === 0
if (success) {
// Clear cache
const cacheKey = this.account.id
sessionCache.delete(cacheKey)
console.log('[DeepSeek] Session deleted:', sessionId)
}
return success
} catch (error) {
console.error('[DeepSeek] Failed to delete session:', error)
return false
}
}
private async getChallenge(targetPath: string): Promise<ChallengeResponse> {
const token = await this.acquireToken()
const result = await axios.post(
`${DEEPSEEK_API_BASE}/v0/chat/create_pow_challenge`,
{ target_path: targetPath },
{
headers: {
Authorization: `Bearer ${token}`,
...FAKE_HEADERS,
},
timeout: 15000,
validateStatus: () => true,
}
)
// Response structure: { code: 0, data: { biz_code: 0, biz_data: { challenge: {...} } } }
const bizData = result.data?.data?.biz_data || result.data?.biz_data
if (result.status !== 200 || !bizData?.challenge) {
throw new Error(`Failed to get challenge: ${result.data?.msg || result.data?.data?.biz_msg || result.status}`)
}
return bizData.challenge
}
private async calculateChallengeAnswer(challenge: ChallengeResponse): Promise<string> {
const { algorithm, challenge: challengeStr, salt, difficulty, expire_at, signature } = challenge
if (algorithm !== 'DeepSeekHashV1') {
throw new Error(`Unsupported algorithm: ${algorithm}`)
}
console.log('[DeepSeek] Challenge parameters:', { difficulty })
const deepSeekHash = await getDeepSeekHash()
const answer = deepSeekHash.calculateHash(algorithm, challengeStr, salt, difficulty, expire_at)
if (answer === undefined) {
throw new Error('Challenge calculation failed')
}
console.log('[DeepSeek] Challenge answer found:', answer)
return Buffer.from(JSON.stringify({
algorithm,
challenge: challengeStr,
salt,
answer,
signature,
target_path: '/api/v0/chat/completion',
})).toString('base64')
}
private messagesToPrompt(messages: DeepSeekMessage[], isMultiTurn: boolean = false): string {
const processedMessages = messages.map(message => {
let text: string
// Handle tool calls in assistant message
if (message.role === 'assistant' && message.tool_calls && message.tool_calls.length > 0) {
const toolCallsText = message.tool_calls.map(tc => {
return `<tool_calling>
<name>${tc.function.name}</name>
<arguments>${tc.function.arguments}</arguments>
</tool_calling>`
}).join('\n')
text = toolCallsText
}
// Handle tool response message
else if (message.role === 'tool' && message.tool_call_id) {
text = `<tool_response tool_call_id="${message.tool_call_id}">
${message.content || ''}
</tool_response>`
}
else if (Array.isArray(message.content)) {
const texts = message.content
.filter((item: any) => item.type === 'text')
.map((item: any) => item.text)
text = texts.join('\n')
} else {
text = String(message.content || '')
}
return { role: message.role, text }
})
if (processedMessages.length === 0) return ''
// For multi-turn mode, only send the last user message
if (isMultiTurn) {
let lastUserIdx = -1
for (let i = processedMessages.length - 1; i >= 0; i--) {
if (processedMessages[i].role === 'user') {
lastUserIdx = i
break
}
}
if (lastUserIdx !== -1) {
const lastUserMsg = processedMessages[lastUserIdx]
let text = lastUserMsg.text
for (let i = lastUserIdx + 1; i < processedMessages.length; i++) {
if (processedMessages[i].role === 'tool') {
text += `\n\n${processedMessages[i].text}`
}
}
return `<|User|>${text}`
}
}
const mergedBlocks: { role: string; text: string }[] = []
let currentBlock = { ...processedMessages[0] }
for (let i = 1; i < processedMessages.length; i++) {
const msg = processedMessages[i]
if (msg.role === currentBlock.role) {
currentBlock.text += `\n\n${msg.text}`
} else {
mergedBlocks.push(currentBlock)
currentBlock = { ...msg }
}
}
mergedBlocks.push(currentBlock)
return mergedBlocks
.map((block, index) => {
if (block.role === 'assistant') {
return `<|Assistant|>${block.text}<|end of sentence|>`
}
if (block.role === 'user' || block.role === 'system') {
return index > 0 ? `<|User|>${block.text}` : block.text
}
if (block.role === 'tool') {
return `<|User|>${block.text}`
}
return block.text
})
.join('')
.replace(/!\[.+\]\(.+\)/g, '')
}
async chatCompletion(request: ChatCompletionRequest): Promise<{ response: AxiosResponse; sessionId: string }> {
const token = await this.acquireToken()
// Reuse existing session or create a new one
const sessionId = request.providerSessionId || await this.createSession()
console.log('[DeepSeek] Using session:', sessionId, request.providerSessionId ? '(reused)' : '(new)')
const parentMessageId = request.parentMessageId || null
const challenge = await this.getChallenge('/api/v0/chat/completion')
const challengeAnswer = await this.calculateChallengeAnswer(challenge)
// Clone messages to avoid modifying original request
// Note: Tool prompt injection is already handled by Forwarder.transformRequestForPromptToolUse()
const messages = [...request.messages]
let prompt = this.messagesToPrompt(messages, !!request.providerSessionId)
// Use request parameters for mode control (OpenAI compatible)
let searchEnabled = false
let thinkingEnabled = false
let modelType = 'default'
if (request.web_search) {
searchEnabled = true
console.log('[DeepSeek] Web search enabled')
}
if (request.reasoning_effort) {
thinkingEnabled = true
console.log('[DeepSeek] Reasoning mode enabled, effort:', request.reasoning_effort)
}
// Fallback: check model name for backward compatibility
const modelLower = request.model.toLowerCase()
if (modelLower.includes('expert')) {
modelType = 'expert'
}
if (!searchEnabled && modelLower.includes('search')) {
searchEnabled = true
console.log('[DeepSeek] Web search enabled (from model name)')
}
if (!thinkingEnabled && (modelLower.includes('r1') || modelLower.includes('think'))) {
thinkingEnabled = true
console.log('[DeepSeek] Reasoning mode enabled (from model name)')
}
// Also check prompt for deep thinking keyword
if (!thinkingEnabled && prompt.includes('deep thinking')) {
thinkingEnabled = true
console.log('[DeepSeek] Reasoning mode enabled (from prompt)')
}
const response = await axios.post(
`${DEEPSEEK_API_BASE}/v0/chat/completion`,
{
chat_session_id: sessionId,
parent_message_id: parentMessageId,
prompt,
ref_file_ids: [],
search_enabled: searchEnabled,
thinking_enabled: thinkingEnabled,
model_type: modelType,
},
{
headers: {
Authorization: `Bearer ${token}`,
...FAKE_HEADERS,
Cookie: generateCookie(),
'X-Ds-Pow-Response': challengeAnswer,
},
timeout: 120000,
validateStatus: () => true,
responseType: 'stream',
}
)
return { response, sessionId }
}
async deleteAllChats(): Promise<boolean> {
try {
const token = await this.acquireToken()
const result = await axios.post(
`${DEEPSEEK_API_BASE}/v0/chat_session/delete_all`,
{},
{
headers: {
Authorization: `Bearer ${token}`,
...FAKE_HEADERS,
},
timeout: 30000,
validateStatus: () => true,
}
)
console.log('[DeepSeek] Delete all chats response:', JSON.stringify(result.data, null, 2))
const success = result.status === 200 && result.data?.code === 0
if (success) {
sessionCache.clear()
console.log('[DeepSeek] All chats deleted')
}
return success
} catch (error) {
console.error('[DeepSeek] Failed to delete all chats:', error)
return false
}
}
static isDeepSeekProvider(provider: Provider): boolean {
return provider.id === 'deepseek' || provider.apiEndpoint.includes('deepseek.com')
}
/**
* Clear session cache for a specific account
* This should be called when a session is deleted externally (e.g., from web)
*/
static clearSessionCache(accountId: string): void {
sessionCache.delete(accountId)
console.log('[DeepSeek] Cleared session cache for account:', accountId)
}
}
export const deepSeekAdapter = {
DeepSeekAdapter,
}