File size: 17,732 Bytes
76777b5
 
2d01c57
 
 
ceeca02
2d01c57
76777b5
 
 
2d01c57
76777b5
 
ceeca02
2d01c57
76777b5
 
 
 
9fb8bdf
2d01c57
9fb8bdf
 
 
2d01c57
 
 
 
 
 
 
 
 
 
9fb8bdf
2d01c57
 
76777b5
 
2d01c57
76777b5
 
 
 
 
2d01c57
 
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76777b5
 
 
2d01c57
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
 
 
 
 
 
 
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
 
 
 
 
 
 
 
 
 
 
 
76777b5
 
 
 
 
 
 
 
2d01c57
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
 
 
 
 
76777b5
 
 
 
d099b79
 
 
2d01c57
 
 
 
76777b5
d099b79
2d01c57
76777b5
 
 
d099b79
76777b5
2d01c57
76777b5
 
2d01c57
 
76777b5
2d01c57
76777b5
 
2d01c57
 
 
 
 
 
 
 
 
 
d099b79
 
2d01c57
 
 
 
d099b79
2d01c57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ceeca02
 
 
 
 
 
 
 
 
 
 
 
3d42c7f
ceeca02
 
 
 
 
2d01c57
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
 
 
 
 
 
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
76777b5
 
 
 
 
 
 
 
 
 
2d01c57
 
 
 
 
76777b5
 
 
 
 
 
2d01c57
76777b5
 
 
 
 
 
2d01c57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76777b5
 
 
 
2d01c57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76777b5
 
 
 
2d01c57
 
 
 
 
 
 
 
 
 
 
 
 
 
76777b5
 
 
 
2d01c57
 
76777b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d01c57
 
76777b5
 
 
 
 
 
 
 
 
 
 
96f34e3
76777b5
 
 
 
2d01c57
76777b5
 
 
 
 
 
 
 
2d01c57
 
 
76777b5
 
 
 
 
 
 
 
2d01c57
76777b5
2d01c57
 
 
 
 
76777b5
2d01c57
 
 
 
76777b5
2d01c57
d099b79
 
 
2d01c57
 
 
 
 
 
 
d099b79
2d01c57
 
76777b5
 
2d01c57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76777b5
 
 
 
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
import { getTelegramRuntimeConfig } from './telegramConfig.js'
import type {
  TelegramAnswerCallbackQueryResponse,
  TelegramBotCommand,
  TelegramCallbackEvent,
  TelegramChatAction,
  TelegramEditMessageResponse,
  TelegramGetMeResponse,
  TelegramGetUpdatesResponse,
  TelegramInboundEvent,
  TelegramInlineKeyboardMarkup,
  TelegramRuntimeConfig,
  TelegramSendMessageResponse,
  TelegramSendChatActionResponse,
  TelegramSetMyCommandsResponse,
  TelegramServiceState,
  TelegramUpdate,
} from './telegramTypes.js'

// 日志函数 - 已禁用,不再写入文件
function logTelegramDebug(message: string, level: 'debug' | 'error' | 'info' = 'debug'): void {
  // Telegram 功能已完成,禁用日志输出到 log.md
  // 如需调试,可以临时取消注释下面的代码
  /*
  try {
    const fs = require('node:fs')
    const path = require('node:path')
    const LOG_FILE_PATH = path.join(process.cwd(), 'log.md')
    const timestamp = new Date().toISOString()
    const logEntry = `[${timestamp}] [${level.toUpperCase()}] ${message}\n`
    fs.appendFileSync(LOG_FILE_PATH, logEntry, 'utf-8')
  } catch (error) {
    // 忽略文件写入错误
  }
  */
}

type Listener = () => void
type InboundListener = (event: TelegramInboundEvent) => void
type CallbackListener = (event: TelegramCallbackEvent) => void

const TELEGRAM_API_BASE = 'https://api.telegram.org'
const MAX_TELEGRAM_MESSAGE_LENGTH = 4000
const POLL_TIMEOUT_SECONDS = 25
const RETRY_DELAY_MS = 3000
const MAX_TELEGRAM_MENU_COMMANDS = 100
const TELEGRAM_COMMAND_NAME_RE = /^[a-z0-9_]{1,32}$/

