fix: support Harness interactions across IM channels

This commit is contained in:
xmanrui 2026-08-18 14:13:10 +08:00
parent 3e7e1dcdd7
commit cd8175d341
30 changed files with 5433 additions and 555 deletions

View file

@ -1,3 +1,11 @@
import { HarnessClient } from '../weixin/harness-client.mjs';
import { HarnessClient } from '../shared/harness-client.mjs';
export class WecomHarnessClient extends HarnessClient {}
export class WecomHarnessClient extends HarnessClient {
constructor(options) {
super({
...options,
rpcIdPrefix: 'wecom',
logPrefix: 'dsh-wecom',
});
}
}

View file

@ -1,4 +1,9 @@
import { generateReqId } from '@wecom/aibot-node-sdk';
import {
harnessAnswerForQuestion,
harnessQuestionText,
validHarnessQuestion,
} from '../shared/harness-question.mjs';
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
@ -15,6 +20,11 @@ const HELP_TEXT = [
'/help 显示本帮助',
].join('\n');
const MAX_REPLY_BYTES = 18_000;
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
function nonEmptyString(value) {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
function bodyOf(frame) {
return frame?.body && typeof frame.body === 'object' ? frame.body : {};
@ -27,16 +37,23 @@ function conversationKey(frame) {
function messageText(frame) {
const body = bodyOf(frame);
if (body.msgtype === 'text') return typeof body.text?.content === 'string' ? body.text.content.trim() : '';
if (body.msgtype === 'voice') return typeof body.voice?.content === 'string' ? body.voice.content.trim() : '';
if (body.msgtype === 'mixed' && Array.isArray(body.mixed?.msg_item)) {
return body.mixed.msg_item
let text = '';
if (body.msgtype === 'text') {
text = typeof body.text?.content === 'string' ? body.text.content.trim() : '';
} else if (body.msgtype === 'voice') {
text = typeof body.voice?.content === 'string' ? body.voice.content.trim() : '';
} else if (body.msgtype === 'mixed' && Array.isArray(body.mixed?.msg_item)) {
text = body.mixed.msg_item
.filter((item) => item?.msgtype === 'text' && typeof item.text?.content === 'string')
.map((item) => item.text.content)
.join('\n')
.trim();
}
return '';
// Group callbacks retain the leading @bot mention that caused delivery.
// It is routing metadata rather than part of the user's prompt or answer.
return body.chattype === 'group'
? text.replace(/^\s*@\S+(?:\s+|$)/u, '').trim()
: text;
}
function splitUtf8(text, maxBytes = MAX_REPLY_BYTES) {
@ -66,6 +83,12 @@ function progressText(update) {
return update?.text;
}
function canClaimInteractionReply(frame, pending) {
return pending.questions[pending.index]
&& nonEmptyString(bodyOf(frame).from?.userid) === pending.actor
&& nonEmptyString(messageText(frame));
}
export function createWecomBridgeStatus() {
return {
messagesReceived: 0,
@ -86,7 +109,11 @@ export class WecomHarnessBridge {
#logger;
#replyTimeoutMs;
#generateReqId;
#signal;
#queues = new Map();
#pendingInteractions = new Map();
#interactionKeys = new Map();
#acceptedMessageIds = new Set();
constructor({
client,
@ -96,6 +123,7 @@ export class WecomHarnessBridge {
logger = console,
replyTimeoutMs = 600_000,
generateStreamId = generateReqId,
signal,
}) {
if (!client || typeof client.replyStream !== 'function' || typeof client.sendMessage !== 'function') {
throw new TypeError('Enterprise WeChat client is required');
@ -108,6 +136,7 @@ export class WecomHarnessBridge {
this.#logger = logger;
this.#replyTimeoutMs = replyTimeoutMs;
this.#generateReqId = generateStreamId;
this.#signal = signal;
}
get status() {
@ -115,12 +144,65 @@ export class WecomHarnessBridge {
}
accept(frame) {
if (this.#signal?.aborted) return Promise.resolve();
const body = bodyOf(frame);
const messageId = nonEmptyString(body.msgid);
const senderId = nonEmptyString(body.from?.userid);
const chatId = body.chattype === 'group'
? nonEmptyString(body.chatid)
: senderId;
if (!messageId || !senderId || !chatId
|| !['single', 'group'].includes(body.chattype)
|| this.#state.hasSeen(messageId)
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
const key = conversationKey(frame);
this.#acceptedMessageIds.add(messageId);
const pending = this.#pendingInteractions.get(key);
if (pending && pending.actor !== senderId) {
return this.#enqueueMessage(frame, messageId, key);
}
if (pending?.submitting || pending?.claimedReplyMessageId) {
return this.#enqueueMessage(frame, messageId, key);
}
if (pending) {
if (canClaimInteractionReply(frame, pending)) {
pending.claimedReplyMessageId = messageId;
}
const previous = pending.queue ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#processInteractionReply(
frame,
messageId,
senderId,
chatId,
key,
pending,
))
.finally(() => {
this.#acceptedMessageIds.delete(messageId);
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
if (pending.queue === current) pending.queue = null;
});
pending.queue = current;
return current;
}
return this.#enqueueMessage(frame, messageId, key);
}
#enqueueMessage(frame, messageId, key, {
releaseMessageId = true,
alreadyRecorded = false,
} = {}) {
const previous = this.#queues.get(key) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
.then(() => this.#process(frame))
.then(() => this.#process(frame, { alreadyRecorded }))
.finally(() => {
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
if (this.#queues.get(key) === current) this.#queues.delete(key);
});
this.#queues.set(key, current);
@ -128,16 +210,23 @@ export class WecomHarnessBridge {
}
async waitForIdle() {
await Promise.allSettled([...this.#queues.values()]);
await Promise.allSettled([
...this.#queues.values(),
...[...this.#pendingInteractions.values()].flatMap((pending) => (
pending.queue ? [pending.queue] : []
)),
]);
}
async #sendActive(chatId, text) {
for (const chunk of splitUtf8(text)) {
this.#signal?.throwIfAborted();
await this.#client.sendMessage(chatId, { msgtype: 'markdown', markdown: { content: chunk } });
}
}
async #sendImmediate(frame, chatId, text) {
this.#signal?.throwIfAborted();
const chunks = splitUtf8(text);
if (chunks.length === 0) return;
try {
@ -150,17 +239,20 @@ export class WecomHarnessBridge {
}
}
async #process(frame) {
async #process(frame, { alreadyRecorded = false } = {}) {
if (this.#signal?.aborted) return;
const body = bodyOf(frame);
const messageId = typeof body.msgid === 'string' ? body.msgid : '';
const senderId = typeof body.from?.userid === 'string' ? body.from.userid : '';
const chatId = body.chattype === 'group' ? body.chatid : senderId;
if (!messageId || !senderId || !chatId || !['single', 'group'].includes(body.chattype)) return;
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
if (!alreadyRecorded) {
if (this.#state.hasSeen(messageId)) return;
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
}
const text = messageText(frame);
const key = conversationKey(frame);
let streamId = null;
let streamStarted = false;
try {
@ -176,12 +268,11 @@ export class WecomHarnessBridge {
return;
}
if (command === '/status') {
await this.#harness.ensureRunning();
await this.#harness.ensureRunning({ signal: this.#signal });
await this.#sendImmediate(frame, chatId, '企业微信机器人与 DeepSeek Harness 连接正常。');
await this.#state.markSeen(messageId);
return;
}
const key = conversationKey(frame);
if (command === '/new') {
await this.#state.clearSession(key);
await this.#sendImmediate(frame, chatId, '已开启新会话。请发送你的问题。');
@ -210,14 +301,24 @@ export class WecomHarnessBridge {
state: this.#state,
key,
text,
createOptions: { signal: this.#signal },
existsOptions: { signal: this.#signal },
askOptions: {
timeoutMs: this.#replyTimeoutMs,
signal: this.#signal,
onUpdate: streamStarted && typeof this.#client.replyStreamNonBlocking === 'function'
? async (update) => {
const progress = splitUtf8(progressText(update))[0];
if (progress) await this.#client.replyStreamNonBlocking(frame, streamId, progress, false);
}
: undefined,
onInteraction: (interaction) => this.#handleInteraction(interaction, {
key,
actor: senderId,
chatId,
requiresMention: body.chattype === 'group',
}),
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
},
});
@ -240,6 +341,7 @@ export class WecomHarnessBridge {
this.#status.lastReplyAt = new Date().toISOString();
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
this.#status.lastError = error?.message ?? String(error);
this.#logger.error?.('[dsh-im:wecom] failed to process an inbound message');
try {
@ -252,6 +354,276 @@ export class WecomHarnessBridge {
} catch {
this.#logger.error?.('[dsh-im:wecom] failed to send the safe error reply');
}
} finally {
await this.#cancelPendingInteraction(key);
}
}
async #processInteractionReply(frame, messageId, senderId, chatId, key, expected) {
if (this.#signal?.aborted) return;
const current = this.#pendingInteractions.get(key);
const claimed = expected.claimedReplyMessageId === messageId;
if (!current || current !== expected || current.submitting) {
if (claimed && (!current || current !== expected)) {
return this.#discardResolvedInteractionReply(frame, messageId, chatId);
}
return this.#enqueueMessage(frame, messageId, key, { releaseMessageId: false });
}
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
const text = nonEmptyString(messageText(frame));
if (!text) {
await this.#sendImmediate(frame, chatId, '请用文字或语音回答当前问题。')
.catch(() => undefined);
return;
}
const pending = this.#pendingInteractions.get(key);
if (!pending || pending !== expected || pending.submitting) {
if (claimed && (!pending || pending !== expected)) {
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
return this.#enqueueMessage(frame, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
if (pending.actor !== senderId) {
return this.#enqueueMessage(frame, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
pending.chatId = chatId;
if (pending.needsPresentation) {
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = '企业微信交互问题发送失败。';
this.#logger.error?.('[dsh-im:wecom] failed to retry an interaction question');
pending.interaction.reconnect?.();
return;
}
const presentedPending = this.#pendingInteractions.get(key);
if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
if (claimed && (!presentedPending || presentedPending !== expected)) {
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
return this.#enqueueMessage(frame, messageId, key, {
releaseMessageId: false,
alreadyRecorded: true,
});
}
}
const question = pending.questions[pending.index];
if (!question) return;
pending.answers.push(harnessAnswerForQuestion(question, text));
pending.index += 1;
if (pending.index < pending.questions.length) {
if (pending.claimedReplyMessageId === messageId) {
pending.claimedReplyMessageId = null;
}
pending.needsPresentation = true;
try {
await this.#presentInteraction(pending);
} catch {
this.#status.lastError = '企业微信交互问题发送失败。';
this.#logger.error?.('[dsh-im:wecom] failed to send the next interaction question');
pending.interaction.reconnect?.();
}
return;
}
pending.submitting = true;
try {
await pending.interaction.respond({
ok: true,
value: {
sessionId: pending.sessionId,
answer: { answers: pending.answers },
},
});
this.#clearPendingInteraction(key, pending.interactionId);
this.#status.lastError = null;
} catch (error) {
if (this.#signal?.aborted) return;
if (error?.code === 'interaction-not-pending') {
if (this.#pendingInteractions.get(key) === pending) {
this.#clearPendingInteraction(key, pending.interactionId);
}
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT)
.catch(() => undefined);
return;
}
if (this.#pendingInteractions.get(key) !== pending) return;
pending.submitting = false;
pending.answers.pop();
pending.index -= 1;
this.#status.lastError = '回答提交失败。';
this.#logger.error?.('[dsh-im:wecom] failed to answer a Harness interaction');
await this.#sendImmediate(frame, chatId, '回答提交失败,请重新发送当前问题的答案。')
.catch(() => undefined);
}
}
async #handleInteraction(interaction, {
key,
actor,
chatId,
requiresMention,
}) {
// Approval remains unanswered until #5 supplies an authenticated policy.
if (interaction?.kind !== 'question') return;
const questions = interaction?.payload?.questions;
const interactionId = typeof interaction?.interactionId === 'string'
? interaction.interactionId
: interaction?.rpcId;
if (typeof interaction?.rpcId !== 'string'
|| typeof interactionId !== 'string'
|| typeof interaction.sessionId !== 'string'
|| !Array.isArray(questions)
|| questions.length === 0
|| questions.some((question) => !validHarnessQuestion(question))) {
this.#logger.warn?.('[dsh-im:wecom] ignored an invalid Harness question interaction');
return;
}
if (interaction.recovered === true) {
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'Enterprise WeChat safely cancelled an interaction left by an earlier client.',
details: {},
},
});
await this.#sendActive(
chatId,
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。',
).catch(() => undefined);
return;
}
const existing = this.#pendingInteractions.get(key);
if (existing?.interactionId === interactionId) {
existing.interaction = interaction;
if (existing.needsPresentation) await this.#presentInteraction(existing);
return;
}
if (this.#interactionKeys.has(interactionId)) return;
if (existing) {
this.#logger.warn?.('[dsh-im:wecom] cancelled a second pending Harness question');
await interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'Enterprise WeChat is already handling another user interaction.',
details: {},
},
});
return;
}
const pending = {
kind: 'question',
interactionId,
sessionId: interaction.sessionId,
interaction,
actor,
requiresMention,
questions,
answers: [],
index: 0,
chatId,
queue: null,
claimedReplyMessageId: null,
submitting: false,
needsPresentation: true,
presentationPromise: null,
};
this.#pendingInteractions.set(key, pending);
this.#interactionKeys.set(pending.interactionId, key);
await this.#presentInteraction(pending);
}
#handleInteractionResolved(resolution) {
const interactionId = resolution?.interactionId;
if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
const key = this.#interactionKeys.get(interactionId);
if (!key) return;
this.#clearPendingInteraction(key, interactionId);
}
#presentInteraction(pending) {
if (!pending.needsPresentation) return Promise.resolve();
if (pending.presentationPromise) return pending.presentationPromise;
const question = pending.questions[pending.index];
if (!question) return Promise.resolve();
const presentation = this.#sendActive(
pending.chatId,
harnessQuestionText(
question,
pending.index,
pending.questions.length,
{ requiresMention: pending.requiresMention },
),
).then(() => {
pending.needsPresentation = false;
}).finally(() => {
if (pending.presentationPromise === presentation) {
pending.presentationPromise = null;
}
});
pending.presentationPromise = presentation;
return presentation;
}
async #discardResolvedInteractionReply(frame, messageId, chatId) {
if (this.#state.hasSeen(messageId)) return;
await this.#state.markSeen(messageId);
this.#status.messagesReceived += 1;
this.#status.lastMessageAt = new Date().toISOString();
await this.#sendImmediate(frame, chatId, INTERACTION_RESOLVED_TEXT).catch(() => undefined);
}
#takePendingInteraction(key, interactionId) {
const pending = this.#pendingInteractions.get(key);
if (!pending
|| (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
this.#pendingInteractions.delete(key);
this.#interactionKeys.delete(pending.interactionId);
return pending;
}
#clearPendingInteraction(key, interactionId) {
return this.#takePendingInteraction(key, interactionId) !== null;
}
async #cancelPendingInteraction(key) {
const pending = this.#takePendingInteraction(key);
if (!pending || pending.kind !== 'question') return;
try {
await pending.interaction.respond({
ok: false,
error: {
code: 'cancelled',
message: 'The Enterprise WeChat interaction ended before the user answered.',
details: {},
},
}, { signal: AbortSignal.timeout(5_000) });
} catch (error) {
if (error?.code !== 'interaction-not-pending') {
this.#logger.warn?.('[dsh-im:wecom] failed to cancel a pending Harness interaction');
}
}
}
}

View file

@ -36,6 +36,7 @@ export class WecomRuntime {
#bridge = null;
#starting = null;
#startController = null;
#runtimeController = null;
constructor({
config,
@ -69,8 +70,10 @@ export class WecomRuntime {
async start() {
if (this.#status.ready && this.#client) return this.status;
if (this.#starting) return this.#starting;
this.#runtimeController?.abort(new DOMException('Enterprise WeChat runtime replaced', 'AbortError'));
const controller = new AbortController();
this.#startController = controller;
this.#runtimeController = controller;
this.#starting = this.#start(controller.signal).finally(() => {
if (this.#startController === controller) this.#startController = null;
this.#starting = null;
@ -105,6 +108,7 @@ export class WecomRuntime {
status: this.#status,
logger: this.#logger,
replyTimeoutMs: this.#replyTimeoutMs,
signal,
});
let readyResolve;
@ -186,6 +190,8 @@ export class WecomRuntime {
async stop() {
const starting = this.#starting;
this.#startController?.abort(new DOMException('Enterprise WeChat runtime stopped', 'AbortError'));
this.#runtimeController?.abort(new DOMException('Enterprise WeChat runtime stopped', 'AbortError'));
this.#runtimeController = null;
await this.#stopActive();
await starting?.catch(() => undefined);
return this.status;