@zhin.js/adapter-weixin-ilink 1.0.1 → 1.1.2

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 (189) hide show
  1. package/CHANGELOG.md +512 -0
  2. package/README.md +24 -42
  3. package/adapters/weixin-ilink/index.js +32 -0
  4. package/adapters/weixin-ilink/index.ts +43 -0
  5. package/commands/weixin-ilink/endpoint/add/[id]/index.js +3 -0
  6. package/commands/weixin-ilink/endpoint/add/[id]/index.ts +3 -0
  7. package/commands/weixin-ilink/endpoint/definition.js +17 -0
  8. package/commands/weixin-ilink/endpoint/definition.ts +17 -0
  9. package/commands/weixin-ilink/endpoint/list/index.js +3 -0
  10. package/commands/weixin-ilink/endpoint/list/index.ts +3 -0
  11. package/commands/weixin-ilink/endpoint/remove/[id]/index.js +3 -0
  12. package/commands/weixin-ilink/endpoint/remove/[id]/index.ts +3 -0
  13. package/lib/aes-ecb.d.ts +0 -1
  14. package/lib/aes-ecb.js +0 -1
  15. package/lib/cdn-upload.d.ts +0 -1
  16. package/lib/cdn-upload.js +0 -1
  17. package/lib/cdn-url.d.ts +0 -1
  18. package/lib/cdn-url.js +0 -1
  19. package/lib/client.d.ts +35 -0
  20. package/lib/client.js +89 -0
  21. package/lib/context-store.d.ts +15 -2
  22. package/lib/context-store.js +93 -2
  23. package/lib/credentials.d.ts +15 -8
  24. package/lib/credentials.js +59 -43
  25. package/lib/endpoint.d.ts +40 -35
  26. package/lib/endpoint.js +311 -262
  27. package/lib/ilink-api.d.ts +7 -6
  28. package/lib/ilink-api.js +26 -16
  29. package/lib/ilink-config-cache.d.ts +3 -8
  30. package/lib/ilink-config-cache.js +13 -15
  31. package/lib/ilink-logger.d.ts +0 -2
  32. package/lib/ilink-logger.js +11 -26
  33. package/lib/ilink-meta.d.ts +13 -8
  34. package/lib/ilink-meta.js +24 -21
  35. package/lib/ilink-random.d.ts +0 -1
  36. package/lib/ilink-random.js +0 -1
  37. package/lib/ilink-redact.d.ts +0 -1
  38. package/lib/ilink-redact.js +0 -1
  39. package/lib/ilink-session-guard.d.ts +13 -15
  40. package/lib/ilink-session-guard.js +29 -43
  41. package/lib/ilink-types.d.ts +0 -1
  42. package/lib/ilink-types.js +0 -1
  43. package/lib/index.d.ts +8 -20
  44. package/lib/index.js +7 -38
  45. package/lib/login.d.ts +5 -6
  46. package/lib/login.js +85 -77
  47. package/lib/media-download.d.ts +1 -2
  48. package/lib/media-download.js +1 -2
  49. package/lib/mime.d.ts +0 -1
  50. package/lib/mime.js +0 -1
  51. package/lib/outbound-media.d.ts +4 -5
  52. package/lib/outbound-media.js +85 -86
  53. package/lib/pic-decrypt.d.ts +0 -1
  54. package/lib/pic-decrypt.js +0 -1
  55. package/lib/protocol.d.ts +60 -0
  56. package/lib/protocol.js +127 -0
  57. package/lib/silk-transcode.d.ts +0 -1
  58. package/lib/silk-transcode.js +0 -1
  59. package/lib/types.d.ts +2 -26
  60. package/lib/types.js +0 -1
  61. package/lib/upload.d.ts +1 -2
  62. package/lib/upload.js +1 -2
  63. package/lib/weixin-ilink-runtime-state.d.ts +1 -0
  64. package/lib/weixin-ilink-runtime-state.js +6 -0
  65. package/lib/weixin-inbound.d.ts +4 -43
  66. package/lib/weixin-inbound.js +22 -162
  67. package/lib/weixin-send-media.d.ts +0 -1
  68. package/lib/weixin-send-media.js +5 -2
  69. package/lib/weixin-send.d.ts +1 -2
  70. package/lib/weixin-send.js +4 -3
  71. package/package.json +48 -39
  72. package/plugin.js +14 -0
  73. package/schema.json +116 -0
  74. package/src/client.ts +117 -0
  75. package/src/context-store.ts +101 -8
  76. package/src/credentials.ts +68 -45
  77. package/src/endpoint.ts +384 -315
  78. package/src/ilink-api.ts +31 -21
  79. package/src/ilink-config-cache.ts +17 -13
  80. package/src/ilink-logger.ts +11 -26
  81. package/src/ilink-meta.ts +31 -21
  82. package/src/ilink-session-guard.ts +29 -46
  83. package/src/index.ts +41 -56
  84. package/src/login.ts +112 -85
  85. package/src/media-download.ts +1 -2
  86. package/src/outbound-media.ts +97 -97
  87. package/src/protocol.ts +180 -0
  88. package/src/silk-wasm.d.ts +6 -2
  89. package/src/types.ts +5 -25
  90. package/src/upload.test.ts +11 -8
  91. package/src/upload.ts +2 -2
  92. package/src/weixin-ilink-runtime-state.ts +7 -0
  93. package/src/weixin-inbound.ts +25 -187
  94. package/src/weixin-send-media.ts +5 -1
  95. package/src/weixin-send.ts +6 -4
  96. package/client/LoginAssistPanel.tsx +0 -200
  97. package/client/WeixinIlinkManagement.tsx +0 -139
  98. package/client/index.tsx +0 -11
  99. package/client/tsconfig.json +0 -13
  100. package/client/utils/api.ts +0 -30
  101. package/dist/index.js +0 -29
  102. package/lib/adapter.d.ts +0 -12
  103. package/lib/adapter.d.ts.map +0 -1
  104. package/lib/adapter.js +0 -15
  105. package/lib/adapter.js.map +0 -1
  106. package/lib/aes-ecb.d.ts.map +0 -1
  107. package/lib/aes-ecb.js.map +0 -1
  108. package/lib/cdn-upload.d.ts.map +0 -1
  109. package/lib/cdn-upload.js.map +0 -1
  110. package/lib/cdn-upload.test.d.ts +0 -2
  111. package/lib/cdn-upload.test.d.ts.map +0 -1
  112. package/lib/cdn-upload.test.js +0 -150
  113. package/lib/cdn-upload.test.js.map +0 -1
  114. package/lib/cdn-url.d.ts.map +0 -1
  115. package/lib/cdn-url.js.map +0 -1
  116. package/lib/context-store.d.ts.map +0 -1
  117. package/lib/context-store.js.map +0 -1
  118. package/lib/credentials.d.ts.map +0 -1
  119. package/lib/credentials.js.map +0 -1
  120. package/lib/endpoint.d.ts.map +0 -1
  121. package/lib/endpoint.js.map +0 -1
  122. package/lib/ilink-api.d.ts.map +0 -1
  123. package/lib/ilink-api.js.map +0 -1
  124. package/lib/ilink-config-cache.d.ts.map +0 -1
  125. package/lib/ilink-config-cache.js.map +0 -1
  126. package/lib/ilink-logger.d.ts.map +0 -1
  127. package/lib/ilink-logger.js.map +0 -1
  128. package/lib/ilink-meta.d.ts.map +0 -1
  129. package/lib/ilink-meta.js.map +0 -1
  130. package/lib/ilink-random.d.ts.map +0 -1
  131. package/lib/ilink-random.js.map +0 -1
  132. package/lib/ilink-redact.d.ts.map +0 -1
  133. package/lib/ilink-redact.js.map +0 -1
  134. package/lib/ilink-session-guard.d.ts.map +0 -1
  135. package/lib/ilink-session-guard.js.map +0 -1
  136. package/lib/ilink-types.d.ts.map +0 -1
  137. package/lib/ilink-types.js.map +0 -1
  138. package/lib/index.d.ts.map +0 -1
  139. package/lib/index.js.map +0 -1
  140. package/lib/login-assist-routes.d.ts +0 -7
  141. package/lib/login-assist-routes.d.ts.map +0 -1
  142. package/lib/login-assist-routes.js +0 -29
  143. package/lib/login-assist-routes.js.map +0 -1
  144. package/lib/login.d.ts.map +0 -1
  145. package/lib/login.js.map +0 -1
  146. package/lib/media-download.d.ts.map +0 -1
  147. package/lib/media-download.js.map +0 -1
  148. package/lib/mime.d.ts.map +0 -1
  149. package/lib/mime.js.map +0 -1
  150. package/lib/mime.test.d.ts +0 -2
  151. package/lib/mime.test.d.ts.map +0 -1
  152. package/lib/mime.test.js +0 -62
  153. package/lib/mime.test.js.map +0 -1
  154. package/lib/outbound-media.d.ts.map +0 -1
  155. package/lib/outbound-media.js.map +0 -1
  156. package/lib/pic-decrypt.d.ts.map +0 -1
  157. package/lib/pic-decrypt.js.map +0 -1
  158. package/lib/routes.d.ts +0 -8
  159. package/lib/routes.d.ts.map +0 -1
  160. package/lib/routes.js +0 -29
  161. package/lib/routes.js.map +0 -1
  162. package/lib/silk-transcode.d.ts.map +0 -1
  163. package/lib/silk-transcode.js.map +0 -1
  164. package/lib/silk-transcode.test.d.ts +0 -2
  165. package/lib/silk-transcode.test.d.ts.map +0 -1
  166. package/lib/silk-transcode.test.js +0 -53
  167. package/lib/silk-transcode.test.js.map +0 -1
  168. package/lib/types.d.ts.map +0 -1
  169. package/lib/types.js.map +0 -1
  170. package/lib/typing-indicator.d.ts +0 -32
  171. package/lib/typing-indicator.d.ts.map +0 -1
  172. package/lib/typing-indicator.js +0 -95
  173. package/lib/typing-indicator.js.map +0 -1
  174. package/lib/upload.d.ts.map +0 -1
  175. package/lib/upload.js.map +0 -1
  176. package/lib/upload.test.d.ts +0 -2
  177. package/lib/upload.test.d.ts.map +0 -1
  178. package/lib/upload.test.js +0 -250
  179. package/lib/upload.test.js.map +0 -1
  180. package/lib/weixin-inbound.d.ts.map +0 -1
  181. package/lib/weixin-inbound.js.map +0 -1
  182. package/lib/weixin-send-media.d.ts.map +0 -1
  183. package/lib/weixin-send-media.js.map +0 -1
  184. package/lib/weixin-send.d.ts.map +0 -1
  185. package/lib/weixin-send.js.map +0 -1
  186. package/src/adapter.ts +0 -18
  187. package/src/login-assist-routes.ts +0 -36
  188. package/src/routes.ts +0 -39
  189. package/src/typing-indicator.ts +0 -139
