@xmanrui/dsh-im 4.39.0 → 5.0.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/README.en.md +10 -2
- package/README.md +10 -2
- package/lib/client.js +4 -3
- package/lib/index.js +279 -279
- package/package.json +4 -3
- package/plugin-src/host/modern-harness-api.mjs +10 -4
- package/src/channels/qq/qq-bridge.mjs +147 -1
- package/src/channels/qq/state-store.mjs +89 -0
- package/src/channels/shared/conversation-state-store.mjs +94 -0
- package/src/channels/shared/deferred-delivery-coordinator.mjs +5 -1
- package/src/channels/shared/harness-client.mjs +9 -1
- package/src/channels/shared/i18n-en/shared-b.mjs +2 -0
- package/src/channels/shared/prompt-failure-tracker.mjs +65 -0
- package/src/channels/shared/text-harness-bridge.mjs +156 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xmanrui/dsh-im",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "5.0.0",
|
|
4
4
|
"icon": "./assets/logo-plugin-message-link-gradient.webp",
|
|
5
5
|
"description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
|
|
6
6
|
"keywords": [
|
|
@@ -87,9 +87,10 @@
|
|
|
87
87
|
"platform": "web"
|
|
88
88
|
},
|
|
89
89
|
"compatibility": {
|
|
90
|
-
"dsh": "0.2.
|
|
90
|
+
"dsh": "0.2.1-rc.2",
|
|
91
91
|
"dshReleases": {
|
|
92
|
-
"0.2.0-rc.2": "compatible"
|
|
92
|
+
"0.2.0-rc.2": "compatible",
|
|
93
|
+
"0.2.1-rc.2": "compatible"
|
|
93
94
|
},
|
|
94
95
|
"profiles": [
|
|
95
96
|
"web"
|
|
@@ -37,12 +37,13 @@ function rpcResult(request, operation) {
|
|
|
37
37
|
);
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
function remoteRequest(namespace, method, args, signal) {
|
|
40
|
+
function remoteRequest(namespace, method, args, signal, peer) {
|
|
41
41
|
return {
|
|
42
42
|
namespace,
|
|
43
43
|
method,
|
|
44
44
|
args,
|
|
45
45
|
...(signal === undefined ? {} : { signal }),
|
|
46
|
+
...(peer === undefined ? {} : { peer }),
|
|
46
47
|
};
|
|
47
48
|
}
|
|
48
49
|
|
|
@@ -196,6 +197,7 @@ class MuxSubscription {
|
|
|
196
197
|
|
|
197
198
|
class ModernHarnessApi {
|
|
198
199
|
#gateway;
|
|
200
|
+
#peer;
|
|
199
201
|
#deliveryService;
|
|
200
202
|
#scope;
|
|
201
203
|
#mux = new Set();
|
|
@@ -209,6 +211,9 @@ class ModernHarnessApi {
|
|
|
209
211
|
constructor(ctx, gateway, scope) {
|
|
210
212
|
this.#gateway = gateway;
|
|
211
213
|
this.#scope = scope;
|
|
214
|
+
// New Hosts require an explicit caller. IM interactions use the adapter's
|
|
215
|
+
// existing event listeners; this peer only owns Gateway calls and streams.
|
|
216
|
+
this.#peer = ctx.connection?.createPeer?.({ principal: { kind: 'owner' }, interactions: 'none' });
|
|
212
217
|
|
|
213
218
|
this.host = Object.freeze({
|
|
214
219
|
describe: (request) => rpcResult(request, () => ({ ready: true, transport: 'typert' })),
|
|
@@ -292,7 +297,7 @@ class ModernHarnessApi {
|
|
|
292
297
|
}
|
|
293
298
|
|
|
294
299
|
async #invoke(namespace, method, args, signal) {
|
|
295
|
-
return this.#gateway.invoke(remoteRequest(namespace, method, args, signal));
|
|
300
|
+
return this.#gateway.invoke(remoteRequest(namespace, method, args, signal, this.#peer));
|
|
296
301
|
}
|
|
297
302
|
|
|
298
303
|
async #streamFirst(namespace, method, args, signal) {
|
|
@@ -303,7 +308,7 @@ class ModernHarnessApi {
|
|
|
303
308
|
let iterator;
|
|
304
309
|
try {
|
|
305
310
|
const source = await this.#gateway.stream(remoteRequest(
|
|
306
|
-
namespace, method, args, streamSignal,
|
|
311
|
+
namespace, method, args, streamSignal, this.#peer,
|
|
307
312
|
));
|
|
308
313
|
iterator = source[Symbol.asyncIterator]();
|
|
309
314
|
const first = await iterator.next();
|
|
@@ -866,6 +871,7 @@ class ModernHarnessApi {
|
|
|
866
871
|
questionError('dsh-im interaction adapter was disposed', 'ASK_ABORTED'),
|
|
867
872
|
);
|
|
868
873
|
for (const dispose of this.#disposers.splice(0).reverse()) dispose?.();
|
|
874
|
+
return this.#peer?.dispose();
|
|
869
875
|
}
|
|
870
876
|
}
|
|
871
877
|
|
|
@@ -890,7 +896,7 @@ export function modernHarnessApi(ctx, { deliveryService } = {}) {
|
|
|
890
896
|
if (typeof ctx.effect === 'function') {
|
|
891
897
|
ctx.effect(() => () => {
|
|
892
898
|
if (modernApis.get(scope) === api) modernApis.delete(scope);
|
|
893
|
-
api.dispose();
|
|
899
|
+
return api.dispose();
|
|
894
900
|
}, 'dsh-im: modern Harness compatibility API');
|
|
895
901
|
}
|
|
896
902
|
return api;
|
|
@@ -95,6 +95,13 @@ export const QQ_IMAGE_HOSTS = Object.freeze([
|
|
|
95
95
|
|
|
96
96
|
const QQ_IMAGE_FILENAME = /\.(?:gif|jpe?g|png|webp)$/i;
|
|
97
97
|
|
|
98
|
+
/** Durable queue-entry id; the conversation key keeps ids unique across chats. */
|
|
99
|
+
function pendingMessageId(key, messageId) {
|
|
100
|
+
return `${key}\u0000${messageId}`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const PENDING_RESTART_NOTICE = '排队中的消息在服务重启时被中断。为避免重复执行,未自动重放;如果该消息尚未处理,请重新发送。';
|
|
104
|
+
|
|
98
105
|
function helpText() {
|
|
99
106
|
return [
|
|
100
107
|
t('QQ 机器人已连接 DeepSeek Harness。'),
|
|
@@ -448,6 +455,8 @@ export class QqHarnessBridge {
|
|
|
448
455
|
#fetchImpl;
|
|
449
456
|
#fileUploadTimeoutMs;
|
|
450
457
|
#queues = new Map();
|
|
458
|
+
// Crash-recovery for #queues, started with the bridge; see recoverPendingMessages().
|
|
459
|
+
#pendingRecovery = null;
|
|
451
460
|
#busyMessages = new BusyMessageDispatcher();
|
|
452
461
|
#pendingInteractions = new Map();
|
|
453
462
|
#interactionKeys = new Map();
|
|
@@ -498,6 +507,10 @@ export class QqHarnessBridge {
|
|
|
498
507
|
this.#fetchImpl = fetchImpl;
|
|
499
508
|
this.#fileUploadTimeoutMs = Math.min(fileUploadTimeoutMs, DEFAULT_FILE_UPLOAD_TIMEOUT_MS);
|
|
500
509
|
this.#approvals = new HarnessApprovalQueue({ label: 'qq', logger });
|
|
510
|
+
// A queued message lives only in #queues. If the process dies before its
|
|
511
|
+
// turn runs the user has already been told it is queued, so the persisted
|
|
512
|
+
// entry must be replayed or reported as soon as the bridge starts.
|
|
513
|
+
this.recoverPendingMessages();
|
|
501
514
|
}
|
|
502
515
|
|
|
503
516
|
get status() {
|
|
@@ -714,6 +727,9 @@ export class QqHarnessBridge {
|
|
|
714
727
|
alreadyRecorded = false,
|
|
715
728
|
batchSubmission = null,
|
|
716
729
|
} = {}) {
|
|
730
|
+
// Persist before the message joins the in-memory chain: the chain may wait
|
|
731
|
+
// behind a long turn, and a restart in that window must not lose the input.
|
|
732
|
+
const pending = this.#recordPendingMessage(message, messageId, key);
|
|
717
733
|
const addressed = isQqMessageAddressed(message);
|
|
718
734
|
const preparedMessage = addressed
|
|
719
735
|
? prefetchInboundFiles(
|
|
@@ -724,19 +740,143 @@ export class QqHarnessBridge {
|
|
|
724
740
|
const previous = this.#queues.get(key) ?? Promise.resolve();
|
|
725
741
|
const current = previous
|
|
726
742
|
.catch(() => undefined)
|
|
743
|
+
.then(() => pending)
|
|
727
744
|
.then(() => this.#process(message, key, {
|
|
728
745
|
alreadyRecorded,
|
|
729
746
|
preparedMessage,
|
|
730
747
|
batchSubmission,
|
|
731
748
|
}))
|
|
732
|
-
.finally(() => {
|
|
749
|
+
.finally(async () => {
|
|
733
750
|
if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
|
|
734
751
|
if (this.#queues.get(key) === current) this.#queues.delete(key);
|
|
752
|
+
await this.#removePendingMessage(pendingMessageId(key, messageId));
|
|
735
753
|
});
|
|
736
754
|
this.#queues.set(key, current);
|
|
737
755
|
return current;
|
|
738
756
|
}
|
|
739
757
|
|
|
758
|
+
/**
|
|
759
|
+
* Replay (submitted: false) or report (submitted: true) the messages this
|
|
760
|
+
* bridge persisted before a restart. Idempotent: each entry is removed as it
|
|
761
|
+
* is handled, and the returned promise is shared with waitForIdle().
|
|
762
|
+
*/
|
|
763
|
+
recoverPendingMessages() {
|
|
764
|
+
this.#pendingRecovery ??= this.#recoverPendingMessages().catch((error) => {
|
|
765
|
+
this.#logger.warn?.('[dsh-im:qq] queued-message recovery failed:', error?.message ?? error);
|
|
766
|
+
});
|
|
767
|
+
return this.#pendingRecovery;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
async #recoverPendingMessages() {
|
|
771
|
+
if (typeof this.#state?.pendingMessages !== 'function') return;
|
|
772
|
+
const entries = this.#state.pendingMessages();
|
|
773
|
+
if (!Array.isArray(entries) || entries.length === 0) return;
|
|
774
|
+
for (const entry of entries) {
|
|
775
|
+
if (!entry || this.#signal?.aborted) return;
|
|
776
|
+
try {
|
|
777
|
+
if (entry.submitted === true) {
|
|
778
|
+
await this.#notifyInterruptedPending(entry);
|
|
779
|
+
await this.#removePendingMessage(entry.id);
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
this.#logger.warn?.(
|
|
783
|
+
'[dsh-im:qq] replaying a queued message that a restart interrupted:',
|
|
784
|
+
entry.messageId,
|
|
785
|
+
);
|
|
786
|
+
// The turn never reached Harness, so any earlier mark-seen is an
|
|
787
|
+
// attempt, not a completed delivery; clear it so the replay can run.
|
|
788
|
+
if (typeof this.#state.unmarkSeen === 'function') {
|
|
789
|
+
await this.#state.unmarkSeen(entry.messageId).catch(() => undefined);
|
|
790
|
+
}
|
|
791
|
+
await this.#replayPendingMessage(entry);
|
|
792
|
+
} catch (error) {
|
|
793
|
+
this.#logger.warn?.(
|
|
794
|
+
'[dsh-im:qq] failed to recover a queued message:',
|
|
795
|
+
entry?.messageId,
|
|
796
|
+
error?.message ?? error,
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
#recordPendingMessage(message, messageId, key) {
|
|
803
|
+
if (typeof this.#state?.putPendingMessage !== 'function') return Promise.resolve();
|
|
804
|
+
const text = safeText(message);
|
|
805
|
+
if (!text) return Promise.resolve();
|
|
806
|
+
const senderId = nonEmptyString(message.senderId);
|
|
807
|
+
const entry = {
|
|
808
|
+
id: pendingMessageId(key, messageId),
|
|
809
|
+
key,
|
|
810
|
+
messageId,
|
|
811
|
+
kind: message.kind === 'group' ? 'group' : 'c2c',
|
|
812
|
+
text,
|
|
813
|
+
submitted: false,
|
|
814
|
+
createdAt: new Date().toISOString(),
|
|
815
|
+
...(senderId ? { senderId } : {}),
|
|
816
|
+
...(message.replyTarget !== undefined ? { target: message.replyTarget } : {}),
|
|
817
|
+
};
|
|
818
|
+
return this.#state.putPendingMessage(entry).catch((error) => {
|
|
819
|
+
this.#logger.warn?.('[dsh-im:qq] failed to persist a queued message:', error?.message ?? error);
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
async #markPendingSubmitted(key, messageId) {
|
|
824
|
+
if (typeof this.#state?.patchPendingMessage !== 'function') return;
|
|
825
|
+
await this.#state.patchPendingMessage(pendingMessageId(key, messageId), { submitted: true });
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
async #removePendingMessage(id) {
|
|
829
|
+
if (typeof this.#state?.removePendingMessage !== 'function') return;
|
|
830
|
+
try {
|
|
831
|
+
await this.#state.removePendingMessage(id);
|
|
832
|
+
} catch (error) {
|
|
833
|
+
this.#logger.warn?.('[dsh-im:qq] failed to clear a queued-message entry:', error?.message ?? error);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
#replayPendingMessage(entry) {
|
|
838
|
+
const message = this.#pendingReplayMessage(entry);
|
|
839
|
+
if (!message) return Promise.resolve();
|
|
840
|
+
return this.#enqueueMessage(message, entry.messageId, entry.key);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
#pendingReplayMessage(entry) {
|
|
844
|
+
const separator = String(entry.key).indexOf(':');
|
|
845
|
+
if (separator < 0) return null;
|
|
846
|
+
const kind = entry.key.slice(0, separator) === 'group' ? 'group' : 'c2c';
|
|
847
|
+
const conversationId = entry.key.slice(separator + 1);
|
|
848
|
+
if (!conversationId || !entry.messageId) return null;
|
|
849
|
+
// Rebuild exactly the turn fields the queue path reads, so the recovered
|
|
850
|
+
// text is dispatched as the user's own message with no added framing.
|
|
851
|
+
return {
|
|
852
|
+
kind,
|
|
853
|
+
rawEventType: kind === 'group' ? 'GROUP_AT_MESSAGE_CREATE' : 'C2C_MESSAGE_CREATE',
|
|
854
|
+
senderId: entry.senderId ?? '',
|
|
855
|
+
messageId: entry.messageId,
|
|
856
|
+
content: entry.text,
|
|
857
|
+
...(kind === 'group' ? { groupOpenid: conversationId } : {}),
|
|
858
|
+
...(entry.target !== undefined ? { replyTarget: entry.target } : {}),
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
async #notifyInterruptedPending(entry) {
|
|
863
|
+
if (entry.target === undefined || entry.target === null) {
|
|
864
|
+
this.#logger.warn?.(
|
|
865
|
+
'[dsh-im:qq] a queued message was interrupted by a restart but has no delivery target:',
|
|
866
|
+
entry.messageId,
|
|
867
|
+
);
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
try {
|
|
871
|
+
await this.#bot.sendText(entry.target, t(PENDING_RESTART_NOTICE));
|
|
872
|
+
} catch (error) {
|
|
873
|
+
this.#logger.warn?.(
|
|
874
|
+
'[dsh-im:qq] failed to report an interrupted queued message:',
|
|
875
|
+
error?.message ?? error,
|
|
876
|
+
);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
740
880
|
async #deliverDeferredOutcome(entry, outcome) {
|
|
741
881
|
await sendMarkdownReply(this.#bot, entry.target, deferredOutcomeText(outcome), { logger: this.#logger });
|
|
742
882
|
return true;
|
|
@@ -843,6 +983,7 @@ export class QqHarnessBridge {
|
|
|
843
983
|
}
|
|
844
984
|
|
|
845
985
|
async waitForIdle() {
|
|
986
|
+
await this.#pendingRecovery;
|
|
846
987
|
await this.#busyMessages.whenIdle();
|
|
847
988
|
await Promise.allSettled([
|
|
848
989
|
...this.#queues.values(),
|
|
@@ -1107,6 +1248,11 @@ export class QqHarnessBridge {
|
|
|
1107
1248
|
// Persist consumption before handing the prompt to Harness. Provider
|
|
1108
1249
|
// redelivery after a failed error notice must never execute it twice.
|
|
1109
1250
|
await markMessageSeen();
|
|
1251
|
+
// The prompt is about to enter the Harness inbox, which is itself
|
|
1252
|
+
// durable. Marking the entry submitted first means a crash after this
|
|
1253
|
+
// point reports the message instead of replaying a turn the Harness may
|
|
1254
|
+
// already own.
|
|
1255
|
+
await this.#markPendingSubmitted(key, messageId);
|
|
1110
1256
|
({ answer, artifacts = [] } = await askInWorkspaceSession({
|
|
1111
1257
|
deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
|
|
1112
1258
|
harness: this.#harness,
|
|
@@ -4,8 +4,48 @@ import fs from 'node:fs/promises';
|
|
|
4
4
|
import { dirname } from 'node:path';
|
|
5
5
|
import { qqStateError } from './state-error.mjs';
|
|
6
6
|
|
|
7
|
+
const PENDING_MESSAGE_LIMIT = 200;
|
|
7
8
|
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [] });
|
|
8
9
|
|
|
10
|
+
/**
|
|
11
|
+
* A message persisted when it enters the QQ bridge's in-memory queue, so a
|
|
12
|
+
* restart before its turn runs can replay it (submitted: false) or report it
|
|
13
|
+
* (submitted: true, meaning the Harness inbox already owns it). Mirrors the
|
|
14
|
+
* shared ConversationStateStore contract used by the other text bridges.
|
|
15
|
+
*/
|
|
16
|
+
function validPendingMessage(value) {
|
|
17
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
18
|
+
&& ['id', 'key', 'messageId', 'kind', 'text']
|
|
19
|
+
.every((field) => typeof value[field] === 'string' && value[field]);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function normalizePendingMessage(value) {
|
|
23
|
+
if (!validPendingMessage(value)) return null;
|
|
24
|
+
const entry = {
|
|
25
|
+
id: value.id,
|
|
26
|
+
key: value.key,
|
|
27
|
+
messageId: value.messageId,
|
|
28
|
+
kind: value.kind,
|
|
29
|
+
text: value.text,
|
|
30
|
+
submitted: value.submitted === true,
|
|
31
|
+
};
|
|
32
|
+
if (typeof value.senderId === 'string' && value.senderId) entry.senderId = value.senderId;
|
|
33
|
+
if (typeof value.createdAt === 'string' && value.createdAt) entry.createdAt = value.createdAt;
|
|
34
|
+
if (value.target !== undefined) {
|
|
35
|
+
try {
|
|
36
|
+
entry.target = structuredClone(value.target);
|
|
37
|
+
} catch {
|
|
38
|
+
// A target that cannot be persisted is dropped; the entry still replays.
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return entry;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function normalizePendingMessages(value) {
|
|
45
|
+
if (!Array.isArray(value)) return [];
|
|
46
|
+
return value.map(normalizePendingMessage).filter(Boolean).slice(-PENDING_MESSAGE_LIMIT);
|
|
47
|
+
}
|
|
48
|
+
|
|
9
49
|
function normalizeState(value) {
|
|
10
50
|
if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
|
|
11
51
|
const sessions = {};
|
|
@@ -16,10 +56,14 @@ function normalizeState(value) {
|
|
|
16
56
|
}
|
|
17
57
|
}
|
|
18
58
|
}
|
|
59
|
+
// An empty queue leaves no key behind, so an untouched state file keeps the
|
|
60
|
+
// shape earlier versions wrote.
|
|
61
|
+
const pendingMessages = normalizePendingMessages(value.pendingMessages);
|
|
19
62
|
return {
|
|
20
63
|
version: 1,
|
|
21
64
|
sessions,
|
|
22
65
|
includeArchivedSessions: value.includeArchivedSessions === true,
|
|
66
|
+
...(pendingMessages.length ? { pendingMessages } : {}),
|
|
23
67
|
...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
|
|
24
68
|
seenMessageIds: Array.isArray(value.seenMessageIds)
|
|
25
69
|
? value.seenMessageIds.filter((id) => typeof id === 'string').slice(-1_000)
|
|
@@ -77,6 +121,51 @@ export class QqStateStore {
|
|
|
77
121
|
patchDeferred(id, patch) { return this.#deferred.patch(id, patch); }
|
|
78
122
|
removeDeferred(id) { return this.#deferred.remove(id); }
|
|
79
123
|
|
|
124
|
+
pendingMessages() {
|
|
125
|
+
return structuredClone(this.#state.pendingMessages ?? []);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async putPendingMessage(entry) {
|
|
129
|
+
const normalized = normalizePendingMessage({
|
|
130
|
+
createdAt: new Date().toISOString(),
|
|
131
|
+
...entry,
|
|
132
|
+
});
|
|
133
|
+
if (!normalized) throw new TypeError('Invalid pending message entry');
|
|
134
|
+
const list = this.#state.pendingMessages ??= [];
|
|
135
|
+
const index = list.findIndex((candidate) => candidate.id === normalized.id);
|
|
136
|
+
if (index < 0) list.push(normalized);
|
|
137
|
+
else list[index] = normalized;
|
|
138
|
+
if (list.length > PENDING_MESSAGE_LIMIT) {
|
|
139
|
+
list.splice(0, list.length - PENDING_MESSAGE_LIMIT);
|
|
140
|
+
}
|
|
141
|
+
await this.#persist();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async patchPendingMessage(id, patch) {
|
|
145
|
+
const current = (this.#state.pendingMessages ?? []).find((entry) => entry.id === id);
|
|
146
|
+
if (!current) return null;
|
|
147
|
+
const next = {
|
|
148
|
+
...current,
|
|
149
|
+
...patch,
|
|
150
|
+
id: current.id,
|
|
151
|
+
key: current.key,
|
|
152
|
+
messageId: current.messageId,
|
|
153
|
+
kind: current.kind,
|
|
154
|
+
text: current.text,
|
|
155
|
+
};
|
|
156
|
+
await this.putPendingMessage(next);
|
|
157
|
+
return normalizePendingMessage(next);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async removePendingMessage(id) {
|
|
161
|
+
const list = this.#state.pendingMessages ?? [];
|
|
162
|
+
const next = list.filter((entry) => entry.id !== id);
|
|
163
|
+
if (next.length === list.length) return;
|
|
164
|
+
if (next.length) this.#state.pendingMessages = next;
|
|
165
|
+
else delete this.#state.pendingMessages;
|
|
166
|
+
await this.#persist();
|
|
167
|
+
}
|
|
168
|
+
|
|
80
169
|
includesArchivedSessions() { return this.#state.includeArchivedSessions === true; }
|
|
81
170
|
|
|
82
171
|
async setIncludeArchivedSessions(include) {
|
|
@@ -10,8 +10,53 @@ const EXTENSION_KEYS = Object.freeze([
|
|
|
10
10
|
'emailBindings', 'mailCursor', 'pendingAuth', 'threadIds', 'rootAnchors',
|
|
11
11
|
]);
|
|
12
12
|
|
|
13
|
+
const PENDING_MESSAGE_LIMIT = 200;
|
|
14
|
+
|
|
13
15
|
const EMPTY_STATE = Object.freeze({ version: 1, sessions: {}, seenMessageIds: [], cursor: null });
|
|
14
16
|
|
|
17
|
+
/**
|
|
18
|
+
* A message persisted when it enters a bridge's in-memory queue, so a restart
|
|
19
|
+
* before its turn runs can replay it (submitted: false) or report it
|
|
20
|
+
* (submitted: true, meaning the Harness inbox already owns it).
|
|
21
|
+
*
|
|
22
|
+
* Wired today by TextHarnessBridge (telegram, slack, discord, matrix,
|
|
23
|
+
* whatsapp, email, imessage) and QqHarnessBridge. The channels that run their
|
|
24
|
+
* own queue path (weixin, dingtalk, wecom, wecom-app, feishu) still need the
|
|
25
|
+
* same treatment.
|
|
26
|
+
*/
|
|
27
|
+
function validPendingMessage(value) {
|
|
28
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
|
29
|
+
&& ['id', 'key', 'messageId', 'kind', 'text']
|
|
30
|
+
.every((field) => typeof value[field] === 'string' && value[field]);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function normalizePendingMessage(value) {
|
|
34
|
+
if (!validPendingMessage(value)) return null;
|
|
35
|
+
const entry = {
|
|
36
|
+
id: value.id,
|
|
37
|
+
key: value.key,
|
|
38
|
+
messageId: value.messageId,
|
|
39
|
+
kind: value.kind,
|
|
40
|
+
text: value.text,
|
|
41
|
+
submitted: value.submitted === true,
|
|
42
|
+
};
|
|
43
|
+
if (typeof value.senderId === 'string' && value.senderId) entry.senderId = value.senderId;
|
|
44
|
+
if (typeof value.createdAt === 'string' && value.createdAt) entry.createdAt = value.createdAt;
|
|
45
|
+
if (value.target !== undefined) {
|
|
46
|
+
try {
|
|
47
|
+
entry.target = structuredClone(value.target);
|
|
48
|
+
} catch {
|
|
49
|
+
// A target that cannot be persisted is dropped; the entry still replays.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return entry;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function normalizePendingMessages(value) {
|
|
56
|
+
if (!Array.isArray(value)) return [];
|
|
57
|
+
return value.map(normalizePendingMessage).filter(Boolean).slice(-PENDING_MESSAGE_LIMIT);
|
|
58
|
+
}
|
|
59
|
+
|
|
15
60
|
function normalizeState(value) {
|
|
16
61
|
if (!value || typeof value !== 'object') return structuredClone(EMPTY_STATE);
|
|
17
62
|
const sessions = {};
|
|
@@ -22,9 +67,13 @@ function normalizeState(value) {
|
|
|
22
67
|
}
|
|
23
68
|
}
|
|
24
69
|
}
|
|
70
|
+
// An empty queue leaves no key behind, so an untouched state file keeps the
|
|
71
|
+
// shape earlier versions wrote.
|
|
72
|
+
const pendingMessages = normalizePendingMessages(value.pendingMessages);
|
|
25
73
|
const normalized = {
|
|
26
74
|
version: 1,
|
|
27
75
|
sessions,
|
|
76
|
+
...(pendingMessages.length ? { pendingMessages } : {}),
|
|
28
77
|
...(value.deferred ? { deferred: normalizeDeferredState(value.deferred) } : {}),
|
|
29
78
|
seenMessageIds: Array.isArray(value.seenMessageIds)
|
|
30
79
|
? value.seenMessageIds.filter((id) => typeof id === 'string' && id).slice(-1_000)
|
|
@@ -65,6 +114,51 @@ export class ConversationStateStore {
|
|
|
65
114
|
patchDeferred(id, patch) { return this.#deferred.patch(id, patch); }
|
|
66
115
|
removeDeferred(id) { return this.#deferred.remove(id); }
|
|
67
116
|
|
|
117
|
+
pendingMessages() {
|
|
118
|
+
return structuredClone(this.#state.pendingMessages ?? []);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async putPendingMessage(entry) {
|
|
122
|
+
const normalized = normalizePendingMessage({
|
|
123
|
+
createdAt: new Date().toISOString(),
|
|
124
|
+
...entry,
|
|
125
|
+
});
|
|
126
|
+
if (!normalized) throw new TypeError('Invalid pending message entry');
|
|
127
|
+
const list = this.#state.pendingMessages ??= [];
|
|
128
|
+
const index = list.findIndex((candidate) => candidate.id === normalized.id);
|
|
129
|
+
if (index < 0) list.push(normalized);
|
|
130
|
+
else list[index] = normalized;
|
|
131
|
+
if (list.length > PENDING_MESSAGE_LIMIT) {
|
|
132
|
+
list.splice(0, list.length - PENDING_MESSAGE_LIMIT);
|
|
133
|
+
}
|
|
134
|
+
await this.#persist();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async patchPendingMessage(id, patch) {
|
|
138
|
+
const current = (this.#state.pendingMessages ?? []).find((entry) => entry.id === id);
|
|
139
|
+
if (!current) return null;
|
|
140
|
+
const next = {
|
|
141
|
+
...current,
|
|
142
|
+
...patch,
|
|
143
|
+
id: current.id,
|
|
144
|
+
key: current.key,
|
|
145
|
+
messageId: current.messageId,
|
|
146
|
+
kind: current.kind,
|
|
147
|
+
text: current.text,
|
|
148
|
+
};
|
|
149
|
+
await this.putPendingMessage(next);
|
|
150
|
+
return normalizePendingMessage(next);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async removePendingMessage(id) {
|
|
154
|
+
const list = this.#state.pendingMessages ?? [];
|
|
155
|
+
const next = list.filter((entry) => entry.id !== id);
|
|
156
|
+
if (next.length === list.length) return;
|
|
157
|
+
if (next.length) this.#state.pendingMessages = next;
|
|
158
|
+
else delete this.#state.pendingMessages;
|
|
159
|
+
await this.#persist();
|
|
160
|
+
}
|
|
161
|
+
|
|
68
162
|
sessionFor(key) {
|
|
69
163
|
return this.#state.sessions[key] ?? null;
|
|
70
164
|
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { createDeferredDeliveryRegistry, extractCompletedTurnAnswer } from './deferred-delivery.mjs';
|
|
2
2
|
import { t } from './i18n.mjs';
|
|
3
3
|
import { channelDeliveryFailure } from './message-failure.mjs';
|
|
4
|
+
import { PromptFailureTracker } from './prompt-failure-tracker.mjs';
|
|
4
5
|
|
|
5
6
|
export function deferredOutcomeText(outcome) {
|
|
6
7
|
if (outcome.found && outcome.text) return outcome.text;
|
|
7
8
|
const reason = outcome.reason === 'stopped' ? t('已停止')
|
|
8
9
|
: ['aborted', 'cancelled'].includes(outcome.reason) ? t('已中止')
|
|
9
|
-
: outcome.reason
|
|
10
|
+
: ['failed', 'error'].includes(outcome.reason) ? t('任务失败') : t('已结束');
|
|
10
11
|
return t('后台任务已结束({reason}),没有可推送的最终结果。', { reason });
|
|
11
12
|
}
|
|
12
13
|
|
|
@@ -83,7 +84,10 @@ export function createDeferredDeliveryCoordinator({
|
|
|
83
84
|
const ordered = [...events.values()].sort((a, b) => a.seq - b.seq);
|
|
84
85
|
if (targetTurn === null && entry.promptRpcId) {
|
|
85
86
|
let openTurn = null;
|
|
87
|
+
const earlyFailure = new PromptFailureTracker(entry.promptRpcId, entry.afterSeq);
|
|
86
88
|
for (const event of ordered) {
|
|
89
|
+
const failedTurn = earlyFailure.consume(event);
|
|
90
|
+
if (failedTurn !== null) { targetTurn = failedTurn; break; }
|
|
87
91
|
if (event.type === 'turn/start') openTurn = event.data?.turn ?? null;
|
|
88
92
|
if (event.type === 'user/message' && event.data?.source?.rpcId === entry.promptRpcId) {
|
|
89
93
|
targetTurn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : openTurn;
|
|
@@ -23,6 +23,7 @@ import { outboundArtifactRegistry } from './semantic/artifact.mjs';
|
|
|
23
23
|
import { t } from './i18n.mjs';
|
|
24
24
|
import { watchHarnessMux } from './harness-mux.mjs';
|
|
25
25
|
import { extractConnectionEvidence, messageDiagnosticError } from './connection-error.mjs';
|
|
26
|
+
import { PromptFailureTracker } from './prompt-failure-tracker.mjs';
|
|
26
27
|
|
|
27
28
|
// Every channel plugin runs in the same Host process. Sharing ownership by
|
|
28
29
|
// Host identity (or an explicitly configured HTTP origin) prevents clients
|
|
@@ -582,6 +583,7 @@ export function harnessToolCallFromEvent(event) {
|
|
|
582
583
|
|
|
583
584
|
export class HarnessReplyTracker {
|
|
584
585
|
#promptRpcId;
|
|
586
|
+
#promptFailure;
|
|
585
587
|
#lastSeq;
|
|
586
588
|
#openTurn = null;
|
|
587
589
|
#targetTurn = null;
|
|
@@ -599,6 +601,7 @@ export class HarnessReplyTracker {
|
|
|
599
601
|
|
|
600
602
|
constructor({ promptRpcId, afterSeq = -1, reasoning = false, finalAnswerOnly = false }) {
|
|
601
603
|
this.#promptRpcId = promptRpcId;
|
|
604
|
+
this.#promptFailure = new PromptFailureTracker(promptRpcId, afterSeq);
|
|
602
605
|
this.#lastSeq = afterSeq;
|
|
603
606
|
// Reasoning updates are opt-in per consumer: only channels that surface
|
|
604
607
|
// thinking traces (Telegram thinking mode) subscribe; every other channel
|
|
@@ -697,6 +700,7 @@ export class HarnessReplyTracker {
|
|
|
697
700
|
// The mux is lossy across reconnects. Only history may advance the
|
|
698
701
|
// durable cursor or finish the reply; the mux supplements reasoning.
|
|
699
702
|
if (fromMux && !isReasoning) continue;
|
|
703
|
+
const failedTurn = fromMux ? null : this.#promptFailure.consume(event);
|
|
700
704
|
if (isReasoning) {
|
|
701
705
|
if (!live || !Number.isFinite(seq)) continue;
|
|
702
706
|
if (this.#targetTurn === null) this.#bufferReasoning(event);
|
|
@@ -720,8 +724,12 @@ export class HarnessReplyTracker {
|
|
|
720
724
|
this.#emitReasoning(pending, pushUpdate);
|
|
721
725
|
}
|
|
722
726
|
}
|
|
727
|
+
continue;
|
|
723
728
|
}
|
|
724
|
-
|
|
729
|
+
// Model resolution or pre-step hooks can fail after the inbox claim
|
|
730
|
+
// but before user/message. Only a proved claim may close this wait.
|
|
731
|
+
if (event.type !== 'turn/end' || failedTurn === null || failedTurn !== event.data?.turn) continue;
|
|
732
|
+
this.#targetTurn = failedTurn;
|
|
725
733
|
}
|
|
726
734
|
if (seq <= this.#lastSeq) continue;
|
|
727
735
|
this.#lastSeq = seq;
|
|
@@ -285,6 +285,8 @@ export default {
|
|
|
285
285
|
'任务已结束,没有正在运行的任务,无法补充指令。请直接发送消息开始新任务。':
|
|
286
286
|
'The task has ended and there is no running task to steer. Send a message to start a new task.',
|
|
287
287
|
'已排队,等待前序消息处理。': 'Queued. Waiting for the preceding messages to finish.',
|
|
288
|
+
'排队中的消息在服务重启时被中断。为避免重复执行,未自动重放;如果该消息尚未处理,请重新发送。':
|
|
289
|
+
'A queued message was interrupted when the service restarted. It was not replayed automatically to avoid running it twice; if it was not processed, please send it again.',
|
|
288
290
|
'已提交补充指令,Agent 会在下一步读取。':
|
|
289
291
|
'Additional instruction submitted; the Agent will read it at the next step.',
|
|
290
292
|
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Correlate failures before user/message via the durable inbox's exact claim.
|
|
2
|
+
* This grants no live turn/interaction ownership and never guesses from the
|
|
3
|
+
* next turn/start: other callers may already be queued in the same Session.
|
|
4
|
+
*/
|
|
5
|
+
export class PromptFailureTracker {
|
|
6
|
+
#rpcId;
|
|
7
|
+
#seq;
|
|
8
|
+
#pending = new Map();
|
|
9
|
+
#openTurn = null;
|
|
10
|
+
#claimedTurn = null;
|
|
11
|
+
#failedTurn = null;
|
|
12
|
+
|
|
13
|
+
constructor(rpcId, afterSeq = -1) {
|
|
14
|
+
this.#rpcId = rpcId;
|
|
15
|
+
this.#seq = afterSeq;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
consume(event) {
|
|
19
|
+
const { seq, type, data = {} } = event;
|
|
20
|
+
if (!Number.isSafeInteger(seq) || seq <= this.#seq || this.#failedTurn !== null) {
|
|
21
|
+
return this.#failedTurn;
|
|
22
|
+
}
|
|
23
|
+
// Missing splices could have changed queue positions or canceled the input.
|
|
24
|
+
// Prefer no attribution over attributing another caller's failure.
|
|
25
|
+
if (seq !== this.#seq + 1) {
|
|
26
|
+
this.#pending.clear();
|
|
27
|
+
this.#openTurn = null;
|
|
28
|
+
this.#claimedTurn = null;
|
|
29
|
+
}
|
|
30
|
+
this.#seq = seq;
|
|
31
|
+
if (type === 'turn/start') this.#openTurn = data.turn ?? null;
|
|
32
|
+
if (type === 'agent/inbox/spliced') {
|
|
33
|
+
const { target, start, inserted, outcome } = data;
|
|
34
|
+
const count = data.removedCount ?? 0;
|
|
35
|
+
if (!['next-turn', 'next-step'].includes(target) || !Number.isSafeInteger(start) || start < 0
|
|
36
|
+
|| !Number.isSafeInteger(count) || count < 0 || !Array.isArray(inserted)) {
|
|
37
|
+
this.#pending.clear();
|
|
38
|
+
this.#claimedTurn = null;
|
|
39
|
+
return this.#failedTurn;
|
|
40
|
+
}
|
|
41
|
+
const positions = this.#pending.get(target) ?? [];
|
|
42
|
+
const next = [];
|
|
43
|
+
for (const index of positions) {
|
|
44
|
+
if (index < start) next.push(index);
|
|
45
|
+
else if (index >= start + count) next.push(index + inserted.length - count);
|
|
46
|
+
else if (outcome === undefined && inserted.length === 0 && Number.isSafeInteger(this.#openTurn)) {
|
|
47
|
+
this.#claimedTurn = this.#openTurn;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
inserted.forEach((message, index) => {
|
|
51
|
+
if (message?.source?.rpcId === this.#rpcId) next.push(start + index);
|
|
52
|
+
});
|
|
53
|
+
this.#pending.set(target, next);
|
|
54
|
+
}
|
|
55
|
+
if (type === 'turn/end') {
|
|
56
|
+
const kind = typeof data.reason === 'string' ? data.reason : data.reason?.kind;
|
|
57
|
+
if (Number.isSafeInteger(this.#claimedTurn) && data.turn === this.#claimedTurn && kind && kind !== 'completed') {
|
|
58
|
+
this.#failedTurn = data.turn;
|
|
59
|
+
}
|
|
60
|
+
if (data.turn === this.#claimedTurn) this.#claimedTurn = null;
|
|
61
|
+
this.#openTurn = null;
|
|
62
|
+
}
|
|
63
|
+
return this.#failedTurn;
|
|
64
|
+
}
|
|
65
|
+
}
|