@michengai/dsh-im-connect 1.0.26 → 1.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,58 @@
1
+ import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
2
+ import { DeliveryRejected } from '../engine/deferred-delivery.js'
3
+
4
+ const TRANSIENT_STATUS = new Set([408, 425, 429, 500, 502, 503, 504])
5
+ const TRANSIENT_CODE = new Set(['ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'EAI_AGAIN', 'ENETUNREACH', 'EHOSTUNREACH', 'EPIPE', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET'])
6
+
7
+ /** Only transport/timeouts and explicit temporary platform errors, never arbitrary application failures. */
8
+ export function isTelegramTransient(error: unknown, depth = 0): boolean {
9
+ if (!error || typeof error !== 'object' || depth > 4) return false
10
+ const e = error as { status?: number | string | null; code?: string; name?: string; message?: string; cause?: unknown; errors?: unknown[] }
11
+ if (e.status !== undefined && e.status !== null) {
12
+ const status = Number(e.status)
13
+ if (Number.isFinite(status)) return TRANSIENT_STATUS.has(status)
14
+ }
15
+ if (TRANSIENT_CODE.has(e.code ?? '') || e.name === 'TimeoutError') return true
16
+ // A generic fetch wrapper can hide permanent TLS/configuration errors in its cause.
17
+ if (e.name === 'TypeError' && e.message === 'fetch failed' && !e.cause) return true
18
+ return isTelegramTransient(e.cause, depth + 1) || (Array.isArray(e.errors) && e.errors.some(cause => isTelegramTransient(cause, depth + 1)))
19
+ }
20
+
21
+ export interface TelegramRetryOptions {
22
+ signal?: AbortSignal
23
+ budgetMs?: number
24
+ delaysMs?: readonly number[]
25
+ log?: (line: string) => void
26
+ /** Fixed method name only; never log token-bearing URLs, payloads or raw network errors. */
27
+ method?: string
28
+ /** 已有消息的编辑可安全重试;新建操作默认只重试明确拒收。 */
29
+ edit?: boolean
30
+ }
31
+
32
+ /** 新建操作只重试明确限流,编辑已有消息可重试临时错误。 */
33
+ export async function retryTelegram<T>(operation: (signal: AbortSignal) => Promise<T>, options: TelegramRetryOptions = {}): Promise<T> {
34
+ const delays = options.delaysMs ?? [1000, 3000, 8000]
35
+ const budget = options.budgetMs ?? 90_000
36
+ const deadline = Date.now() + budget
37
+ const signal = timeoutSignal(budget, options.signal)
38
+ let ambiguous = false
39
+ for (let attempt = 0; ; attempt++) {
40
+ signal.throwIfAborted()
41
+ try { return await operation(signal) }
42
+ catch (error) {
43
+ signal.throwIfAborted()
44
+ const limited = error instanceof DeliveryRejected && (error as { status?: number }).status === 429
45
+ const canRetry = options.edit ? isTelegramTransient(error) : limited
46
+ // 先前编辑可能已经落地,不能让后来的明确拒收触发新消息兜底。
47
+ const finalError = () => ambiguous && (error as { rejected?: boolean })?.rejected === true
48
+ ? new Error(error instanceof Error ? error.message : 'telegram delivery unknown', { cause: error }) : error
49
+ if (!canRetry || attempt >= delays.length) throw finalError()
50
+ const retryAfterMs = Number((error as { retryAfterMs?: number }).retryAfterMs)
51
+ const delay = Math.max(delays[attempt]!, Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : 0)
52
+ if (Date.now() + delay >= deadline) throw finalError()
53
+ if (!limited) ambiguous = true
54
+ options.log?.(`[telegram] ${options.method ?? 'delivery'} 临时发送失败,${delay / 1000}s 后重试(${attempt + 1}/${delays.length})`)
55
+ await sleepWithSignal(delay, signal)
56
+ }
57
+ }
58
+ }
@@ -8,6 +8,7 @@ import { fileForm, fileRequest } from './file-send.js'
8
8
  import { JsonStateFile } from '../engine/json-state.js'