function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms))
}

function normalizeTelegramError(error: unknown): string {
  if (error instanceof Error) return error.message
  return String(error)
}

function chunkTelegramMessage(text: string): string[] {
  const normalized = text.trim()
  if (!normalized) return ['模型本轮没有返回可发送的文本结果。']

  const chunks: string[] = []
  for (let i = 0; i < normalized.length; i += MAX_TELEGRAM_MESSAGE_LENGTH) {
    chunks.push(normalized.slice(i, i + MAX_TELEGRAM_MESSAGE_LENGTH))
  }
  return chunks
}

function hasSameConfig(
  left: TelegramRuntimeConfig | undefined,
  right: TelegramRuntimeConfig,
): boolean {
  if (!left) return false
  return (
    left.botToken === right.botToken &&
    left.allowedUserIds.join(',') === right.allowedUserIds.join(',')
  )
}

function normalizeCommandDescription(description: string): string {
  return description.replace(/\s+/g, ' ').trim().slice(0, 256)
}

async function getTelegramMenuCommands(): Promise<TelegramBotCommand[]> {
  const { getCommands, getCommandName } = await import('../../commands.js')
  const commands = await getCommands(process.cwd())
  const results: TelegramBotCommand[] = []
  const seen = new Set<string>()

  for (const command of commands) {
    const candidates = [getCommandName(command), ...(command.aliases ?? [])]
    const name = candidates.find(candidate => TELEGRAM_COMMAND_NAME_RE.test(candidate))
    if (!name || seen.has(name)) continue

    results.push({
      command: name,
      description: normalizeCommandDescription(command.description),
    })
    seen.add(name)

    if (results.length >= MAX_TELEGRAM_MENU_COMMANDS) {
      break
    }
  }

  return results
}

class TelegramService {
  private listeners = new Set<Listener>()
  private inboundListeners = new Set<InboundListener>()
  private callbackListeners = new Set<CallbackListener>()
  private state: TelegramServiceState = { status: 'stopped' }
  private config?: TelegramRuntimeConfig
  private abortController: AbortController | null = null
  private runId = 0
  private nextUpdateOffset: number | undefined

  subscribe = (listener: Listener): (() => void) => {
    this.listeners.add(listener)
    return () => {
      this.listeners.delete(listener)
    }
  }

  subscribeToInbound = (listener: InboundListener): (() => void) => {
    this.inboundListeners.add(listener)
    return () => {
      this.inboundListeners.delete(listener)
    }
  }

  subscribeToCallbacks = (listener: CallbackListener): (() => void) => {
    this.callbackListeners.add(listener)
    return () => {
      this.callbackListeners.delete(listener)
    }
  }

  getStateSnapshot = (): TelegramServiceState => this.state

  async start(config: TelegramRuntimeConfig): Promise<void> {
    if (this.state.status === 'running' && hasSameConfig(this.config, config)) {
      return
    }

    await this.stop()

    const runId = ++this.runId
    const abortController = new AbortController()
    this.abortController = abortController
    this.config = config
    this.nextUpdateOffset = undefined

    this.setState({
      status: 'starting',
      lastError: undefined,
      botUsername: undefined,
      botDisplayName: undefined,
      startedAt: undefined,
      activeChatId: undefined,
      activeUserId: undefined,
    })

    try {
      const response = await this.callTelegram<TelegramGetMeResponse>(
        config,
        'getMe',
        {},
        abortController.signal,
      )

      if (runId !== this.runId || abortController.signal.aborted) return

      try {
        await this.refreshTelegramMenu(config, abortController.signal)
      } catch (error) {
        if (!abortController.signal.aborted && runId === this.runId) {
          const message = normalizeTelegramError(error)
          logTelegramDebug(`[telegram] failed to refresh menu: ${message}`, 'error')
          this.patchState({ lastError: message })
        }
      }

      if (runId !== this.runId || abortController.signal.aborted) return

      this.setState({
        status: 'running',
        botUsername: response.result?.username,
        botDisplayName: response.result?.first_name,
        startedAt: new Date().toISOString(),
        lastError: undefined,
      })

      logTelegramDebug(
        `[telegram] connected as @${response.result?.username ?? 'unknown'}`,
      )

      void this.pollLoop(runId, config, abortController.signal)
    } catch (error) {
      if (abortController.signal.aborted || runId !== this.runId) return
      const message = normalizeTelegramError(error)
      this.setState({
        status: 'stopped',
        lastError: message,
      })
      throw error
    }
  }

