@tencent-connect/qqbot-nodejs 1.0.4 → 1.0.6

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.
Files changed (65) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -86
  4. package/README.zh-CN.md +293 -0
  5. package/USAGE.md +80 -27
  6. package/assets/docs/feedback.jpg +0 -0
  7. package/assets/docs/qqchannel.jpg +0 -0
  8. package/dist/QQBot.d.ts +66 -3
  9. package/dist/QQBot.d.ts.map +1 -1
  10. package/dist/QQBot.js +144 -33
  11. package/dist/QQBot.js.map +1 -1
  12. package/dist/index.d.ts +4 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +2 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/protocol/api/token.d.ts.map +1 -1
  17. package/dist/protocol/api/token.js +6 -2
  18. package/dist/protocol/api/token.js.map +1 -1
  19. package/dist/protocol/gateway/constants.d.ts +6 -1
  20. package/dist/protocol/gateway/constants.d.ts.map +1 -1
  21. package/dist/protocol/gateway/constants.js +6 -1
  22. package/dist/protocol/gateway/constants.js.map +1 -1
  23. package/dist/protocol/gateway/errors.d.ts +22 -0
  24. package/dist/protocol/gateway/errors.d.ts.map +1 -0
  25. package/dist/protocol/gateway/errors.js +24 -0
  26. package/dist/protocol/gateway/errors.js.map +1 -0
  27. package/dist/protocol/gateway/event-dispatcher.d.ts +22 -0
  28. package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -1
  29. package/dist/protocol/gateway/event-dispatcher.js +17 -0
  30. package/dist/protocol/gateway/event-dispatcher.js.map +1 -1
  31. package/dist/protocol/gateway/gateway-connection.d.ts +69 -4
  32. package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -1
  33. package/dist/protocol/gateway/gateway-connection.js +349 -146
  34. package/dist/protocol/gateway/gateway-connection.js.map +1 -1
  35. package/dist/protocol/gateway/reconnect.d.ts +24 -1
  36. package/dist/protocol/gateway/reconnect.d.ts.map +1 -1
  37. package/dist/protocol/gateway/reconnect.js +56 -9
  38. package/dist/protocol/gateway/reconnect.js.map +1 -1
  39. package/dist/protocol/index.d.ts +5 -4
  40. package/dist/protocol/index.d.ts.map +1 -1
  41. package/dist/protocol/index.js +3 -2
  42. package/dist/protocol/index.js.map +1 -1
  43. package/dist/protocol/types.d.ts +49 -10
  44. package/dist/protocol/types.d.ts.map +1 -1
  45. package/dist/protocol/types.js.map +1 -1
  46. package/dist/protocol/utils/file-utils.d.ts +2 -2
  47. package/dist/protocol/utils/file-utils.js +2 -2
  48. package/dist/protocol/utils/image-size.d.ts +3 -3
  49. package/dist/protocol/utils/image-size.js +3 -3
  50. package/dist/protocol/utils/ref-index-store.d.ts +1 -1
  51. package/dist/protocol/utils/ref-index-store.js +1 -1
  52. package/package.json +24 -7
  53. package/src/QQBot.ts +173 -36
  54. package/src/index.ts +6 -0
  55. package/src/protocol/api/token.ts +6 -2
  56. package/src/protocol/gateway/constants.ts +6 -1
  57. package/src/protocol/gateway/errors.ts +32 -0
  58. package/src/protocol/gateway/event-dispatcher.ts +41 -0
  59. package/src/protocol/gateway/gateway-connection.ts +389 -160
  60. package/src/protocol/gateway/reconnect.ts +76 -10
  61. package/src/protocol/index.ts +11 -1
  62. package/src/protocol/types.ts +46 -10
  63. package/src/protocol/utils/file-utils.ts +2 -2
  64. package/src/protocol/utils/image-size.ts +3 -3
  65. package/src/protocol/utils/ref-index-store.ts +1 -1
package/src/QQBot.ts CHANGED
@@ -35,8 +35,13 @@ import { ChunkedMediaApi } from "./protocol/api/media-chunked.js";
35
35
  import { MediaApi } from "./protocol/api/media.js";
36
36
  import { MessageApi } from "./protocol/api/messages.js";
37
37
  import { TokenManager } from "./protocol/api/token.js";