package/src/endpoint.ts CHANGED
@@ -1,354 +1,355 @@
1
1
  /**
2
- * 微信 iLink Bot:长轮询入站 + CDN 媒体收发
2
+ * WeixinIlinkEndpoint — lifecycle, long-poll inbound, outbound send.
3
3
  */
4
- import crypto from "node:crypto";
5
- import fs from "node:fs";
6
- import path from "node:path";
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
7
  import {
8
8
  Endpoint,
9
- Message,
10
- type MessageSegment,
11
- type SendContent,
12
- type SendOptions,
13
- segment,
14
- } from "zhin.js";
15
- import { getUpdates, notifyStart, notifyStop, sendTyping } from "./ilink-api.js";
9
+ type EndpointFriend,
10
+ type EndpointControl,
11
+ type EndpointManagement,
12
+ type EndpointSendRequest,
13
+ } from 'zhin.js/adapter';
14
+ import { formatCompact, getAdapterLogger } from '@zhin.js/logger';
15
+ import type { CapabilityId } from 'zhin.js';
16
+ import { getUpdates, notifyStart, notifyStop } from './ilink-api.js';
17
+ import { IlinkClientMetadata } from './ilink-meta.js';
16
18
  import {
17
- configureIlinkMeta,
18
- DEFAULT_API_BASE_URL,
19
- DEFAULT_CDN_BASE_URL,
20
- } from "./ilink-meta.js";
21
- import {
22
- loadSyncBuf,
23
- resolveStateDir,
24
- saveSyncBuf,
25
19
  type WeixinIlinkCredentials,
26
- } from "./credentials.js";
27
- import { resolveCredentials } from "./login.js";
20
+ WeixinIlinkStateStore,
21
+ } from './credentials.js';
22
+ import { resolveCredentials } from './login.js';
28
23
  import {
29
- bodyFromItemList,
30
- getContextToken,
31
- isMediaItem,
32
- restoreContextTokens,
33
- setContextToken,
34
- } from "./context-store.js";
35
- import { WeixinConfigManager } from "./ilink-config-cache.js";
24
+ WeixinContextTokenStore,
25
+ } from './context-store.js';
26
+ import { WeixinConfigManager } from './ilink-config-cache.js';
36
27
  import {
37
- getRemainingPauseMs,
38
- isSessionPaused,
39
- pauseSession,
28
+ IlinkSessionGuard,
40
29
  SESSION_EXPIRED_ERRCODE,
41
- } from "./ilink-session-guard.js";
42
- import { downloadMediaFromItem } from "./media-download.js";
43
- import { sendMessageWeixin } from "./weixin-send.js";
44
- import { sendWeixinMediaFile } from "./weixin-send-media.js";
45
- import { materializeOutboundMedia, segmentMediaRef } from "./outbound-media.js";
46
- import type { MessageItem, WeixinMessage } from "./ilink-types.js";
47
- import { MessageItemType } from "./ilink-types.js";
48
- import { getExtensionFromMime, sniffMimeFromBuffer } from "./mime.js";
49
- import type { WeixinInboundMediaOpts } from "./weixin-inbound.js";
50
- import type { WeixinIlinkEndpointConfig } from "./types.js";
51
- import type { WeixinIlinkAdapter } from "./adapter.js";
30
+ } from './ilink-session-guard.js';
31
+ import { downloadMediaFromItem } from './media-download.js';
32
+ import { sendMessageWeixin } from './weixin-send.js';
33
+ import { materializeOutboundMedia } from './outbound-media.js';
34
+ import { MessageItemType, type WeixinMessage } from './ilink-types.js';
35
+ import { getExtensionFromMime, sniffMimeFromBuffer } from './mime.js';
36
+ import type { WeixinInboundMediaOpts } from './weixin-inbound.js';
52
37
  import {
53
- WeixinIlinkTypingIndicatorManager,
54
- type WeixinIlinkTypingIndicatorConfig,
55
- } from "./typing-indicator.js";
38
+ formatInboundContent,
39
+ weixinInboundSegments,
40
+ weixinReplyTo,
41
+ formatOutboundSegments,
42
+ inboundMessageId,
43
+ segmentLocalPath,
44
+ sleep,
45
+ weixinIlinkInboundConversation,
46
+ type ResolvedWeixinIlinkConfig,
47
+ type WeixinMessageWithMedia,
48
+ type WeixinWireSegment,
49
+ } from './protocol.js';
50
+ import { WeixinIlinkClient } from './client.js';
56
51
 