  async startFromSavedConfig(): Promise<void> {
    await this.start(getTelegramRuntimeConfig())
  }

  async restartFromSavedConfig(): Promise<void> {
    await this.startFromSavedConfig()
  }

  async stop(): Promise<void> {
    this.runId++
    this.abortController?.abort()
    this.abortController = null
    this.config = undefined
    this.nextUpdateOffset = undefined

    if (this.state.status !== 'stopped') {
      this.setState({
        ...this.state,
        status: 'stopped',
        startedAt: undefined,
      })
    }
  }

  async sendMessage(
    chatId: string,
    text: string,
    replyMarkup?: TelegramInlineKeyboardMarkup,
  ): Promise<number | undefined> {
    if (!this.config) {
      throw new Error('Telegram service is not running')
    }

    // Telegram API 支持 chat_id 为字符串格式(特别是对于超出安全整数范围的 ID)
    // 直接使用字符串格式,避免整数溢出问题
    logTelegramDebug(`[telegram] sendMessage called: chatId=${chatId} (type: ${typeof chatId}), text length=${text.length}`)
    logTelegramDebug(`[telegram] allowedUserIds: ${JSON.stringify(this.config.allowedUserIds)}`)

    let lastMessageId: number | undefined

    for (const chunk of chunkTelegramMessage(text)) {
      logTelegramDebug(`[telegram] sending chunk to chat_id: ${chatId}`)
      const response = await this.callTelegram<TelegramSendMessageResponse>(
        this.config,
        'sendMessage',
        {
          chat_id: chatId,
          text: chunk,
          ...(replyMarkup ? { reply_markup: replyMarkup } : {}),
        },
      )
      lastMessageId = response.result?.message_id
      logTelegramDebug(`[telegram] sendMessage succeeded: messageId=${lastMessageId}`)
    }
    return lastMessageId
  }

  async editMessage(
    chatId: string,
    messageId: number,
    text: string,
    replyMarkup?: TelegramInlineKeyboardMarkup,
  ): Promise<void> {
    if (!this.config) {
      throw new Error('Telegram service is not running')
    }

    // Telegram API 支持 chat_id 为字符串格式(特别是对于超出安全整数范围的 ID)
    // 直接使用字符串格式,避免整数溢出问题
    await this.callTelegram<TelegramEditMessageResponse>(
      this.config,
      'editMessageText',
      {
        chat_id: chatId,
        message_id: messageId,
        text,
        ...(replyMarkup ? { reply_markup: replyMarkup } : {}),
      },
    )
  }

  async answerCallbackQuery(
    callbackQueryId: string,
    text?: string,
  ): Promise<void> {
    if (!this.config) {
      throw new Error('Telegram service is not running')
    }

    await this.callTelegram<TelegramAnswerCallbackQueryResponse>(
      this.config,
      'answerCallbackQuery',
      {
        callback_query_id: callbackQueryId,
        ...(text ? { text } : {}),
      },
    )
  }

  async sendChatAction(
    chatId: string,
    action: TelegramChatAction = 'typing',
  ): Promise<void> {
    if (!this.config) {
      throw new Error('Telegram service is not running')
    }

    await this.callTelegram<TelegramSendChatActionResponse>(
      this.config,
      'sendChatAction',
      {
        chat_id: chatId,
        action,
      },
    )
  }


