@xmanrui/dsh-im 4.5.0 → 4.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +4 -1
- package/lib/index.js +247 -239
- package/package.json +1 -1
- package/src/channels/dingtalk/dingtalk-bridge.mjs +166 -20
- package/src/channels/dingtalk/dingtalk-card-stream.mjs +9 -2
- package/src/channels/dingtalk/state-store.mjs +98 -0
- package/src/channels/discord/discord-api.mjs +7 -0
- package/src/channels/discord/discord-runtime.mjs +97 -2
- package/src/channels/feishu/bridge.mjs +11 -5
- package/src/channels/feishu/message-utils.mjs +229 -0
- package/src/channels/qq/qq-bridge.mjs +48 -6
- package/src/channels/shared/batch-input.mjs +3 -3
- package/src/channels/shared/harness-client.mjs +82 -30
- package/src/channels/shared/i18n-en/shared-c.mjs +6 -4
- package/src/channels/shared/image-prompt.mjs +51 -0
- package/src/channels/shared/semantic/reply-reference.mjs +153 -0
- package/src/channels/shared/session-reply-recovery.mjs +104 -0
- package/src/channels/shared/session-title.mjs +1 -1
- package/src/channels/shared/text-harness-bridge.mjs +12 -6
- package/src/channels/slack/manifest.mjs +3 -0
- package/src/channels/slack/slack-api.mjs +18 -0
- package/src/channels/slack/slack-runtime.mjs +56 -0
- package/src/channels/telegram/telegram-runtime.mjs +117 -2
- package/src/channels/wecom/wecom-bridge.mjs +49 -7
- package/src/channels/weixin/state-store.mjs +110 -0
- package/src/channels/weixin/weixin-api.mjs +86 -2
- package/src/channels/weixin/weixin-bridge.mjs +96 -9
- package/src/channels/weixin/weixin-runtime.mjs +26 -6
- package/src/channels/whatsapp/whatsapp-runtime.mjs +56 -0
|
@@ -33,7 +33,6 @@ import {
|
|
|
33
33
|
ImagePromptError,
|
|
34
34
|
imagePromptDiagnostic,
|
|
35
35
|
imagePromptUserMessage,
|
|
36
|
-
promptContentForMessage,
|
|
37
36
|
} from '../shared/image-prompt.mjs';
|
|
38
37
|
import {
|
|
39
38
|
hasInboundFiles,
|
|
@@ -42,6 +41,10 @@ import {
|
|
|
42
41
|
import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
|
|
43
42
|
import { trackOutboundArtifactProviderPromise } from '../shared/semantic/artifact.mjs';
|
|
44
43
|
import { deliverOutboundArtifacts } from '../shared/semantic/artifact-delivery.mjs';
|
|
44
|
+
import {
|
|
45
|
+
hasReplyReference,
|
|
46
|
+
promptContentForInboundMessage,
|
|
47
|
+
} from '../shared/semantic/reply-reference.mjs';
|
|
45
48
|
import {
|
|
46
49
|
createDeliveryReceipt,
|
|
47
50
|
} from '../shared/semantic/delivery.mjs';
|
|
@@ -108,8 +111,7 @@ function conversationKey(frame) {
|
|
|
108
111
|
return body.chattype === 'group' ? `group:${body.chatid}` : `direct:${body.from?.userid}`;
|
|
109
112
|
}
|
|
110
113
|
|
|
111
|
-
function
|
|
112
|
-
const body = bodyOf(frame);
|
|
114
|
+
function messageContentText(body) {
|
|
113
115
|
let text = '';
|
|
114
116
|
if (body.msgtype === 'text') {
|
|
115
117
|
text = typeof body.text?.content === 'string' ? body.text.content.trim() : '';
|
|
@@ -122,6 +124,12 @@ function messageText(frame) {
|
|
|
122
124
|
.join('\n')
|
|
123
125
|
.trim();
|
|
124
126
|
}
|
|
127
|
+
return text;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function messageText(frame) {
|
|
131
|
+
const body = bodyOf(frame);
|
|
132
|
+
const text = messageContentText(body);
|
|
125
133
|
// Group callbacks retain the leading @bot mention that caused delivery.
|
|
126
134
|
// It is routing metadata rather than part of the user's prompt or answer.
|
|
127
135
|
return body.chattype === 'group'
|
|
@@ -145,6 +153,36 @@ function fileContents(frame) {
|
|
|
145
153
|
: [];
|
|
146
154
|
}
|
|
147
155
|
|
|
156
|
+
function quoteAttachments(quote) {
|
|
157
|
+
if (quote?.msgtype === 'image') return [{ kind: 'image' }];
|
|
158
|
+
if (quote?.msgtype === 'voice') return [{ kind: 'audio' }];
|
|
159
|
+
if (quote?.msgtype === 'file') {
|
|
160
|
+
const name = nonEmptyString(
|
|
161
|
+
quote.file?.filename ?? quote.file?.file_name ?? quote.file?.name,
|
|
162
|
+
);
|
|
163
|
+
return [{ kind: 'file', ...(name ? { name } : {}) }];
|
|
164
|
+
}
|
|
165
|
+
if (quote?.msgtype !== 'mixed' || !Array.isArray(quote.mixed?.msg_item)) return [];
|
|
166
|
+
return quote.mixed.msg_item
|
|
167
|
+
.filter((item) => item?.msgtype === 'image')
|
|
168
|
+
.map(() => ({ kind: 'image' }));
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function replyReferenceForBody(body) {
|
|
172
|
+
const quote = body?.quote;
|
|
173
|
+
if (!quote || typeof quote !== 'object') return null;
|
|
174
|
+
const content = messageContentText(quote);
|
|
175
|
+
const attachments = quoteAttachments(quote);
|
|
176
|
+
const supported = ['text', 'image', 'mixed', 'voice', 'file'].includes(quote.msgtype);
|
|
177
|
+
return {
|
|
178
|
+
...(content ? { content } : {}),
|
|
179
|
+
...(attachments.length > 0 ? { attachments } : {}),
|
|
180
|
+
...(!content && attachments.length === 0
|
|
181
|
+
? { unavailableReason: supported ? 'not-delivered' : 'unsupported' }
|
|
182
|
+
: {}),
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
148
186
|
function imageSource(client, image) {
|
|
149
187
|
const url = nonEmptyString(image?.url);
|
|
150
188
|
if (!url) return null;
|
|
@@ -200,10 +238,13 @@ function fileSource(client, file) {
|
|
|
200
238
|
}
|
|
201
239
|
|
|
202
240
|
export function wecomInboundMessage(frame, client) {
|
|
241
|
+
const body = bodyOf(frame);
|
|
242
|
+
const replyTo = replyReferenceForBody(body);
|
|
203
243
|
return {
|
|
204
244
|
content: messageText(frame),
|
|
205
245
|
images: imageContents(frame).map((image) => imageSource(client, image)).filter(Boolean),
|
|
206
246
|
files: fileContents(frame).map((file) => fileSource(client, file)).filter(Boolean),
|
|
247
|
+
...(replyTo ? { replyTo } : {}),
|
|
207
248
|
};
|
|
208
249
|
}
|
|
209
250
|
|
|
@@ -604,7 +645,7 @@ export class WecomHarnessBridge {
|
|
|
604
645
|
&& (this.#queues.has(key) || pending || this.#approvals.hasPending(key))
|
|
605
646
|
? { handled: true, kind: 'busy', message: batchInputBusyMessage() }
|
|
606
647
|
: this.#batchInputs.handle(key, commandText, {
|
|
607
|
-
plainText: isNativeWecomText(frame),
|
|
648
|
+
plainText: isNativeWecomText(frame) && !hasReplyReference(commandMessage),
|
|
608
649
|
});
|
|
609
650
|
if (result.handled) {
|
|
610
651
|
if (result.kind === 'submit') {
|
|
@@ -934,6 +975,7 @@ export class WecomHarnessBridge {
|
|
|
934
975
|
const text = message.content;
|
|
935
976
|
const hasImages = hasInboundImages(message);
|
|
936
977
|
const hasFiles = hasInboundFiles(message);
|
|
978
|
+
const hasReply = hasReplyReference(message);
|
|
937
979
|
const key = conversationKey(frame);
|
|
938
980
|
let streamId = null;
|
|
939
981
|
let streamStarted = false;
|
|
@@ -942,7 +984,7 @@ export class WecomHarnessBridge {
|
|
|
942
984
|
let batchSettled = batchSubmission === null;
|
|
943
985
|
let promptRecorded = false;
|
|
944
986
|
try {
|
|
945
|
-
if (!text && !hasImages && !hasFiles) {
|
|
987
|
+
if (!text && !hasImages && !hasFiles && !hasReply) {
|
|
946
988
|
await this.#sendImmediate(frame, chatId, t('目前支持文字、图片、文件和语音转写消息。'));
|
|
947
989
|
await this.#state.markSeen(messageId);
|
|
948
990
|
return;
|
|
@@ -1003,8 +1045,8 @@ export class WecomHarnessBridge {
|
|
|
1003
1045
|
this.#logger.warn?.('[dsh-im:wecom] unable to start a stream; using an active reply:', error);
|
|
1004
1046
|
}
|
|
1005
1047
|
|
|
1006
|
-
let content = hasImages
|
|
1007
|
-
? await
|
|
1048
|
+
let content = hasImages || hasReply
|
|
1049
|
+
? await promptContentForInboundMessage(message, { signal: this.#signal })
|
|
1008
1050
|
: undefined;
|
|
1009
1051
|
const snapshot = this.#acceptedMessageIds.get(messageId);
|
|
1010
1052
|
let contextEnhanced = false;
|
|
@@ -1,13 +1,67 @@
|
|
|
1
1
|
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
|
|
4
|
+
import { weixinMessageTimestampMs } from './weixin-api.mjs';
|
|
5
|
+
|
|
4
6
|
const EMPTY_STATE = Object.freeze({
|
|
5
7
|
version: 1,
|
|
6
8
|
sessions: {},
|
|
7
9
|
seenMessageIds: [],
|
|
8
10
|
getUpdatesBuf: '',
|
|
11
|
+
recentOutboundMessages: [],
|
|
9
12
|
});
|
|
10
13
|
|
|
14
|
+
export const WEIXIN_RECENT_OUTBOUND_LIMIT = 200;
|
|
15
|
+
export const WEIXIN_RECENT_OUTBOUND_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
|
|
16
|
+
export const WEIXIN_RECENT_OUTBOUND_TEXT_LIMIT = 8_000;
|
|
17
|
+
export const WEIXIN_RECENT_OUTBOUND_MATCH_TOLERANCE_MS = 15_000;
|
|
18
|
+
|
|
19
|
+
function nonEmptyString(value) {
|
|
20
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function timestamp(value) {
|
|
24
|
+
const number = typeof value === 'string' && value.trim() ? Number(value) : value;
|
|
25
|
+
return Number.isFinite(number) && number >= 0 ? Math.trunc(number) : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function providerMessageIds(value) {
|
|
29
|
+
if (!Array.isArray(value)) return [];
|
|
30
|
+
return [...new Set(value
|
|
31
|
+
.map((id) => (id === undefined || id === null ? null : nonEmptyString(String(id))))
|
|
32
|
+
.filter(Boolean))];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function truncateText(value) {
|
|
36
|
+
const text = nonEmptyString(value);
|
|
37
|
+
return text ? [...text].slice(0, WEIXIN_RECENT_OUTBOUND_TEXT_LIMIT).join('') : null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function normalizeRecentOutboundMessage(value) {
|
|
41
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
|
|
42
|
+
const toUserId = nonEmptyString(value.toUserId);
|
|
43
|
+
const text = truncateText(value.text);
|
|
44
|
+
const sentAt = timestamp(value.sentAt);
|
|
45
|
+
const completedAt = timestamp(value.completedAt) ?? sentAt;
|
|
46
|
+
if (!toUserId || !text || sentAt === null || completedAt === null) return null;
|
|
47
|
+
return {
|
|
48
|
+
toUserId,
|
|
49
|
+
text,
|
|
50
|
+
sentAt,
|
|
51
|
+
completedAt: Math.max(sentAt, completedAt),
|
|
52
|
+
providerMessageIds: providerMessageIds(value.providerMessageIds),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function recentOutboundMessages(value, now = Date.now()) {
|
|
57
|
+
if (!Array.isArray(value)) return [];
|
|
58
|
+
const cutoff = now - WEIXIN_RECENT_OUTBOUND_TTL_MS;
|
|
59
|
+
return value
|
|
60
|
+
.map(normalizeRecentOutboundMessage)
|
|
61
|
+
.filter((entry) => entry && entry.completedAt >= cutoff)
|
|
62
|
+
.slice(-WEIXIN_RECENT_OUTBOUND_LIMIT);
|
|
63
|
+
}
|
|
64
|
+
|
|
11
65
|
function normalizeState(value) {
|
|
12
66
|
if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
|
|
13
67
|
const sessions = {};
|
|
@@ -25,6 +79,7 @@ function normalizeState(value) {
|
|
|
25
79
|
? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
|
|
26
80
|
: [],
|
|
27
81
|
getUpdatesBuf: typeof value.getUpdatesBuf === 'string' ? value.getUpdatesBuf : '',
|
|
82
|
+
recentOutboundMessages: recentOutboundMessages(value.recentOutboundMessages),
|
|
28
83
|
};
|
|
29
84
|
}
|
|
30
85
|
|
|
@@ -90,6 +145,61 @@ export class WeixinStateStore {
|
|
|
90
145
|
await this.#persist();
|
|
91
146
|
}
|
|
92
147
|
|
|
148
|
+
async rememberOutboundMessage({
|
|
149
|
+
toUserId,
|
|
150
|
+
text,
|
|
151
|
+
sentAt = Date.now(),
|
|
152
|
+
completedAt = Date.now(),
|
|
153
|
+
providerMessageIds: messageIds = [],
|
|
154
|
+
} = {}) {
|
|
155
|
+
const entry = normalizeRecentOutboundMessage({
|
|
156
|
+
toUserId,
|
|
157
|
+
text,
|
|
158
|
+
sentAt,
|
|
159
|
+
completedAt,
|
|
160
|
+
providerMessageIds: messageIds,
|
|
161
|
+
});
|
|
162
|
+
if (!entry) throw new TypeError('Invalid Weixin outbound message');
|
|
163
|
+
this.#state.recentOutboundMessages = recentOutboundMessages([
|
|
164
|
+
...this.#state.recentOutboundMessages,
|
|
165
|
+
entry,
|
|
166
|
+
]);
|
|
167
|
+
await this.#persist();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
recentOutboundTextFor({
|
|
171
|
+
toUserId,
|
|
172
|
+
messageId,
|
|
173
|
+
createTimeMs,
|
|
174
|
+
updateTimeMs,
|
|
175
|
+
now = Date.now(),
|
|
176
|
+
} = {}) {
|
|
177
|
+
const recipient = nonEmptyString(toUserId);
|
|
178
|
+
if (!recipient) return null;
|
|
179
|
+
const active = recentOutboundMessages(this.#state.recentOutboundMessages, now)
|
|
180
|
+
.filter((entry) => entry.toUserId === recipient);
|
|
181
|
+
const quotedMessageId = messageId === undefined || messageId === null
|
|
182
|
+
? null
|
|
183
|
+
: nonEmptyString(String(messageId));
|
|
184
|
+
if (quotedMessageId) {
|
|
185
|
+
const exact = active.filter((entry) => entry.providerMessageIds.includes(quotedMessageId));
|
|
186
|
+
if (exact.length === 1) return exact[0].text;
|
|
187
|
+
if (exact.length > 1) return null;
|
|
188
|
+
}
|
|
189
|
+
const quotedTimes = [
|
|
190
|
+
timestamp(createTimeMs),
|
|
191
|
+
timestamp(updateTimeMs),
|
|
192
|
+
weixinMessageTimestampMs(quotedMessageId, { now }),
|
|
193
|
+
]
|
|
194
|
+
.filter((value) => value !== null);
|
|
195
|
+
if (quotedTimes.length === 0) return null;
|
|
196
|
+
const candidates = active.filter((entry) => quotedTimes.some((quotedAt) => (
|
|
197
|
+
quotedAt >= entry.sentAt - WEIXIN_RECENT_OUTBOUND_MATCH_TOLERANCE_MS
|
|
198
|
+
&& quotedAt <= entry.completedAt + WEIXIN_RECENT_OUTBOUND_MATCH_TOLERANCE_MS
|
|
199
|
+
)));
|
|
200
|
+
return candidates.length === 1 ? candidates[0].text : null;
|
|
201
|
+
}
|
|
202
|
+
|
|
93
203
|
snapshot() {
|
|
94
204
|
return structuredClone(this.#state);
|
|
95
205
|
}
|
|
@@ -21,6 +21,9 @@ const ILINK_CLIENT_VERSION = (2 << 16) | (4 << 8) | 6;
|
|
|
21
21
|
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
22
22
|
const DEFAULT_LONG_POLL_TIMEOUT_MS = 35_000;
|
|
23
23
|
const WEIXIN_CDN_UPLOAD_RETRIES = 3;
|
|
24
|
+
const WEIXIN_MESSAGE_ID_TIMESTAMP_SHIFT = 22n;
|
|
25
|
+
const WEIXIN_MESSAGE_ID_MIN_TIMESTAMP_MS = Date.UTC(2020, 0, 1);
|
|
26
|
+
const WEIXIN_MESSAGE_ID_MAX_FUTURE_MS = 24 * 60 * 60 * 1_000;
|
|
24
27
|
const LOGIN_STATUSES = new Set([
|
|
25
28
|
'wait',
|
|
26
29
|
'scaned',
|
|
@@ -689,6 +692,7 @@ export function createWeixinApi({ fetchImpl = fetch } = {}) {
|
|
|
689
692
|
const recipient = nonEmptyString(toUserId);
|
|
690
693
|
const content = nonEmptyString(text);
|
|
691
694
|
if (!recipient || !content) throw new TypeError('toUserId and text are required');
|
|
695
|
+
const clientId = `dsh-weixin-${randomUUID()}`;
|
|
692
696
|
const response = await requestJson(fetchImpl, {
|
|
693
697
|
method: 'POST',
|
|
694
698
|
baseUrl,
|
|
@@ -699,7 +703,7 @@ export function createWeixinApi({ fetchImpl = fetch } = {}) {
|
|
|
699
703
|
msg: {
|
|
700
704
|
from_user_id: '',
|
|
701
705
|
to_user_id: recipient,
|
|
702
|
-
client_id:
|
|
706
|
+
client_id: clientId,
|
|
703
707
|
message_type: 2,
|
|
704
708
|
message_state: 2,
|
|
705
709
|
item_list: [{ type: 1, text_item: { text: content } }],
|
|
@@ -717,7 +721,10 @@ export function createWeixinApi({ fetchImpl = fetch } = {}) {
|
|
|
717
721
|
{ providerCode: sendRejection },
|
|
718
722
|
);
|
|
719
723
|
}
|
|
720
|
-
return
|
|
724
|
+
return {
|
|
725
|
+
...(response && typeof response === 'object' ? response : {}),
|
|
726
|
+
providerMessageIds: [clientId],
|
|
727
|
+
};
|
|
721
728
|
},
|
|
722
729
|
|
|
723
730
|
async sendFile(request) {
|
|
@@ -791,6 +798,83 @@ export function extractWeixinText(message) {
|
|
|
791
798
|
return null;
|
|
792
799
|
}
|
|
793
800
|
|
|
801
|
+
function weixinReplyAttachment(item) {
|
|
802
|
+
if (item?.type === 2 || (item?.image_item && typeof item.image_item === 'object')) {
|
|
803
|
+
return { kind: 'image' };
|
|
804
|
+
}
|
|
805
|
+
if (item?.type === 3 || (item?.voice_item && typeof item.voice_item === 'object')) {
|
|
806
|
+
return { kind: 'audio' };
|
|
807
|
+
}
|
|
808
|
+
if (item?.type === 4 || (item?.file_item && typeof item.file_item === 'object')) {
|
|
809
|
+
const name = nonEmptyString(item?.file_item?.file_name);
|
|
810
|
+
return { kind: 'file', ...(name ? { name } : {}) };
|
|
811
|
+
}
|
|
812
|
+
if (item?.type === 5 || (item?.video_item && typeof item.video_item === 'object')) {
|
|
813
|
+
return { kind: 'video' };
|
|
814
|
+
}
|
|
815
|
+
return null;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function weixinQuotedText(item) {
|
|
819
|
+
const text = nonEmptyString(item?.text_item?.text);
|
|
820
|
+
if (text) return text;
|
|
821
|
+
return nonEmptyString(item?.voice_item?.text);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/** Extract the one-level reply snapshot embedded in an inbound iLink message item. */
|
|
825
|
+
export function extractWeixinReplyReference(message, { resolveContent, loadContent } = {}) {
|
|
826
|
+
const container = (message?.item_list ?? []).find((item) => (
|
|
827
|
+
item?.ref_msg && typeof item.ref_msg === 'object'
|
|
828
|
+
));
|
|
829
|
+
if (!container) return null;
|
|
830
|
+
const ref = container.ref_msg;
|
|
831
|
+
const quotedItem = ref.message_item && typeof ref.message_item === 'object'
|
|
832
|
+
? ref.message_item
|
|
833
|
+
: null;
|
|
834
|
+
const quotedText = weixinQuotedText(quotedItem);
|
|
835
|
+
let content = quotedText ?? nonEmptyString(ref.title);
|
|
836
|
+
const attachment = weixinReplyAttachment(quotedItem);
|
|
837
|
+
const messageId = quotedItem?.msg_id === undefined || quotedItem?.msg_id === null
|
|
838
|
+
? null
|
|
839
|
+
: nonEmptyString(String(quotedItem.msg_id));
|
|
840
|
+
const referenceDetails = {
|
|
841
|
+
messageId,
|
|
842
|
+
createTimeMs: quotedItem?.create_time_ms ?? ref.create_time_ms,
|
|
843
|
+
updateTimeMs: quotedItem?.update_time_ms ?? ref.update_time_ms,
|
|
844
|
+
};
|
|
845
|
+
if (!content && !attachment && typeof resolveContent === 'function') {
|
|
846
|
+
content = nonEmptyString(resolveContent(referenceDetails));
|
|
847
|
+
}
|
|
848
|
+
const load = !content && !attachment && typeof loadContent === 'function'
|
|
849
|
+
? (options) => loadContent(referenceDetails, options)
|
|
850
|
+
: null;
|
|
851
|
+
const knownType = quotedItem && [1, 2, 3, 4, 5, 8].includes(quotedItem.type);
|
|
852
|
+
return {
|
|
853
|
+
...(messageId ? { messageId } : {}),
|
|
854
|
+
...(content ? { content } : {}),
|
|
855
|
+
...(attachment ? { attachments: [attachment] } : {}),
|
|
856
|
+
...(load ? { load } : {}),
|
|
857
|
+
...(!content && !attachment && !load
|
|
858
|
+
? { unavailableReason: quotedItem && !knownType ? 'unsupported' : 'not-delivered' }
|
|
859
|
+
: {}),
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/** Decode the millisecond timestamp carried by current 64-bit iLink message IDs. */
|
|
864
|
+
export function weixinMessageTimestampMs(messageId, { now = Date.now() } = {}) {
|
|
865
|
+
const value = messageId === undefined || messageId === null ? '' : String(messageId).trim();
|
|
866
|
+
if (!/^\d{16,20}$/u.test(value)) return null;
|
|
867
|
+
try {
|
|
868
|
+
const timestampMs = Number(BigInt(value) >> WEIXIN_MESSAGE_ID_TIMESTAMP_SHIFT);
|
|
869
|
+
if (!Number.isSafeInteger(timestampMs)
|
|
870
|
+
|| timestampMs < WEIXIN_MESSAGE_ID_MIN_TIMESTAMP_MS
|
|
871
|
+
|| timestampMs > now + WEIXIN_MESSAGE_ID_MAX_FUTURE_MS) return null;
|
|
872
|
+
return timestampMs;
|
|
873
|
+
} catch {
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
794
878
|
export function weixinMessageId(message) {
|
|
795
879
|
if (message?.message_id !== undefined && message.message_id !== null) {
|
|
796
880
|
return String(message.message_id);
|
|
@@ -2,9 +2,11 @@ import {
|
|
|
2
2
|
DEFAULT_WEIXIN_MAX_MESSAGE_CHARS,
|
|
3
3
|
extractWeixinFiles,
|
|
4
4
|
extractWeixinImages,
|
|
5
|
+
extractWeixinReplyReference,
|
|
5
6
|
extractWeixinText,
|
|
6
7
|
splitWeixinText,
|
|
7
8
|
weixinMessageId,
|
|
9
|
+
weixinMessageTimestampMs,
|
|
8
10
|
} from './weixin-api.mjs';
|
|
9
11
|
import {
|
|
10
12
|
harnessAnswerForQuestion,
|
|
@@ -38,7 +40,6 @@ import {
|
|
|
38
40
|
hasInboundImages,
|
|
39
41
|
imagePromptDiagnostic,
|
|
40
42
|
imagePromptUserMessage,
|
|
41
|
-
promptContentForMessage,
|
|
42
43
|
} from '../shared/image-prompt.mjs';
|
|
43
44
|
import {
|
|
44
45
|
hasInboundFiles,
|
|
@@ -47,10 +48,15 @@ import {
|
|
|
47
48
|
} from '../shared/inbound-file.mjs';
|
|
48
49
|
import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
|
|
49
50
|
import { deliverOutboundArtifacts } from '../shared/semantic/artifact-delivery.mjs';
|
|
51
|
+
import {
|
|
52
|
+
hasReplyReference,
|
|
53
|
+
promptContentForInboundMessage,
|
|
54
|
+
} from '../shared/semantic/reply-reference.mjs';
|
|
50
55
|
import {
|
|
51
56
|
createDeliveryReceipt,
|
|
52
57
|
providerMessageIdsFor,
|
|
53
58
|
} from '../shared/semantic/delivery.mjs';
|
|
59
|
+
import { recoverAssistantTextByTimestamp } from '../shared/session-reply-recovery.mjs';
|
|
54
60
|
import {
|
|
55
61
|
channelDeliveryFailure,
|
|
56
62
|
clearLastMessageFailure,
|
|
@@ -67,6 +73,10 @@ const INTERACTION_RESOLVED_TEXT = () => t('这个问题已在其他客户端处
|
|
|
67
73
|
const DEFAULT_TYPING_KEEPALIVE_MS = 5_000;
|
|
68
74
|
const TYPING_RETRY_DELAY_MS = 60_000;
|
|
69
75
|
const WEIXIN_SEND_DIAGNOSTIC = Symbol('weixin-send-diagnostic');
|
|
76
|
+
const WEIXIN_REPLY_HISTORY_PAGE_SIZE = 100;
|
|
77
|
+
const WEIXIN_REPLY_HISTORY_MAX_PAGES = 3;
|
|
78
|
+
const WEIXIN_REPLY_HISTORY_TIMEOUT_MS = 5_000;
|
|
79
|
+
const WEIXIN_REPLY_HISTORY_MATCH_TOLERANCE_MS = 15_000;
|
|
70
80
|
|
|
71
81
|
const HELP_TEXT = () => [
|
|
72
82
|
t('微信已连接 DeepSeek Harness。'),
|
|
@@ -182,7 +192,20 @@ function weixinSendFailureOptions(error) {
|
|
|
182
192
|
return undefined;
|
|
183
193
|
}
|
|
184
194
|
|
|
185
|
-
export function weixinInboundMessage(message, api) {
|
|
195
|
+
export function weixinInboundMessage(message, api, state, { loadReplyContent } = {}) {
|
|
196
|
+
const toUserId = nonEmptyString(message?.from_user_id);
|
|
197
|
+
const replyTo = extractWeixinReplyReference(message, {
|
|
198
|
+
resolveContent: (reference) => state?.recentOutboundTextFor?.({
|
|
199
|
+
toUserId,
|
|
200
|
+
...reference,
|
|
201
|
+
}),
|
|
202
|
+
...(typeof loadReplyContent === 'function' ? {
|
|
203
|
+
loadContent: (reference, options) => loadReplyContent({
|
|
204
|
+
toUserId,
|
|
205
|
+
...reference,
|
|
206
|
+
}, options),
|
|
207
|
+
} : {}),
|
|
208
|
+
});
|
|
186
209
|
return {
|
|
187
210
|
content: extractWeixinText(message) ?? '',
|
|
188
211
|
images: typeof api?.inboundImages === 'function'
|
|
@@ -191,6 +214,7 @@ export function weixinInboundMessage(message, api) {
|
|
|
191
214
|
files: typeof api?.inboundFiles === 'function'
|
|
192
215
|
? api.inboundFiles(message)
|
|
193
216
|
: extractWeixinFiles(message),
|
|
217
|
+
...(replyTo ? { replyTo } : {}),
|
|
194
218
|
};
|
|
195
219
|
}
|
|
196
220
|
|
|
@@ -375,7 +399,8 @@ export class WeixinHarnessBridge {
|
|
|
375
399
|
&& (this.#queues.has(key) || pending || this.#approvals.hasPending(key))
|
|
376
400
|
? { handled: true, kind: 'busy', message: batchInputBusyMessage() }
|
|
377
401
|
: this.#batchInputs.handle(key, commandText, {
|
|
378
|
-
plainText: isNativeWeixinText(message)
|
|
402
|
+
plainText: isNativeWeixinText(message)
|
|
403
|
+
&& !extractWeixinReplyReference(message),
|
|
379
404
|
});
|
|
380
405
|
if (result.handled) {
|
|
381
406
|
if (result.kind === 'submit') {
|
|
@@ -489,7 +514,7 @@ export class WeixinHarnessBridge {
|
|
|
489
514
|
batchSubmission = null,
|
|
490
515
|
} = {}) {
|
|
491
516
|
const preparedMessage = prefetchInboundFiles(
|
|
492
|
-
|
|
517
|
+
this.#inboundMessage(message),
|
|
493
518
|
{ signal: this.#signal },
|
|
494
519
|
);
|
|
495
520
|
const previous = this.#queues.get(key) ?? Promise.resolve();
|
|
@@ -508,6 +533,54 @@ export class WeixinHarnessBridge {
|
|
|
508
533
|
return current;
|
|
509
534
|
}
|
|
510
535
|
|
|
536
|
+
#inboundMessage(message) {
|
|
537
|
+
return weixinInboundMessage(message, this.#api, this.#state, {
|
|
538
|
+
loadReplyContent: (reference, options) => this.#loadReplyContent(reference, options),
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
async #loadReplyContent(reference, { signal: callerSignal } = {}) {
|
|
543
|
+
const indexed = this.#state.recentOutboundTextFor?.(reference);
|
|
544
|
+
if (indexed) return { content: indexed };
|
|
545
|
+
const quotedAt = [
|
|
546
|
+
weixinMessageTimestampMs(reference?.messageId),
|
|
547
|
+
Number(reference?.createTimeMs),
|
|
548
|
+
Number(reference?.updateTimeMs),
|
|
549
|
+
].find(Number.isSafeInteger);
|
|
550
|
+
if (quotedAt === undefined) return { unavailableReason: 'not-delivered' };
|
|
551
|
+
const sender = nonEmptyString(reference?.toUserId);
|
|
552
|
+
const sessionId = sender ? this.#state.sessionFor(conversationKey(sender)) : null;
|
|
553
|
+
const session = typeof sessionId === 'string' && sessionId
|
|
554
|
+
? this.#harness.workspaceSession?.(sessionId)
|
|
555
|
+
: null;
|
|
556
|
+
if (typeof session?.readHistory !== 'function') {
|
|
557
|
+
return { unavailableReason: 'not-delivered' };
|
|
558
|
+
}
|
|
559
|
+
const text = await recoverAssistantTextByTimestamp({
|
|
560
|
+
session,
|
|
561
|
+
quotedAt,
|
|
562
|
+
signal: callerSignal,
|
|
563
|
+
pageSize: WEIXIN_REPLY_HISTORY_PAGE_SIZE,
|
|
564
|
+
maxPages: WEIXIN_REPLY_HISTORY_MAX_PAGES,
|
|
565
|
+
timeoutMs: WEIXIN_REPLY_HISTORY_TIMEOUT_MS,
|
|
566
|
+
toleranceMs: WEIXIN_REPLY_HISTORY_MATCH_TOLERANCE_MS,
|
|
567
|
+
});
|
|
568
|
+
if (!text) return { unavailableReason: 'not-delivered' };
|
|
569
|
+
const messageId = nonEmptyString(reference?.messageId);
|
|
570
|
+
try {
|
|
571
|
+
await this.#state.rememberOutboundMessage?.({
|
|
572
|
+
toUserId: sender,
|
|
573
|
+
text,
|
|
574
|
+
sentAt: quotedAt,
|
|
575
|
+
completedAt: quotedAt,
|
|
576
|
+
providerMessageIds: messageId ? [messageId] : [],
|
|
577
|
+
});
|
|
578
|
+
} catch (error) {
|
|
579
|
+
this.#logger.warn?.('[dsh-weixin] failed to remember a recovered quote:', error);
|
|
580
|
+
}
|
|
581
|
+
return { content: text };
|
|
582
|
+
}
|
|
583
|
+
|
|
511
584
|
#finishBatchResult(message, messageId, key, sender, contextToken, runId, result) {
|
|
512
585
|
let task;
|
|
513
586
|
task = Promise.resolve().then(async () => {
|
|
@@ -644,11 +717,12 @@ export class WeixinHarnessBridge {
|
|
|
644
717
|
let batchSettled = batchSubmission === null;
|
|
645
718
|
let promptRecorded = false;
|
|
646
719
|
try {
|
|
647
|
-
const promptMessage = preparedMessage ??
|
|
720
|
+
const promptMessage = preparedMessage ?? this.#inboundMessage(message);
|
|
648
721
|
const text = promptMessage.content;
|
|
649
722
|
const hasImages = hasInboundImages(promptMessage);
|
|
650
723
|
const hasFiles = hasInboundFiles(promptMessage);
|
|
651
|
-
|
|
724
|
+
const hasReply = hasReplyReference(promptMessage);
|
|
725
|
+
if (!text && !hasImages && !hasFiles && !hasReply) {
|
|
652
726
|
await this.#send(sender, t('目前支持文字、图片、文件,以及微信已转成文字的语音消息。'), contextToken, runId);
|
|
653
727
|
await this.#state.markSeen(messageId);
|
|
654
728
|
return;
|
|
@@ -701,8 +775,8 @@ export class WeixinHarnessBridge {
|
|
|
701
775
|
let artifacts = [];
|
|
702
776
|
await this.#startTyping(sender, contextToken);
|
|
703
777
|
try {
|
|
704
|
-
let content = hasImages
|
|
705
|
-
? await
|
|
778
|
+
let content = hasImages || hasReply
|
|
779
|
+
? await promptContentForInboundMessage(promptMessage, { signal: this.#signal })
|
|
706
780
|
: undefined;
|
|
707
781
|
const snapshot = this.#acceptedMessageIds.get(messageId);
|
|
708
782
|
let contextEnhanced = false;
|
|
@@ -1154,6 +1228,7 @@ export class WeixinHarnessBridge {
|
|
|
1154
1228
|
const chunks = splitWeixinText(text, this.#maxMessageChars);
|
|
1155
1229
|
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex += 1) {
|
|
1156
1230
|
const chunk = chunks[chunkIndex];
|
|
1231
|
+
const sentAt = Date.now();
|
|
1157
1232
|
try {
|
|
1158
1233
|
const result = await this.#api.sendText({
|
|
1159
1234
|
baseUrl: this.#baseUrl,
|
|
@@ -1164,7 +1239,19 @@ export class WeixinHarnessBridge {
|
|
|
1164
1239
|
runId,
|
|
1165
1240
|
signal: this.#signal,
|
|
1166
1241
|
});
|
|
1167
|
-
|
|
1242
|
+
const chunkMessageIds = providerMessageIdsFor(result);
|
|
1243
|
+
providerMessageIds.push(...chunkMessageIds);
|
|
1244
|
+
try {
|
|
1245
|
+
await this.#state.rememberOutboundMessage?.({
|
|
1246
|
+
toUserId,
|
|
1247
|
+
text: chunk,
|
|
1248
|
+
sentAt,
|
|
1249
|
+
completedAt: Date.now(),
|
|
1250
|
+
providerMessageIds: chunkMessageIds,
|
|
1251
|
+
});
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
this.#logger.warn?.('[dsh-weixin] failed to remember an outbound message:', error);
|
|
1254
|
+
}
|
|
1168
1255
|
} catch (error) {
|
|
1169
1256
|
throw weixinSendError(error, {
|
|
1170
1257
|
baseUrl: this.#baseUrl,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { DEFAULT_WEIXIN_MAX_MESSAGE_CHARS, WeixinApiError } from './weixin-api.mjs';
|
|
2
2
|
import { createWeixinBridgeStatus, WeixinHarnessBridge } from './weixin-bridge.mjs';
|
|
3
|
+
import { providerMessageIdsFor } from '../shared/semantic/delivery.mjs';
|
|
3
4
|
import {
|
|
4
5
|
connectionTestTarget,
|
|
5
6
|
connectionTestTargetUnavailable,
|
|
@@ -324,9 +325,7 @@ export class WeixinRuntime {
|
|
|
324
325
|
if (!this.#status.ready || !this.#abortController) {
|
|
325
326
|
throw new Error('Weixin runtime is not connected');
|
|
326
327
|
}
|
|
327
|
-
await this.#
|
|
328
|
-
baseUrl: this.#config.baseUrl,
|
|
329
|
-
token: this.#token,
|
|
328
|
+
await this.#sendTrackedText({
|
|
330
329
|
toUserId,
|
|
331
330
|
text,
|
|
332
331
|
signal: this.#abortController.signal,
|
|
@@ -334,6 +333,29 @@ export class WeixinRuntime {
|
|
|
334
333
|
return { sent: true };
|
|
335
334
|
}
|
|
336
335
|
|
|
336
|
+
async #sendTrackedText({ toUserId, text, signal }) {
|
|
337
|
+
const sentAt = Date.now();
|
|
338
|
+
const result = await this.#api.sendText({
|
|
339
|
+
baseUrl: this.#config.baseUrl,
|
|
340
|
+
token: this.#token,
|
|
341
|
+
toUserId,
|
|
342
|
+
text,
|
|
343
|
+
signal,
|
|
344
|
+
});
|
|
345
|
+
try {
|
|
346
|
+
await this.#state.rememberOutboundMessage?.({
|
|
347
|
+
toUserId,
|
|
348
|
+
text,
|
|
349
|
+
sentAt,
|
|
350
|
+
completedAt: Date.now(),
|
|
351
|
+
providerMessageIds: providerMessageIdsFor(result),
|
|
352
|
+
});
|
|
353
|
+
} catch (error) {
|
|
354
|
+
this.#logger.warn?.('[dsh-weixin] failed to remember an outbound message:', error);
|
|
355
|
+
}
|
|
356
|
+
return result;
|
|
357
|
+
}
|
|
358
|
+
|
|
337
359
|
async sendProactiveText(target, text, { signal } = {}) {
|
|
338
360
|
const toUserId = typeof target?.route?.toUserId === 'string'
|
|
339
361
|
? target.route.toUserId.trim() : '';
|
|
@@ -348,9 +370,7 @@ export class WeixinRuntime {
|
|
|
348
370
|
throw error;
|
|
349
371
|
}
|
|
350
372
|
signal?.throwIfAborted();
|
|
351
|
-
await this.#
|
|
352
|
-
baseUrl: this.#config.baseUrl,
|
|
353
|
-
token: this.#token,
|
|
373
|
+
await this.#sendTrackedText({
|
|
354
374
|
toUserId,
|
|
355
375
|
text,
|
|
356
376
|
signal: signal ?? this.#abortController.signal,
|