mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-11 23:53:50 +08:00
fix: support Harness interactions in DingTalk and Feishu
This commit is contained in:
parent
c9ec84cc67
commit
3e7e1dcdd7
13 changed files with 5061 additions and 881 deletions
|
|
@ -3,11 +3,17 @@ import {
|
|||
splitDingtalkText,
|
||||
} from './dingtalk-api.mjs';
|
||||
import { createDingTalkCardStream } from './dingtalk-card-stream.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 CARD_INITIAL_TEXT = '已连接 DeepSeek Harness,正在思考…';
|
||||
const CARD_ERROR_TEXT = '消息处理失败,请稍后重试。';
|
||||
const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
|
||||
|
||||
const HELP_TEXT = [
|
||||
'钉钉机器人已连接 DeepSeek Harness。',
|
||||
|
|
@ -55,6 +61,19 @@ function progressText(update) {
|
|||
return `_${nonEmptyString(update?.text) ?? '正在处理…'}_`;
|
||||
}
|
||||
|
||||
function canClaimInteractionReply(message, pending, sender) {
|
||||
if (pending.needsPresentation || !pending.questions[pending.index]) return false;
|
||||
if (pending.actor !== sender) return false;
|
||||
if (String(message?.conversationType) === '2' && message?.isInAtList !== true) return false;
|
||||
if (message?.msgtype !== 'text' || !nonEmptyString(message?.text?.content)) return false;
|
||||
try {
|
||||
normalizeDingtalkSessionWebhook(message.sessionWebhook);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureStats(status) {
|
||||
status.stats ??= {};
|
||||
for (const key of ['messagesReceived', 'messagesReplied', 'messagesRejected', 'messagesIgnored']) {
|
||||
|
|
@ -102,6 +121,8 @@ export class DingtalkHarnessBridge {
|
|||
#maxMessageChars;
|
||||
#signal;
|
||||
#queues = new Map();
|
||||
#pendingInteractions = new Map();
|
||||
#interactionKeys = new Map();
|
||||
#acceptedMessageIds = new Set();
|
||||
|
||||
constructor({
|
||||
|
|
@ -157,12 +178,49 @@ export class DingtalkHarnessBridge {
|
|||
this.#status.lastRejectedAt = new Date().toISOString();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
const pending = this.#pendingInteractions.get(key);
|
||||
if (pending && pending.actor !== sender) {
|
||||
return this.#enqueueMessage(message, messageId, sender, key);
|
||||
}
|
||||
// Once one valid answer has been claimed, later messages are subsequent
|
||||
// prompts even if the network submission eventually needs a retry. Invalid
|
||||
// replies do not claim the question, so the next valid answer can still
|
||||
// pass through this interaction queue.
|
||||
if (pending?.submitting || pending?.claimedReplyMessageId) {
|
||||
return this.#enqueueMessage(message, messageId, sender, key);
|
||||
}
|
||||
if (pending) {
|
||||
if (canClaimInteractionReply(message, pending, sender)) {
|
||||
pending.claimedReplyMessageId = messageId;
|
||||
}
|
||||
const previous = pending.queue ?? Promise.resolve();
|
||||
const current = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => this.#processInteractionReply(message, messageId, sender, 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(message, messageId, sender, key);
|
||||
}
|
||||
|
||||
#enqueueMessage(message, messageId, sender, key, {
|
||||
releaseMessageId = true,
|
||||
alreadyRecorded = false,
|
||||
} = {}) {
|
||||
const previous = this.#queues.get(key) ?? Promise.resolve();
|
||||
const current = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => this.#process(message, messageId, sender, key))
|
||||
.then(() => this.#process(message, messageId, sender, key, { alreadyRecorded }))
|
||||
.finally(() => {
|
||||
this.#acceptedMessageIds.delete(messageId);
|
||||
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
|
||||
if (this.#queues.get(key) === current) this.#queues.delete(key);
|
||||
});
|
||||
this.#queues.set(key, current);
|
||||
|
|
@ -170,15 +228,22 @@ export class DingtalkHarnessBridge {
|
|||
}
|
||||
|
||||
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, messageId, sender, key) {
|
||||
async #process(message, messageId, sender, key, { alreadyRecorded = false } = {}) {
|
||||
this.#signal?.throwIfAborted();
|
||||
if (this.#state.hasSeen(messageId)) return;
|
||||
await this.#state.markSeen(messageId);
|
||||
increment(this.#status, 'messagesReceived');
|
||||
this.#status.lastMessageAt = new Date().toISOString();
|
||||
if (!alreadyRecorded) {
|
||||
if (this.#state.hasSeen(messageId)) return;
|
||||
await this.#state.markSeen(messageId);
|
||||
increment(this.#status, 'messagesReceived');
|
||||
this.#status.lastMessageAt = new Date().toISOString();
|
||||
}
|
||||
|
||||
if (String(message.conversationType) === '2' && message.isInAtList !== true) {
|
||||
increment(this.#status, 'messagesIgnored');
|
||||
|
|
@ -253,6 +318,13 @@ export class DingtalkHarnessBridge {
|
|||
onUpdate: cardStarted
|
||||
? (update) => cardStream.push(progressText(update))
|
||||
: undefined,
|
||||
onInteraction: (interaction) => this.#handleInteraction(interaction, {
|
||||
key,
|
||||
actor: sender,
|
||||
sessionWebhook,
|
||||
requiresMention: String(message.conversationType) === '2',
|
||||
}),
|
||||
onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
|
||||
},
|
||||
});
|
||||
const streamed = cardStarted && await cardStream.finish(answer);
|
||||
|
|
@ -270,6 +342,286 @@ export class DingtalkHarnessBridge {
|
|||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to send the safe error reply');
|
||||
}
|
||||
} finally {
|
||||
await this.#cancelPendingInteraction(key);
|
||||
}
|
||||
}
|
||||
|
||||
async #processInteractionReply(message, messageId, sender, 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, sender, key, { releaseMessageId: false });
|
||||
}
|
||||
if (this.#state.hasSeen(messageId)) return;
|
||||
await this.#state.markSeen(messageId);
|
||||
increment(this.#status, 'messagesReceived');
|
||||
this.#status.lastMessageAt = new Date().toISOString();
|
||||
|
||||
if (String(message.conversationType) === '2' && message.isInAtList !== true) {
|
||||
increment(this.#status, 'messagesIgnored');
|
||||
return;
|
||||
}
|
||||
|
||||
let sessionWebhook;
|
||||
try {
|
||||
sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
|
||||
} catch {
|
||||
increment(this.#status, 'messagesRejected');
|
||||
this.#status.lastRejectedAt = new Date().toISOString();
|
||||
this.#status.lastError = '钉钉消息没有安全的回复地址。';
|
||||
return;
|
||||
}
|
||||
|
||||
const text = message?.msgtype === 'text' ? nonEmptyString(message?.text?.content) : null;
|
||||
if (!text) {
|
||||
try {
|
||||
await this.#send(sessionWebhook, '请用文字回答当前问题。');
|
||||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to reject a non-text interaction reply');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = this.#pendingInteractions.get(key);
|
||||
if (!pending || pending !== expected || pending.submitting) {
|
||||
if (claimed && (!pending || pending !== expected)) {
|
||||
try {
|
||||
await this.#send(sessionWebhook, INTERACTION_RESOLVED_TEXT);
|
||||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to send an expired interaction notice');
|
||||
}
|
||||
return;
|
||||
}
|
||||
return this.#enqueueMessage(message, messageId, sender, key, {
|
||||
releaseMessageId: false,
|
||||
alreadyRecorded: true,
|
||||
});
|
||||
}
|
||||
pending.sessionWebhook = sessionWebhook;
|
||||
if (pending.needsPresentation) {
|
||||
try {
|
||||
await this.#presentInteraction(pending);
|
||||
} catch {
|
||||
this.#status.lastError = '钉钉交互问题发送失败。';
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to retry an interaction question');
|
||||
pending.interaction.reconnect?.();
|
||||
}
|
||||
return;
|
||||
}
|
||||
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-dingtalk] 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 (this.#pendingInteractions.get(key) !== pending) return;
|
||||
if (error?.code === 'interaction-not-pending') {
|
||||
this.#clearPendingInteraction(key, pending.interactionId);
|
||||
try {
|
||||
await this.#send(sessionWebhook, INTERACTION_RESOLVED_TEXT);
|
||||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to send an expired interaction notice');
|
||||
}
|
||||
return;
|
||||
}
|
||||
pending.submitting = false;
|
||||
pending.answers.pop();
|
||||
pending.index -= 1;
|
||||
this.#status.lastError = '回答提交失败。';
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to answer a Harness interaction');
|
||||
try {
|
||||
await this.#send(sessionWebhook, '回答提交失败,请重新发送当前问题的答案。');
|
||||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to send an interaction retry notice');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async #handleInteraction(interaction, {
|
||||
key,
|
||||
actor,
|
||||
sessionWebhook,
|
||||
requiresMention,
|
||||
}) {
|
||||
// The transport deliberately exposes every interaction kind. Approval is
|
||||
// left unanswered until #5 adds its own policy and renderer.
|
||||
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-dingtalk] ignored an invalid Harness question interaction');
|
||||
return;
|
||||
}
|
||||
|
||||
if (interaction.recovered === true) {
|
||||
await interaction.respond({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'cancelled',
|
||||
message: 'DingTalk safely cancelled an interaction left by an earlier client.',
|
||||
details: {},
|
||||
},
|
||||
});
|
||||
try {
|
||||
await this.#send(sessionWebhook, '检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。');
|
||||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to send an interaction recovery notice');
|
||||
}
|
||||
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-dingtalk] cancelled a second pending Harness question');
|
||||
await interaction.respond({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'cancelled',
|
||||
message: 'DingTalk is already handling another user interaction.',
|
||||
details: {},
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = {
|
||||
kind: 'question',
|
||||
interactionId,
|
||||
sessionId: interaction.sessionId,
|
||||
interaction,
|
||||
actor,
|
||||
requiresMention,
|
||||
questions,
|
||||
answers: [],
|
||||
index: 0,
|
||||
sessionWebhook,
|
||||
queue: null,
|
||||
claimedReplyMessageId: null,
|
||||
submitting: false,
|
||||
needsPresentation: true,
|
||||
};
|
||||
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);
|
||||
}
|
||||
|
||||
async #presentInteraction(pending) {
|
||||
const question = pending.questions[pending.index];
|
||||
if (!question) return;
|
||||
await this.#send(
|
||||
pending.sessionWebhook,
|
||||
harnessQuestionText(
|
||||
question,
|
||||
pending.index,
|
||||
pending.questions.length,
|
||||
{ requiresMention: pending.requiresMention },
|
||||
),
|
||||
);
|
||||
pending.needsPresentation = false;
|
||||
}
|
||||
|
||||
async #discardResolvedInteractionReply(message, messageId) {
|
||||
if (this.#state.hasSeen(messageId)) return;
|
||||
await this.#state.markSeen(messageId);
|
||||
increment(this.#status, 'messagesReceived');
|
||||
this.#status.lastMessageAt = new Date().toISOString();
|
||||
let sessionWebhook;
|
||||
try {
|
||||
sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
|
||||
} catch {
|
||||
increment(this.#status, 'messagesRejected');
|
||||
this.#status.lastRejectedAt = new Date().toISOString();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.#send(sessionWebhook, INTERACTION_RESOLVED_TEXT);
|
||||
} catch {
|
||||
this.#logger.error?.('[dsh-dingtalk] failed to send an expired interaction notice');
|
||||
}
|
||||
}
|
||||
|
||||
#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 DingTalk interaction ended before the user answered.',
|
||||
details: {},
|
||||
},
|
||||
}, { signal: AbortSignal.timeout(5_000) });
|
||||
} catch (error) {
|
||||
if (error?.code !== 'interaction-not-pending') {
|
||||
this.#logger.warn?.('[dsh-dingtalk] failed to cancel a pending Harness interaction');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,369 +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';
|
||||
|
||||
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 sleep(ms, signal) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
#fetch;
|
||||
#managedProcess = null;
|
||||
|
||||
constructor({
|
||||
baseUrl,
|
||||
workspace,
|
||||
agentPreset = 'standard',
|
||||
autostart = false,
|
||||
dshBin = 'dsh',
|
||||
fetchImpl = fetch,
|
||||
}) {
|
||||
this.#baseUrl = new URL(baseUrl);
|
||||
this.#workspace = workspace;
|
||||
this.#agentPreset = agentPreset;
|
||||
this.#autostart = autostart;
|
||||
this.#dshBin = dshBin;
|
||||
this.#fetch = fetchImpl;
|
||||
}
|
||||
|
||||
async rpc(method, payload = {}, timeoutMs = 30_000, options = {}) {
|
||||
const rpcId = options.rpcId ?? `dingtalk-${randomUUID()}`;
|
||||
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
||||
const signal = options.signal
|
||||
? AbortSignal.any([options.signal, timeoutSignal])
|
||||
: timeoutSignal;
|
||||
const response = await this.#fetch(new URL(`/api/${method}`, this.#baseUrl), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'client-request', rpcId, method, payload }),
|
||||
signal,
|
||||
export class HarnessClient extends SharedHarnessClient {
|
||||
constructor(options) {
|
||||
super({
|
||||
...options,
|
||||
rpcIdPrefix: 'dingtalk',
|
||||
logPrefix: 'dsh-dingtalk',
|
||||
});
|
||||
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(options = {}) {
|
||||
await this.rpc('host.describe', {}, 5_000, options);
|
||||
return true;
|
||||
}
|
||||
|
||||
async ensureRunning(options = {}) {
|
||||
try {
|
||||
return await this.health(options);
|
||||
} 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-dingtalk] failed to start Harness:', error.message);
|
||||
});
|
||||
}
|
||||
|
||||
const deadline = Date.now() + 60_000;
|
||||
let lastError;
|
||||
while (Date.now() < deadline) {
|
||||
await sleep(1_000, options.signal);
|
||||
try {
|
||||
return await this.health(options);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw new Error(`Harness did not become ready: ${lastError?.message ?? 'timeout'}`);
|
||||
}
|
||||
|
||||
async listWorkspaces(options = {}) {
|
||||
await this.ensureRunning(options);
|
||||
return workspacePaths(await this.rpc('workspace.list', {}, 30_000, options));
|
||||
}
|
||||
|
||||
async listWorkspaceSessions(workspacePath, options = {}) {
|
||||
await this.ensureRunning(options);
|
||||
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 = this.#workspace, ...rpcOptions } = options;
|
||||
const { items } = await this.rpc('workspace.list', {}, 30_000, rpcOptions);
|
||||
const existing = items.find((item) => item.path === workspace);
|
||||
if (existing) return existing.workspaceId;
|
||||
const created = await this.rpc('workspace.create', { path: workspace }, 30_000, rpcOptions);
|
||||
return created.workspace.workspaceId;
|
||||
}
|
||||
|
||||
async createSession(options = {}) {
|
||||
await this.ensureRunning(options);
|
||||
const workspaceId = await this.workspaceId(options);
|
||||
const created = await this.rpc('session.create', {
|
||||
workspaceId,
|
||||
agentPreset: this.#agentPreset,
|
||||
}, 30_000, options);
|
||||
return created.sessionId;
|
||||
}
|
||||
|
||||
async sessionExists(sessionId, options = {}) {
|
||||
try {
|
||||
await this.rpc('session.history', { sessionId, maxMessages: 1 }, 30_000, options);
|
||||
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 signal = options.signal;
|
||||
const onUpdate = typeof options.onUpdate === 'function' ? options.onUpdate : null;
|
||||
await this.ensureRunning({ signal });
|
||||
const before = await this.rpc(
|
||||
'session.history',
|
||||
{ sessionId, maxMessages: 1 },
|
||||
30_000,
|
||||
{ signal },
|
||||
);
|
||||
const baselineSeq = Math.max(-1, ...(before.events ?? []).map(({ event }) => event.seq ?? -1));
|
||||
const promptRpcId = `dingtalk-${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, signal });
|
||||
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
await sleep(300, signal);
|
||||
const history = await this.rpc(
|
||||
'session.history',
|
||||
{ sessionId, maxMessages: 50 },
|
||||
30_000,
|
||||
{ signal },
|
||||
);
|
||||
const update = tracker.consume(history.events ?? []);
|
||||
if (update && onUpdate) {
|
||||
try {
|
||||
await onUpdate(update);
|
||||
} catch (error) {
|
||||
console.warn('[dsh-dingtalk] 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');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue