@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
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Weixin iLink protocol helpers (no legacy Adapter/Endpoint / segment-mapper).
3
+ * Canonicalization is owned by gateway/core before endpoint.send.
4
+ */
5
+ import { isMediaRef } from '@zhin.js/im-contract';
6
+ import { bodyFromItemList } from './weixin-inbound.js';
7
+ import { DEFAULT_API_BASE_URL, DEFAULT_CDN_BASE_URL } from './ilink-meta.js';
8
+ const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
9
+ export function resolveWeixinIlinkConfig(config) {
10
+ const id = typeof config.id === 'string' ? config.id.trim() : '';
11
+ if (!/^[A-Za-z0-9_.-]+$/u.test(id)) {
12
+ throw new TypeError('Weixin iLink endpoint id must use letters, numbers, dot, underscore, or hyphen');
13
+ }
14
+ const botToken = typeof config.botToken === 'string'
15
+ ? config.botToken.trim() || undefined
16
+ : undefined;
17
+ const dataDir = config.dataDir?.trim() || 'data/weixin-ilink';
18
+ // No throw here: missing botToken is resolved later by resolveCredentials()
19
+ // (sidecar credentials file / QR login) during endpoint.start().
20
+ return {
21
+ context: 'weixin-ilink',
22
+ id,
23
+ botAgent: config.botAgent,
24
+ baseUrl: config.baseUrl ?? DEFAULT_API_BASE_URL,
25
+ cdnBaseUrl: config.cdnBaseUrl ?? DEFAULT_CDN_BASE_URL,
26
+ longPollTimeoutMs: config.longPollTimeoutMs ?? DEFAULT_LONG_POLL_TIMEOUT_MS,
27
+ botToken,
28
+ dataDir,
29
+ };
30
+ }
31
+ /** Build inbound text for OutboundMessageService.receive (gateway owns reply routing). */
32
+ export function formatInboundContent(msg) {
33
+ return bodyFromItemList(msg.item_list).trim();
34
+ }
35
+ export function weixinInboundSegments(msg) {
36
+ const segments = [];
37
+ const text = formatInboundContent(msg);
38
+ if (text)
39
+ segments.push({ type: 'text', data: { text } });
40
+ const media = msg._media;
41
+ if (media?.decryptedPicPath) {
42
+ segments.push({ type: 'image', data: { media: { kind: 'path', value: media.decryptedPicPath } } });
43
+ }
44
+ else if (media?.decryptedVideoPath) {
45
+ segments.push({ type: 'video', data: { media: { kind: 'path', value: media.decryptedVideoPath } } });
46
+ }
47
+ else if (media?.decryptedFilePath) {
48
+ segments.push({ type: 'file', data: { media: { kind: 'path', value: media.decryptedFilePath } } });
49
+ }
50
+ else if (media?.decryptedVoicePath) {
51
+ segments.push({ type: 'audio', data: { media: { kind: 'path', value: media.decryptedVoicePath } } });
52
+ }
53
+ return Object.freeze(segments);
54
+ }
55
+ export function weixinReplyTo(msg) {
56
+ for (const item of msg.item_list ?? []) {
57
+ const id = item.ref_msg?.message_item?.msg_id;
58
+ if (id && String(id).trim())
59
+ return Object.freeze({ id: String(id).trim() });
60
+ }
61
+ return undefined;
62
+ }
63
+ export function inboundMessageId(msg) {
64
+ return String(msg.message_id ?? msg.client_id ?? msg.seq ?? Date.now());
65
+ }
66
+ /**
67
+ * 入站归一化 → ConversationRef:个人微信无群/频道概念,全部会话都是
68
+ * 与 `from_user_id` 的 private 会话(无 parent)。
69
+ */
70
+ export function weixinIlinkInboundConversation(endpointKey, userId) {
71
+ return {
72
+ endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
73
+ kind: 'private',
74
+ id: userId,
75
+ };
76
+ }
77
+ /**
78
+ * Wire-encode an already-rendered outbound payload into Weixin wire segments.
79
+ * Segment canonicalization is intentionally not done here.
80
+ */
81
+ export function formatOutboundSegments(payload) {
82
+ if (typeof payload === 'string') {
83
+ return [{ type: 'text', data: { text: payload } }];
84
+ }
85
+ const items = Array.isArray(payload)
86
+ ? payload
87
+ : payload && typeof payload === 'object' && 'type' in payload
88
+ ? [payload]
89
+ : [];
90
+ if (items.length === 0) {
91
+ const text = payload == null
92
+ ? ''
93
+ : typeof payload === 'object'
94
+ ? JSON.stringify(payload)
95
+ : String(payload);
96
+ return [{ type: 'text', data: { text } }];
97
+ }
98
+ const segs = [];
99
+ for (const item of items) {
100
+ if (typeof item === 'string') {
101
+ segs.push({ type: 'text', data: { text: item } });
102
+ continue;
103
+ }
104
+ segs.push({ type: item.type, data: item.data ?? {} });
105
+ }
106
+ return segs.length ? segs : [{ type: 'text', data: { text: '' } }];
107
+ }
108
+ /** 物化后的媒体段(data.media kind=path)→ 本地文件路径;其余返回 undefined。 */
109
+ export function segmentLocalPath(seg) {
110
+ const media = (seg.data ?? {}).media;
111
+ if (!isMediaRef(media) || media.kind !== 'path')
112
+ return undefined;
113
+ return media.value;
114
+ }
115
+ export function sleep(ms, signal) {
116
+ return new Promise((resolve) => {
117
+ if (signal?.aborted) {
118
+ resolve();
119
+ return;
120
+ }
121
+ const timer = setTimeout(resolve, ms);
122
+ signal?.addEventListener('abort', () => {
123
+ clearTimeout(timer);
124
+ resolve();
125
+ }, { once: true });
126
+ });
127
+ }
@@ -6,4 +6,3 @@
6
6
  * Callers should fall back to passing the raw SILK file when null is returned.
7
7
  */
8
8
  export declare function silkToWav(silkBuf: Buffer): Promise<Buffer | null>;
9
- //# sourceMappingURL=silk-transcode.d.ts.map
@@ -61,4 +61,3 @@ export async function silkToWav(silkBuf) {
61
61
  return null;
62
62
  }
63
63
  }
64
- //# sourceMappingURL=silk-transcode.js.map
package/lib/types.d.ts CHANGED
@@ -1,26 +1,2 @@
1
- export interface WeixinIlinkEndpointConfig {
2
- context: "weixin-ilink";
3
- name: string;
4
- /** 观测用 bot_agent,默认 Zhin.js/<version> */
5
- botAgent?: string;
6
- /** iLink API 根地址,默认 https://ilinkai.weixin.qq.com */
7
- baseUrl?: string;
8
- /** CDN 根地址 */
9
- cdnBaseUrl?: string;
10
- /** 长轮询超时(ms),默认 35000 */
11
- longPollTimeoutMs?: number;
12
- /** 直接配置 token(优先于侧车凭证文件) */
13
- botToken?: string;
14
- typingIndicator?: {
15
- enabled?: boolean;
16
- /** sendTyping 保活间隔(ms) */
17
- keepaliveIntervalMs?: number;
18
- privateConfig?: {
19
- type?: "typing";
20
- autoRemove?: boolean;
21
- platformConfig?: Record<string, unknown>;
22
- };
23
- };
24
- }
25
- export type { WeixinMessage, MessageItem } from "./ilink-types.js";
26
- //# sourceMappingURL=types.d.ts.map
1
+ export type { WeixinIlinkEndpointConfig, ResolvedWeixinIlinkConfig, } from './protocol.js';
2
+ export type { WeixinMessage, MessageItem } from './ilink-types.js';
package/lib/types.js CHANGED
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=types.js.map
package/lib/upload.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { WeixinApiOptions } from "./ilink-api.js";
1
+ import { type WeixinApiOptions } from './ilink-api.js';
2
2
  export type UploadedFileInfo = {
3
3
  filekey: string;
4
4
  /** 由 upload_param 上传后 CDN 返回的下载加密参数; fill into ImageItem.media.encrypt_query_param */
@@ -40,4 +40,3 @@ export declare function uploadFileAttachmentToWeixin(params: {
40
40
  opts: WeixinApiOptions;
41
41
  cdnBaseUrl: string;
42
42
  }): Promise<UploadedFileInfo>;
43
- //# sourceMappingURL=upload.d.ts.map
package/lib/upload.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { getUploadUrl } from "./ilink-api.js";
4
+ import { getUploadUrl } from './ilink-api.js';
5
5
  import { aesEcbPaddedSize } from "./aes-ecb.js";
6
6
  import { uploadBufferToCdn } from "./cdn-upload.js";
7
7
  import { logger } from "./ilink-logger.js";
@@ -103,4 +103,3 @@ export async function uploadFileAttachmentToWeixin(params) {
103
103
  label: "uploadFileAttachmentToWeixin",
104
104
  });
105
105
  }
106
- //# sourceMappingURL=upload.js.map
@@ -0,0 +1 @@
1
+ export declare const weixinIlinkRuntimeStateToken: import("zhin.js").Token<import("@zhin.js/adapter").EndpointRuntimeState>;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Weixin iLink 插件实例的运行时状态:adapter create() 注册的 endpoint 列表。
3
+ * 由 plugin.ts setup() provide,adapter create 与 `weixin-ilink endpoint` 命令共享(同一 owner generation)。
4
+ */
5
+ import { defineEndpointRuntimeStateToken } from 'zhin.js/adapter';
6
+ export const weixinIlinkRuntimeStateToken = defineEndpointRuntimeStateToken('weixin-ilink');
@@ -1,71 +1,32 @@
1
- import type { WeixinMessage, MessageItem } from "./ilink-types.js";
2
- /**
3
- * Restore persisted context tokens for an account into the in-memory map.
4
- * Called once during gateway startAccount to survive restarts.
5
- */
6
- export declare function restoreContextTokens(accountId: string): void;
7
- /** Remove all context tokens for a given account (memory + disk). */
8
- export declare function clearContextTokensForAccount(accountId: string): void;
9
- /** Store a context token for a given account+user pair (memory + disk). */
10
- export declare function setContextToken(accountId: string, userId: string, token: string): void;
11
- /** Retrieve the cached context token for a given account+user pair. */
12
- export declare function getContextToken(accountId: string, userId: string): string | undefined;
13
- /**
14
- * Find all accountIds that have an active contextToken for the given userId.
15
- * Used to infer the sending bot account from the recipient address when
16
- * accountId is not explicitly provided (e.g. cron delivery).
17
- *
18
- * Returns all matching accountIds (not just the first) so the caller can
19
- * detect ambiguity when multiple accounts have sessions with the same user.
20
- */
21
- export declare function findAccountIdsByContextToken(accountIds: string[], userId: string): string[];
22
- /** Inbound context passed to the OpenClaw core pipeline (matches MsgContext shape). */
1
+ import { type WeixinMessage, type MessageItem } from './ilink-types.js';
23
2
  export type WeixinMsgContext = {
24
3
  Body: string;
25
4
  From: string;
26
5
  To: string;
27
6
  AccountId: string;
28
- OriginatingChannel: "openclaw-weixin";
7
+ OriginatingChannel: 'openclaw-weixin';
29
8
  OriginatingTo: string;
30
9
  MessageSid: string;
31
10
  Timestamp?: number;
32
- Provider: "openclaw-weixin";
33
- ChatType: "direct";
34
- /** Set by monitor after resolveAgentRoute so dispatchReplyFromConfig uses the correct session. */
11
+ Provider: 'openclaw-weixin';
12
+ ChatType: 'direct';
35
13
  SessionKey?: string;
36
14
  context_token?: string;
37
15
  MediaUrl?: string;
38
16
  MediaPath?: string;
39
17
  MediaType?: string;
40
- /** Raw message body for framework command authorization. */
41
18
  CommandBody?: string;
42
- /** Whether the sender is authorized to execute slash commands. */
43
19
  CommandAuthorized?: boolean;
44
20
  };
45
- /** Returns true if the message item is a media type (image, video, file, or voice). */
46
21
  export declare function isMediaItem(item: MessageItem): boolean;
47
22
  export declare function bodyFromItemList(itemList?: MessageItem[]): string;
48
23
  export type WeixinInboundMediaOpts = {
49
- /** Local path to decrypted image file. */
50
24
  decryptedPicPath?: string;
51
- /** Local path to transcoded/raw voice file (.wav or .silk). */
52
25
  decryptedVoicePath?: string;
53
- /** MIME type for the voice file (e.g. "audio/wav" or "audio/silk"). */
54
26
  voiceMediaType?: string;
55
- /** Local path to decrypted file attachment. */
56
27
  decryptedFilePath?: string;
57
- /** MIME type for the file attachment (guessed from file_name). */
58
28
  fileMediaType?: string;
59
- /** Local path to decrypted video file. */
60
29
  decryptedVideoPath?: string;
61
30
  };
62
- /**
63
- * Convert a WeixinMessage from getUpdates to the inbound MsgContext for the core pipeline.
64
- * Media: only pass MediaPath (local file, after CDN download + decrypt).
65
- * We never pass MediaUrl — the upstream CDN URL is encrypted/auth-only.
66
- * Priority when multiple media types present: image > video > file > voice.
67
- */
68
31
  export declare function weixinMessageToMsgContext(msg: WeixinMessage, accountId: string, opts?: WeixinInboundMediaOpts): WeixinMsgContext;
69
- /** Extract the context_token from an inbound WeixinMsgContext. */
70
32
  export declare function getContextTokenFromMsgContext(ctx: WeixinMsgContext): string | undefined;
71
- //# sourceMappingURL=weixin-inbound.d.ts.map
@@ -1,201 +1,61 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { logger } from "./ilink-logger.js";
4
- import { generateId } from "./ilink-random.js";
5
- import { MessageItemType } from "./ilink-types.js";
6
- import { resolveStateDir } from "./credentials.js";
7
- // ---------------------------------------------------------------------------
8
- // Context token store (in-process cache + disk persistence)
9
- // ---------------------------------------------------------------------------
10
- /**
11
- * contextToken is issued per-message by the Weixin getupdates API and must
12
- * be echoed verbatim in every outbound send. The in-memory map is the primary
13
- * lookup; a disk-backed file per account ensures tokens survive gateway restarts.
14
- */
15
- const contextTokenStore = new Map();
16
- function contextTokenKey(accountId, userId) {
17
- return `${accountId}:${userId}`;
18
- }
19
- // ---------------------------------------------------------------------------
20
- // Disk persistence helpers
21
- // ---------------------------------------------------------------------------
22
- function resolveContextTokenFilePath(accountId) {
23
- return path.join(resolveStateDir(), "context-tokens", `${accountId}.context-tokens.json`);
24
- }
25
- /** Persist all context tokens for a given account to disk. */
26
- function persistContextTokens(accountId) {
27
- const prefix = `${accountId}:`;
28
- const tokens = {};
29
- for (const [k, v] of contextTokenStore) {
30
- if (k.startsWith(prefix)) {
31
- tokens[k.slice(prefix.length)] = v;
32
- }
33
- }
34
- const filePath = resolveContextTokenFilePath(accountId);
35
- try {
36
- const dir = path.dirname(filePath);
37
- fs.mkdirSync(dir, { recursive: true });
38
- fs.writeFileSync(filePath, JSON.stringify(tokens, null, 0), "utf-8");
39
- }
40
- catch (err) {
41
- logger.warn(`persistContextTokens: failed to write ${filePath}: ${String(err)}`);
42
- }
43
- }
44
- /**
45
- * Restore persisted context tokens for an account into the in-memory map.
46
- * Called once during gateway startAccount to survive restarts.
47
- */
48
- export function restoreContextTokens(accountId) {
49
- const filePath = resolveContextTokenFilePath(accountId);
50
- try {
51
- if (!fs.existsSync(filePath))
52
- return;
53
- const raw = fs.readFileSync(filePath, "utf-8");
54
- const tokens = JSON.parse(raw);
55
- let count = 0;
56
- for (const [userId, token] of Object.entries(tokens)) {
57
- if (typeof token === "string" && token) {
58
- contextTokenStore.set(contextTokenKey(accountId, userId), token);
59
- count++;
60
- }
61
- }
62
- logger.info(`restoreContextTokens: restored ${count} tokens for account=${accountId}`);
63
- }
64
- catch (err) {
65
- logger.warn(`restoreContextTokens: failed to read ${filePath}: ${String(err)}`);
66
- }
67
- }
68
- /** Remove all context tokens for a given account (memory + disk). */
69
- export function clearContextTokensForAccount(accountId) {
70
- const prefix = `${accountId}:`;
71
- for (const k of [...contextTokenStore.keys()]) {
72
- if (k.startsWith(prefix)) {
73
- contextTokenStore.delete(k);
74
- }
75
- }
76
- const filePath = resolveContextTokenFilePath(accountId);
77
- try {
78
- if (fs.existsSync(filePath))
79
- fs.unlinkSync(filePath);
80
- }
81
- catch (err) {
82
- logger.warn(`clearContextTokensForAccount: failed to remove ${filePath}: ${String(err)}`);
83
- }
84
- logger.info(`clearContextTokensForAccount: cleared tokens for account=${accountId}`);
85
- }
86
- /** Store a context token for a given account+user pair (memory + disk). */
87
- export function setContextToken(accountId, userId, token) {
88
- const k = contextTokenKey(accountId, userId);
89
- logger.debug(`setContextToken: key=${k}`);
90
- contextTokenStore.set(k, token);
91
- persistContextTokens(accountId);
92
- }
93
- /** Retrieve the cached context token for a given account+user pair. */
94
- export function getContextToken(accountId, userId) {
95
- const k = contextTokenKey(accountId, userId);
96
- const val = contextTokenStore.get(k);
97
- logger.debug(`getContextToken: key=${k} found=${val !== undefined} storeSize=${contextTokenStore.size}`);
98
- return val;
99
- }
100
- /**
101
- * Find all accountIds that have an active contextToken for the given userId.
102
- * Used to infer the sending bot account from the recipient address when
103
- * accountId is not explicitly provided (e.g. cron delivery).
104
- *
105
- * Returns all matching accountIds (not just the first) so the caller can
106
- * detect ambiguity when multiple accounts have sessions with the same user.
107
- */
108
- export function findAccountIdsByContextToken(accountIds, userId) {
109
- return accountIds.filter((id) => contextTokenStore.has(contextTokenKey(id, userId)));
110
- }
111
- // ---------------------------------------------------------------------------
112
- // Message ID generation
113
- // ---------------------------------------------------------------------------
1
+ import { generateId } from './ilink-random.js';
2
+ import { MessageItemType } from './ilink-types.js';
114
3
  function generateMessageSid() {
115
- return generateId("openclaw-weixin");
4
+ return generateId('openclaw-weixin');
116
5
  }
117
- /** Returns true if the message item is a media type (image, video, file, or voice). */
118
6
  export function isMediaItem(item) {
119
- return (item.type === MessageItemType.IMAGE ||
120
- item.type === MessageItemType.VIDEO ||
121
- item.type === MessageItemType.FILE ||
122
- item.type === MessageItemType.VOICE);
7
+ return item.type === MessageItemType.IMAGE
8
+ || item.type === MessageItemType.VIDEO
9
+ || item.type === MessageItemType.FILE
10
+ || item.type === MessageItemType.VOICE;
123
11
  }
124
12
  export function bodyFromItemList(itemList) {
125
13
  if (!itemList?.length)
126
- return "";
14
+ return '';
127
15
  for (const item of itemList) {
128
16
  if (item.type === MessageItemType.TEXT && item.text_item?.text != null) {
129
- const text = String(item.text_item.text);
130
- const ref = item.ref_msg;
131
- if (!ref)
132
- return text;
133
- // Quoted media is passed as MediaPath; only include the current text as body.
134
- if (ref.message_item && isMediaItem(ref.message_item))
135
- return text;
136
- // Build quoted context from both title and message_item content.
137
- const parts = [];
138
- if (ref.title)
139
- parts.push(ref.title);
140
- if (ref.message_item) {
141
- const refBody = bodyFromItemList([ref.message_item]);
142
- if (refBody)
143
- parts.push(refBody);
144
- }
145
- if (!parts.length)
146
- return text;
147
- return `[引用: ${parts.join(" | ")}]\n${text}`;
17
+ return String(item.text_item.text);
148
18
  }
149
- // 语音转文字:如果语音消息有 text 字段,直接使用文字内容
150
19
  if (item.type === MessageItemType.VOICE && item.voice_item?.text) {
151
20
  return item.voice_item.text;
152
21
  }
153
22
  }
154
- return "";
23
+ return '';
155
24
  }
156
- /**
157
- * Convert a WeixinMessage from getUpdates to the inbound MsgContext for the core pipeline.
158
- * Media: only pass MediaPath (local file, after CDN download + decrypt).
159
- * We never pass MediaUrl — the upstream CDN URL is encrypted/auth-only.
160
- * Priority when multiple media types present: image > video > file > voice.
161
- */
162
25
  export function weixinMessageToMsgContext(msg, accountId, opts) {
163
- const from_user_id = msg.from_user_id ?? "";
26
+ const fromUserId = msg.from_user_id ?? '';
164
27
  const ctx = {
165
28
  Body: bodyFromItemList(msg.item_list),
166
- From: from_user_id,
167
- To: from_user_id,
29
+ From: fromUserId,
30
+ To: fromUserId,
168
31
  AccountId: accountId,
169
- OriginatingChannel: "openclaw-weixin",
170
- OriginatingTo: from_user_id,
32
+ OriginatingChannel: 'openclaw-weixin',
33
+ OriginatingTo: fromUserId,
171
34
  MessageSid: generateMessageSid(),
172
35
  Timestamp: msg.create_time_ms,
173
- Provider: "openclaw-weixin",
174
- ChatType: "direct",
36
+ Provider: 'openclaw-weixin',
37
+ ChatType: 'direct',
175
38
  };
176
- if (msg.context_token) {
39
+ if (msg.context_token)
177
40
  ctx.context_token = msg.context_token;
178
- }
179
41
  if (opts?.decryptedPicPath) {
180
42
  ctx.MediaPath = opts.decryptedPicPath;
181
- ctx.MediaType = "image/*";
43
+ ctx.MediaType = 'image/*';
182
44
  }
183
45
  else if (opts?.decryptedVideoPath) {
184
46
  ctx.MediaPath = opts.decryptedVideoPath;
185
- ctx.MediaType = "video/mp4";
47
+ ctx.MediaType = 'video/mp4';
186
48
  }
187
49
  else if (opts?.decryptedFilePath) {
188
50
  ctx.MediaPath = opts.decryptedFilePath;
189
- ctx.MediaType = opts.fileMediaType ?? "application/octet-stream";
51
+ ctx.MediaType = opts.fileMediaType ?? 'application/octet-stream';
190
52
  }
191
53
  else if (opts?.decryptedVoicePath) {
192
54
  ctx.MediaPath = opts.decryptedVoicePath;
193
- ctx.MediaType = opts.voiceMediaType ?? "audio/wav";
55
+ ctx.MediaType = opts.voiceMediaType ?? 'audio/wav';
194
56
  }
195
57
  return ctx;
196
58
  }
