@chen_hu_hu/pi-qq 1.6.1 → 1.7.0

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.
package/src/infra/i18n.ts CHANGED
@@ -56,7 +56,7 @@ const enUS = {
56
56
  "commands.compact.done": "Context compaction triggered.",
57
57
  "commands.compact.busy": "Task is running; use /stop before /compact.",
58
58
  "commands.last.none": "No completed message yet.",
59
- "commands.last.running": "The task is still running; the final reply will be sent when it finishes.",
59
+ "commands.last.empty": "Nothing to repush yet; the task is still running.",
60
60
  "commands.new.busy": "Task is running; use /stop before resetting.",
61
61
  "commands.new.resetting": "Resetting the session…",
62
62
  "commands.unknown": "Unknown command {cmd}; use /help.",
@@ -131,7 +131,6 @@ const enUS = {
131
131
  "diagnostics.budget.passiveRemainingNone": "Passive remaining: —",
132
132
  "diagnostics.budget.estimatedNone": "Estimated remaining: — (diagnostic only)",
133
133
  "diagnostics.budget.windowNone": "msgId window: —",
134
- "diagnostics.budget.none": "none",
135
134
  "diagnostics.budget.passiveRemaining": "Passive remaining: {remaining}",
136
135
  "diagnostics.budget.streamBubbles": "Stream bubbles: {count} (current msgId)",
137
136
  "diagnostics.budget.estimated": "Estimated remaining: {remaining} (diagnostic only)",
@@ -167,73 +166,11 @@ const enUS = {
167
166
  "settings.invalidFields": "Invalid config file ({path}): {errors}; invalid values were ignored.",
168
167
  "settings.parseFailed": "Failed to parse config file ({path}): {message}",
169
168
  "settings.deliverAs": 'deliverAs must be "steer" or "followUp"',
170
- "settings.replyType": 'replyType must be "full", "simple", or "last"',
169
+ "settings.replyType": 'replyType must be "full" or "simple"',
171
170
  "settings.fileMaxSize": "fileMaxSize must be a positive finite number",
172
171
  "settings.logLevel": 'logLevel must be "silent", "error", "warn", "info", or "debug"',
173
172
  "settings.language": 'language must be "zh-cn" or "en-us"',
174
173
  "settings.debug": "debug must be a boolean",
175
-
176
- "log.doneFailed": "DONE failed",
177
- "log.qqCommand": "QQ command",
178
- "log.qrCodeDisplayed": "QR code displayed",
179
- "log.qrCodeExpired": "QR code expired; refreshing",
180
- "log.qrLoginCommandFailed": "QR login command failed",
181
- "log.qrLoginNoOpenid": "QR login did not return a user openid",
182
- "log.qrLoginFailed": "QR login failed",
183
- "log.qrLoginStarted": "QR login started",
184
- "log.qrLoginSucceeded": "QR login succeeded",
185
- "log.assistantMessageEnded": "assistant message ended",
186
- "log.assistantMessageNoText": "assistant message has no text",
187
- "log.attachmentFailureSummary": "attachment failure summary",
188
- "log.attachmentsPending": "attachments pending for instruction",
189
- "log.bubbleSplit": "bubble split",
190
- "log.bubbleSplitFailed": "bubble split failed",
191
- "log.clearedPendingAttachments": "cleared pending attachments for /new",
192
- "log.toolEnd": "end",
193
- "log.runEnded": "run ended",
194
- "log.botErrorEvent": "error event",
195
- "log.uploadIndexWriteFailed": "failed to write upload index",
196
- "log.inboundMessage": "inbound message",
197
- "log.botHandlerRejected": "message handler rejected",
198
- "log.noBoundUser": "no bound user; reply skipped",
199
- "log.noInjectableContent": "no injectable content after attachment handling",
200
- "log.passiveSendFailed": "passive send failed; retrying proactively",
201
- "log.proactiveRetryFailed": "proactive retry failed",
202
- "log.runStarted": "run started",
203
- "log.savingAttachments": "saving attachments",
204
- "log.sendingReply": "sending reply",
205
- "log.sendingTextChunk": "sending text chunk",
206
- "log.sentToPi": "sent to pi",
207
- "log.shuttingDown": "shutting down",
208
- "log.skippedSender": "skipped non-allowlisted sender",
209
- "log.skippedNonC2c": "skipped non-c2c message",
210
- "log.toolStart": "start",
211
- "log.sessionStarted": "started",
212
- "log.botStarting": "starting",
213
- "log.sessionStartingBot": "starting bot",
214
- "log.startBotAfterLoginFailed": "starting bot after login failed",
215
- "log.streamError": "stream error",
216
- "log.streamReplyFallback": "stream reply failed; falling back to text",
217
- "log.streamTakeoverDecision": "stream takeover decision",
218
- "log.streamUnavailable": "stream unavailable",
219
- "log.textChunkFailed": "text chunk failed",
220
- "log.textChunkSent": "text chunk sent",
221
- "log.unsupportedMessage": "unsupported message: no text and no attachments",
222
- "log.voiceNoText": "voice ASR returned no text",
223
- "log.voiceNoTextUseContent": "voice ASR returned no text; using text content",
224
- "log.voiceMessage": "voice message",
225
- "log.voiceTranscript": "voice transcript",
226
- "log.streamFrameFailed": "frame index={index} failed after {attempts} attempt(s): {reason}",
227
- "log.streamFrameRateLimited": "frame index={index} rate limited (attempt {attempt}), retry in {delay}ms: {reason}",
228
- "log.botConnected": "connected",
229
- "log.botReconnecting": "reconnecting",
230
- "log.botStopped": "stopped",
231
- "log.botBlocked": "blocked",
232
- "log.messageReceived": "message received",
233
- "log.ended": "ended",
234
- "log.starting": "starting",
235
- "log.streamTiming": "stream timing",
236
- "log.eventLoopDelay": "event loop delay",
237
174
  } as const;
238
175
 
239
176
  export type TranslationKey = keyof typeof enUS;
@@ -288,7 +225,7 @@ const zhCN: Record<TranslationKey, string> = {
288
225
  "commands.compact.done": "已触发上下文压缩。",
289
226
  "commands.compact.busy": "任务正在运行;请先使用 /stop 再执行 /compact。",
290
227
  "commands.last.none": "还没有已完成的消息。",
291
- "commands.last.running": "任务仍在进行中,完成后会自动推送最终回复。",
228
+ "commands.last.empty": "当前没有可重推的内容,任务仍在执行中。",
292
229
  "commands.new.busy": "任务正在运行;请先使用 /stop 再重置会话。",
293
230
  "commands.new.resetting": "正在重置会话…",
294
231
  "commands.unknown": "未知命令 {cmd};请使用 /help。",
@@ -363,7 +300,6 @@ const zhCN: Record<TranslationKey, string> = {
363
300
  "diagnostics.budget.passiveRemainingNone": "被动剩余:—",
364
301
  "diagnostics.budget.estimatedNone": "预计剩余:—(仅诊断)",
365
302
  "diagnostics.budget.windowNone": "msgId 窗口:—",
366
- "diagnostics.budget.none": "无",
367
303
  "diagnostics.budget.passiveRemaining": "被动剩余:{remaining}",
368
304
  "diagnostics.budget.streamBubbles": "流式气泡:{count}(当前 msgId)",
369
305
  "diagnostics.budget.estimated": "预计剩余:{remaining}(仅诊断)",
@@ -399,73 +335,11 @@ const zhCN: Record<TranslationKey, string> = {
399
335
  "settings.invalidFields": "配置文件无效({path}):{errors};无效值已忽略。",
400
336
  "settings.parseFailed": "解析配置文件失败({path}):{message}",
401
337
  "settings.deliverAs": 'deliverAs 必须是 "steer" 或 "followUp"',
402
- "settings.replyType": 'replyType 必须是 "full"、"simple" 或 "last"',
338
+ "settings.replyType": 'replyType 必须是 "full" 或 "simple"',
403
339
  "settings.fileMaxSize": "fileMaxSize 必须是正有限数",
404
340
  "settings.logLevel": 'logLevel 必须是 "silent"、"error"、"warn"、"info" 或 "debug"',
405
341
  "settings.language": 'language 必须是 "zh-cn" 或 "en-us"',
406
342
  "settings.debug": "debug 必须是布尔值",
407
-
408
- "log.doneFailed": "DONE 失败",
409
- "log.qqCommand": "QQ 命令",
410
- "log.qrCodeDisplayed": "二维码已显示",
411
- "log.qrCodeExpired": "二维码已过期,正在刷新",
412
- "log.qrLoginCommandFailed": "扫码登录命令失败",
413
- "log.qrLoginNoOpenid": "扫码登录未返回用户 openid",
414
- "log.qrLoginFailed": "扫码登录失败",
415
- "log.qrLoginStarted": "开始扫码登录",
416
- "log.qrLoginSucceeded": "扫码登录成功",
417
- "log.assistantMessageEnded": "assistant 消息结束",
418
- "log.assistantMessageNoText": "assistant 消息没有文本",
419
- "log.attachmentFailureSummary": "附件失败汇总",
420
- "log.attachmentsPending": "附件等待指令",
421
- "log.bubbleSplit": "气泡切分",
422
- "log.bubbleSplitFailed": "气泡切分失败",
423
- "log.clearedPendingAttachments": "已清除 /new 的待处理附件",
424
- "log.toolEnd": "工具结束",
425
- "log.runEnded": "运行结束",
426
- "log.botErrorEvent": "错误事件",
427
- "log.uploadIndexWriteFailed": "写入上传索引失败",
428
- "log.inboundMessage": "收到消息",
429
- "log.botHandlerRejected": "消息处理器异常",
430
- "log.noBoundUser": "未绑定用户,跳过回复",
431
- "log.noInjectableContent": "附件处理后没有可注入内容",
432
- "log.passiveSendFailed": "被动回复失败,正在尝试主动消息",
433
- "log.proactiveRetryFailed": "主动消息重试失败",
434
- "log.runStarted": "运行开始",
435
- "log.savingAttachments": "正在保存附件",
436
- "log.sendingReply": "发送回复",
437
- "log.sendingTextChunk": "发送文本分片",
438
- "log.sentToPi": "已发送给 pi",
439
- "log.shuttingDown": "正在关闭",
440
- "log.skippedSender": "跳过非白名单发送者",
441
- "log.skippedNonC2c": "跳过非 C2C 消息",
442
- "log.toolStart": "工具开始",
443
- "log.sessionStarted": "会话开始",
444
- "log.botStarting": "机器人启动中",
445
- "log.sessionStartingBot": "正在启动机器人",
446
- "log.startBotAfterLoginFailed": "登录后启动机器人失败",
447
- "log.streamError": "流式错误",
448
- "log.streamReplyFallback": "流式回复失败,回退为文本",
449
- "log.streamTakeoverDecision": "流式接管决策",
450
- "log.streamUnavailable": "流式不可用",
451
- "log.textChunkFailed": "文本分片发送失败",
452
- "log.textChunkSent": "文本分片已发送",
453
- "log.unsupportedMessage": "不支持的消息:没有文本和附件",
454
- "log.voiceNoText": "语音 ASR 没有返回文本",
455
- "log.voiceNoTextUseContent": "语音 ASR 没有返回文本,使用文本内容",
456
- "log.voiceMessage": "语音消息",
457
- "log.voiceTranscript": "语音转写",
458
- "log.streamFrameFailed": "帧 index={index} 在 {attempts} 次尝试后失败:{reason}",
459
- "log.streamFrameRateLimited": "帧 index={index} 被限流(第 {attempt} 次尝试),{delay}ms 后重试:{reason}",
460
- "log.botConnected": "已连接",
461
- "log.botReconnecting": "正在重连",
462
- "log.botStopped": "已停止",
463
- "log.botBlocked": "连接被阻止",
464
- "log.messageReceived": "收到消息",
465
- "log.ended": "已结束",
466
- "log.starting": "启动中",
467
- "log.streamTiming": "流式时序",
468
- "log.eventLoopDelay": "事件循环延迟",
469
343
  };
470
344
 
471
345
  const dictionaries: Record<Language, Record<TranslationKey, string>> = {
@@ -499,69 +373,3 @@ export function translate(
499
373
  export function t(key: TranslationKey, params?: Record<string, string | number | undefined>): string {
500
374
  return translate(activeLanguage, key, params);
501
375
  }
502
-
503
- const LOG_MESSAGE_KEYS: Record<string, TranslationKey> = {
504
- "DONE failed": "log.doneFailed",
505
- "QQ command": "log.qqCommand",
506
- "QR code displayed": "log.qrCodeDisplayed",
507
- "QR code expired; refreshing": "log.qrCodeExpired",
508
- "QR login command failed": "log.qrLoginCommandFailed",
509
- "QR login did not return a user openid": "log.qrLoginNoOpenid",
510
- "QR login failed": "log.qrLoginFailed",
511
- "QR login started": "log.qrLoginStarted",
512
- "QR login succeeded": "log.qrLoginSucceeded",
513
- "assistant message ended": "log.assistantMessageEnded",
514
- "assistant message has no text": "log.assistantMessageNoText",
515
- "attachment failure summary": "log.attachmentFailureSummary",
516
- "attachments pending for instruction": "log.attachmentsPending",
517
- "bubble split": "log.bubbleSplit",
518
- "bubble split failed": "log.bubbleSplitFailed",
519
- "cleared pending attachments for /new": "log.clearedPendingAttachments",
520
- end: "log.toolEnd",
521
- ended: "log.ended",
522
- "error event": "log.botErrorEvent",
523
- "failed to write upload index": "log.uploadIndexWriteFailed",
524
- "inbound message": "log.inboundMessage",
525
- "message handler rejected": "log.botHandlerRejected",
526
- "message received": "log.messageReceived",
527
- "no bound user; reply skipped": "log.noBoundUser",
528
- "no injectable content after attachment handling": "log.noInjectableContent",
529
- "passive send failed; retrying proactively": "log.passiveSendFailed",
530
- "proactive retry failed": "log.proactiveRetryFailed",
531
- "run ended": "log.runEnded",
532
- "run started": "log.runStarted",
533
- "saving attachments": "log.savingAttachments",
534
- "sending reply": "log.sendingReply",
535
- "sending text chunk": "log.sendingTextChunk",
536
- "sent to pi": "log.sentToPi",
537
- "shutting down": "log.shuttingDown",
538
- "skipped non-allowlisted sender": "log.skippedSender",
539
- "skipped non-c2c message": "log.skippedNonC2c",
540
- start: "log.toolStart",
541
- started: "log.sessionStarted",
542
- starting: "log.botStarting",
543
- "stream timing": "log.streamTiming",
544
- "event loop delay": "log.eventLoopDelay",
545
- "starting bot": "log.sessionStartingBot",
546
- "starting bot after login failed": "log.startBotAfterLoginFailed",
547
- "stream error": "log.streamError",
548
- "stream reply failed; falling back to text": "log.streamReplyFallback",
549
- "stream takeover decision": "log.streamTakeoverDecision",
550
- "stream unavailable": "log.streamUnavailable",
551
- "text chunk failed": "log.textChunkFailed",
552
- "text chunk sent": "log.textChunkSent",
553
- "unsupported message: no text and no attachments": "log.unsupportedMessage",
554
- "voice ASR returned no text": "log.voiceNoText",
555
- "voice ASR returned no text; using text content": "log.voiceNoTextUseContent",
556
- "voice message": "log.voiceMessage",
557
- "voice transcript": "log.voiceTranscript",
558
- connected: "log.botConnected",
559
- reconnecting: "log.botReconnecting",
560
- stopped: "log.botStopped",
561
- blocked: "log.botBlocked",
562
- };
563
-
564
- export function localizeLogMessage(message: string): { msg: string; msgKey?: TranslationKey } {
565
- const key = LOG_MESSAGE_KEYS[message];
566
- return key ? { msg: t(key), msgKey: key } : { msg: message };
567
- }
@@ -0,0 +1,66 @@
1
+ const LOG_MESSAGE_KEYS = {
2
+ "DONE failed": "log.doneFailed",
3
+ "QQ command": "log.qqCommand",
4
+ "QR code displayed": "log.qrCodeDisplayed",
5
+ "QR code expired; refreshing": "log.qrCodeExpired",
6
+ "QR login command failed": "log.qrLoginCommandFailed",
7
+ "QR login did not return a user openid": "log.qrLoginNoOpenid",
8
+ "QR login failed": "log.qrLoginFailed",
9
+ "QR login started": "log.qrLoginStarted",
10
+ "QR login succeeded": "log.qrLoginSucceeded",
11
+ "assistant message ended": "log.assistantMessageEnded",
12
+ "assistant message has no text": "log.assistantMessageNoText",
13
+ "attachment failure summary": "log.attachmentFailureSummary",
14
+ "attachments pending for instruction": "log.attachmentsPending",
15
+ "bubble split": "log.bubbleSplit",
16
+ "bubble split failed": "log.bubbleSplitFailed",
17
+ "cleared pending attachments for /new": "log.clearedPendingAttachments",
18
+ end: "log.toolEnd",
19
+ ended: "log.ended",
20
+ "error event": "log.botErrorEvent",
21
+ "failed to write upload index": "log.uploadIndexWriteFailed",
22
+ "inbound message": "log.inboundMessage",
23
+ "message handler rejected": "log.botHandlerRejected",
24
+ "message received": "log.messageReceived",
25
+ "no bound user; reply skipped": "log.noBoundUser",
26
+ "no injectable content after attachment handling": "log.noInjectableContent",
27
+ "passive send failed; retrying proactively": "log.passiveSendFailed",
28
+ "proactive retry failed": "log.proactiveRetryFailed",
29
+ "run ended": "log.runEnded",
30
+ "run started": "log.runStarted",
31
+ "saving attachments": "log.savingAttachments",
32
+ "sending reply": "log.sendingReply",
33
+ "sending text chunk": "log.sendingTextChunk",
34
+ "sent to pi": "log.sentToPi",
35
+ "shutting down": "log.shuttingDown",
36
+ "skipped non-allowlisted sender": "log.skippedSender",
37
+ "skipped non-c2c message": "log.skippedNonC2c",
38
+ start: "log.toolStart",
39
+ started: "log.sessionStarted",
40
+ starting: "log.botStarting",
41
+ "stream timing": "log.streamTiming",
42
+ "event loop delay": "log.eventLoopDelay",
43
+ "starting bot": "log.sessionStartingBot",
44
+ "starting bot after login failed": "log.startBotAfterLoginFailed",
45
+ "stream error": "log.streamError",
46
+ "stream reply failed; falling back to text": "log.streamReplyFallback",
47
+ "stream takeover decision": "log.streamTakeoverDecision",
48
+ "stream unavailable": "log.streamUnavailable",
49
+ "text chunk failed": "log.textChunkFailed",
50
+ "text chunk sent": "log.textChunkSent",
51
+ "unsupported message: no text and no attachments": "log.unsupportedMessage",
52
+ "voice ASR returned no text": "log.voiceNoText",
53
+ "voice ASR returned no text; using text content": "log.voiceNoTextUseContent",
54
+ "voice message": "log.voiceMessage",
55
+ "voice transcript": "log.voiceTranscript",
56
+ connected: "log.botConnected",
57
+ reconnecting: "log.botReconnecting",
58
+ stopped: "log.botStopped",
59
+ blocked: "log.botBlocked",
60
+ } as const;
61
+
62
+ export type LogMessageKey = (typeof LOG_MESSAGE_KEYS)[keyof typeof LOG_MESSAGE_KEYS];
63
+
64
+ export function logMessageKey(message: string): LogMessageKey | undefined {
65
+ return (LOG_MESSAGE_KEYS as Record<string, LogMessageKey>)[message];
66
+ }
@@ -41,13 +41,7 @@ export function parseWindowsBattery(output: string): PowerStatus | undefined {
41
41
  const percent = clampPercent(Number(battery.EstimatedChargeRemaining));
42
42
  const status = Number(battery.BatteryStatus);
43
43
  const state =
44
- status === 1 || status === 4 || status === 5
45
- ? "discharging"
46
- : status >= 6 && status <= 9
47
- ? "charging"
48
- : status === 2 || status === 3
49
- ? "ac"
50
- : "ac";
44
+ status === 1 || status === 4 || status === 5 ? "discharging" : status >= 6 && status <= 9 ? "charging" : "ac";
51
45
  return { percent, state };
52
46
  }
53
47
 
@@ -108,7 +102,3 @@ export function getPowerStatus(now = Date.now()): PowerStatus | undefined {
108
102
  cache = { at: now, value };
109
103
  return value;
110
104
  }
111
-
112
- export function resetPowerStatusCache(): void {
113
- cache = undefined;
114
- }
@@ -1,4 +1,4 @@
1
- export const REPLY_TYPES = ["full", "simple", "last"] as const;
1
+ const REPLY_TYPES = ["full", "simple"] as const;
2
2
 
3
3
  export type ReplyType = (typeof REPLY_TYPES)[number];
4
4
 
@@ -5,14 +5,14 @@ import { log } from "../infra/file-logger";
5
5
  import { t } from "../infra/i18n";
6
6
  import { isVoiceAttachment, resolveVoiceTranscript } from "../attachments/voice-transcript";
7
7
 
8
- export interface ResolveInboundOptions {
8
+ interface ResolveInboundOptions {
9
9
  contentText: string;
10
10
  maxSize: number;
11
11
  uploadDir: string;
12
12
  saveFiles: typeof saveInboundFiles;
13
13
  }
14
14
 
15
- export type ResolvedInbound =
15
+ type ResolvedInbound =
16
16
  | { status: "rejected"; reply: string }
17
17
  | {
18
18
  status: "resolved";
@@ -1,5 +1,4 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import type { ReplyType } from "../infra/reply-type";
3
2
  import { log } from "../infra/file-logger";
4
3
  import { t } from "../infra/i18n";
5
4
 
@@ -18,14 +17,17 @@ export interface InboundCommandDeps {
18
17
  ctx: InboundContext;
19
18
  getStatusLines: () => string[];
20
19
  getLastMessage?: () => string | undefined;
21
- getReplyType?: () => ReplyType;
22
20
  onStop?: () => void;
23
21
  waitForEnd?: () => Promise<void>;
24
22
  }
25
23
 
24
+ export interface InboundPushResult {
25
+ ok: boolean;
26
+ }
27
+
26
28
  export interface InboundCommandExtras {
27
29
  streamReply?: (text: string) => Promise<void>;
28
- restartPush?: () => void;
30
+ restartPush?: () => InboundPushResult;
29
31
  }
30
32
 
31
33
  export async function handleInboundCommand(
@@ -79,11 +81,10 @@ export async function handleInboundCommand(
79
81
  break;
80
82
  case "/last": {
81
83
  if (!deps.ctx.isIdle()) {
82
- if (deps.getReplyType?.() === "last") {
83
- await reply(t("commands.last.running"));
84
- break;
84
+ const result = extras.restartPush?.();
85
+ if (result && !result.ok) {
86
+ await reply(t("commands.last.empty"));
85
87
  }
86
- extras.restartPush?.();
87
88
  } else {
88
89
  const text = deps.getLastMessage?.();
89
90
  if (text) {
@@ -18,6 +18,7 @@ import { log } from "../infra/file-logger";
18
18
  import { t } from "../infra/i18n";
19
19
  import type { ReplyBudget } from "../quota/reply-quota";
20
20
  import { TEXT_CHUNK_LIMIT } from "./reply-sender";
21
+ import { sendWithMsgSeq } from "./msg-seq-send";
21
22
 
22
23
  export const MEDIA_TOOL_NAME = "qq_send_media";
23
24
 
@@ -48,7 +49,7 @@ export interface MediaToolDetails {
48
49
  total?: number;
49
50
  }
50
51
 
51
- export interface PreparedMedia {
52
+ interface PreparedMedia {
52
53
  path: string;
53
54
  fileType: MediaFileType;
54
55
  size: number;
@@ -56,7 +57,7 @@ export interface PreparedMedia {
56
57
  details: MediaToolDetails;
57
58
  }
58
59
 
59
- export interface MediaToolLogin {
60
+ interface MediaToolLogin {
60
61
  allowedOpenid: string;
61
62
  }
62
63
 
@@ -70,7 +71,6 @@ export interface MediaToolDeps {
70
71
  export interface MediaToolController {
71
72
  activate(): void;
72
73
  deactivate(): void;
73
- isActive(): boolean;
74
74
  }
75
75
 
76
76
  function mediaErrorMessage(err: unknown): Error {
@@ -298,14 +298,46 @@ function createTool(deps: MediaToolDeps): ToolDefinition<typeof mediaParams, Med
298
298
  captionLength: caption?.length ?? 0,
299
299
  });
300
300
 
301
- try {
302
- const message = await bot.mediaApi.sendMediaMessage("c2c", targetId, upload.file_info, bot.getCredentials(), {
303
- msgId,
304
- content: caption,
301
+ const sendMedia = (target: string, passiveMsgId?: string) =>
302
+ sendWithMsgSeq(bot, {
303
+ target: {
304
+ scope: "c2c",
305
+ targetId: target,
306
+ ...(passiveMsgId ? { msgId: passiveMsgId } : {}),
307
+ },
308
+ media: { file_info: upload.file_info },
309
+ ...(caption ? { content: caption } : {}),
305
310
  });
311
+ const buildResult = (
312
+ messageId: string,
313
+ mode: "passive" | "proactive",
314
+ elapsedMs: number,
315
+ ): { content: Array<{ type: "text"; text: string }>; details: MediaToolDetails } => ({
316
+ content: [
317
+ {
318
+ type: "text",
319
+ text: t("mediaTool.sent", {
320
+ kind: mediaKindLabel(prepared.fileType),
321
+ name: prepared.displayName,
322
+ mode: t(mode === "passive" ? "mediaTool.modePassive" : "mediaTool.modeProactive"),
323
+ }),
324
+ },
325
+ ],
326
+ details: {
327
+ ...prepared.details,
328
+ phase: "sent",
329
+ mode,
330
+ messageId,
331
+ fileUuid: upload.file_uuid,
332
+ ttlSec: upload.ttl,
333
+ elapsedMs,
334
+ },
335
+ });
336
+
337
+ try {
338
+ const message = await sendMedia(targetId, msgId);
306
339
  if (msgId) deps.budget.commitPassive(msgId);
307
340
  const elapsedMs = Date.now() - sendStartedAt;
308
- const mode = reply.mode === "passive" ? t("mediaTool.modePassive") : t("mediaTool.modeProactive");
309
341
  log.debug("media", "media tool", {
310
342
  phase: "send.done",
311
343
  toolCallId,
@@ -320,27 +352,7 @@ function createTool(deps: MediaToolDeps): ToolDefinition<typeof mediaParams, Med
320
352
  mode: reply.mode,
321
353
  messageId: message.id,
322
354
  });
323
- return {
324
- content: [
325
- {
326
- type: "text",
327
- text: t("mediaTool.sent", {
328
- kind: mediaKindLabel(prepared.fileType),
329
- name: prepared.displayName,
330
- mode,
331
- }),
332
- },
333
- ],
334
- details: {
335
- ...prepared.details,
336
- phase: "sent",
337
- mode: reply.mode,
338
- messageId: message.id,
339
- fileUuid: upload.file_uuid,
340
- ttlSec: upload.ttl,
341
- elapsedMs: Date.now() - startedAt,
342
- },
343
- };
355
+ return buildResult(message.id, reply.mode, Date.now() - startedAt);
344
356
  } catch (err) {
345
357
  if (!msgId) {
346
358
  log.warn("media", "media tool", { phase: "call.error", toolCallId, stage: "send", err });
@@ -360,16 +372,9 @@ function createTool(deps: MediaToolDeps): ToolDefinition<typeof mediaParams, Med
360
372
  });
361
373
 
362
374
  try {
363
- const message = await bot.mediaApi.sendMediaMessage(
364
- "c2c",
365
- login.allowedOpenid,
366
- upload.file_info,
367
- bot.getCredentials(),
368
- { content: caption },
369
- );
375
+ const message = await sendMedia(login.allowedOpenid);
370
376
  deps.onWarn(t("outbound.passiveFailed"));
371
377
  const elapsedMs = Date.now() - sendStartedAt;
372
- const mode = t("mediaTool.modeProactive");
373
378
  log.debug("media", "media tool", {
374
379
  phase: "send.done",
375
380
  toolCallId,
@@ -384,27 +389,7 @@ function createTool(deps: MediaToolDeps): ToolDefinition<typeof mediaParams, Med
384
389
  mode: "proactive",
385
390
  messageId: message.id,
386
391
  });
387
- return {
388
- content: [
389
- {
390
- type: "text",
391
- text: t("mediaTool.sent", {
392
- kind: mediaKindLabel(prepared.fileType),
393
- name: prepared.displayName,
394
- mode,
395
- }),
396
- },
397
- ],
398
- details: {
399
- ...prepared.details,
400
- phase: "sent",
401
- mode: "proactive",
402
- messageId: message.id,
403
- fileUuid: upload.file_uuid,
404
- ttlSec: upload.ttl,
405
- elapsedMs: Date.now() - startedAt,
406
- },
407
- };
392
+ return buildResult(message.id, "proactive", Date.now() - startedAt);
408
393
  } catch (retryErr) {
409
394
  log.warn("media", "media tool", {
410
395
  phase: "call.error",
@@ -451,8 +436,5 @@ export function registerMediaTool(pi: ExtensionAPI, deps: MediaToolDeps): MediaT
451
436
  activeCount: pi.getActiveTools().length,
452
437
  });
453
438
  },
454
- isActive() {
455
- return pi.getActiveTools().includes(MEDIA_TOOL_NAME);
456
- },
457
439
  };
458
440
  }
@@ -0,0 +1,11 @@
1
+ import type { QQBot, SendMessageOptions } from "@tencent-connect/qqbot-nodejs";
2
+ import { allocateMsgSeq } from "../relay/msg-seq";
3
+
4
+ export function sendWithMsgSeq(bot: QQBot, options: SendMessageOptions) {
5
+ const msgId = options.target.msgId;
6
+ if (!msgId) return bot.send(options);
7
+ return bot.send({
8
+ ...options,
9
+ extra: { ...options.extra, msg_seq: allocateMsgSeq(msgId) },
10
+ });
11
+ }
package/src/qq/qq-bot.ts CHANGED
@@ -13,7 +13,7 @@ import { t } from "../infra/i18n";
13
13
 
14
14
  export type BotState = "stopped" | "starting" | "connected" | "reconnecting" | "blocked";
15
15
 
16
- export interface StartBotOptions {
16
+ interface StartBotOptions {
17
17
  credentials: Credentials;
18
18
  allowedOpenid: string;
19
19
  onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
@@ -5,8 +5,9 @@ import { AppendStream } from "../relay/stream-session";
5
5
  import type { RunningBot } from "./qq-bot";
6
6
  import { t } from "../infra/i18n";
7
7
  import { thinkingHeader } from "../relay/stream-block-format";
8
+ import { sendWithMsgSeq } from "./msg-seq-send";
8
9
 
9
- export interface QQDiagnosticsDeps {
10
+ interface QQDiagnosticsDeps {
10
11
  getRunning: () => RunningBot | undefined;
11
12
  budget: ReplyBudget;
12
13
  getBoundOpenid: () => string | undefined;
@@ -42,7 +43,7 @@ export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps)
42
43
  }
43
44
  const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
44
45
  try {
45
- await running.bot.sendMarkdown(target, content);
46
+ await sendWithMsgSeq(running.bot, { target, markdown: { content } });
46
47
  ctx.ui.notify(t("diagnostics.mdSent"), "info");
47
48
  } catch (err) {
48
49
  ctx.ui.notify(t("diagnostics.mdFailed", { message: (err as Error).message }), "error");