  private setState(nextState: TelegramServiceState): void {
    this.state = nextState
    for (const listener of this.listeners) {
      listener()
    }
  }

  private patchState(patch: Partial<TelegramServiceState>): void {
    this.setState({
      ...this.state,
      ...patch,
    })
  }

  private emitInbound(event: TelegramInboundEvent): void {
    for (const listener of this.inboundListeners) {
      listener(event)
    }
  }
  
  private emitCallback(event: TelegramCallbackEvent): void {
    for (const listener of this.callbackListeners) {
      listener(event)
    }
  }

  private async pollLoop(
    runId: number,
    config: TelegramRuntimeConfig,
    signal: AbortSignal,
  ): Promise<void> {
    while (!signal.aborted && runId === this.runId) {
      try {
        const response = await this.callTelegram<TelegramGetUpdatesResponse>(
          config,
          'getUpdates',
          {
            offset: this.nextUpdateOffset,
            timeout: POLL_TIMEOUT_SECONDS,
            allowed_updates: ['message', 'callback_query'],
          },
          signal,
        )

        if (signal.aborted || runId !== this.runId) return

        if (this.state.lastError) {
          this.patchState({ lastError: undefined })
        }

        const updates = response.result ?? []
        logTelegramDebug(`[telegram] received ${updates.length} updates from Telegram`)

        for (const update of updates) {
          logTelegramDebug(`[telegram] processing update: update_id=${update.update_id}`)
          this.handleUpdate(update, config)
        }
      } catch (error) {
        if (signal.aborted || runId !== this.runId) return

        const message = normalizeTelegramError(error)
        logTelegramDebug(`[telegram] polling failed: ${message}`, 'error')
        this.patchState({ lastError: message })
        await sleep(RETRY_DELAY_MS)
      }
    }
  }

  private async refreshTelegramMenu(
    config: TelegramRuntimeConfig,
    signal: AbortSignal,
  ): Promise<void> {
    const commands = await getTelegramMenuCommands()

    await this.callTelegram<TelegramSetMyCommandsResponse>(
      config,
      'setMyCommands',
      {
        commands,
      },
      signal,
    )

    logTelegramDebug(`[telegram] refreshed menu commands: ${commands.length}`)
  }

  private handleUpdate(
    update: TelegramUpdate,
    config: TelegramRuntimeConfig,
  ): void {
    try {
      logTelegramDebug(`[telegram] handleUpdate called, update_id: ${update.update_id}`)
      this.nextUpdateOffset = update.update_id + 1

      const message = update.message
      const callbackQuery = update.callback_query

      logTelegramDebug(`[telegram] update structure: has_message=${!!message}, has_callback=${!!callbackQuery}`)

      if (callbackQuery?.data) {
      const chatId = callbackQuery.message?.chat?.id
      const userId = callbackQuery.from?.id
      const messageId = callbackQuery.message?.message_id
      if (
        chatId !== undefined &&
        userId !== undefined &&
        messageId !== undefined &&
        !callbackQuery.from?.is_bot
      ) {
        if (!config.allowedUserIds.includes(String(userId))) {
          return
        }
        this.emitCallback({
          kind: 'callback-query',
          callbackQueryId: callbackQuery.id,
          chatId: String(chatId),
          userId: String(userId),
          messageId,
          data: callbackQuery.data,
        })
      }
      return
    }

    const chatId = message?.chat?.id
    const userId = message?.from?.id

    logTelegramDebug(`[telegram] message details: chatId=${chatId}, userId=${userId}, is_bot=${message?.from?.is_bot}, chat_type=${message?.chat?.type}`)

    if (!message || chatId === undefined || userId === undefined) {
      logTelegramDebug(`[telegram] message rejected: missing required fields`)
      return
    }
    if (message.from?.is_bot) {
      logTelegramDebug(`[telegram] message rejected: from bot`)
      return
    }
    if (message.chat?.type !== 'private') {
      logTelegramDebug(`[telegram] message rejected: not private chat`)
      return
    }

    const normalizedChatId = String(chatId)
    const normalizedUserId = String(userId)

    logTelegramDebug(`[telegram] user validation: normalizedUserId=${normalizedUserId}, allowedUserIds=${JSON.stringify(config.allowedUserIds)}`)

    if (!config.allowedUserIds.includes(normalizedUserId)) {
      void this.sendMessage(
        normalizedChatId,
        '这个 Telegram user id 尚未被当前 /telegram 配置授权。',
      ).catch(() => {})
      return
    }

    this.patchState({
      activeChatId: normalizedChatId,
      activeUserId: normalizedUserId,
    })

    const text = message.text?.trim()

    logTelegramDebug(`[telegram] inbound message from chatId: ${normalizedChatId}, userId: ${normalizedUserId}, text: ${text?.slice(0, 50)}`)

    if (!text) {
      void this.sendMessage(
        normalizedChatId,
        '当前只支持文本消息,请发送纯文本内容。',
      ).catch(() => {})
      return
    }

    if (text === '/start') {
      void this.sendMessage(
        normalizedChatId,
        'Telegram 已连接到当前 Codev 会话。直接发送文本即可开始远程对话。',
      ).catch(() => {})
      return
    }

    logTelegramDebug(`[telegram] emitting inbound event with chatId: ${normalizedChatId}`)
    this.emitInbound({
      kind: 'inbound-message',
      chatId: normalizedChatId,
      userId: normalizedUserId,
      text,
      messageId: message.message_id,
      updateId: update.update_id,
    })
    } catch (error) {
      logTelegramDebug(`[telegram] handleUpdate error: ${error instanceof Error ? error.message : String(error)}`, 'error')
    }
  }