197
- /** Extract the context_token from an inbound WeixinMsgContext. */
198
59
  export function getContextTokenFromMsgContext(ctx) {
199
60
  return ctx.context_token;
200
61
  }
201
- //# sourceMappingURL=weixin-inbound.js.map
@@ -19,4 +19,3 @@ export declare function sendWeixinMediaFile(params: {
19
19
  }): Promise<{
20
20
  messageId: string;
21
21
  }>;
22
- //# sourceMappingURL=weixin-send-media.d.ts.map
@@ -15,7 +15,11 @@ import { uploadFileAttachmentToWeixin, uploadFileToWeixin, uploadVideoToWeixin }
15
15
  export async function sendWeixinMediaFile(params) {
16
16
  const { filePath, to, text, opts, cdnBaseUrl } = params;
17
17
  const mime = getMimeFromFilename(filePath);
18
- const uploadOpts = { baseUrl: opts.baseUrl, token: opts.token };
18
+ const uploadOpts = {
19
+ baseUrl: opts.baseUrl,
20
+ metadata: opts.metadata,
21
+ token: opts.token,
22
+ };
19
23
  if (mime.startsWith("video/")) {
20
24
  logger.info(`[weixin] sendWeixinMediaFile: uploading video filePath=${filePath} to=${to}`);
21
25
  const uploaded = await uploadVideoToWeixin({
@@ -51,4 +55,3 @@ export async function sendWeixinMediaFile(params) {
51
55
  logger.info(`[weixin] sendWeixinMediaFile: file upload done filekey=${uploaded.filekey} size=${uploaded.fileSize}`);
52
56
  return sendFileMessageWeixin({ to, text, fileName, uploaded, opts });
53
57
  }
54
- //# sourceMappingURL=weixin-send-media.js.map
@@ -1,4 +1,4 @@
1
- import type { WeixinApiOptions } from "./ilink-api.js";
1
+ import { type WeixinApiOptions } from './ilink-api.js';
2
2
  import type { UploadedFileInfo } from "./upload.js";
3
3
  /**
4
4
  * Send a plain text message downstream.
@@ -62,4 +62,3 @@ export declare function sendFileMessageWeixin(params: {
62
62
  }): Promise<{
63
63
  messageId: string;
64
64
  }>;
65
- //# sourceMappingURL=weixin-send.d.ts.map
@@ -1,7 +1,7 @@
1
- import { sendMessage as sendMessageApi } from "./ilink-api.js";
1
+ import { sendMessage as sendMessageApi } from './ilink-api.js';
2
2
  import { logger } from "./ilink-logger.js";
3
3
  import { generateId } from "./ilink-random.js";
4
- import { MessageItemType, MessageState, MessageType } from "./ilink-types.js";
4
+ import { MessageItemType, MessageState, MessageType } from './ilink-types.js';
5
5
  function generateClientId() {
6
6
  return generateId("weixin-ilink");
7
7
  }
@@ -51,6 +51,7 @@ export async function sendMessageWeixin(params) {
51
51
  try {
52
52
  await sendMessageApi({
53
53
  baseUrl: opts.baseUrl,
54
+ metadata: opts.metadata,
54
55
  token: opts.token,
55
56
  timeoutMs: opts.timeoutMs,
56
57
  body: req,
@@ -90,6 +91,7 @@ async function sendMediaItems(params) {
90
91
  try {
91
92
  await sendMessageApi({
92
93
  baseUrl: opts.baseUrl,
94
+ metadata: opts.metadata,
93
95
  token: opts.token,
94
96
  timeoutMs: opts.timeoutMs,
95
97
  body: req,
@@ -178,4 +180,3 @@ export async function sendFileMessageWeixin(params) {
178
180
  };
179
181
  return sendMediaItems({ to, text, mediaItem: fileItem, opts, label: "sendFileMessageWeixin" });
180
182
  }
181
- //# sourceMappingURL=weixin-send.js.map