9
9
  import { sleepWithSignal, timeoutSignal } from '../engine/abort.js'
10
10
  import { fileMedia, imageMedia, MAX_CHANNEL_IMAGE_BYTES } from './channel-image-download.js'
11
+ import { retryTelegram } from './telegram-retry.js'
11
12
 
12
13
  export interface TelegramConfig {
13
14
  token?: string
@@ -176,6 +177,23 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
176
177
 
177
178
  // Rich message 是较新的 Bot API 方法;一旦确认不可用就一直走纯文本,避免每条消息都先失败一次。
178
179
  let richDisabled = false
180
+ // 429 按聊天记冷却:一个群/会话限流不应阻塞其他聊天的正常发送。
181
+ const MAX_COOLDOWN_MS = 5 * 60_000
182
+ const rateLimitedUntil = new Map<string, number>()
183
+ function cooldownKey(chatId: unknown): string { return chatId === undefined || chatId === null ? '' : String(chatId) }
184
+ function noteCooldown(chatId: unknown, retryAfterMs: number): void {
185
+ const key = cooldownKey(chatId)
186
+ if (!key) return
187
+ const wait = Math.min(Math.max(1000, Number.isFinite(retryAfterMs) ? retryAfterMs : 0), MAX_COOLDOWN_MS)
188
+ rateLimitedUntil.set(key, Math.max(rateLimitedUntil.get(key) ?? 0, Date.now() + wait))
189
+ }
190
+ function checkCooldown(chatId: unknown): void {
191
+ const key = cooldownKey(chatId)
192
+ const remaining = key ? (rateLimitedUntil.get(key) ?? 0) - Date.now() : 0
193
+ if (remaining > 0) throw Object.assign(new DeliveryRejected('telegram delivery rate limited'), {
194
+ status: 429, rejected: true, retryAfterMs: remaining,
195
+ })
196
+ }
179
197
  // 每个聊天当前还没收口的那条回复消息(见 beginReply):中途重新开流时复用它,不再另发一条。
180
198
  const openReplies = new Map<string, OpenReply>()
181
199
  const openingReplies = new Map<string, object>()
@@ -183,7 +201,8 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
183
201
  function richUnsupported(error: unknown): boolean {
184
202
  const status = Number((error as { status?: number } | undefined)?.status)
185
203
  if (status === 404) return true
186
- return /not found|unknown method|unsupported/i.test(error instanceof Error ? error.message : '')
204
+ // 只认「方法不存在」;消息被删/chat 不存在不能当成富文本能力缺失,否则会全局退化为纯文本。
205
+ return /unknown method|unsupported/i.test(error instanceof Error ? error.message : '')
187
206
  }
188
207
 
189
208
  async function sendMessageText(chatId: string, text: string): Promise<void> {
@@ -195,34 +214,63 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
195
214
  await api('sendRichMessage', { chat_id: route.chatId, ...threadParam, rich_message: { markdown } })
196
215
  return
197
216
  } catch (error) {
198
- // 响应超时或连接中断时,原消息可能已经送达,不能再发一份。
217
+ // Transport retries already ran; do not restart their budget by switching formats.
199
218
  if ((error as { rejected?: boolean })?.rejected !== true) throw error
200
- // 限流时再发一次纯文本只会再被限流,直接交给上层退避重试。
201
219
  if (error instanceof DeliveryRejected) throw error
220
+ // Only unsupported rich payload/method errors may fall back to plain text.
221
+ if (![400, 404].includes(Number((error as { status?: number }).status))) throw error
202
222
  if (richUnsupported(error)) richDisabled = true
203
223
  }
204
224
  }
205
225
  await api('sendMessage', { chat_id: route.chatId, ...threadParam, text })
206
226
  }
207
227
 