57
- const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
58
52
  const MAX_CONSECUTIVE_FAILURES = 3;
59
53
  const BACKOFF_DELAY_MS = 30_000;
60
54
  const RETRY_DELAY_MS = 2_000;
61
55
  const WEIXIN_MEDIA_MAX_BYTES = 100 * 1024 * 1024;
62
-
63
- export type WeixinMessageWithMedia = WeixinMessage & {
64
- _media?: WeixinInboundMediaOpts;
65
- };
66
-
67
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
68
- return new Promise((resolve) => {
69
- if (signal?.aborted) {
70
- resolve();
71
- return;
72
- }
73
- const timer = setTimeout(resolve, ms);
74
- signal?.addEventListener(
75
- "abort",
76
- () => {
77
- clearTimeout(timer);
78
- resolve();
79
- },
80
- { once: true },
81
- );
82
- });
56
+ /** 入站媒体保留 24h,每小时清扫一次。 */
57
+ const INBOUND_MEDIA_TTL_MS = 24 * 60 * 60 * 1000;
58
+ const MEDIA_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
59
+
60
+ export type WeixinIlinkSendText = typeof sendMessageWeixin;
61
+ export type WeixinIlinkNotifyStart = typeof notifyStart;
62
+ export type WeixinIlinkNotifyStop = typeof notifyStop;
63
+ export type WeixinIlinkGetUpdates = typeof getUpdates;
64
+
65
+ export interface WeixinIlinkEndpointOptions {
66
+ readonly id: CapabilityId;
67
+ readonly config: ResolvedWeixinIlinkConfig;
68
+ readonly resolveCredentials?: (
69
+ config: ResolvedWeixinIlinkConfig,
70
+ metadata: IlinkClientMetadata,
71
+ state: WeixinIlinkStateStore,
72
+ signal?: AbortSignal,
73
+ ) => Promise<WeixinIlinkCredentials>;
74
+ /** Test / internal: override network side effects. */
75
+ readonly notifyStart?: WeixinIlinkNotifyStart;
76
+ readonly notifyStop?: WeixinIlinkNotifyStop;
77
+ readonly getUpdates?: WeixinIlinkGetUpdates;
78
+ readonly sendText?: WeixinIlinkSendText;
79
+ readonly state?: WeixinIlinkStateStore;
80
+ readonly contextTokens?: WeixinContextTokenStore;
81
+ readonly sessionGuard?: IlinkSessionGuard;
83
82
  }
84
83
 
85
- function segmentLocalPath(seg: MessageSegment): string | undefined {
86
- const ref = segmentMediaRef(seg);
87
- if (!ref || ref.startsWith("base64://") || /^data:/.test(ref) || /^https?:\/\//i.test(ref)) {
88
- return undefined;
89
- }
90
- return ref.replace(/^file:\/\//, "");
91
- }
92
-
93
- export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig, WeixinMessage> {
94
- $connected = false;
95
- $typingIndicator?: WeixinIlinkTypingIndicatorManager;
96
-
97
- private creds: WeixinIlinkCredentials | null = null;
98
- private pollAbort?: AbortController;
99
- private pollPromise?: Promise<void>;
100
- private configManager?: WeixinConfigManager;
84
+ export class WeixinIlinkEndpoint extends Endpoint<WeixinIlinkClient> {
85
+ readonly client: WeixinIlinkClient;
86
+ readonly #logger!: ReturnType<typeof getAdapterLogger>;
87
+
88
+ readonly #options: WeixinIlinkEndpointOptions;
89
+ readonly #resolveCredentials: (
90
+ config: ResolvedWeixinIlinkConfig,
91
+ metadata: IlinkClientMetadata,
92
+ state: WeixinIlinkStateStore,
93
+ signal?: AbortSignal,
94
+ ) => Promise<WeixinIlinkCredentials>;
95
+ readonly #notifyStart: WeixinIlinkNotifyStart;
96
+ readonly #notifyStop: WeixinIlinkNotifyStop;
97
+ readonly #getUpdates: WeixinIlinkGetUpdates;
98
+ readonly #sendText: WeixinIlinkSendText;
99
+ readonly #state: WeixinIlinkStateStore;
100
+ readonly #contextTokens: WeixinContextTokenStore;
101
+ readonly #sessionGuard: IlinkSessionGuard;
102
+ readonly #metadata: IlinkClientMetadata;
103
+ #creds: WeixinIlinkCredentials | null = null;
104
+ #pollAbort?: AbortController;
105
+ #pollPromise?: Promise<void>;
106
+ #loginAbort?: AbortController;
107
+ #configManager?: WeixinConfigManager;
108
+ #mediaSweepTimer?: ReturnType<typeof setInterval>;
109
+ #open = false;
110
+ #started = false;
111
+ readonly management: EndpointManagement = createWeixinIlinkEndpointManagement(() => this.client);
112
+ readonly control: EndpointControl = Object.freeze<EndpointControl>({
113
+ typing: async (conversation, active) => {
114
+ await this.client.sendTyping(
115
+ conversation.id,
116
+ active === false ? 2 : 1,
117
+ );
118
+ },
119
+ });
101
120
 
102
- get $id(): string {
103
- return this.$config.name;
121
+ constructor(options: WeixinIlinkEndpointOptions) {
122
+ super();
123
+ this.#logger = getAdapterLogger('weixin-ilink', options.config.id);
124
+ this.#options = options;
125
+ this.#resolveCredentials = options.resolveCredentials ?? resolveCredentials;
126
+ this.#notifyStart = options.notifyStart ?? notifyStart;
127
+ this.#notifyStop = options.notifyStop ?? notifyStop;
128
+ this.#getUpdates = options.getUpdates ?? getUpdates;
129
+ this.#sendText = options.sendText ?? sendMessageWeixin;
130
+ this.#state = options.state
131
+ ?? new WeixinIlinkStateStore(options.config.id, options.config.dataDir);
132
+ this.#contextTokens = options.contextTokens ?? new WeixinContextTokenStore(this.#state);
133
+ this.#sessionGuard = options.sessionGuard ?? new IlinkSessionGuard(options.config.id);
134
+ this.#metadata = new IlinkClientMetadata({ botAgent: options.config.botAgent });
135
+ this.client = new WeixinIlinkClient(
136
+ options.config,
137
+ this.#metadata,
138
+ () => this.#creds,
139
+ () => this.#configManager,
140
+ this.#sendText,
141
+ this.#contextTokens,
142
+ );
104
143
  }
105
144
 
106
145
  get hasCredentials(): boolean {
107
- return Boolean(this.creds?.botToken);
146
+ return this.client.authenticated;
108
147
  }
109
148
 
110
- get pluginLogger() {
111
- return this.adapter.plugin.logger;
112
- }
149
+ async start(): Promise<void> {
150
+ if (this.#started) return;
151
+ this.#started = true;
152
+ try {
153
+ // QR 登录最长 8 分钟:stop() 必须能打断
154
+ this.#loginAbort = new AbortController();
155
+ this.#creds = await this.#resolveCredentials(
156
+ this.#options.config,
157
+ this.#metadata,
158
+ this.#state,
159
+ this.#loginAbort.signal,
160
+ );
161
+ this.#contextTokens.restore();
113
162
 
114
- constructor(
115
- public adapter: WeixinIlinkAdapter,
116
- public $config: WeixinIlinkEndpointConfig,
117
- ) {}
163
+ await this.#notifyStart({
164
+ baseUrl: this.client.apiBaseUrl,
165
+ metadata: this.#metadata,
166
+ token: this.#creds.botToken,
167
+ });
118
168
 
119
- apiBaseUrl(): string {
120
- return this.$config.baseUrl ?? this.creds?.baseUrl ?? DEFAULT_API_BASE_URL;
121
- }
169
+ this.#configManager = new WeixinConfigManager(
170
+ {
171
+ baseUrl: this.client.apiBaseUrl,
172
+ metadata: this.#metadata,
173
+ token: this.#creds.botToken,
174
+ },
175
+ (msg) => this.#logger.debug(msg),
176
+ );
122
177
 
123
- cdnBaseUrl(): string {
124
- return this.$config.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL;
178
+ this.#pollAbort = new AbortController();
179
+ this.#pollPromise = this.#pollLoop(this.#pollAbort.signal);
180
+ this.#startMediaSweep();
181
+ this.#logger.info(formatCompact({
182
+ op: 'connect',
183
+ endpoint: this.#options.config.id,
184
+ }));
185
+ void this.#emitPlatformEvent('system.online', {
186
+ account: this.#options.config.id,
187
+ });
188
+ } catch (error) {
189
+ await this.stop();
190
+ this.#logger.error('Failed to connect weixin-ilink bot:', error);
191
+ throw error;
192
+ }
125
193
  }
126
194
 
127
- async $connect(): Promise<void> {
128
- configureIlinkMeta({ botAgent: this.$config.botAgent });
129
- this.creds = await resolveCredentials(this.adapter.plugin, this.$config);
130
- restoreContextTokens(this.$id);
131
-
132
- await notifyStart({
133
- baseUrl: this.apiBaseUrl(),
134
- token: this.creds.botToken,
135
- });
136
-
137
- this.configManager = new WeixinConfigManager(
138
- { baseUrl: this.apiBaseUrl(), token: this.creds.botToken },
139
- (msg) => this.pluginLogger.debug(msg),
140
- );
141
-
142
- if (this.$config.typingIndicator?.enabled !== false) {
143
- this.$typingIndicator = new WeixinIlinkTypingIndicatorManager(
144
- this,
145
- this.$config.typingIndicator as WeixinIlinkTypingIndicatorConfig | undefined,
146
- );
147
- }
195
+ open(): void {
196
+ this.#open = true;
197
+ }
148
198
 
149
- this.pollAbort = new AbortController();
150
- this.pollPromise = this.pollLoop(this.pollAbort.signal);
151
- this.$connected = true;
152
- this.pluginLogger.info(`weixin-ilink endpoint ${this.$id} connected`);
199
+ close(): void {
200
+ this.#open = false;
153
201
  }
154
202
 
155
- async $disconnect(): Promise<void> {
156
- this.pollAbort?.abort();
203
+ async stop(): Promise<void> {
204
+ this.#open = false;
205
+ this.#loginAbort?.abort();
206
+ this.#pollAbort?.abort();
157
207
  try {
158
- await this.pollPromise;
208
+ await this.#pollPromise;
159
209
  } catch {
160
210
  /* poll loop exit */
161
211
  }
162
- if (this.creds?.botToken) {
212
+ this.#stopMediaSweep();
213
+ // 防抖中的 context token 落盘,避免 stop 丢尾部写入
214
+ this.#contextTokens.flush();
215
+ if (this.#creds?.botToken) {
163
216
  try {
164
- await notifyStop({ baseUrl: this.apiBaseUrl(), token: this.creds.botToken });
217
+ await this.#notifyStop({
218
+ baseUrl: this.client.apiBaseUrl,
219
+ metadata: this.#metadata,
220
+ token: this.#creds.botToken,
221
+ });
165
222
  } catch (err) {
166
- this.pluginLogger.warn(`notifyStop failed: ${String(err)}`);
223
+ this.#logger.warn(formatCompact({
224
+ op: 'notify_stop',
225
+ ok: false,
226
+ error: err instanceof Error ? err.message : String(err),
227
+ }));
167
228
  }
168
229
  }
169
- this.$connected = false;
170
- this.pluginLogger.info(`weixin-ilink endpoint ${this.$id} disconnected`);
171
- }
172
-
173
- async sendTypingToUser(userId: string, status: number): Promise<void> {
174
- if (!this.creds?.botToken || !this.configManager) return;
175
- const contextToken = getContextToken(this.$id, userId);
176
- const cfg = await this.configManager.getForUser(userId, contextToken);
177
- if (!cfg.typingTicket) {
178
- this.pluginLogger.debug(`sendTyping: no typing_ticket for user=${userId}`);
179
- return;
180
- }
181
- await sendTyping({
182
- baseUrl: this.apiBaseUrl(),
183
- token: this.creds.botToken,
184
- body: {
185
- ilink_user_id: userId,
186
- typing_ticket: cfg.typingTicket,
187
- status,
188
- },
189
- });
190
- }
191
-
192
- async $recallMessage(_id: string): Promise<void> {
193
- this.pluginLogger.debug("weixin-ilink does not support message recall");
194
- }
195
-
196
- $formatMessage(msg: WeixinMessageWithMedia): Message<WeixinMessage> {
197
- const userId = msg.from_user_id ?? "";
198
- const content = this.buildInboundContent(msg);
199
- const quoteId = Message.quoteIdFromContent(content);
200
- Message.alignReplySegments(content, quoteId);
201
- const msgId = String(msg.message_id ?? msg.client_id ?? msg.seq ?? Date.now());
202
-
203
- return Message.from(msg, {
204
- $id: msgId,
205
- $adapter: "weixin-ilink",
206
- $endpoint: this.$config.name,
207
- $sender: {
208
- id: userId,
209
- name: userId,
210
- },
211
- $channel: {
212
- id: userId,
213
- type: "private",
214
- },
215
- $content: content,
216
- $quote_id: quoteId,
217
- $raw: bodyFromItemList(msg.item_list),
218
- $timestamp: msg.create_time_ms ?? Date.now(),
219
- $recall: async () => this.$recallMessage(msgId),
220
- $reply: async (replyContent: SendContent, _quote?: boolean | string) => {
221
- if (!Array.isArray(replyContent)) replyContent = [replyContent];
222
- return this.adapter.sendMessage({
223
- context: "weixin-ilink",
224
- endpoint: this.$config.name,
225
- id: userId,
226
- type: "private",
227
- content: replyContent,
228
- });
229
- },
230
+ this.#started = false;
231
+ void this.#emitPlatformEvent('system.offline', {
232
+ account: this.#options.config.id,
230
233
  });
234
+ this.#logger.debug(formatCompact({
235
+ op: 'disconnect',
236
+ }));
231
237
  }
232
238
 
233
- private buildInboundContent(msg: WeixinMessageWithMedia): MessageSegment[] {
234
- const segments: MessageSegment[] = [];
235
- const text = bodyFromItemList(msg.item_list);
236
- if (text) segments.push(segment.text(text));
237
-
238
- const media = msg._media;
239
- if (media?.decryptedPicPath) {
240
- segments.push(segment("image", { file: media.decryptedPicPath }));
241
- } else if (media?.decryptedVideoPath) {
242
- segments.push(segment("video", { file: media.decryptedVideoPath }));
243
- } else if (media?.decryptedFilePath) {
244
- segments.push(segment("file", {
245
- file: media.decryptedFilePath,
246
- name: path.basename(media.decryptedFilePath),
247
- }));
248
- } else if (media?.decryptedVoicePath) {
249
- segments.push(segment("record", { file: media.decryptedVoicePath }));
250
- } else if (!text && msg.item_list?.some((i) => isMediaItem(i))) {
251
- segments.push(segment.text("[媒体消息]"));
252
- }
253
-
254
- return segments.length ? segments : [segment.text("")];
255
- }
256
-
257
- async $sendMessage(options: SendOptions): Promise<string> {
258
- if (!this.creds?.botToken) {
259
- throw new Error("weixin-ilink bot not authenticated");
239
+ async send({ conversation, payload }: EndpointSendRequest): Promise<string> {
240
+ if (!this.#creds?.botToken) {
241
+ throw new Error('weixin-ilink bot not authenticated');
260
242
  }
261
- const peerId = options.id;
262
- const contextToken = getContextToken(this.$id, peerId);
243
+ // 个人微信仅 private 会话,对端 user_id 即 conversation.id
244
+ const target = conversation.id;
245
+ const contextToken = this.client.contextToken(target);
263
246
  if (!contextToken) {
264
- this.pluginLogger.warn(`missing context_token for peer ${peerId}, refusing send`);
265
- throw new Error(`missing context_token for peer ${peerId}`);
247
+ this.#logger.warn(formatCompact({
248
+ op: 'send',
249
+ ok: false,
250
+ reason: 'missing_context_token',
251
+ target,
252
+ }));
253
+ throw new Error(`missing context_token for peer ${target}`);
266
254
  }
267
255
 
268
- const apiOpts = {
269
- baseUrl: this.apiBaseUrl(),
270
- token: this.creds.botToken,
271
- contextToken,
272
- };
273
-
274
- const outboundDir = path.join(resolveStateDir(), "media", "outbound");
275
- const materialized = await materializeOutboundMedia(options.content, outboundDir);
256
+ const outboundDir = this.#state.mediaDirectory('outbound');
257
+ const wire = formatOutboundSegments(payload);
258
+ const materialized = await materializeOutboundMedia(wire, outboundDir);
276
259
  const segments = Array.isArray(materialized) ? materialized : [materialized];
277
- let lastId = "";
278
- let pendingText = "";
260
+ let lastId = '';
261
+ let pendingText = '';
279
262
 
280
263
  for (const raw of segments) {
281
- if (typeof raw === "string") {
264
+ if (typeof raw === 'string') {
282
265
  pendingText += raw;
283
266
  continue;
284
267
  }
285
- if (typeof raw !== "object" || raw === null || !("type" in raw)) {
286
- continue;
287
- }
288
- const seg = raw as MessageSegment;
289
- if (seg.type === "text" || seg.type === "markdown") {
290
- const t = (seg.data as { text?: string }).text ?? "";
291
- pendingText += t;
268
+ if (typeof raw !== 'object' || raw === null || !('type' in raw)) continue;
269
+ const seg = raw as WeixinWireSegment;
270
+ if (seg.type === 'text' || seg.type === 'markdown') {
271
+ pendingText += String((seg.data as { text?: string } | undefined)?.text ?? '');
292
272
  continue;
293
273
  }
294
274
 
295
275
  const filePath = segmentLocalPath(seg);
296
276
  if (filePath && fs.existsSync(filePath)) {
297
- // 微信限制:单条消息不能图文混排 → 先单独发文本,再发纯媒体(不带 caption)
277
+ // 微信限制:单条消息不能图文混排 → 先单独发文本,再发纯媒体
298
278
  if (pendingText.trim()) {
299
- const textResult = await sendMessageWeixin({
300
- to: peerId,
301
- text: pendingText,
302
- opts: apiOpts,
303
- });
304
- pendingText = "";
279
+ const textResult = await this.client.sendText(target, pendingText);
280
+ pendingText = '';
305
281
  lastId = textResult.messageId;
306
282
  }
307
- const result = await sendWeixinMediaFile({
308
- filePath,
309
- to: peerId,
310
- text: "",
311
- opts: apiOpts,
312
- cdnBaseUrl: this.cdnBaseUrl(),
313
- });
283
+ const result = await this.client.sendMedia(target, filePath);
314
284
  lastId = result.messageId;
315
285
  continue;
316
286
  }
317
287
 
318
- if (seg.type === "image" || seg.type === "video" || seg.type === "file" || seg.type === "record") {
319
- this.pluginLogger.warn(`skip outbound ${seg.type}: no local file path`);
288
+ if (seg.type === 'image' || seg.type === 'video' || seg.type === 'file' || seg.type === 'record') {
289
+ this.#logger.warn(formatCompact({
290
+ op: 'send',
291
+ skip: 'no_local_file',
292
+ type: seg.type,
293
+ }));
320
294
  }
321
295
  }
322
296
 
323
297
  if (pendingText.trim()) {
324
- const result = await sendMessageWeixin({
325
- to: peerId,
326
- text: pendingText,
327
- opts: apiOpts,
328
- });
298
+ const result = await this.client.sendText(target, pendingText);
329
299
  lastId = result.messageId;
330
300
  }
331
301
 
332
302
  return lastId || `weixin-ilink-${Date.now()}`;
333
303
  }
334
304
 
