mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-17 18:30:50 +08:00
fix: support Harness interactions across IM channels
This commit is contained in:
parent
3e7e1dcdd7
commit
cd8175d341
30 changed files with 5433 additions and 555 deletions
|
|
@ -1,329 +1,19 @@
|
|||
import { spawn } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isAbsolute } from 'node:path';
|
||||
import {
|
||||
HarnessClient as SharedHarnessClient,
|
||||
} from '../shared/harness-client.mjs';
|
||||
|
||||
import { adoptRegisteredWorkspaceSession } from '../shared/harness-session-binding.mjs';
|
||||
export {
|
||||
HarnessInteractionError,
|
||||
HarnessReplyTracker,
|
||||
HarnessRpcError,
|
||||
} from '../shared/harness-client.mjs';
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
function workspacePaths(value) {
|
||||
if (!Array.isArray(value?.items)) return [];
|
||||
return value.items.flatMap((item) => (
|
||||
typeof item?.path === 'string' && isAbsolute(item.path) ? [item.path] : []
|
||||
));
|
||||
}
|
||||
|
||||
function workspaceFromList(workspacePath, workspaceList) {
|
||||
if (!Array.isArray(workspaceList?.items)
|
||||
|| !Array.isArray(workspaceList?.archivedSessionIds)) {
|
||||
throw new Error('Harness returned an invalid response for workspace.list');
|
||||
}
|
||||
|
||||
const workspace = workspaceList.items.find((item) => item?.path === workspacePath);
|
||||
if (!workspace) return null;
|
||||
if (!Array.isArray(workspace.sessionIds)
|
||||
|| workspace.sessionIds.some((sessionId) => typeof sessionId !== 'string')) {
|
||||
throw new Error('Harness returned invalid session IDs for workspace.list');
|
||||
}
|
||||
return workspace;
|
||||
}
|
||||
|
||||
function workspaceSessions(workspace, archivedSessionIds, sessionList) {
|
||||
if (!Array.isArray(sessionList?.items)) {
|
||||
throw new Error('Harness returned an invalid response for session.list');
|
||||
}
|
||||
|
||||
const archived = new Set(archivedSessionIds);
|
||||
const summaries = new Map(sessionList.items.flatMap((item) => (
|
||||
typeof item?.sessionId === 'string' ? [[item.sessionId, item]] : []
|
||||
)));
|
||||
return {
|
||||
workspace: workspace.path,
|
||||
sessions: workspace.sessionIds.map((sessionId) => {
|
||||
const summary = summaries.get(sessionId);
|
||||
const title = summary?.projections?.values?.title;
|
||||
return {
|
||||
sessionId,
|
||||
title: typeof title === 'string' ? title : null,
|
||||
archived: archived.has(sessionId),
|
||||
blank: summary?.blank === true,
|
||||
origin: summary?.origin === 'subagent' ? 'subagent' : null,
|
||||
summaryAvailable: summary !== undefined,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function assistantMessageText(event) {
|
||||
return (event?.data?.message?.content ?? [])
|
||||
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
||||
.map((part) => part.text)
|
||||
.join('\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
export class HarnessReplyTracker {
|
||||
#promptRpcId;
|
||||
#lastSeq;
|
||||
#openTurn = null;
|
||||
#targetTurn = null;
|
||||
#stepText = new Map();
|
||||
#latestText = '';
|
||||
#finished = false;
|
||||
#reason = null;
|
||||
|
||||
constructor({ promptRpcId, afterSeq = -1 }) {
|
||||
this.#promptRpcId = promptRpcId;
|
||||
this.#lastSeq = afterSeq;
|
||||
}
|
||||
|
||||
get finished() {
|
||||
return this.#finished;
|
||||
}
|
||||
|
||||
get answer() {
|
||||
return this.#latestText.trim();
|
||||
}
|
||||
|
||||
get reason() {
|
||||
return this.#reason;
|
||||
}
|
||||
|
||||
consume(entries) {
|
||||
let update = null;
|
||||
const ordered = [...entries]
|
||||
.map((entry) => entry?.event ?? entry)
|
||||
.filter(Boolean)
|
||||
.sort((left, right) => (left.seq ?? -1) - (right.seq ?? -1));
|
||||
|
||||
for (const event of ordered) {
|
||||
const seq = event.seq ?? -1;
|
||||
if (seq <= this.#lastSeq) continue;
|
||||
this.#lastSeq = seq;
|
||||
|
||||
if (event.type === 'turn/start') this.#openTurn = event.data?.turn ?? null;
|
||||
|
||||
if (event.type === 'user/message' && event.data?.source?.rpcId === this.#promptRpcId) {
|
||||
this.#targetTurn = this.#openTurn;
|
||||
continue;
|
||||
}
|
||||
if (this.#targetTurn === null) continue;
|
||||
|
||||
if (event.type === 'turn/end') {
|
||||
if (event.data?.turn !== this.#targetTurn) continue;
|
||||
this.#finished = true;
|
||||
this.#reason = event.data?.reason ?? null;
|
||||
this.#openTurn = null;
|
||||
continue;
|
||||
}
|
||||
if (event.data?.turn !== this.#targetTurn) continue;
|
||||
|
||||
if (event.type === 'assistant/chunk' && event.data?.chunk?.type === 'text-delta') {
|
||||
const step = event.data?.step ?? 0;
|
||||
const index = event.data.chunk.index ?? 0;
|
||||
const key = `${step}:${index}`;
|
||||
this.#stepText.set(key, (this.#stepText.get(key) ?? '') + event.data.chunk.text);
|
||||
const prefix = `${step}:`;
|
||||
const text = [...this.#stepText.entries()]
|
||||
.filter(([partKey]) => partKey.startsWith(prefix))
|
||||
.sort(([left], [right]) => Number(left.split(':')[1]) - Number(right.split(':')[1]))
|
||||
.map(([, part]) => part)
|
||||
.join('\n')
|
||||
.trim();
|
||||
if (text && text !== this.#latestText) {
|
||||
this.#latestText = text;
|
||||
update = { type: 'text', text };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === 'assistant/message') {
|
||||
const text = assistantMessageText(event);
|
||||
if (text && text !== this.#latestText) {
|
||||
this.#latestText = text;
|
||||
update = { type: 'text', text };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (event.type === 'tool/call') {
|
||||
update = { type: 'tool', name: event.data?.name ?? '工具' };
|
||||
} else if (event.type === 'tool/result') {
|
||||
update = { type: 'status', text: '正在整理结果…' };
|
||||
}
|
||||
}
|
||||
return update;
|
||||
}
|
||||
}
|
||||
|
||||
export class HarnessRpcError extends Error {
|
||||
constructor(method, error) {
|
||||
super(`${method}: ${error?.message ?? 'unknown Harness RPC error'}`);
|
||||
this.name = 'HarnessRpcError';
|
||||
this.method = method;
|
||||
this.code = error?.code ?? 'internal';
|
||||
this.details = error?.details ?? {};
|
||||
}
|
||||
}
|
||||
|
||||
export class HarnessClient {
|
||||
#baseUrl;
|
||||
#workspace;
|
||||
#agentPreset;
|
||||
#autostart;
|
||||
#dshBin;
|
||||
#managedProcess = null;
|
||||
|
||||
constructor({ baseUrl, workspace, agentPreset = 'standard', autostart = false, dshBin = 'dsh' }) {
|
||||
this.#baseUrl = new URL(baseUrl);
|
||||
this.#workspace = workspace;
|
||||
this.#agentPreset = agentPreset;
|
||||
this.#autostart = autostart;
|
||||
this.#dshBin = dshBin;
|
||||
}
|
||||
|
||||
async rpc(method, payload = {}, timeoutMs = 30_000, options = {}) {
|
||||
const rpcId = options.rpcId ?? `weixin-${randomUUID()}`;
|
||||
const response = await fetch(new URL(`/api/${method}`, this.#baseUrl), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'client-request', rpcId, method, payload }),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
export class HarnessClient extends SharedHarnessClient {
|
||||
constructor(options) {
|
||||
super({
|
||||
...options,
|
||||
rpcIdPrefix: 'weixin',
|
||||
logPrefix: 'dsh-weixin',
|
||||
});
|
||||
if (!response.ok) throw new Error(`Harness transport ${method} failed: HTTP ${response.status}`);
|
||||
const body = await response.json();
|
||||
if (body?.type !== 'server-response' || body?.rpcId !== rpcId) {
|
||||
throw new Error(`Harness returned an invalid response for ${method}`);
|
||||
}
|
||||
if (!body.result?.ok) throw new HarnessRpcError(method, body.result?.error);
|
||||
return body.result.value;
|
||||
}
|
||||
|
||||
async health() {
|
||||
await this.rpc('host.describe', {}, 5_000);
|
||||
return true;
|
||||
}
|
||||
|
||||
async ensureRunning() {
|
||||
try {
|
||||
return await this.health();
|
||||
} catch (firstError) {
|
||||
if (!this.#autostart) throw firstError;
|
||||
}
|
||||
|
||||
if (!this.#managedProcess || this.#managedProcess.exitCode !== null) {
|
||||
const port = this.#baseUrl.port || (this.#baseUrl.protocol === 'https:' ? '443' : '80');
|
||||
this.#managedProcess = spawn(this.#dshBin, [
|
||||
'web', '--host', this.#baseUrl.hostname, '--port', port,
|
||||
], {
|
||||
cwd: this.#workspace,
|
||||
env: process.env,
|
||||
stdio: ['ignore', 'inherit', 'inherit'],
|
||||
});
|
||||
this.#managedProcess.on('error', (error) => {
|
||||
console.error('[dsh-weixin] failed to start Harness:', error.message);
|
||||
});
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 60_000;
|
||||
let lastError;
|
||||
while (Date.now() < deadline) {
|
||||
await sleep(1_000);
|
||||
try {
|
||||
return await this.health();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw new Error(`Harness did not become ready: ${lastError?.message ?? 'timeout'}`);
|
||||
}
|
||||
|
||||
async listWorkspaces(options = {}) {
|
||||
await this.ensureRunning();
|
||||
return workspacePaths(await this.rpc('workspace.list', {}, 30_000, options));
|
||||
}
|
||||
|
||||
async listWorkspaceSessions(workspacePath, options = {}) {
|
||||
await this.ensureRunning();
|
||||
const workspaceList = await this.rpc('workspace.list', {}, 30_000, options);
|
||||
const workspace = workspaceFromList(workspacePath, workspaceList);
|
||||
if (!workspace) return { workspace: workspacePath, sessions: [] };
|
||||
const sessionList = await this.rpc('session.list', {}, 30_000, options);
|
||||
return workspaceSessions(workspace, workspaceList.archivedSessionIds, sessionList);
|
||||
}
|
||||
|
||||
async adoptWorkspaceSession(value, options = {}) {
|
||||
return adoptRegisteredWorkspaceSession(this, value, options);
|
||||
}
|
||||
|
||||
async workspaceId(options = {}) {
|
||||
const workspace = options.workspace ?? this.#workspace;
|
||||
const { items } = await this.rpc('workspace.list', {});
|
||||
const existing = items.find((item) => item.path === workspace);
|
||||
if (existing) return existing.workspaceId;
|
||||
const created = await this.rpc('workspace.create', { path: workspace });
|
||||
return created.workspace.workspaceId;
|
||||
}
|
||||
|
||||
async createSession(options = {}) {
|
||||
await this.ensureRunning();
|
||||
const workspaceId = await this.workspaceId(options);
|
||||
const created = await this.rpc('session.create', {
|
||||
workspaceId,
|
||||
agentPreset: this.#agentPreset,
|
||||
});
|
||||
return created.sessionId;
|
||||
}
|
||||
|
||||
async sessionExists(sessionId) {
|
||||
try {
|
||||
await this.rpc('session.history', { sessionId, maxMessages: 1 });
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof HarnessRpcError && error.code === 'session-not-found') return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async ask(sessionId, text, options = {}) {
|
||||
if (typeof options === 'number') options = { timeoutMs: options };
|
||||
const timeoutMs = options.timeoutMs ?? 600_000;
|
||||
const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
|
||||
await this.ensureRunning();
|
||||
const before = await this.rpc('session.history', { sessionId, maxMessages: 1 });
|
||||
const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
|
||||
const promptRpcId = `weixin-${randomUUID()}`;
|
||||
const tracker = new HarnessReplyTracker({ promptRpcId, afterSeq: baselineSeq });
|
||||
|
||||
await this.rpc('session.prompt', {
|
||||
sessionId,
|
||||
mode: 'queue',
|
||||
content: [{ type: 'text', text }],
|
||||
clientTimeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
}, 30_000, { rpcId: promptRpcId });
|
||||
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
await sleep(300);
|
||||
const history = await this.rpc('session.history', { sessionId, maxMessages: 50 });
|
||||
const update = tracker.consume(history.events ?? []);
|
||||
if (update && onUpdate) {
|
||||
try {
|
||||
await onUpdate(update);
|
||||
} catch (error) {
|
||||
console.warn('[dsh-weixin] ignored a progress update failure:', error.message);
|
||||
}
|
||||
}
|
||||
if (!tracker.finished) continue;
|
||||
if (tracker.answer) return tracker.answer;
|
||||
throw new Error(
|
||||
`Harness turn ended without a text reply${tracker.reason ? ` (${JSON.stringify(tracker.reason)})` : ''}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Harness reply timed out after ${Math.round(timeoutMs / 1_000)} seconds`);
|
||||
}
|
||||
|
||||
stopManagedProcess() {
|
||||
if (this.#managedProcess?.exitCode === null) this.#managedProcess.kill('SIGTERM');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,9 +3,16 @@ import {
|
|||
splitWeixinText,
|
||||
weixinMessageId,
|
||||
} from './weixin-api.mjs';
|
||||
import {
|
||||
harnessAnswerForQuestion,
|
||||
harnessQuestionText,
|
||||
validHarnessQuestion,
|
||||
} from '../shared/harness-question.mjs';
|
||||
import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
|
||||
import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
|
||||
|
||||
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
|
||||
|
||||
const HELP_TEXT = [
|
||||
'微信已连接 DeepSeek Harness。',
|
||||
'',
|
||||
|
|
@ -23,6 +30,16 @@ function conversationKey(userId) {
|
|||
return `p2p:${userId}`;
|
||||
}
|
||||
|
||||
function nonEmptyString(value) {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function canClaimInteractionReply(message, pending) {
|
||||
return pending.questions[pending.index]
|
||||
&& nonEmptyString(message?.from_user_id) === pending.actor
|
||||
&& nonEmptyString(extractWeixinText(message));
|
||||
}
|
||||
|
||||
export function createWeixinBridgeStatus() {
|
||||
return {
|
||||
messagesReceived: 0,
|
||||
|
|
@ -46,7 +63,11 @@ export class WeixinHarnessBridge {
|
|||
#logger;
|
||||
#replyTimeoutMs;
|
||||
#maxMessageChars;
|
||||
#signal;
|
||||
#queues = new Map();
|
||||
#pendingInteractions = new Map();
|
||||
#interactionKeys = new Map();
|
||||
#acceptedMessageIds = new Set();
|
||||
|
||||
constructor({
|
||||
api,
|
||||
|
|
@ -59,6 +80,7 @@ export class WeixinHarnessBridge {
|
|||
logger = console,
|
||||
replyTimeoutMs = 600_000,
|
||||
maxMessageChars = 4_000,
|
||||
signal,
|
||||
}) {
|
||||
if (!api || typeof api.sendText !== 'function') throw new TypeError('Weixin API is required');
|
||||
if (!baseUrl || !token || !ownerUserId) throw new TypeError('Weixin account credentials are required');
|
||||
|
|
@ -73,6 +95,7 @@ export class WeixinHarnessBridge {
|
|||
this.#logger = logger;
|
||||
this.#replyTimeoutMs = replyTimeoutMs;
|
||||
this.#maxMessageChars = maxMessageChars;
|
||||
this.#signal = signal;
|
||||
}
|
||||
|
||||
get status() {
|
||||
|
|
@ -80,31 +103,73 @@ export class WeixinHarnessBridge {
|
|||
}
|
||||
|
||||
accept(message) {
|
||||
const sender = typeof message?.from_user_id === 'string' ? message.from_user_id : '';
|
||||
const previous = this.#queues.get(sender) ?? Promise.resolve();
|
||||
if (this.#signal?.aborted) return Promise.resolve();
|
||||
if (message?.message_type === 2) return Promise.resolve();
|
||||
const messageId = weixinMessageId(message);
|
||||
const sender = nonEmptyString(message?.from_user_id);
|
||||
if (!messageId || !sender || this.#state.hasSeen(messageId)
|
||||
|| this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
|
||||
this.#acceptedMessageIds.add(messageId);
|
||||
const key = conversationKey(sender);
|
||||
const pending = this.#pendingInteractions.get(key);
|
||||
if (pending?.submitting || pending?.claimedReplyMessageId) {
|
||||
return this.#enqueueMessage(message, messageId, key);
|
||||
}
|
||||
if (pending) {
|
||||
if (canClaimInteractionReply(message, pending)) {
|
||||
pending.claimedReplyMessageId = messageId;
|
||||
}
|
||||
const previous = pending.queue ?? Promise.resolve();
|
||||
const current = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => this.#processInteractionReply(message, messageId, key, pending))
|
||||
.catch((error) => this.#handleInteractionFailure(message, messageId, error))
|
||||
.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(message, messageId, key);
|
||||
}
|
||||
|
||||
#enqueueMessage(message, messageId, key, {
|
||||
releaseMessageId = true,
|
||||
alreadyRecorded = false,
|
||||
} = {}) {
|
||||
const previous = this.#queues.get(key) ?? Promise.resolve();
|
||||
const current = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => this.#process(message))
|
||||
.then(() => this.#process(message, key, { alreadyRecorded }))
|
||||
.finally(() => {
|
||||
if (this.#queues.get(sender) === current) this.#queues.delete(sender);
|
||||
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
|
||||
if (this.#queues.get(key) === current) this.#queues.delete(key);
|
||||
});
|
||||
this.#queues.set(sender, current);
|
||||
this.#queues.set(key, current);
|
||||
return current;
|
||||
}
|
||||
|
||||
async waitForIdle() {
|
||||
await Promise.allSettled([...this.#queues.values()]);
|
||||
await Promise.allSettled([
|
||||
...this.#queues.values(),
|
||||
...[...this.#pendingInteractions.values()].flatMap((pending) => (
|
||||
pending.queue ? [pending.queue] : []
|
||||
)),
|
||||
]);
|
||||
}
|
||||
|
||||
async #process(message) {
|
||||
if (message?.message_type === 2) return;
|
||||
async #process(message, key, { alreadyRecorded = false } = {}) {
|
||||
this.#signal?.throwIfAborted();
|
||||
const messageId = weixinMessageId(message);
|
||||
const sender = typeof message?.from_user_id === 'string' ? message.from_user_id : '';
|
||||
const sender = nonEmptyString(message?.from_user_id);
|
||||
if (!messageId || !sender) 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();
|
||||
}
|
||||
if (sender !== this.#ownerUserId) {
|
||||
this.#status.messagesRejected += 1;
|
||||
this.#status.lastRejectedAt = new Date().toISOString();
|
||||
|
|
@ -122,14 +187,13 @@ export class WeixinHarnessBridge {
|
|||
}
|
||||
|
||||
const command = text.trim().toLowerCase();
|
||||
const key = conversationKey(sender);
|
||||
if (command === '/help') {
|
||||
await this.#send(sender, HELP_TEXT, contextToken, runId);
|
||||
await this.#state.markSeen(messageId);
|
||||
return;
|
||||
}
|
||||
if (command === '/status') {
|
||||
await this.#harness.ensureRunning();
|
||||
await this.#harness.ensureRunning({ signal: this.#signal });
|
||||
await this.#send(sender, '微信与 DeepSeek Harness 连接正常。', contextToken, runId);
|
||||
await this.#state.markSeen(messageId);
|
||||
return;
|
||||
|
|
@ -149,19 +213,37 @@ export class WeixinHarnessBridge {
|
|||
return;
|
||||
}
|
||||
|
||||
const { answer } = await askInWorkspaceSession({
|
||||
harness: this.#harness,
|
||||
state: this.#state,
|
||||
key,
|
||||
text,
|
||||
askOptions: { timeoutMs: this.#replyTimeoutMs },
|
||||
});
|
||||
let answer;
|
||||
try {
|
||||
({ answer } = await askInWorkspaceSession({
|
||||
harness: this.#harness,
|
||||
state: this.#state,
|
||||
key,
|
||||
text,
|
||||
createOptions: { signal: this.#signal },
|
||||
existsOptions: { signal: this.#signal },
|
||||
askOptions: {
|
||||
timeoutMs: this.#replyTimeoutMs,
|
||||
signal: this.#signal,
|
||||
onInteraction: (interaction) => this.#handleInteraction(interaction, {
|
||||
key,
|
||||
actor: sender,
|
||||
contextToken,
|
||||
runId,
|
||||
}),
|
||||
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
|
||||
},
|
||||
}));
|
||||
} finally {
|
||||
await this.#cancelPendingInteraction(key);
|
||||
}
|
||||
await this.#send(sender, answer, contextToken, runId);
|
||||
await this.#state.markSeen(messageId);
|
||||
this.#status.messagesReplied += 1;
|
||||
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-weixin] failed to process an inbound message:', error);
|
||||
try {
|
||||
|
|
@ -173,6 +255,304 @@ export class WeixinHarnessBridge {
|
|||
}
|
||||
}
|
||||
|
||||
async #processInteractionReply(message, messageId, key, expected) {
|
||||
this.#signal?.throwIfAborted();
|
||||
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(message, messageId);
|
||||
}
|
||||
return this.#enqueueMessage(message, 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(extractWeixinText(message));
|
||||
const contextToken = nonEmptyString(message?.context_token) ?? undefined;
|
||||
const runId = nonEmptyString(message?.run_id) ?? undefined;
|
||||
if (!text) {
|
||||
await this.#send(
|
||||
expected.actor,
|
||||
'请用文字回答当前问题。',
|
||||
contextToken,
|
||||
runId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = this.#pendingInteractions.get(key);
|
||||
if (!pending || pending !== expected || pending.submitting) {
|
||||
if (claimed && (!pending || pending !== expected)) {
|
||||
await this.#send(
|
||||
expected.actor,
|
||||
INTERACTION_RESOLVED_TEXT,
|
||||
contextToken,
|
||||
runId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
return this.#enqueueMessage(message, messageId, key, {
|
||||
releaseMessageId: false,
|
||||
alreadyRecorded: true,
|
||||
});
|
||||
}
|
||||
pending.contextToken = contextToken;
|
||||
pending.runId = runId;
|
||||
if (pending.needsPresentation) {
|
||||
try {
|
||||
await this.#presentInteraction(pending);
|
||||
} catch {
|
||||
this.#status.lastError = '微信交互问题发送失败。';
|
||||
this.#logger.error?.('[dsh-weixin] 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.#send(
|
||||
expected.actor,
|
||||
INTERACTION_RESOLVED_TEXT,
|
||||
contextToken,
|
||||
runId,
|
||||
).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
return this.#enqueueMessage(message, 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-weixin] 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') {
|
||||
this.#clearPendingInteraction(key, pending.interactionId);
|
||||
await this.#send(
|
||||
pending.actor,
|
||||
INTERACTION_RESOLVED_TEXT,
|
||||
pending.contextToken,
|
||||
pending.runId,
|
||||
).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-weixin] failed to answer a Harness interaction');
|
||||
await this.#send(
|
||||
pending.actor,
|
||||
'回答提交失败,请重新发送当前问题的答案。',
|
||||
pending.contextToken,
|
||||
pending.runId,
|
||||
).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async #handleInteraction(interaction, {
|
||||
key,
|
||||
actor,
|
||||
contextToken,
|
||||
runId,
|
||||
}) {
|
||||
// Approval remains fail-closed until #5 adds 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-weixin] ignored an invalid Harness question interaction');
|
||||
return;
|
||||
}
|
||||
|
||||
if (interaction.recovered === true) {
|
||||
await interaction.respond({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'cancelled',
|
||||
message: 'Weixin safely cancelled an interaction left by an earlier client.',
|
||||
details: {},
|
||||
},
|
||||
});
|
||||
await this.#send(
|
||||
actor,
|
||||
'检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。',
|
||||
contextToken,
|
||||
runId,
|
||||
).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) {
|
||||
await interaction.respond({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'cancelled',
|
||||
message: 'Weixin is already handling another user interaction.',
|
||||
details: {},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = {
|
||||
kind: 'question',
|
||||
interactionId,
|
||||
sessionId: interaction.sessionId,
|
||||
interaction,
|
||||
actor,
|
||||
questions,
|
||||
answers: [],
|
||||
index: 0,
|
||||
contextToken,
|
||||
runId,
|
||||
queue: null,
|
||||
claimedReplyMessageId: null,
|
||||
presentationPromise: null,
|
||||
submitting: false,
|
||||
needsPresentation: true,
|
||||
};
|
||||
this.#pendingInteractions.set(key, pending);
|
||||
this.#interactionKeys.set(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.#send(
|
||||
pending.actor,
|
||||
harnessQuestionText(question, pending.index, pending.questions.length),
|
||||
pending.contextToken,
|
||||
pending.runId,
|
||||
).then(() => {
|
||||
pending.needsPresentation = false;
|
||||
}).finally(() => {
|
||||
if (pending.presentationPromise === presentation) pending.presentationPromise = null;
|
||||
});
|
||||
pending.presentationPromise = presentation;
|
||||
return presentation;
|
||||
}
|
||||
|
||||
async #discardResolvedInteractionReply(message, messageId) {
|
||||
if (this.#state.hasSeen(messageId)) return;
|
||||
await this.#state.markSeen(messageId);
|
||||
this.#status.messagesReceived += 1;
|
||||
this.#status.lastMessageAt = new Date().toISOString();
|
||||
await this.#send(
|
||||
nonEmptyString(message?.from_user_id),
|
||||
INTERACTION_RESOLVED_TEXT,
|
||||
nonEmptyString(message?.context_token) ?? undefined,
|
||||
nonEmptyString(message?.run_id) ?? undefined,
|
||||
).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 Weixin interaction ended before the user answered.',
|
||||
details: {},
|
||||
},
|
||||
}, { signal: AbortSignal.timeout(5_000) });
|
||||
} catch (error) {
|
||||
if (error?.code !== 'interaction-not-pending') {
|
||||
this.#logger.warn?.('[dsh-weixin] failed to cancel a pending Harness interaction');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #handleInteractionFailure(message, messageId, error) {
|
||||
if (this.#signal?.aborted) return;
|
||||
this.#status.lastError = error?.message ?? String(error);
|
||||
this.#logger.error?.('[dsh-weixin] failed to process an interaction reply:', error);
|
||||
if (!this.#state.hasSeen(messageId)) {
|
||||
await this.#state.markSeen(messageId).catch(() => undefined);
|
||||
}
|
||||
await this.#send(
|
||||
nonEmptyString(message?.from_user_id),
|
||||
'消息处理失败,请稍后重试。',
|
||||
nonEmptyString(message?.context_token) ?? undefined,
|
||||
nonEmptyString(message?.run_id) ?? undefined,
|
||||
).catch(() => undefined);
|
||||
}
|
||||
|
||||
async #send(toUserId, text, contextToken, runId) {
|
||||
for (const chunk of splitWeixinText(text, this.#maxMessageChars)) {
|
||||
await this.#api.sendText({
|
||||
|
|
|
|||
|
|
@ -116,6 +116,8 @@ export class WeixinRuntime {
|
|||
await this.#harness.ensureRunning();
|
||||
this.#status.harnessReachable = true;
|
||||
await this.#notifyStart();
|
||||
this.#abortController = new AbortController();
|
||||
const signal = this.#abortController.signal;
|
||||
this.#bridge = new WeixinHarnessBridge({
|
||||
api: this.#api,
|
||||
baseUrl: this.#config.baseUrl,
|
||||
|
|
@ -127,12 +129,11 @@ export class WeixinRuntime {
|
|||
logger: this.#logger,
|
||||
replyTimeoutMs: this.#replyTimeoutMs,
|
||||
maxMessageChars: this.#maxMessageChars,
|
||||
signal,
|
||||
});
|
||||
this.#abortController = new AbortController();
|
||||
this.#status.ready = true;
|
||||
this.#status.weixinConnectionState = 'connected';
|
||||
this.#status.lastCheckedAt = Date.now();
|
||||
const signal = this.#abortController.signal;
|
||||
this.#monitor = this.#runMonitor(signal).catch((error) => {
|
||||
if (signal.aborted) return;
|
||||
this.#status.ready = false;
|
||||
|
|
@ -142,6 +143,9 @@ export class WeixinRuntime {
|
|||
});
|
||||
return this.status;
|
||||
} catch (error) {
|
||||
this.#abortController?.abort();
|
||||
this.#abortController = null;
|
||||
this.#bridge = null;
|
||||
this.#status.ready = false;
|
||||
this.#status.weixinConnectionState = 'failed';
|
||||
this.#status.lastError = error?.message ?? String(error);
|
||||
|
|
@ -195,7 +199,13 @@ export class WeixinRuntime {
|
|||
this.#status.lastError = null;
|
||||
|
||||
for (const message of response?.msgs ?? []) {
|
||||
await this.#bridge.accept(message);
|
||||
void this.#bridge.accept(message).catch((error) => {
|
||||
if (signal.aborted) return;
|
||||
this.#logger.error?.(
|
||||
`[dsh-weixin] account ${this.#config.botId} message handling failed:`,
|
||||
error,
|
||||
);
|
||||
});
|
||||
}
|
||||
if (typeof response?.get_updates_buf === 'string' && response.get_updates_buf) {
|
||||
await this.#state.setGetUpdatesBuf(response.get_updates_buf);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue