@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.
- package/CHANGELOG.md +512 -0
- package/README.md +24 -42
- package/adapters/weixin-ilink/index.js +32 -0
- package/adapters/weixin-ilink/index.ts +43 -0
- package/commands/weixin-ilink/endpoint/add/[id]/index.js +3 -0
- package/commands/weixin-ilink/endpoint/add/[id]/index.ts +3 -0
- package/commands/weixin-ilink/endpoint/definition.js +17 -0
- package/commands/weixin-ilink/endpoint/definition.ts +17 -0
- package/commands/weixin-ilink/endpoint/list/index.js +3 -0
- package/commands/weixin-ilink/endpoint/list/index.ts +3 -0
- package/commands/weixin-ilink/endpoint/remove/[id]/index.js +3 -0
- package/commands/weixin-ilink/endpoint/remove/[id]/index.ts +3 -0
- package/lib/aes-ecb.d.ts +0 -1
- package/lib/aes-ecb.js +0 -1
- package/lib/cdn-upload.d.ts +0 -1
- package/lib/cdn-upload.js +0 -1
- package/lib/cdn-url.d.ts +0 -1
- package/lib/cdn-url.js +0 -1
- package/lib/client.d.ts +35 -0
- package/lib/client.js +89 -0
- package/lib/context-store.d.ts +15 -2
- package/lib/context-store.js +93 -2
- package/lib/credentials.d.ts +15 -8
- package/lib/credentials.js +59 -43
- package/lib/endpoint.d.ts +40 -35
- package/lib/endpoint.js +311 -262
- package/lib/ilink-api.d.ts +7 -6
- package/lib/ilink-api.js +26 -16
- package/lib/ilink-config-cache.d.ts +3 -8
- package/lib/ilink-config-cache.js +13 -15
- package/lib/ilink-logger.d.ts +0 -2
- package/lib/ilink-logger.js +11 -26
- package/lib/ilink-meta.d.ts +13 -8
- package/lib/ilink-meta.js +24 -21
- package/lib/ilink-random.d.ts +0 -1
- package/lib/ilink-random.js +0 -1
- package/lib/ilink-redact.d.ts +0 -1
- package/lib/ilink-redact.js +0 -1
- package/lib/ilink-session-guard.d.ts +13 -15
- package/lib/ilink-session-guard.js +29 -43
- package/lib/ilink-types.d.ts +0 -1
- package/lib/ilink-types.js +0 -1
- package/lib/index.d.ts +8 -20
- package/lib/index.js +7 -38
- package/lib/login.d.ts +5 -6
- package/lib/login.js +85 -77
- package/lib/media-download.d.ts +1 -2
- package/lib/media-download.js +1 -2
- package/lib/mime.d.ts +0 -1
- package/lib/mime.js +0 -1
- package/lib/outbound-media.d.ts +4 -5
- package/lib/outbound-media.js +85 -86
- package/lib/pic-decrypt.d.ts +0 -1
- package/lib/pic-decrypt.js +0 -1
- package/lib/protocol.d.ts +60 -0
- package/lib/protocol.js +127 -0
- package/lib/silk-transcode.d.ts +0 -1
- package/lib/silk-transcode.js +0 -1
- package/lib/types.d.ts +2 -26
- package/lib/types.js +0 -1
- package/lib/upload.d.ts +1 -2
- package/lib/upload.js +1 -2
- package/lib/weixin-ilink-runtime-state.d.ts +1 -0
- package/lib/weixin-ilink-runtime-state.js +6 -0
- package/lib/weixin-inbound.d.ts +4 -43
- package/lib/weixin-inbound.js +22 -162
- package/lib/weixin-send-media.d.ts +0 -1
- package/lib/weixin-send-media.js +5 -2
- package/lib/weixin-send.d.ts +1 -2
- package/lib/weixin-send.js +4 -3
- package/package.json +48 -39
- package/plugin.js +14 -0
- package/schema.json +116 -0
- package/src/client.ts +117 -0
- package/src/context-store.ts +101 -8
- package/src/credentials.ts +68 -45
- package/src/endpoint.ts +384 -315
- package/src/ilink-api.ts +31 -21
- package/src/ilink-config-cache.ts +17 -13
- package/src/ilink-logger.ts +11 -26
- package/src/ilink-meta.ts +31 -21
- package/src/ilink-session-guard.ts +29 -46
- package/src/index.ts +41 -56
- package/src/login.ts +112 -85
- package/src/media-download.ts +1 -2
- package/src/outbound-media.ts +97 -97
- package/src/protocol.ts +180 -0
- package/src/silk-wasm.d.ts +6 -2
- package/src/types.ts +5 -25
- package/src/upload.test.ts +11 -8
- package/src/upload.ts +2 -2
- package/src/weixin-ilink-runtime-state.ts +7 -0
- package/src/weixin-inbound.ts +25 -187
- package/src/weixin-send-media.ts +5 -1
- package/src/weixin-send.ts +6 -4
- package/client/LoginAssistPanel.tsx +0 -200
- package/client/WeixinIlinkManagement.tsx +0 -139
- package/client/index.tsx +0 -11
- package/client/tsconfig.json +0 -13
- package/client/utils/api.ts +0 -30
- package/dist/index.js +0 -29
- package/lib/adapter.d.ts +0 -12
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -15
- package/lib/adapter.js.map +0 -1
- package/lib/aes-ecb.d.ts.map +0 -1
- package/lib/aes-ecb.js.map +0 -1
- package/lib/cdn-upload.d.ts.map +0 -1
- package/lib/cdn-upload.js.map +0 -1
- package/lib/cdn-upload.test.d.ts +0 -2
- package/lib/cdn-upload.test.d.ts.map +0 -1
- package/lib/cdn-upload.test.js +0 -150
- package/lib/cdn-upload.test.js.map +0 -1
- package/lib/cdn-url.d.ts.map +0 -1
- package/lib/cdn-url.js.map +0 -1
- package/lib/context-store.d.ts.map +0 -1
- package/lib/context-store.js.map +0 -1
- package/lib/credentials.d.ts.map +0 -1
- package/lib/credentials.js.map +0 -1
- package/lib/endpoint.d.ts.map +0 -1
- package/lib/endpoint.js.map +0 -1
- package/lib/ilink-api.d.ts.map +0 -1
- package/lib/ilink-api.js.map +0 -1
- package/lib/ilink-config-cache.d.ts.map +0 -1
- package/lib/ilink-config-cache.js.map +0 -1
- package/lib/ilink-logger.d.ts.map +0 -1
- package/lib/ilink-logger.js.map +0 -1
- package/lib/ilink-meta.d.ts.map +0 -1
- package/lib/ilink-meta.js.map +0 -1
- package/lib/ilink-random.d.ts.map +0 -1
- package/lib/ilink-random.js.map +0 -1
- package/lib/ilink-redact.d.ts.map +0 -1
- package/lib/ilink-redact.js.map +0 -1
- package/lib/ilink-session-guard.d.ts.map +0 -1
- package/lib/ilink-session-guard.js.map +0 -1
- package/lib/ilink-types.d.ts.map +0 -1
- package/lib/ilink-types.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/login-assist-routes.d.ts +0 -7
- package/lib/login-assist-routes.d.ts.map +0 -1
- package/lib/login-assist-routes.js +0 -29
- package/lib/login-assist-routes.js.map +0 -1
- package/lib/login.d.ts.map +0 -1
- package/lib/login.js.map +0 -1
- package/lib/media-download.d.ts.map +0 -1
- package/lib/media-download.js.map +0 -1
- package/lib/mime.d.ts.map +0 -1
- package/lib/mime.js.map +0 -1
- package/lib/mime.test.d.ts +0 -2
- package/lib/mime.test.d.ts.map +0 -1
- package/lib/mime.test.js +0 -62
- package/lib/mime.test.js.map +0 -1
- package/lib/outbound-media.d.ts.map +0 -1
- package/lib/outbound-media.js.map +0 -1
- package/lib/pic-decrypt.d.ts.map +0 -1
- package/lib/pic-decrypt.js.map +0 -1
- package/lib/routes.d.ts +0 -8
- package/lib/routes.d.ts.map +0 -1
- package/lib/routes.js +0 -29
- package/lib/routes.js.map +0 -1
- package/lib/silk-transcode.d.ts.map +0 -1
- package/lib/silk-transcode.js.map +0 -1
- package/lib/silk-transcode.test.d.ts +0 -2
- package/lib/silk-transcode.test.d.ts.map +0 -1
- package/lib/silk-transcode.test.js +0 -53
- package/lib/silk-transcode.test.js.map +0 -1
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js.map +0 -1
- package/lib/typing-indicator.d.ts +0 -32
- package/lib/typing-indicator.d.ts.map +0 -1
- package/lib/typing-indicator.js +0 -95
- package/lib/typing-indicator.js.map +0 -1
- package/lib/upload.d.ts.map +0 -1
- package/lib/upload.js.map +0 -1
- package/lib/upload.test.d.ts +0 -2
- package/lib/upload.test.d.ts.map +0 -1
- package/lib/upload.test.js +0 -250
- package/lib/upload.test.js.map +0 -1
- package/lib/weixin-inbound.d.ts.map +0 -1
- package/lib/weixin-inbound.js.map +0 -1
- package/lib/weixin-send-media.d.ts.map +0 -1
- package/lib/weixin-send-media.js.map +0 -1
- package/lib/weixin-send.d.ts.map +0 -1
- package/lib/weixin-send.js.map +0 -1
- package/src/adapter.ts +0 -18
- package/src/login-assist-routes.ts +0 -36
- package/src/routes.ts +0 -39
- package/src/typing-indicator.ts +0 -139
package/lib/protocol.js
ADDED
|
@@ -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
|
+
}
|
package/lib/silk-transcode.d.ts
CHANGED
package/lib/silk-transcode.js
CHANGED
package/lib/types.d.ts
CHANGED
|
@@ -1,26 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
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
package/lib/upload.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
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
|
|
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');
|
package/lib/weixin-inbound.d.ts
CHANGED
|
@@ -1,71 +1,32 @@
|
|
|
1
|
-
import type
|
|
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:
|
|
7
|
+
OriginatingChannel: 'openclaw-weixin';
|
|
29
8
|
OriginatingTo: string;
|
|
30
9
|
MessageSid: string;
|
|
31
10
|
Timestamp?: number;
|
|
32
|
-
Provider:
|
|
33
|
-
ChatType:
|
|
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
|
package/lib/weixin-inbound.js
CHANGED
|
@@ -1,201 +1,61 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
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(
|
|
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
|
|
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
|
-
|
|
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
|
|
26
|
+
const fromUserId = msg.from_user_id ?? '';
|
|
164
27
|
const ctx = {
|
|
165
28
|
Body: bodyFromItemList(msg.item_list),
|
|
166
|
-
From:
|
|
167
|
-
To:
|
|
29
|
+
From: fromUserId,
|
|
30
|
+
To: fromUserId,
|
|
168
31
|
AccountId: accountId,
|
|
169
|
-
OriginatingChannel:
|
|
170
|
-
OriginatingTo:
|
|
32
|
+
OriginatingChannel: 'openclaw-weixin',
|
|
33
|
+
OriginatingTo: fromUserId,
|
|
171
34
|
MessageSid: generateMessageSid(),
|
|
172
35
|
Timestamp: msg.create_time_ms,
|
|
173
|
-
Provider:
|
|
174
|
-
ChatType:
|
|
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 =
|
|
43
|
+
ctx.MediaType = 'image/*';
|
|
182
44
|
}
|
|
183
45
|
else if (opts?.decryptedVideoPath) {
|
|
184
46
|
ctx.MediaPath = opts.decryptedVideoPath;
|
|
185
|
-
ctx.MediaType =
|
|
47
|
+
ctx.MediaType = 'video/mp4';
|
|
186
48
|
}
|
|
187
49
|
else if (opts?.decryptedFilePath) {
|
|
188
50
|
ctx.MediaPath = opts.decryptedFilePath;
|
|
189
|
-
ctx.MediaType = opts.fileMediaType ??
|
|
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 ??
|
|
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
|
package/lib/weixin-send-media.js
CHANGED
|
@@ -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 = {
|
|
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
|
package/lib/weixin-send.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
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
|
package/lib/weixin-send.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { sendMessage as sendMessageApi } from
|
|
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
|
|
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
|