335
- private async pollLoop(abortSignal: AbortSignal): Promise<void> {
336
- if (!this.creds?.botToken) return;
305
+ /** Test / internal: admit a parsed message when the endpoint is open. */
306
+ admit(msg: WeixinMessageWithMedia): void {
307
+ if (!this.#open) return;
308
+ const userId = msg.from_user_id ?? '';
309
+ if (msg.context_token && userId) {
310
+ this.#contextTokens.set(userId, msg.context_token);
311
+ }
312
+ const conversation = weixinIlinkInboundConversation(String(this.#options.id), userId);
313
+ const replyTo = weixinReplyTo(msg);
314
+ void this.emit('message.receive', {
315
+ conversation,
316
+ message: { conversation, id: inboundMessageId(msg) },
317
+ content: formatInboundContent(msg),
318
+ segments: weixinInboundSegments(msg),
319
+ ...(replyTo ? { replyTo } : {}),
320
+ sender: { id: userId },
321
+ endpointId: this.#options.config.id,
322
+ metadata: Object.freeze({
323
+ messageType: msg.message_type,
324
+ createTimeMs: msg.create_time_ms,
325
+ }),
326
+ }).catch((err) => {
327
+ this.#logger.warn(formatCompact({
328
+ op: 'weixin_ilink_gateway_receive_failed',
329
+ target: userId,
330
+ error: err instanceof Error ? err.message : String(err),
331
+ }));
332
+ });
333
+ }
334
+
335
+ async #pollLoop(abortSignal: AbortSignal): Promise<void> {
336
+ if (!this.#creds?.botToken) return;
337
337
 
338
- let getUpdatesBuf = loadSyncBuf(this.$id);
339
- let nextTimeoutMs = this.$config.longPollTimeoutMs ?? DEFAULT_LONG_POLL_TIMEOUT_MS;
338
+ let getUpdatesBuf = this.#state.loadSyncBuf();
339
+ let nextTimeoutMs = this.#options.config.longPollTimeoutMs;
340
340
  let consecutiveFailures = 0;
341
341
 
342
342
  while (!abortSignal.aborted) {
343
- if (isSessionPaused(this.$id)) {
344
- await sleep(getRemainingPauseMs(this.$id), abortSignal);
343
+ if (this.#sessionGuard.paused) {
344
+ await sleep(this.#sessionGuard.remainingMs, abortSignal);
345
345
  continue;
346
346
  }
347
347
 
348
348
  try {
349
- const resp = await getUpdates({
350
- baseUrl: this.apiBaseUrl(),
351
- token: this.creds.botToken,
349
+ const resp = await this.#getUpdates({
350
+ baseUrl: this.client.apiBaseUrl,
351
+ metadata: this.#metadata,
352
+ token: this.#creds.botToken,
352
353
  get_updates_buf: getUpdatesBuf,
353
354
  timeoutMs: nextTimeoutMs,
354
355
  abortSignal,
@@ -359,21 +360,21 @@ export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig,
359
360
  }
360
361
 
361
362
  const isApiError =
362
- (resp.ret !== undefined && resp.ret !== 0) ||
363
- (resp.errcode !== undefined && resp.errcode !== 0);
363
+ (resp.ret !== undefined && resp.ret !== 0)
364
+ || (resp.errcode !== undefined && resp.errcode !== 0);
364
365
 
365
366
  if (isApiError) {
366
367
  const sessionExpired =
367
368
  resp.errcode === SESSION_EXPIRED_ERRCODE || resp.ret === SESSION_EXPIRED_ERRCODE;
368
369
  if (sessionExpired) {
369
- pauseSession(this.$id);
370
+ this.#sessionGuard.pause();
370
371
  consecutiveFailures = 0;
371
- await sleep(getRemainingPauseMs(this.$id), abortSignal);
372
+ await sleep(this.#sessionGuard.remainingMs, abortSignal);
372
373
  continue;
373
374
  }
374
375
  consecutiveFailures += 1;
376
+ // 退避后不清零:对端持续挂时清零会让重试固定打满 RETRY_DELAY_MS。
375
377
  if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
376
- consecutiveFailures = 0;
377
378
  await sleep(BACKOFF_DELAY_MS, abortSignal);
378
379
  } else {
379
380
  await sleep(RETRY_DELAY_MS, abortSignal);
@@ -382,20 +383,24 @@ export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig,
382
383
  }
383
384
 
384
385
  consecutiveFailures = 0;
385
- if (resp.get_updates_buf) {
386
- getUpdatesBuf = resp.get_updates_buf;
387
- saveSyncBuf(this.$id, getUpdatesBuf);
388
- }
389
-
386
+ // 先分发再推进 buf:分发途中崩溃时 buf 未推进,下一轮重拉不丢消息。
387
+ const nextBuf = resp.get_updates_buf;
390
388
  for (const inbound of resp.msgs ?? []) {
391
- await this.handleInboundMessage(inbound);
389
+ await this.#handleInboundMessage(inbound);
390
+ }
391
+ if (nextBuf) {
392
+ getUpdatesBuf = nextBuf;
393
+ this.#state.saveSyncBuf(getUpdatesBuf);
392
394
  }
393
395
  } catch (err) {
394
396
  if (abortSignal.aborted) return;
395
397
  consecutiveFailures += 1;
396
- this.pluginLogger.error(`weixin-ilink poll error: ${String(err)}`);
398
+ this.#logger.error(formatCompact({
399
+ op: 'poll',
400
+ ok: false,
401
+ error: err instanceof Error ? err.message : String(err),
402
+ }));
397
403
  if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
398
- consecutiveFailures = 0;
399
404
  await sleep(BACKOFF_DELAY_MS, abortSignal);
400
405
  } else {
401
406
  await sleep(RETRY_DELAY_MS, abortSignal);
@@ -404,80 +409,144 @@ export class WeixinIlinkEndpoint implements Endpoint<WeixinIlinkEndpointConfig,
404
409
  }
405
410
  }
406
411
 
407
- private async handleInboundMessage(full: WeixinMessage): Promise<void> {
408
- const fromUserId = full.from_user_id ?? "";
409
- if (full.context_token && fromUserId) {
410
- setContextToken(this.$id, fromUserId, full.context_token);
411
- }
412
+ async #handleInboundMessage(full: WeixinMessage): Promise<void> {
413
+ void this.#emitPlatformEvent(`message.${full.message_type ?? 'unknown'}`, full);
414
+ const fromUserId = full.from_user_id ?? '';
415
+
416
+ const mediaOpts = await this.#downloadInboundMedia(full);
417
+ this.admit({ ...full, _media: mediaOpts });
418
+ this.#logger.debug(formatCompact({
419
+ op: 'recv',
420
+ endpoint: this.#options.config.id,
421
+ target: fromUserId,
422
+ preview: formatInboundContent({ ...full, _media: mediaOpts }).slice(0, 80),
423
+ }));
424
+ }
412
425
 
413
- const mediaOpts = await this.downloadInboundMedia(full);
414
- // 入站保持单条 message.receive(文字+媒体同条),供 AI context / im_transcripts / agent_messages 组装。
415
- // 出站才按微信限制拆分图文(见 sendMessage)。
416
- const message = this.$formatMessage({ ...full, _media: mediaOpts });
417
- this.adapter.emit("message.receive", message);
418
- this.pluginLogger.debug(
419
- `${this.$id} recv private(${message.$channel.id}): ${segment.raw(message.$content)}`,
420
- );
426
+ async #emitPlatformEvent(name: string, event: unknown): Promise<void> {
427
+ await this.emitPlatform(name, event).catch((error) => {
428
+ this.#logger.warn(formatCompact({
429
+ op: 'weixin_ilink_platform_event_failed',
430
+ event: name,
431
+ error: error instanceof Error ? error.message : String(error),
432
+ }));
433
+ });
421
434
  }
422
435
 