  private async callTelegram<T>(
    config: TelegramRuntimeConfig,
    method: string,
    payload: Record<string, unknown>,
    signal?: AbortSignal,
  ): Promise<T> {
    logTelegramDebug(`[telegram] calling API: ${method}`)

    // 创建超时信号(30秒超时)
    const timeoutController = new AbortController()
    const timeoutId = setTimeout(() => {
      timeoutController.abort()
    }, 30000)

    // 合并外部信号和超时信号
    const combinedSignal = signal
      ? AbortSignal.any([signal, timeoutController.signal])
      : timeoutController.signal

    try {
      const body = JSON.stringify(payload)
      logTelegramDebug(`[telegram] API request body: ${body}`)

      const response = await fetch(
        `${TELEGRAM_API_BASE}/bot${config.botToken}/${method}`,
        {
          method: 'POST',
          headers: {
            'content-type': 'application/json',
          },
          body,
          signal: combinedSignal,
        },
      )

      clearTimeout(timeoutId)

      if (!response.ok) {
        const errorText = await response.text().catch(() => 'unknown error')
        logTelegramDebug(`[telegram] API error: ${method} failed with HTTP ${response.status}: ${errorText}`, 'error')
        throw new Error(`Telegram API ${method} failed with HTTP ${response.status}: ${errorText}`)
      }

      const json = await response.json() as {
        ok?: boolean
        description?: string
      }

      if (!json.ok) {
        logTelegramDebug(`[telegram] API error: ${method} failed: ${json.description ?? 'unknown error'}`, 'error')
        throw new Error(
          `Telegram API ${method} failed: ${json.description ?? 'unknown error'}`,
        )
      }

      return json as T
    } catch (error) {
      clearTimeout(timeoutId)

      if (error instanceof Error) {
        if (error.name === 'AbortError') {
          logTelegramDebug(`[telegram] API error: ${method} timed out or was aborted`, 'error')
          throw new Error(`Telegram API ${method} timed out`)
        }
        logTelegramDebug(`[telegram] API error: ${method} failed: ${error.message}`, 'error')
        throw new Error(`Telegram API ${method} failed: ${error.message}`)
      }

      logTelegramDebug(`[telegram] API error: ${method} failed with unknown error`, 'error')
      throw new Error(`Telegram API ${method} failed with unknown error`)
    }
  }
}

export const telegramService = new TelegramService()