208
- async function api<T>(method: string, body: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
209
- const res = await fetchTelegram(`${API}/bot${token}/${method}`, {
210
- method: 'POST',
211
- headers: { 'content-type': 'application/json' },
212
- body: JSON.stringify(body),
213
- signal: timeoutSignal(timeoutMs, lifecycle?.signal),
214
- })
215
- const data = (await res.json()) as { ok: boolean; description?: string; error_code?: number; result: T }
216
- if (!data.ok) {
217
- const message = `telegram ${method}: ${data.description ?? 'unknown'}`
218
- // 429 表示平台因限流未受理该请求,重发不会重复。
219
- const error = Object.assign(data.error_code === 429 ? new DeliveryRejected(message) : new Error(message), { status: data.error_code, rejected: true })
220
- if (data.error_code === 401) (error as Error & { code?: string }).code = 'telegram-401'
228
+ async function readApiResult<T>(method: string, res: Response, chatId: unknown): Promise<T> {
229
+ // Gateways may return HTML on transient HTTP failures; do not lose the status to JSON parsing.
230
+ if (res.status >= 500 || [408, 425].includes(res.status)) {
231
+ await res.body?.cancel().catch(() => undefined)
232
+ throw Object.assign(new Error(`telegram ${method}: HTTP ${res.status}`), { status: res.status })
233
+ }
234
+ let data: { ok: boolean; description?: string; error_code?: number; parameters?: { retry_after?: number }; result: T }
235
+ try { data = await res.json() as typeof data }
236
+ catch (error) {
237
+ if (!(res.status >= 400)) throw error
238
+ const retryAfterMs = Number(res.headers?.get('retry-after')) * 1000
239
+ if (res.status === 429) noteCooldown(chatId, retryAfterMs)
240
+ throw Object.assign(res.status === 429 ? new DeliveryRejected(`telegram ${method}: HTTP 429`) : new Error(`telegram ${method}: HTTP ${res.status}`), {
241
+ status: res.status, rejected: true, retryAfterMs,
242
+ })
243
+ }
244
+ if (!data.ok || res.ok === false) {
245
+ const status = data.error_code ?? res.status
246
+ const message = `telegram ${method}: ${data.description ?? 'request rejected'}`
247
+ const error = Object.assign(status === 429 ? new DeliveryRejected(message) : new Error(message), {
248
+ status, rejected: true, retryAfterMs: Number(data.parameters?.retry_after ?? res.headers?.get('retry-after')) * 1000,
249
+ })
250
+ if (status === 429) noteCooldown(chatId, error.retryAfterMs)
251
+ if (status === 401) (error as Error & { code?: string }).code = 'telegram-401'
221
252
  throw error
222
253
  }
223
254
  return data.result
224
255
  }
225
256
 
257
+ async function api<T>(method: string, body: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
258
+ if (stopped) throw new DOMException('Telegram channel stopped', 'AbortError')
259
+ const request = async (signal?: AbortSignal) => {
260
+ if (stopped) throw new DOMException('Telegram channel stopped', 'AbortError')
261
+ if (['sendMessage', 'sendRichMessage', 'editMessageText'].includes(method)) checkCooldown(body.chat_id)
262
+ const res = await fetchTelegram(`${API}/bot${token}/${method}`, {
263
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
264
+ redirect: 'error', signal: timeoutSignal(timeoutMs, signal ?? lifecycle?.signal),
265
+ })
266
+ return readApiResult<T>(method, res, body.chat_id)
267
+ }
268
+ // Retry delivery, never task execution, polling, topic creation or unrelated mutations.
269
+ return ['sendMessage', 'sendRichMessage', 'editMessageText'].includes(method)
270
+ ? retryTelegram(request, { signal: lifecycle?.signal, method, log, edit: method === 'editMessageText' })
271
+ : request()
272
+ }
273
+
226
274
  function mentioned(message: NonNullable<TgUpdate['message']>): boolean {
227
275
  const text = message.text ?? message.caption
228
276
  const entities = message.text !== undefined ? message.entities : message.caption_entities
@@ -382,8 +430,10 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
382
430
  maxMessageLength: 4000,
383
431
  /** 占位消息支持顶部状态行(思考 / 工具进度),网关据此推送中间态。 */
384
432
  replyStatus: true,
433
+ interactionRetryRequiresDefinite: true,
385
434
  async start() {
386
435
  albumAccess.clear()
436
+ rateLimitedUntil.clear()
387
437
  lifecycle?.abort()
388
438
  lifecycle = new AbortController()
389
439
  stopped = false
@@ -412,13 +462,21 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
412
462
  await sendMessageText(chatId, text)
413
463
  },
414
464
  async sendFile(chatId, file, signal) {
465
+ if (stopped) throw new DOMException('Telegram channel stopped', 'AbortError')
415
466
  const route = parseTelegramChatId(chatId)
416
- const form = fileForm(file, 'document')
417
- form.append('chat_id', String(route.chatId))
418
- if (route.threadId !== undefined) {
419
- form.append('message_thread_id', String(route.threadId))
420
- }
421
- await fileRequest(`${API}/bot${token}/sendDocument`, { method: 'POST', body: form, signal: timeoutSignal(120_000, AbortSignal.any([...(signal ? [signal] : []), ...(lifecycle ? [lifecycle.signal] : [])])) }, fetchTelegram)
467
+ await retryTelegram(async attemptSignal => {
468
+ if (stopped) throw new DOMException('Telegram channel stopped', 'AbortError')
469
+ checkCooldown(route.chatId)
470
+ // Multipart bodies are recreated for each upload attempt; never reuse a consumed body.
471
+ const form = fileForm(file, 'document')
472
+ form.append('chat_id', String(route.chatId))
473
+ if (route.threadId !== undefined) form.append('message_thread_id', String(route.threadId))
474
+ const res = await fetchTelegram(`${API}/bot${token}/sendDocument`, {
475
+ // Preserve the original upload allowance; the shared signal already bounds all attempts.
476
+ method: 'POST', body: form, redirect: 'error', signal: attemptSignal,
477
+ })
478
+ await readApiResult('sendDocument', res, route.chatId)
479
+ }, { signal: AbortSignal.any([...(signal ? [signal] : []), ...(lifecycle ? [lifecycle.signal] : [])]), budgetMs: 120_000, method: 'sendDocument', log })
422
480
  },
423
481
  /**
424
482
  * 把会话标题写成话题名。只有论坛话题(话题群 / 私聊话题)有这一层级;
@@ -554,13 +612,14 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
554
612
  current.last = next
555
613
  return
556
614
  } catch (error) {
557
- // 富文本被拒就退回纯文本编辑;确认方法不可用后不再重试。
558
- if (richUnsupported(error)) richDisabled = true
559
- else if (!(error instanceof Error && error.message.includes('message is not modified'))) {
560
- await api('editMessageText', { chat_id: route.chatId, message_id: current.messageId, text: next })
615
+ // A confirmed no-op is success; only rich-format rejection permits plain fallback.
616
+ if (error instanceof Error && error.message.includes('message is not modified')) {
561
617
  current.last = next
562
618
  return
563
619
  }
620
+ if ((error as { rejected?: boolean })?.rejected !== true
621
+ || ![400, 404].includes(Number((error as { status?: number }).status))) throw error
622
+ if (richUnsupported(error)) richDisabled = true
564
623
  }
565
624
  }
566
625
  await api('editMessageText', { chat_id: route.chatId, message_id: current.messageId, text: next })
@@ -572,6 +631,11 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
572
631
  return
573
632
  }
574
633
  if (!allowSend) return
634
+ // Only a definitively uneditable/deleted placeholder justifies creating a new message.
635
+ // Exhausted transport retries, cancellation and auth errors must not start a new budget.
636
+ if (stopped || (error as { rejected?: boolean })?.rejected !== true
637
+ || Number((error as { status?: number }).status) !== 400
638
+ || !/message to edit not found|message can(?:not|'t) be edited|message_id_invalid/i.test(detail)) throw error
575
639
  await sendMessageText(chatId, next)
576
640
  current.last = next
577
641
  }
@@ -589,6 +653,11 @@ export function createTelegramChannel(config: TelegramConfig, log: (line: string
589
653
  }
590
654
 
591
655
  return {
656
+ seal() {
657
+ // Taken by the hub for final delivery: reserve this message for this handle only.
658
+ // Unlike detach(), sealing must not close it before its original finish().
659
+ if (openReplies.get(chatId) === current) openReplies.delete(chatId)
660
+ },
592
661
  detach() {
593
662
  // 已排队的正文仍需写入旧消息,只解除复用,避免新回合覆盖它。
594
663
  close()
@@ -1,4 +1,5 @@
1
1
  import { DeferredDelivery, DeliveryRejected, DeliveryUnavailable, type DeferredEntry } from './deferred-delivery.js'
2
+ import { ChoiceSendError } from './choice-delivery.js'
2
3
  import { sleepWithSignal } from './abort.js'
3
4
  import { assistantText } from './assistant-text.js'
4
5
  import { readDeliveryHistory } from './delivery-history.js'
@@ -136,6 +137,9 @@ interface LegacyUserQuestionService {
136
137
  interface InteractionDeliveryResult {
137
138
  status: 'delivered' | 'failed' | 'aborted'
138
139
  deliveredAny: boolean
140
+ retrySafe?: boolean
141
+ /** 失败时若平台要求等待,整条重试只会再次撞冷却。 */
142
+ retryAfterMs?: number
139
143
  }
140
144
 
141
145
  const USER_QUESTION_WRAPPER = Symbol('dsh-im-connect.user-question-wrapper')
@@ -1090,6 +1094,11 @@ export class ImEngine {
1090
1094
  return work.catch(error => { this.log(`[im-progress] 会话回复失败: ${error instanceof Error ? error.name : 'Error'}`) })
1091
1095
  }
1092
1096
 
1097
+ /** 取流后因会话失效等原因放弃收口时,清掉只有状态、没有正文的占位。 */
1098
+ private async discardEmptyTake(taken: { stream?: { discard?(): Promise<void> }; text: string }): Promise<void> {
1099
+ if (taken.stream && !taken.text) await taken.stream.discard?.().catch(() => undefined)
1100
+ }
1101
+
1093
1102
  private async processSessionEvent(
1094
1103
  session: DeliverySession,
1095
1104
  event: {
@@ -1237,7 +1246,10 @@ export class ImEngine {
1237
1246
  this.log(`[${channel.id}] 回合失败 ${sessionId}: ${detail}`)
1238
1247
  const failed = notice(this.ctx, '助手没有生成回复,请查看本机日志。')
1239
1248
  const taken = await this.streams.take(streamKey, sessionId)
1240
- if (taken.invalidated || !stillDeliverable()) return
1249
+ if (taken.invalidated || !stillDeliverable()) {
1250
+ await this.discardEmptyTake(taken)
1251
+ return
1252
+ }
1241
1253
  let failureDelivered: boolean
1242
1254
  if (taken.stream) {
1243
1255
  failureDelivered = await taken.stream.finish([taken.text, failed].filter(Boolean).join('\n\n')).then(() => true).catch(() => this.deliver(channel, binding.chatId, failed))
@@ -1268,7 +1280,10 @@ export class ImEngine {
1268
1280
  }
1269
1281
  const taken = await this.streams.take(streamKey, sessionId)
1270
1282
  stopped = !!taken.invalidated || !stillDeliverable()
1271
- if (stopped) return
1283
+ if (stopped) {
1284
+ await this.discardEmptyTake(taken)
1285
+ return
1286
+ }
1272
1287
  if (taken.stream) {
1273
1288
  const finalText = text || taken.text
1274
1289
  // 这一步只有工具调用、没有正文:状态消息留着,下一步继续改同一条,
@@ -1449,7 +1464,10 @@ export class ImEngine {
1449
1464
  terminalIds.push(entry.id)
1450
1465
  }
1451
1466
  const taken = await this.streams.take(`${channel.id}:${message.chatId}`, result.sessionId)
1452
- if (!valid()) return
1467
+ if (!valid()) {
1468
+ await this.discardEmptyTake(taken)
1469
+ return
1470
+ }
1453
1471
  if (taken.stream) {
1454
1472
  const body = text
1455
1473
  // 复用已有回复流发送异常说明;收口结果不明时不重复发送。
@@ -1620,7 +1638,7 @@ export class ImEngine {
1620
1638
  /** 同一条提示失败后再发一次。微信正文和问题撞车时,第一次会失败,排空后的重试仍可在聊天里回答。 */
1621
1639
  private async retryInteraction(channel: ChannelAdapter, deliver: () => Promise<InteractionDeliveryResult>): Promise<InteractionDeliveryResult> {
1622
1640
  const first = await deliver()
1623
- if (first.status !== 'failed') return first
1641
+ if (first.status !== 'failed' || first.retrySafe === false || first.retryAfterMs !== undefined) return first
1624
1642
  this.log(`[${channel.id}] 交互提示发送失败,重试一次`)
1625
1643
  return deliver()
1626
1644
  }
@@ -1634,8 +1652,19 @@ export class ImEngine {
1634
1652
  interactive?: { sessionId: string; message: ImMessage; choices: Choice[]; valid: () => boolean },
1635
1653
  ): Promise<InteractionDeliveryResult> {
1636
1654
  let deliveredAny = false
1655
+ const requiresDefinite = channel.interactionRetryRequiresDefinite === true
1656
+ let cardUnknown = false
1637
1657
  if (channel.sendChoices && interactive && text.length < channel.maxMessageLength - 512 && !signal?.aborted) {
1638
- const result = await withReplyLocale(this.ctx, () => this.choices.show(channel, interactive.message, text, interactive.choices,
1658
+ const choiceChannel = requiresDefinite ? Object.assign(Object.create(channel) as ChannelAdapter, {
1659
+ sendChoices: async (...args: Parameters<NonNullable<ChannelAdapter['sendChoices']>>) => {
1660
+ try { return await channel.sendChoices!(...args) }
1661
+ catch (error) {
1662
+ if (error instanceof ChoiceSendError && error.reason === 'delivery-unknown') cardUnknown = true
1663
+ throw error
1664
+ }
1665
+ },
1666
+ }) : channel
1667
+ const result = await withReplyLocale(this.ctx, () => this.choices.show(choiceChannel, interactive.message, text, interactive.choices,
1639
1668
  interactive.sessionId, interactive.valid, replyText('点击按钮或按提示回复文字。')))
1640
1669
  if (!result) return { status: signal?.aborted ? 'aborted' : 'delivered', deliveredAny: true }
1641
1670
  }
@@ -1647,7 +1676,13 @@ export class ImEngine {
1647
1676
  this.log(`[${channel.id}] 已投递交互 ${chatId},长度 ${chunk.length}`)
1648
1677
  } catch (error) {
1649
1678
  this.log(`[${channel.id}] 交互提示发送失败: ${error instanceof Error ? error.message : String(error)}`)
1650
- return { status: 'failed', deliveredAny }
1679
+ const retryAfterMs = Number((error as { retryAfterMs?: number })?.retryAfterMs)
1680
+ return {
1681
+ status: 'failed',
1682
+ deliveredAny,
1683
+ retrySafe: !requiresDefinite || (!cardUnknown && !deliveredAny && isDefiniteSendFailure(error)),
1684
+ retryAfterMs: Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : undefined,
1685
+ }
1651
1686
  }
1652
1687
  if (signal?.aborted) return { status: 'aborted', deliveredAny }
1653
1688
  }
@@ -16,10 +16,10 @@ export class ReplyStreamHub {
16
16
  // 回合纪元:reset 时自增,迟到的旧回合增量据此丢弃,不会重建流
17
17
  private readonly generations = new Map<string, number>()
18
18
  // 顶部状态行(思考进度 / 工具进度);占位消息创建时用它做首屏文字。
19
- private readonly statuses = new Map<string, string>()
19
+ private readonly statuses = new Map<string, { text: string }>()
20
20
 
21
21
  statusOf(key: string): string | undefined {
22
- return this.statuses.get(key)
22
+ return this.statuses.get(key)?.text
23
23
  }
24
24
 
25
25
  onTextDelta(key: string, delta: string, start: () => Promise<ReplyStream | undefined>, sessionId?: string): Promise<void> {
@@ -61,7 +61,8 @@ export class ReplyStreamHub {
61
61
  this.owners.set(key, sessionId)
62
62
  }
63
63
  const generation = this.generations.get(key) ?? 0
64
- this.statuses.set(key, status)
64
+ const statusEntry = { text: status }
65
+ this.statuses.set(key, statusEntry)
65
66
  const prev = this.tails.get(key) ?? Promise.resolve()
66
67
  const next = prev.catch(() => undefined).then(async () => {
67
68
  if (generation !== (this.generations.get(key) ?? 0)) return
@@ -74,7 +75,7 @@ export class ReplyStreamHub {
74
75
  }
75
76
  if (!stream) {
76
77
  // 开流失败:清掉状态,别让下一条正文把过期状态写进去
77
- if (this.statuses.get(key) === status) this.statuses.delete(key)
78
+ if (this.statuses.get(key) === statusEntry) this.statuses.delete(key)
78
79
  return
79
80
  }
80
81
  this.streams.set(key, stream)
@@ -90,15 +91,25 @@ export class ReplyStreamHub {
90
91
  async take(key: string, sessionId?: string): Promise<{ stream?: ReplyStream; text: string; invalidated?: boolean }> {
91
92
  if (sessionId !== undefined && this.owners.has(key) && this.owners.get(key) !== sessionId) return { text: '' }
92
93
  const generation = this.generations.get(key) ?? 0
93
- await (this.tails.get(key) ?? Promise.resolve()).catch(() => undefined)
94
- if (generation !== (this.generations.get(key) ?? 0)) return { text: '', invalidated: true }
95
- const stream = this.streams.get(key)
96
- const text = this.texts.get(key) ?? ''
97
- this.streams.delete(key)
98
- this.texts.delete(key)
99
- this.tails.delete(key)
100
- this.statuses.delete(key)
101
- return { stream, text }
94
+ const statusEntry = this.statuses.get(key)
95
+ const prev = this.tails.get(key) ?? Promise.resolve()
96
+ // Extraction is itself a queued operation. Later deltas must not reuse the handle
97
+ // that is now being finalized, nor lose their own tail to an unconditional delete.
98
+ const next = prev.catch(() => undefined).then(() => {
99
+ if (generation !== (this.generations.get(key) ?? 0)) return { text: '', invalidated: true }
100
+ const stream = this.streams.get(key)
101
+ const text = this.texts.get(key) ?? ''
102
+ stream?.seal?.()
103
+ this.streams.delete(key)
104
+ this.texts.delete(key)
105
+ // 只清理取流前的状态,保留之后入队的状态(即使文案相同)。
106
+ if (this.statuses.get(key) === statusEntry) this.statuses.delete(key)
107
+ return { stream, text }
108
+ })
109
+ const tail = next.then(() => undefined, () => undefined)
110
+ this.tails.set(key, tail)
111
+ try { return await next }
112
+ finally { if (this.tails.get(key) === tail) this.tails.delete(key) }
102
113
  }
103
114
 
104
115
  /** 读当前流但不取走:只有状态行的占位要留在原地,等下一步继续改。 */
@@ -27,6 +27,8 @@ export interface ImMessage {
27
27
  export interface ReplyStream {
28
28
  update(text: string): Promise<void>
29
29
  finish(text: string): Promise<void>
30
+ /** Stop channel-level reuse when taken for finalization, without closing this handle. */
31
+ seal?(): void
30
32
  /** 只改顶部状态行(思考 / 工具进度),不碰正文;渠道不支持时省略。 */
31
33
  setStatus?(text: string): Promise<void>
32
34
  /** 新回合接管时删掉还没写正文的占位消息,避免聊天里留下停在「第 N 步」的消息。 */
@@ -44,6 +46,8 @@ export interface ChannelAdapter {
44
46
  readonly maxMessageLength: number
45
47
  /** 抑制含工具调用的助手文字;实时与补发共用规则,不计为已投递。 */
46
48
  readonly skipInterimText?: boolean
49
+ /** 交互提示仅在明确拒收且没有已送分片时允许整体重试。 */
50
+ readonly interactionRetryRequiresDefinite?: boolean
47
51
  start(): void | Promise<void>
48
52
  stop(): void | Promise<void>
49
53
  send(chatId: string, text: string): Promise<void>