423
- private async downloadInboundMedia(full: WeixinMessage): Promise<WeixinInboundMediaOpts> {
436
+ async #downloadInboundMedia(full: WeixinMessage): Promise<WeixinInboundMediaOpts> {
424
437
  const hasDownloadableMedia = (m?: { encrypt_query_param?: string; full_url?: string }) =>
425
438
  Boolean(m?.encrypt_query_param || m?.full_url);
426
439
 
427
440
  const mediaItem =
428
441
  full.item_list?.find(
429
442
  (i) => i.type === MessageItemType.IMAGE && hasDownloadableMedia(i.image_item?.media),
430
- ) ??
431
- full.item_list?.find(
443
+ )
444
+ ?? full.item_list?.find(
432
445
  (i) => i.type === MessageItemType.VIDEO && hasDownloadableMedia(i.video_item?.media),
433
- ) ??
434
- full.item_list?.find(
446
+ )
447
+ ?? full.item_list?.find(
435
448
  (i) => i.type === MessageItemType.FILE && hasDownloadableMedia(i.file_item?.media),
436
- ) ??
437
- full.item_list?.find(
449
+ )
450
+ ?? full.item_list?.find(
438
451
  (i) => i.type === MessageItemType.VOICE && hasDownloadableMedia(i.voice_item?.media),
439
452
  );
440
453
 
441
454
  if (!mediaItem) return {};
442
455
 
443
456
  return downloadMediaFromItem(mediaItem, {
444
- cdnBaseUrl: this.cdnBaseUrl(),
457
+ cdnBaseUrl: this.client.cdnBaseUrl,
445
458
  saveMedia: (buffer, contentType, subdir, maxBytes, originalFilename) =>
446
- this.saveInboundMedia(buffer, contentType, subdir, maxBytes, originalFilename),
447
- log: (msg) => this.pluginLogger.debug(msg),
448
- errLog: (msg) => this.pluginLogger.warn(msg),
449
- label: `inbound:${fromUserIdLabel(full)}`,
459
+ this.#saveInboundMedia(buffer, contentType, subdir, maxBytes, originalFilename),
460
+ log: (msg) => this.#logger.debug(msg),
461
+ errLog: (msg) => this.#logger.warn(msg),
462
+ label: `inbound:${full.from_user_id ?? 'unknown'}`,
450
463
  });
451
464
  }
452
465
 
453
- private async saveInboundMedia(
466
+ async #saveInboundMedia(
454
467
  buffer: Buffer,
455
468
  contentType?: string,
456
- subdir = "inbound",
469
+ subdir = 'inbound',
457
470
  maxBytes = WEIXIN_MEDIA_MAX_BYTES,
458
471
  originalFilename?: string,
459
472
  ): Promise<{ path: string }> {
460
473
  if (buffer.length > maxBytes) {
461
474
  throw new Error(`media exceeds max size ${maxBytes}`);
462
475
  }
463
- const dir = path.join(resolveStateDir(), "media", subdir);
476
+ const dir = this.#state.mediaDirectory(subdir);
464
477
  fs.mkdirSync(dir, { recursive: true });
465
478
  const resolvedMime = contentType ?? sniffMimeFromBuffer(buffer);
466
479
  const ext = originalFilename
467
480
  ? path.extname(originalFilename)
468
481
  : resolvedMime
469
482
  ? getExtensionFromMime(resolvedMime)
470
- : ".bin";
483
+ : '.bin';
471
484
  const base = originalFilename
472
485
  ? path.basename(originalFilename, ext)
473
- : "media";
474
- const fileName = `${base}-${Date.now()}-${crypto.randomBytes(4).toString("hex")}${ext}`;
486
+ : 'media';
487
+ const fileName = `${base}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}${ext}`;
475
488
  const filePath = path.join(dir, fileName);
476
489
  fs.writeFileSync(filePath, buffer);
477
490
  return { path: filePath };
478
491
  }
492
+
493
+ /** 入站媒体 TTL 清扫:start 时立即扫一次,之后每小时扫一次。 */
494
+ #startMediaSweep(): void {
495
+ this.#stopMediaSweep();
496
+ const sweep = () => this.#sweepInboundMedia();
497
+ sweep();
498
+ this.#mediaSweepTimer = setInterval(sweep, MEDIA_SWEEP_INTERVAL_MS);
499
+ (this.#mediaSweepTimer as { unref?: () => void }).unref?.();
500
+ }
501
+
502
+ #stopMediaSweep(): void {
503
+ if (this.#mediaSweepTimer) {
504
+ clearInterval(this.#mediaSweepTimer);
505
+ this.#mediaSweepTimer = undefined;
506
+ }
507
+ }
508
+
509
+ #sweepInboundMedia(): void {
510
+ const dir = this.#state.mediaDirectory('inbound');
511
+ let entries: fs.Dirent[];
512
+ try {
513
+ entries = fs.readdirSync(dir, { withFileTypes: true });
514
+ } catch {
515
+ return;
516
+ }
517
+ const now = Date.now();
518
+ for (const entry of entries) {
519
+ if (!entry.isFile()) continue;
520
+ const filePath = path.join(dir, entry.name);
521
+ try {
522
+ const stat = fs.statSync(filePath);
523
+ if (now - stat.mtimeMs <= INBOUND_MEDIA_TTL_MS) continue;
524
+ fs.unlinkSync(filePath);
525
+ this.#logger.debug(formatCompact({
526
+ op: 'media_sweep',
527
+ endpoint: this.#options.config.id,
528
+ file: entry.name,
529
+ }));
530
+ } catch {
531
+ /* 单个文件失败不阻塞整体清扫 */
532
+ }
533
+ }
534
+ }
479
535
  }
480
536
 
481
- function fromUserIdLabel(msg: WeixinMessage): string {
482
- return msg.from_user_id ?? "unknown";
537
+ function createWeixinIlinkEndpointManagement(
538
+ requireClient: () => WeixinIlinkClient,
539
+ ): EndpointManagement {
540
+ return Object.freeze<EndpointManagement>({
541
+ // 个人微信无群概念(listGroups/listGroupMembers 不接),也没有通讯录/资料接口。
542
+ // "好友"只能从会话推导:凡持有 context_token 的对端(来过消息,含重启后从磁盘恢复的)
543
+ // 即为可达私聊对端;昵称不可得,用 user_id 占位并在 remark 注明来源。
544
+ async listFriends(): Promise<readonly EndpointFriend[]> {
545
+ return requireClient().reachableUserIds().map((userId) => ({
546
+ user_id: userId,
547
+ nickname: userId,
548
+ remark: 'ilink: 从会话 context_token 推导,非通讯录',
549
+ }));
550
+ },
551
+ });
483
552
  }