38
- import { GatewayConnection, type SessionPersistencePort } from "./protocol/gateway/gateway-connection.js";
38
+ import {
39
+ GatewayConnection,
40
+ type GatewayDisconnect,
41
+ type SessionPersistencePort,
42
+ } from "./protocol/gateway/gateway-connection.js";
39
43
  import type { InboundMessage } from "./protocol/gateway/event-dispatcher.js";
44
+ import { resolveReconnectPolicy, type ReconnectPolicy } from "./protocol/gateway/reconnect.js";
40
45
  import { WebhookTransport } from "./protocol/transport/webhook.js";
41
46
  import type { EventTransport, WebhookServerAdapter } from "./protocol/transport/types.js";
42
47
  import {
@@ -145,6 +150,13 @@ export interface QQBotOptions {
145
150
  sessionPersistence?: SessionPersistencePort;
146
151
  /** Custom intent mask. Defaults to FULL_INTENTS (group + c2c + interaction). */
147
152
  intents?: number;
153
+ /**
154
+ * WebSocket reconnect budget. `maxAttempts` defaults to `Infinity` (retry
155
+ * forever). When a finite budget is exhausted, `start()` rejects with a
156
+ * `GatewayError` (`GATEWAY_RETRY_EXHAUSTED`) — set one when an outer
157
+ * supervisor restarts the bot.
158
+ */
159
+ reconnect?: Partial<ReconnectPolicy>;
148
160
  /** Override the upload cache. Defaults to a private in-memory cache. */
149
161
  uploadCache?: UploadCache;
150
162
 
@@ -207,6 +219,9 @@ export interface RawEventContext {
207
219
  export type QQBotEventMap = {
208
220
  ready: (data: unknown) => void;
209
221
  resumed: (data: unknown) => void;
222
+ disconnected: (event: GatewayDisconnect) => void;
223
+ /** Transport connection state transition (`connectionState` is the same value, readable at any time). */
224
+ connection: (state: ConnectionState, previous: ConnectionState) => void;
210
225
  error: (err: Error) => void;
211
226
  message: (ctx: MiddlewareContext, msg: QQBotInboundMessage) => void | Promise<void>;
212
227
  interaction: (ctx: InteractionContext, event: InteractionEvent) => void | Promise<void>;
@@ -230,6 +245,22 @@ export type QQBotEventMap = {
230
245
  rawEvent: (ctx: RawEventContext) => void | Promise<void>;
231
246
  };
232
247
 
248
+ /**
249
+ * Transport connection state, readable at any time via
250
+ * {@link QQBot.connectionState} without subscribing to events.
251
+ *
252
+ * - `idle`: never started, or stopped.
253
+ * - `connecting`: startup (IDENTIFY) or an automatic reconnect is in progress.
254
+ * - `resuming`: a reconnect is recovering the previous session via RESUME.
255
+ * - `connected`: the WS gateway completed READY/RESUMED, or the webhook
256
+ * server is listening.
257
+ * - `disconnected`: startup failed, or the gateway gave up reconnecting.
258
+ *
259
+ * Custom `EventTransport` implementations have no ready signal, so they stay
260
+ * `connecting` until the run ends.
261
+ */
262
+ export type ConnectionState = "idle" | "connecting" | "resuming" | "connected" | "disconnected";
263
+
233
264
  /**
234
265
  * Augmented inbound message with a ready-to-use `replyTarget`.
235
266
  */
@@ -272,6 +303,8 @@ export class QQBot {
272
303
  private readonly handlers: { [K in keyof QQBotEventMap]: Set<QQBotEventMap[K]> } = {
273
304
  ready: new Set(),
274
305
  resumed: new Set(),
306
+ disconnected: new Set(),
307
+ connection: new Set(),
275
308
  error: new Set(),
276
309
  message: new Set(),
277
310
  interaction: new Set(),
@@ -280,6 +313,12 @@ export class QQBot {
280
313
 
281
314
  private gateway: GatewayConnection | null = null;
282
315
  private abortController: AbortController | null = null;
316
+ /** Mutated only by the start/stop lifecycle and the transport callbacks. */
317
+ private _connectionState: ConnectionState = "idle";
318
+ /** Last heartbeat ACK latency in ms; -1 before the first ACK of the current run. */
319
+ private _ping = -1;
320
+ /** Timestamp of the last heartbeat ACK; undefined until the first ACK of the current run. */
321
+ private _lastHeartbeatAt: number | undefined;
283
322
  private _apiGateway: ApiGateway | null = null;
284
323
 
285
324
  constructor(options: QQBotOptions) {
@@ -289,6 +328,7 @@ export class QQBot {
289
328
  if (!options.appSecret) {
290
329
  throw new Error("QQBot: appSecret is required");
291
330
  }
331
+ resolveReconnectPolicy(options.reconnect); // fail fast on an invalid budget
292
332
  this.opts = options;
293
333
  this.logger = options.logger ?? noopLogger;
294
334
  this.userAgent = options.userAgent ?? `qqbot-nodejs/0.1.0 (Node/${process.versions.node})`;
@@ -363,11 +403,42 @@ export class QQBot {
363
403
  return this.creds.appId;
364
404
  }
365
405
 
406
+ /**
407
+ * Current transport connection state. Read it any time instead of tracking
408
+ * `ready` / `resumed` / `disconnected` yourself.
409
+ */
410
+ get connectionState(): ConnectionState {
411
+ return this._connectionState;
412
+ }
413
+
414
+ /** Last heartbeat ACK latency in milliseconds, or `-1` before the first ACK. */
415
+ get ping(): number {
416
+ return this._ping;
417
+ }
418
+
419
+ /** Last heartbeat ACK timestamp (epoch ms), or `undefined` before the first ACK. */
420
+ get lastHeartbeatAt(): number | undefined {
421
+ return this._lastHeartbeatAt;
422
+ }
423
+
366
424
  /** The stable account id (defaults to appId). */
367
425
  get accountId(): string {
368
426
  return this.account.accountId;
369
427
  }
370
428
 
429
+ /**
430
+ * Return a read-only snapshot of the credentials this bot was constructed
431
+ * with. Prefer this over reaching into private fields when you need to
432
+ * call into the raw protocol-layer APIs (`bot.messageApi`, `bot.mediaApi`,
433
+ * ...) that require a `Credentials` argument.
434
+ *
435
+ * The returned object is a shallow copy; mutating it does NOT affect the
436
+ * bot instance.
437
+ */
438
+ getCredentials(): Credentials {
439
+ return { appId: this.creds.appId, clientSecret: this.creds.clientSecret };
440
+ }
441
+
371
442
  // ============ Event listeners ============
372
443
 
373
444
  on<K extends keyof QQBotEventMap>(event: K, handler: QQBotEventMap[K]): this {
@@ -435,43 +506,72 @@ export class QQBot {
435
506
  * - **Webhook mode**: starts an HTTP server to receive POST callbacks.
436
507
  *
437
508
  * Resolves when {@link stop} or the abort signal terminates the connection.
509
+ * Rejects when startup fails, or — in WebSocket mode — with a `GatewayError`
510
+ * when a finite `reconnect.maxAttempts` is exhausted (`GATEWAY_RETRY_EXHAUSTED`) or the
511
+ * gateway closes with a non-retryable code (`GATEWAY_FATAL_CLOSE`). Resources
512
+ * are released either way, so the bot can be started again.
438
513
  */
439
514
  async start(externalSignal?: AbortSignal): Promise<void> {
440
- if (this.gateway) {
441
- throw new Error("QQBot: already started");
515
+ if (this.abortController) throw new Error("QQBot: already started");
516
+ // The controller doubles as the run's ownership token: only the run that
517
+ // still owns it may reset shared state (see stop()).
518
+ const controller = new AbortController();
519
+ this.abortController = controller;
520
+ const onAbort = () => controller.abort();
521
+ if (externalSignal?.aborted) {
522
+ controller.abort();
523
+ } else {
524
+ externalSignal?.addEventListener("abort", onAbort, { once: true });
442
525
  }
443
- this.abortController = new AbortController();
444
- if (externalSignal) {
445
- if (externalSignal.aborted) {
446
- this.abortController.abort();
526
+
527
+ this.setConnectionState("connecting");
528
+ this._ping = -1;
529
+ this._lastHeartbeatAt = undefined;
530
+ try {
531
+ if (controller.signal.aborted) return;
532
+ const transportMode = this.opts.transport ?? "websocket";
533
+ if (transportMode === "webhook") {
534
+ await this.startWebhook(controller.signal);
535
+ } else if (transportMode === "websocket") {
536
+ await this.startWebSocket(controller.signal);
447
537
  } else {
448
- externalSignal.addEventListener("abort", () => this.abortController?.abort(), {
449
- once: true,
450
- });
538
+ await this.startCustomTransport(transportMode, controller.signal);
539
+ }
540
+ } catch (error) {
541
+ // 启动失败是终态:留给 stop()/下一次 start() 重置
542
+ this.setConnectionState("disconnected");
543
+ throw error;
544
+ } finally {
545
+ externalSignal?.removeEventListener("abort", onAbort);
546
+ if (this.abortController === controller) {
547
+ this.releaseRun();
548
+ // 正常结束(stop/abort)回到 idle;保留启动失败留下的 disconnected
549
+ if (this._connectionState !== "disconnected") this.setConnectionState("idle");
451
550
  }
452
551
  }
552
+ }
453
553
 
454
- const transportMode = this.opts.transport ?? "websocket";
455
-
456
- if (transportMode === "webhook") {
457
- await this.startWebhook();
458
- } else if (transportMode === "websocket") {
459
- await this.startWebSocket();
460
- } else {
461
- // Custom EventTransport instance
462
- const custom = transportMode as EventTransport;
463
- await custom.start();
464
- }
554
+ /**
555
+ * Stop the transport and background refreshers.
556
+ *
557
+ * Ownership is released synchronously, so `start()` may be called again
558
+ * right away; the previous `start()` promise still resolves on its own.
559
+ */
560
+ stop(): void {
561
+ const controller = this.abortController;
562
+ this.releaseRun();
563
+ this.setConnectionState("idle");
564
+ controller?.abort();
565
+ }
465
566
 
466
- // Cleanup
467
- this.tokenManager.stopBackgroundRefresh(this.creds.appId);
468
- this.gateway = null;
469
- this.abortController = null;
567
+ private setConnectionState(state: ConnectionState): void {
568
+ if (this._connectionState === state) return;
569
+ const previous = this._connectionState;
570
+ this._connectionState = state;
571
+ void this.emit("connection", state, previous);
470
572
  }
471
573
 
472
- /** Stop the transport and background refreshers. */
473
- stop(): void {
474
- this.abortController?.abort();
574
+ private releaseRun(): void {
475
575
  this.tokenManager.stopBackgroundRefresh(this.creds.appId);
476
576
  this.gateway = null;
477
577
  this.abortController = null;
@@ -487,7 +587,7 @@ export class QQBot {
487
587
  * - `"async"`: fires the token fetch in the background and starts the
488
588
  * background refresher immediately — trades fail-fast for faster startup.
489
589
  */
490
- private async initToken(): Promise<void> {
590
+ private async initToken(signal: AbortSignal): Promise<void> {
491
591
  const mode = this.opts.tokenPrefetch ?? "sync";
492
592
 
493
593
  if (mode === "sync") {
@@ -500,36 +600,58 @@ export class QQBot {
500
600
  });
501
601
  }
502
602
 
503
- this.tokenManager.startBackgroundRefresh(this.creds.appId, this.creds.clientSecret);
603
+ if (!signal.aborted) this.tokenManager.startBackgroundRefresh(this.creds.appId, this.creds.clientSecret);
504
604
  }
505
605
 
506
606
  // ============ Transport: WebSocket ============
507
607
 
508
- private async startWebSocket(): Promise<void> {
509
- await this.initToken();
608
+ private async startWebSocket(signal: AbortSignal): Promise<void> {
609
+ await this.initToken(signal);
610
+ if (signal.aborted) return;
510
611
 
511
612
  this.gateway = new GatewayConnection({
512
613
  account: this.account,
513
- abortSignal: this.abortController!.signal,
614
+ abortSignal: signal,
514
615
  log: this.logger,
515
616
  userAgent: this.userAgent,
516
617
  intents: this.opts.intents,
618
+ reconnect: this.opts.reconnect,
517
619
  session: this.opts.sessionPersistence,
518
620
  getAccessToken: () =>
519
621
  this.tokenManager.getAccessToken(this.creds.appId, this.creds.clientSecret),
520
622
  clearTokenCache: () => this.tokenManager.clearCache(this.creds.appId),
521
623
  getGatewayUrl: () => this.messageApi.getGatewayUrl(this.creds),
522
624
  onReady: (data) => {
625
+ this.setConnectionState("connected");
523
626
  this.logger.info?.(`[qqbot] gateway READY`);
524
627
  void this.emit("ready", data);
525
628
  },
526
629
  onResumed: (data) => {
630
+ this.setConnectionState("connected");
527
631
  this.logger.info?.(`[qqbot] gateway RESUMED`);
528
632
  void this.emit("resumed", data);
529
633
  },
634
+ onResuming: () => {
635
+ this.setConnectionState("resuming");
636
+ this.logger.debug?.(`[qqbot] gateway resuming session`);
637
+ },
638
+ onIdentifying: () => {
639
+ // RESUME 被拒(session 失效)后重新 IDENTIFY:从 resuming 回到 connecting
640
+ this.setConnectionState("connecting");
641
+ this.logger.debug?.(`[qqbot] gateway identifying`);
642
+ },
643
+ onHeartbeat: (latencyMs) => {
644
+ this._ping = latencyMs;
645
+ this._lastHeartbeatAt = Date.now();
646
+ },
530
647
  onError: (err) => {
531
648
  void this.emit("error", err);
532
649
  },
650
+ onDisconnected: (event) => {
651
+ // 自动重连期间保持 connecting;willReconnect=false 表示不再恢复
652
+ this.setConnectionState(event.willReconnect ? "connecting" : "disconnected");
653
+ void this.emit("disconnected", event);
654
+ },
533
655
  onMessage: (raw) => this.handleInboundMessage(raw),
534
656
  onInteraction: (event) => {
535
657
  const ctx: InteractionContext = { bot: this, event, state: {}, receivedAt: Date.now() };
@@ -546,8 +668,9 @@ export class QQBot {
546
668
 
547
669
  // ============ Transport: Webhook ============
548
670
 
549
- private async startWebhook(): Promise<void> {
550
- await this.initToken();
671
+ private async startWebhook(signal: AbortSignal): Promise<void> {
672
+ await this.initToken(signal);
673
+ if (signal.aborted) return;
551
674
 
552
675
  const webhook = new WebhookTransport(
553
676
  {
@@ -558,14 +681,16 @@ export class QQBot {
558
681
  server: this.opts.webhook?.server,
559
682
  accountId: this.account.accountId,
560
683
  log: this.logger,
561
- abortSignal: this.abortController!.signal,
684
+ abortSignal: signal,
562
685
  },
563
686
  {
564
687
  onReady: (data) => {
688
+ this.setConnectionState("connected");
565
689
  this.logger.info?.(`[qqbot] webhook READY`);
566
690
  void this.emit("ready", data);
567
691
  },
568
692
  onResumed: (data) => {
693
+ this.setConnectionState("connected");
569
694
  void this.emit("resumed", data);
570
695
  },
571
696
  onError: (err) => {
@@ -582,6 +707,18 @@ export class QQBot {
582
707
  await webhook.start();
583
708
  }
584
709
 
710
+ // ============ Transport: custom ============
711
+
712
+ private async startCustomTransport(transport: EventTransport, signal: AbortSignal): Promise<void> {
713
+ const onAbort = () => transport.stop();
714
+ signal.addEventListener("abort", onAbort, { once: true });
715
+ try {
716
+ await transport.start();
717
+ } finally {
718
+ signal.removeEventListener("abort", onAbort);
719
+ }
720
+ }
721
+
585
722
  // ============ Shared inbound message handler ============
586
723
 
587
724
  private async handleInboundMessage(raw: InboundMessage): Promise<void> {
package/src/index.ts CHANGED
@@ -34,6 +34,7 @@
34
34
  export { QQBot } from "./QQBot.js";
35
35
  export { MsgType } from "./QQBot.js";
36
36
  export type {
37
+ ConnectionState,
37
38
  QQBotOptions,
38
39
  QQBotEventMap,
39
40
  QQBotInboundMessage,
@@ -152,6 +153,11 @@ export {
152
153
 
153
154
  export type { InboundMessage } from "./protocol/gateway/event-dispatcher.js";
154
155
 
156
+ // Gateway lifecycle: `start()` rejects with GatewayError; `disconnected` carries GatewayDisconnect.
157
+ export { GatewayError, GatewayErrorCode } from "./protocol/gateway/errors.js";
158
+ export type { GatewayDisconnect } from "./protocol/gateway/gateway-connection.js";
159
+ export type { ReconnectPolicy } from "./protocol/gateway/reconnect.js";
160
+
155
161
  export type {
156
162
  WebhookRequest,
157
163
  WebhookResponse,
@@ -151,12 +151,16 @@ export class TokenManager {
151
151
  }
152
152
  }
153
153
 
154
- this.refreshControllers.delete(appId);
154
+ // Only release the slot we own: a stop→start cycle may already have
155
+ // registered a replacement loop for the same appId.
156
+ if (this.refreshControllers.get(appId) === controller) {
157
+ this.refreshControllers.delete(appId);
158
+ }
155
159
  this.logger?.info?.(`[qqbot:token:${appId}] Background refresh stopped`);
156
160
  };
157
161
 
158
162
  loop().catch((err) => {
159
- if (this.refreshControllers.has(appId)) {
163
+ if (this.refreshControllers.get(appId) === controller) {
160
164
  this.refreshControllers.delete(appId);
161
165
  this.logger?.error?.(
162
166
  `[qqbot:token:${appId}] Background refresh crashed: ${formatErrorMessage(err)}`,
@@ -25,9 +25,14 @@ export const FULL_INTENTS =
25
25
 
26
26
  export const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 30000, 60000] as const;
27
27
  export const RATE_LIMIT_DELAY = 60000;
28
- export const MAX_RECONNECT_ATTEMPTS = 100;
28
+ /** Default reconnect budget: unlimited. Set `reconnect.maxAttempts` to bound it. */
29
+ export const MAX_RECONNECT_ATTEMPTS = Number.POSITIVE_INFINITY;
29
30
  export const MAX_QUICK_DISCONNECT_COUNT = 3;
30
31
  export const QUICK_DISCONNECT_THRESHOLD = 5000;
32
+ /** Delay before reconnecting after opcode 9 (INVALID_SESSION). */
33
+ export const INVALID_SESSION_DELAY = 3000;
34
+ /** Default WebSocket upgrade timeout; bounds black-holed handshakes. */
35
+ export const HANDSHAKE_TIMEOUT_MS = 30_000;
31
36
 
32
37
  /** Gateway opcodes used by the QQ Bot WebSocket protocol. */
33
38
  export const GatewayOp = {
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Terminal gateway errors — the reasons a {@link GatewayConnection} stops
3
+ * retrying and rejects its `start()` promise.
4
+ */
5
+
6
+ /** Stable error codes. Match on `code` rather than `instanceof` across module copies. */
7
+ export const GatewayErrorCode = {
8
+ /** A finite `reconnect.maxAttempts` was exhausted (never raised with the unlimited default). */
9
+ RETRY_EXHAUSTED: "GATEWAY_RETRY_EXHAUSTED",
10
+ /** Non-retryable close (4914 offline/sandbox-only, 4915 banned). Needs operator action. */
11
+ FATAL_CLOSE: "GATEWAY_FATAL_CLOSE",
12
+ } as const;
13
+ export type GatewayErrorCode = (typeof GatewayErrorCode)[keyof typeof GatewayErrorCode];
14
+
15
+ /** Error used to reject `GatewayConnection.start()` / `QQBot.start()`. */
16
+ export class GatewayError extends Error {
17
+ readonly code: GatewayErrorCode;
18
+ /** Remote WebSocket close code that caused the failure, when known. */
19
+ readonly closeCode?: number;
20
+
21
+ constructor(
22
+ message: string,
23
+ code: GatewayErrorCode,
24
+ closeCode?: number,
25
+ options?: { cause?: unknown },
26
+ ) {
27
+ super(message, options);
28
+ this.name = "GatewayError";
29
+ this.code = code;
30
+ this.closeCode = closeCode;
31
+ }
32
+ }
@@ -28,6 +28,8 @@ export interface InboundAttachment {
28
28
  voice_wav_url?: string;
29
29
  /** ASR transcription text for voice messages (QQ built-in speech recognition). */
30
30
  asr_refer_text?: string;
31
+ /** Platform-added fields not declared here. */
32
+ [key: string]: unknown;
31
33
  }
32
34
 
33
35
  /** One element from the `msg_elements` array pushed by QQ. */
@@ -42,15 +44,36 @@ export interface InboundMsgElement {
42
44
 
43
45
  // ============ Inbound message ============
44
46
 
47
+ /**
48
+ * Normalized message author — a closed domain model.
49
+ *
50
+ * New sender-related platform fields are mapped here (not as new top-level
51
+ * `InboundMessage` fields), so `keyof InboundAuthor` stays precise and
52
+ * consumers read one nested object instead of a growing flat list.
53
+ */
54
+ export interface InboundAuthor {
55
+ /** Stable sender id (openid; the scope depends on `InboundMessage.kind`). */
56
+ id: string;
57
+ name?: string;
58
+ /** Sender avatar URL when the platform provides one. */
59
+ avatar?: string;
60
+ isBot?: boolean;
61
+ }
62
+
45
63
  /** Inbound message envelope normalised across C2C / Group / Guild scopes. */
46
64
  export interface InboundMessage {
47
65
  /** Raw event type from the gateway. */
48
66
  rawEventType: string;
49
67
  /** Conversation kind. */
50
68
  kind: "c2c" | "group" | "guild" | "dm";
69
+ /** @deprecated Use `author.id`. */
51
70
  senderId: string;
71
+ /** @deprecated Use `author.name`. */
52
72
  senderName?: string;
73
+ /** @deprecated Use `author.isBot`. */
53
74
  senderIsBot?: boolean;
75
+ /** Normalized sender; new sender-related platform fields land here. */
76
+ author: InboundAuthor;
54
77
  content: string;
55
78
  messageId: string;
56
79
  timestamp: string;
@@ -102,6 +125,15 @@ interface Refs {
102
125
 
103
126
  const REF_INDEX_KEY = "msg_idx";
104
127
 
128
+ /**
129
+ * Read the sender avatar, an additive platform field that SDK types only
130
+ * recently declared. Missing or malformed values stay undefined so callers
131
+ * never have to guard the raw event themselves.
132
+ */
133
+ function readAvatar(author: { avatar?: unknown }): string | undefined {
134
+ return typeof author.avatar === "string" && author.avatar !== "" ? author.avatar : undefined;
135
+ }
136
+
105
137
  /**
106
138
  * Parse `ref_idx` and `msg_idx` from message_scene.ext + msg_elements.
107
139
  */
@@ -171,6 +203,7 @@ export function dispatchEvent(
171
203
  rawEventType: eventType,
172
204
  kind: "c2c",
173
205
  senderId: ev.author.user_openid,
206
+ author: { id: ev.author.user_openid, avatar: readAvatar(ev.author) },
174
207
  content: ev.content,
175
208
  messageId: ev.id,
176
209
  timestamp: ev.timestamp,
@@ -197,6 +230,7 @@ export function dispatchEvent(
197
230
  kind: "guild",
198
231
  senderId: ev.author.id,
199
232
  senderName: ev.author.username,
233
+ author: { id: ev.author.id, name: ev.author.username, avatar: readAvatar(ev.author) },
200
234
  content: ev.content,
201
235
  messageId: ev.id,
202
236
  timestamp: ev.timestamp,
@@ -222,6 +256,7 @@ export function dispatchEvent(
222
256
  kind: "dm",
223
257
  senderId: ev.author.id,
224
258
  senderName: ev.author.username,
259
+ author: { id: ev.author.id, name: ev.author.username, avatar: readAvatar(ev.author) },
225
260
  content: ev.content,
226
261
  messageId: ev.id,
227
262
  timestamp: ev.timestamp,
@@ -248,6 +283,12 @@ export function dispatchEvent(
248
283
  senderId: ev.author.member_openid,
249
284
  senderName: ev.author.username,
250
285
  senderIsBot: ev.author.bot,
286
+ author: {
287
+ id: ev.author.member_openid,
288
+ name: ev.author.username,
289
+ isBot: ev.author.bot,
290
+ avatar: readAvatar(ev.author),
291
+ },
251
292
  content: ev.content,
252
293
  messageId: ev.id,
253
294
  timestamp: ev.timestamp,