@xmanrui/dsh-im 4.38.2 → 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 +7 -4
- package/lib/index.js +311 -306
- package/package.json +4 -3
- package/plugin-src/host/injected-context.mjs +13 -1
- package/plugin-src/host/modern-harness-api.mjs +10 -4
- package/src/channels/matrix/matrix-api.mjs +34 -0
- package/src/channels/matrix/matrix-config-store.mjs +50 -2
- package/src/channels/matrix/matrix-normalize.mjs +106 -14
- package/src/channels/matrix/matrix-room-history.mjs +240 -8
- package/src/channels/matrix/matrix-runtime.mjs +563 -3
- package/src/channels/qq/qq-bridge.mjs +147 -1
- package/src/channels/qq/state-store.mjs +89 -0
- package/src/channels/shared/context-enhancement.mjs +2 -0
- package/src/channels/shared/conversation/ambient-provider.mjs +115 -0
- package/src/channels/shared/conversation/context-builder.mjs +148 -0
- package/src/channels/shared/conversation/reply-context.mjs +95 -0
- package/src/channels/shared/conversation/root-context.mjs +101 -0
- package/src/channels/shared/conversation/route.mjs +71 -0
- package/src/channels/shared/conversation/semantic-message.mjs +75 -0
- package/src/channels/shared/conversation/trigger-policy.mjs +80 -0
- package/src/channels/shared/conversation-state-store.mjs +95 -1
- package/src/channels/shared/deferred-delivery-coordinator.mjs +5 -1
- package/src/channels/shared/harness-approval.mjs +19 -0
- package/src/channels/shared/harness-client.mjs +9 -1
- package/src/channels/shared/i18n-en/shared-a.mjs +2 -0
- package/src/channels/shared/i18n-en/shared-b.mjs +2 -0
- package/src/channels/shared/injected-context.mjs +64 -2
- package/src/channels/shared/prompt-failure-tracker.mjs +65 -0
- package/src/channels/shared/speaker-label.mjs +46 -0
- package/src/channels/shared/text-harness-bridge.mjs +504 -33
- package/src/channels/wecom/wecom-cards.mjs +1 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-consumption registry for conversation roots (Feishu topic roots, Matrix
|
|
3
|
+
* thread roots): the first message of a thread is context for that thread's AI
|
|
4
|
+
* conversation, but it must not be re-fed on every turn.
|
|
5
|
+
*
|
|
6
|
+
* The contract mirrors the behavior shipped for Feishu topics in CHANGELOG
|
|
7
|
+
* 4.24.1: the root rides along only until one turn using it completes
|
|
8
|
+
* successfully — commands, rejected messages, and failed lookups or requests
|
|
9
|
+
* never consume it — and a cleared, switched, or rebuilt session receives it
|
|
10
|
+
* again. Anchors persist through the conversation state store's extension
|
|
11
|
+
* mechanism so a restart does not re-inject; a state without that mechanism
|
|
12
|
+
* (tests, older stores) falls back to an in-process table.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export class RootContextRegistry {
|
|
16
|
+
#state;
|
|
17
|
+
// Same shape as the persisted anchor table so every accessor reads one kind of value.
|
|
18
|
+
#fallback = Object.create(null);
|
|
19
|
+
|
|
20
|
+
constructor({ state = null } = {}) {
|
|
21
|
+
this.#state = state;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The live anchor table, creating it inside the persisted state when possible. */
|
|
25
|
+
#table(create = false) {
|
|
26
|
+
const extension = typeof this.#state?.extensionState === 'function' ? this.#state.extensionState() : null;
|
|
27
|
+
if (extension && typeof extension === 'object') {
|
|
28
|
+
if (extension.rootAnchors && typeof extension.rootAnchors === 'object') return extension.rootAnchors;
|
|
29
|
+
if (create) extension.rootAnchors = Object.create(null);
|
|
30
|
+
return extension ? extension.rootAnchors ?? null : null;
|
|
31
|
+
}
|
|
32
|
+
return this.#fallback;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
#persist() {
|
|
36
|
+
if (typeof this.#state?.persist === 'function') return this.#state.persist();
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {{sessionId: ?string, rootId: ?string}|null} anchor
|
|
42
|
+
*/
|
|
43
|
+
anchorFor(routeKey) {
|
|
44
|
+
const anchor = this.#table(false)?.[routeKey];
|
|
45
|
+
if (!anchor || typeof anchor !== 'object') return null;
|
|
46
|
+
return Object.freeze({
|
|
47
|
+
sessionId: typeof anchor.sessionId === 'string' && anchor.sessionId ? anchor.sessionId : null,
|
|
48
|
+
rootId: typeof anchor.rootId === 'string' && anchor.rootId ? anchor.rootId : null,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Whether the root context should ride along on the next prompt.
|
|
54
|
+
* @param {{routeKey: string, sessionId: ?string, rootId: ?string}} request
|
|
55
|
+
* @returns {{inject: boolean, reason: string}}
|
|
56
|
+
*/
|
|
57
|
+
plan({ routeKey, sessionId = null, rootId = null } = {}) {
|
|
58
|
+
if (!routeKey || typeof rootId !== 'string' || !rootId) {
|
|
59
|
+
return Object.freeze({ inject: false, reason: 'no-root' });
|
|
60
|
+
}
|
|
61
|
+
const anchor = this.anchorFor(routeKey);
|
|
62
|
+
const effectiveSessionId = typeof sessionId === 'string' && sessionId ? sessionId : null;
|
|
63
|
+
if (!anchor) return Object.freeze({ inject: true, reason: 'fresh' });
|
|
64
|
+
if (anchor.rootId !== rootId) return Object.freeze({ inject: true, reason: 'root-changed' });
|
|
65
|
+
if (anchor.sessionId !== effectiveSessionId) return Object.freeze({ inject: true, reason: 'session-changed' });
|
|
66
|
+
return Object.freeze({ inject: false, reason: 'consumed' });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Record a successful consumption; only call this after the turn succeeded. */
|
|
70
|
+
async markInjected({ routeKey, sessionId = null, rootId } = {}) {
|
|
71
|
+
if (!routeKey || typeof rootId !== 'string' || !rootId) return false;
|
|
72
|
+
const table = this.#table(true);
|
|
73
|
+
if (!table) return false;
|
|
74
|
+
table[routeKey] = {
|
|
75
|
+
sessionId: typeof sessionId === 'string' && sessionId ? sessionId : null,
|
|
76
|
+
rootId,
|
|
77
|
+
at: new Date().toISOString(),
|
|
78
|
+
};
|
|
79
|
+
await this.#persist();
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Drop one route's anchor so the next successful turn re-receives the root (a cleared session). */
|
|
84
|
+
async clearRoute(routeKey) {
|
|
85
|
+
const table = this.#table(false);
|
|
86
|
+
if (!table || !(routeKey in table)) return false;
|
|
87
|
+
delete table[routeKey];
|
|
88
|
+
await this.#persist();
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Drop every anchor (a full reset of the conversation state). */
|
|
93
|
+
async clearAll() {
|
|
94
|
+
const table = this.#table(false);
|
|
95
|
+
if (table) {
|
|
96
|
+
for (const key of Object.keys(table)) delete table[key];
|
|
97
|
+
await this.#persist();
|
|
98
|
+
}
|
|
99
|
+
for (const key of Object.keys(this.#fallback)) delete this.#fallback[key];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Channel-neutral conversation routes plus the single generator of the
|
|
3
|
+
* conversation session keys stored in a channel's state file.
|
|
4
|
+
*
|
|
5
|
+
* The codecs encode the established on-disk shapes so adopting this module
|
|
6
|
+
* never rewrites an existing key: Matrix keeps `direct:dm:<lower user id>`
|
|
7
|
+
* and `group:room:<roomId>[$<thread root>]` (event ids themselves begin with
|
|
8
|
+
* `$`, so a thread key reads with a `$$` run on disk); Feishu group chats keep
|
|
9
|
+
* `group:<chatId>` and `group:<chatId>:thread:<threadId>`. Feishu p2p keys
|
|
10
|
+
* are produced by the channel's own `conversationKey` helper until the parity
|
|
11
|
+
* cutover moves them here; the codec therefore refuses to encode a Feishu dm
|
|
12
|
+
* route instead of inventing a second shape.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {Object} ConversationRoute
|
|
17
|
+
* @property {string} channel Codec selector ('matrix', 'feishu', ...).
|
|
18
|
+
* @property {?string} botId Bot identity for namespacing; null when the channel key is not bot-scoped.
|
|
19
|
+
* @property {string} chatId Room / chat id: Matrix `room_id`, Feishu `chat_id`.
|
|
20
|
+
* @property {?string} senderId Sender identity, required by dm routes.
|
|
21
|
+
* @property {?string} threadId Server-side thread root (Matrix event id, Feishu thread_id); null on main-feed routes.
|
|
22
|
+
* @property {'dm'|'group'|'thread'} scope
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const MATRIX_CODEC = Object.freeze({
|
|
26
|
+
dm: (route) => `direct:dm:${String(route.senderId ?? '').trim().toLowerCase()}`,
|
|
27
|
+
group: (route) => `group:room:${route.chatId}${route.threadId ? `$${route.threadId}` : ''}`,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const FEISHU_CODEC = Object.freeze({
|
|
31
|
+
dm: null,
|
|
32
|
+
group: (route) => (route.threadId ? `group:${route.chatId}:thread:${route.threadId}` : `group:${route.chatId}`),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const CODECS = Object.freeze({ matrix: MATRIX_CODEC, feishu: FEISHU_CODEC });
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Build one frozen conversation route from the channel-neutral parts.
|
|
39
|
+
* @param {Object} parts - route parts; `kind` accepts 'direct'|'dm'|'group'.
|
|
40
|
+
* @returns {ConversationRoute}
|
|
41
|
+
*/
|
|
42
|
+
export function buildConversationRoute({ channel, botId = null, chatId, senderId = null, threadId = null, kind = 'group' } = {}) {
|
|
43
|
+
if (typeof channel !== 'string' || !channel) throw new TypeError('A conversation route requires a channel');
|
|
44
|
+
if (typeof chatId !== 'string' || !chatId) throw new TypeError('A conversation route requires a chat id');
|
|
45
|
+
const scope = kind === 'direct' || kind === 'dm'
|
|
46
|
+
? 'dm'
|
|
47
|
+
: (typeof threadId === 'string' && threadId ? 'thread' : 'group');
|
|
48
|
+
return Object.freeze({
|
|
49
|
+
channel,
|
|
50
|
+
botId: typeof botId === 'string' && botId ? botId : null,
|
|
51
|
+
chatId,
|
|
52
|
+
senderId: typeof senderId === 'string' && senderId ? senderId : null,
|
|
53
|
+
threadId: scope === 'thread' ? threadId : null,
|
|
54
|
+
scope,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The one place conversation session keys are produced.
|
|
60
|
+
* @param {ConversationRoute} route
|
|
61
|
+
* @returns {string} the durable conversation key, e.g. `group:room:!a:x.org$$root:y.org`.
|
|
62
|
+
*/
|
|
63
|
+
export function encodeConversationRouteKey(route) {
|
|
64
|
+
const codec = CODECS[route?.channel];
|
|
65
|
+
if (!codec) throw new TypeError(`No conversation key codec is registered for channel "${route?.channel ?? '?'}"`);
|
|
66
|
+
const encode = codec[route.scope === 'dm' ? 'dm' : 'group'];
|
|
67
|
+
if (typeof encode !== 'function') {
|
|
68
|
+
throw new TypeError(`Channel "${route.channel}" cannot encode a ${route.scope} route`);
|
|
69
|
+
}
|
|
70
|
+
return encode(route);
|
|
71
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Semantic Message contract every channel adapter normalizes toward.
|
|
3
|
+
*
|
|
4
|
+
* CONTEXT.md separates what must stay platform-neutral (this shape and the
|
|
5
|
+
* conversation route) from the native channel action (cards, edits, reactions,
|
|
6
|
+
* threads as delivery targets). Only the former lives here; anything a channel
|
|
7
|
+
* produces through its own API stays in the channel directory. The shape is a
|
|
8
|
+
* duck-typed contract: existing channel-normalized messages already satisfy it
|
|
9
|
+
* field by field, so adapters may adopt `createSemanticMessage` incrementally.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {Object} MessageRef
|
|
14
|
+
* @property {string} id Platform event/message id.
|
|
15
|
+
* @property {?string} sender Author identity of the referenced message.
|
|
16
|
+
* @property {?number} timestamp Origin ms when known.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @typedef {Object} SemanticMessage
|
|
21
|
+
* @property {string} id
|
|
22
|
+
* @property {string} channel
|
|
23
|
+
* @property {?string} botId
|
|
24
|
+
* @property {string} chatId Room / chat id.
|
|
25
|
+
* @property {?string} threadId Thread root when the message lives in one.
|
|
26
|
+
* @property {{id: string, name?: string}} sender
|
|
27
|
+
* @property {number} timestamp Origin ms; ingestion time when the platform hides it.
|
|
28
|
+
* @property {string} content Model-facing text, verbatim framing is producer-owned.
|
|
29
|
+
* @property {?MessageRef} replyTo
|
|
30
|
+
* @property {{mentionedBot: boolean, repliedToBot: boolean, commandLike: boolean}} trigger
|
|
31
|
+
* @property {'dm'|'group'} kind
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
function clean(value) {
|
|
35
|
+
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Validate and freeze one semantic message. Throws on identity-bearing fields;
|
|
40
|
+
* optional fields normalize to null instead of throwing so an adapter can
|
|
41
|
+
* forward a best-effort projection.
|
|
42
|
+
* @param {Object} fields
|
|
43
|
+
* @returns {SemanticMessage}
|
|
44
|
+
*/
|
|
45
|
+
export function createSemanticMessage({
|
|
46
|
+
id, channel, botId = null, chatId, threadId = null,
|
|
47
|
+
sender = {}, timestamp, content = '', replyTo = null, trigger = {}, kind = 'group',
|
|
48
|
+
} = {}) {
|
|
49
|
+
if (typeof id !== 'string' || !id) throw new TypeError('A semantic message requires an id');
|
|
50
|
+
if (typeof channel !== 'string' || !channel) throw new TypeError('A semantic message requires a channel');
|
|
51
|
+
if (typeof chatId !== 'string' || !chatId) throw new TypeError('A semantic message requires a chat id');
|
|
52
|
+
const senderId = clean(sender?.id);
|
|
53
|
+
if (!senderId) throw new TypeError('A semantic message requires a sender id');
|
|
54
|
+
const senderName = clean(sender?.name);
|
|
55
|
+
const replyId = clean(replyTo?.id);
|
|
56
|
+
return Object.freeze({
|
|
57
|
+
id,
|
|
58
|
+
channel,
|
|
59
|
+
botId: clean(botId),
|
|
60
|
+
chatId,
|
|
61
|
+
threadId: clean(threadId),
|
|
62
|
+
sender: Object.freeze(senderName ? { id: senderId, name: senderName } : { id: senderId }),
|
|
63
|
+
timestamp: Number.isSafeInteger(timestamp) && timestamp > 0 ? timestamp : Date.now(),
|
|
64
|
+
content: typeof content === 'string' ? content : '',
|
|
65
|
+
replyTo: replyId
|
|
66
|
+
? Object.freeze({ id: replyId, sender: clean(replyTo?.sender), timestamp: Number.isSafeInteger(replyTo?.timestamp) && replyTo.timestamp > 0 ? replyTo.timestamp : null })
|
|
67
|
+
: null,
|
|
68
|
+
trigger: Object.freeze({
|
|
69
|
+
mentionedBot: trigger?.mentionedBot === true,
|
|
70
|
+
repliedToBot: trigger?.repliedToBot === true,
|
|
71
|
+
commandLike: trigger?.commandLike === true,
|
|
72
|
+
}),
|
|
73
|
+
kind: kind === 'direct' || kind === 'dm' ? 'dm' : 'group',
|
|
74
|
+
});
|
|
75
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The trigger rule table: which inbound message may wake the AI, and which is
|
|
3
|
+
* only recorded by the channel. The rules are a pure function over the bits an
|
|
4
|
+
* adapter already extracted (mention, command shape, reply relation) plus an
|
|
5
|
+
* optional synchronous classification of a reply's target, so the decision is
|
|
6
|
+
* testable without any transport.
|
|
7
|
+
*
|
|
8
|
+
* `replyMode` is what separates the product shapes a room bot can have; the
|
|
9
|
+
* shipped default is `never`, so a room only wakes the bot through an
|
|
10
|
+
* @-mention or a command:
|
|
11
|
+
* - `never`: replies never address the bot; only mentions and commands do.
|
|
12
|
+
* - `bot-only`: only replies that provably answer one of the bot's own messages
|
|
13
|
+
* address it; a reply to a human message is not a trigger and an
|
|
14
|
+
* unclassifiable target stays unaddressed too, so the classifier (usually the
|
|
15
|
+
* bot-event binding table) must be wired before this mode is enabled.
|
|
16
|
+
* - `any`: the 4.25-era room shape — a reply relation anywhere addresses the bot.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export const TRIGGER_REPLY_MODES = Object.freeze(['any', 'bot-only', 'never']);
|
|
20
|
+
|
|
21
|
+
export function normalizeTriggerPolicy({ requireMention = true, freeResponse = false, replyMode = 'never' } = {}) {
|
|
22
|
+
return Object.freeze({
|
|
23
|
+
requireMention: requireMention !== false,
|
|
24
|
+
freeResponse: freeResponse === true,
|
|
25
|
+
replyMode: TRIGGER_REPLY_MODES.includes(replyMode) ? replyMode : 'never',
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @typedef {Object} TriggerDecision
|
|
31
|
+
* @property {boolean} pass Whether the inbound funnel may keep the message.
|
|
32
|
+
* @property {boolean} addressed Whether the message counts as addressed.
|
|
33
|
+
* @property {string} reason Stable drop/accept label ('mention', 'command', 'reply',
|
|
34
|
+
* 'reply-to-human', 'reply-target-unknown', 'dm', 'free-response', 'mention-required', ...).
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Decide the mention gate and the addressed bit for one message.
|
|
39
|
+
* @param {Object} input
|
|
40
|
+
* @param {'group'|'direct'|'dm'} input.kind
|
|
41
|
+
* @param {boolean} [input.requireMention=true]
|
|
42
|
+
* @param {boolean} [input.freeResponse=false] Room-level override that opens the gate.
|
|
43
|
+
* @param {boolean} [input.mentioned=false]
|
|
44
|
+
* @param {boolean} [input.commandLike=false]
|
|
45
|
+
* @param {boolean} [input.replyToPresent=false]
|
|
46
|
+
* @param {('bot'|'human'|null)} [input.replyTargetKind=null] Synchronous classification of the reply target.
|
|
47
|
+
* @param {('any'|'bot-only'|'never')} [input.replyMode='never']
|
|
48
|
+
* @returns {TriggerDecision}
|
|
49
|
+
*/
|
|
50
|
+
export function evaluateTrigger({
|
|
51
|
+
kind = 'group',
|
|
52
|
+
requireMention = true,
|
|
53
|
+
freeResponse = false,
|
|
54
|
+
mentioned = false,
|
|
55
|
+
commandLike = false,
|
|
56
|
+
replyToPresent = false,
|
|
57
|
+
replyTargetKind = null,
|
|
58
|
+
replyMode = 'never',
|
|
59
|
+
} = {}) {
|
|
60
|
+
const policy = normalizeTriggerPolicy({ requireMention, freeResponse, replyMode });
|
|
61
|
+
if (kind === 'direct' || kind === 'dm') return Object.freeze({ pass: true, addressed: true, reason: 'dm' });
|
|
62
|
+
const gateOpen = !policy.requireMention || policy.freeResponse;
|
|
63
|
+
const replyCounts = replyToPresent && policy.replyMode !== 'never'
|
|
64
|
+
&& !(policy.replyMode === 'bot-only' && replyTargetKind !== 'bot');
|
|
65
|
+
const addressed = mentioned === true || commandLike === true || replyCounts;
|
|
66
|
+
if (!gateOpen && !addressed) {
|
|
67
|
+
if (policy.replyMode === 'bot-only' && replyToPresent && replyTargetKind === 'human') {
|
|
68
|
+
return Object.freeze({ pass: false, addressed: false, reason: 'reply-to-human' });
|
|
69
|
+
}
|
|
70
|
+
if (policy.replyMode === 'bot-only' && replyToPresent && replyTargetKind == null) {
|
|
71
|
+
return Object.freeze({ pass: false, addressed: false, reason: 'reply-target-unknown' });
|
|
72
|
+
}
|
|
73
|
+
return Object.freeze({ pass: false, addressed: false, reason: 'mention-required' });
|
|
74
|
+
}
|
|
75
|
+
const reason = mentioned === true ? 'mention'
|
|
76
|
+
: commandLike === true ? 'command'
|
|
77
|
+
: replyCounts ? 'reply'
|
|
78
|
+
: gateOpen ? 'free-response' : 'other';
|
|
79
|
+
return Object.freeze({ pass: true, addressed, reason });
|
|
80
|
+
}
|
|
@@ -7,11 +7,56 @@ import { dirname } from 'node:path';
|
|
|
7
7
|
* explicit: a subclass reads and writes them through extensionState().
|
|
8
8
|
*/
|
|
9
9
|
const EXTENSION_KEYS = Object.freeze([
|
|
10
|
-
'emailBindings', 'mailCursor', 'pendingAuth', 'threadIds',
|
|
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;
|
|
@@ -134,6 +134,25 @@ export class HarnessApprovalQueue {
|
|
|
134
134
|
return this.#routes.get(key)?.items.some((pending) => !pending.inactive) === true;
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Reject the active approvals of one route: the sender moved on to a new
|
|
139
|
+
* addressed request instead of deciding the tool call, and the conversation
|
|
140
|
+
* must not wait behind a decision that is not coming.
|
|
141
|
+
* @param {string} key The route key.
|
|
142
|
+
* @returns {Promise<number>} How many approvals were rejected.
|
|
143
|
+
*/
|
|
144
|
+
async rejectRoute(key) {
|
|
145
|
+
const route = this.#routes.get(key);
|
|
146
|
+
if (!route) return 0;
|
|
147
|
+
let rejected = 0;
|
|
148
|
+
for (const pending of [...route.items]) {
|
|
149
|
+
if (pending.inactive || pending.resolving) continue;
|
|
150
|
+
await this.#submit(pending, 'rejected').catch(() => undefined);
|
|
151
|
+
rejected += 1;
|
|
152
|
+
}
|
|
153
|
+
return rejected;
|
|
154
|
+
}
|
|
155
|
+
|
|
137
156
|
claimReply({
|
|
138
157
|
key,
|
|
139
158
|
actor,
|
|
@@ -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;
|
|
@@ -229,6 +229,8 @@ export default {
|
|
|
229
229
|
'正在使用{name}…': 'Using {name}…',
|
|
230
230
|
'已停止。': 'Stopped.',
|
|
231
231
|
'请用文字回答当前问题。': 'Please answer the current question with text.',
|
|
232
|
+
'已不再等待原有的待回答或待审批,已将其取消,先回应你的新请求。':
|
|
233
|
+
'The pending question or approval is no longer waited on and has been cancelled; your new request is being answered first.',
|
|
232
234
|
'{label}交互问题发送失败。': 'Failed to send the {label} interaction question.',
|
|
233
235
|
'回答提交失败。': 'Failed to submit the answer.',
|
|
234
236
|
'回答提交失败,请重新发送当前问题的答案。':
|
|
@@ -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
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Pair one injected context block with the user message that carried it.
|
|
2
2
|
//
|
|
3
3
|
// The prompt RPC carries no message source, so a channel encodes its source
|
|
4
|
-
// block, its optional guidance,
|
|
5
|
-
// user prompt. `installInjectedContext` splits them back out at
|
|
4
|
+
// block, its optional guidance, any quoted reply, and any collected
|
|
5
|
+
// conversation-context blocks as leading text of the user prompt. `installInjectedContext` splits them back out at
|
|
6
6
|
// `agent/pre-step` -- after the Agent inbox claimed the message but before
|
|
7
7
|
// anything is committed -- and enters plugin-sourced context messages beside
|
|
8
8
|
// the untouched user text. Pairing is decided by message identity, never by
|
|
@@ -37,6 +37,21 @@ export const DEFAULT_REPLY_LABEL = 'Quoted';
|
|
|
37
37
|
/** Fallback row label for a source block whose fields carry no readable value. */
|
|
38
38
|
export const DEFAULT_SOURCE_LABEL = 'Source';
|
|
39
39
|
|
|
40
|
+
/** Fallback row label for one collected conversation-context block. */
|
|
41
|
+
export const DEFAULT_CONTEXT_LABEL = 'Context';
|
|
42
|
+
|
|
43
|
+
/** Static note stamped into every context block; states what the block is not. */
|
|
44
|
+
export const CONTEXT_NOTE = 'Conversation context collected by the bot; not the current question.';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Every field one conversation-context block may carry. A block is ours only
|
|
48
|
+
* when its body is a non-empty object drawn from these keys with a named
|
|
49
|
+
* collector and verbatim content, mirroring how source blocks are judged.
|
|
50
|
+
*/
|
|
51
|
+
export const CONTEXT_BLOCK_FIELDS = Object.freeze([
|
|
52
|
+
'note', 'collector', 'room', 'event', 'sender', 'ts', 'content',
|
|
53
|
+
]);
|
|
54
|
+
|
|
40
55
|
/**
|
|
41
56
|
* Every field the source producer can project -- the same canonical list the
|
|
42
57
|
* settings UI validates against, so the two cannot drift. A block is ours only
|
|
@@ -143,6 +158,40 @@ function isSourceBlock(body) {
|
|
|
143
158
|
&& fields.every((field) => SOURCE_BLOCK_FIELDS.includes(field));
|
|
144
159
|
}
|
|
145
160
|
|
|
161
|
+
/**
|
|
162
|
+
* Decide whether one body is a conversation-context block this plugin wrote.
|
|
163
|
+
* Shape-only, like `isSourceBlock`: a well-formed object of unknown fields is
|
|
164
|
+
* user text that happens to use the tag and is left alone.
|
|
165
|
+
*
|
|
166
|
+
* @param body - the text between the context tags.
|
|
167
|
+
* @returns whether the body is one of our context blocks.
|
|
168
|
+
*/
|
|
169
|
+
function isContextBlock(body) {
|
|
170
|
+
const parsed = parseBlockJson(body);
|
|
171
|
+
if (parsed === null) return false;
|
|
172
|
+
const fields = Object.keys(parsed);
|
|
173
|
+
return fields.length > 0
|
|
174
|
+
&& fields.every((field) => CONTEXT_BLOCK_FIELDS.includes(field))
|
|
175
|
+
&& typeof parsed.collector === 'string' && parsed.collector.trim().length > 0
|
|
176
|
+
&& typeof parsed.content === 'string' && parsed.content.length > 0;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* One-line account of a context block: the row label plus the collector roles
|
|
181
|
+
* that produced it, e.g. `上下文 · thread-root+reply`.
|
|
182
|
+
*/
|
|
183
|
+
function contextSummary(body, labels) {
|
|
184
|
+
const parsed = parseBlockJson(body);
|
|
185
|
+
if (parsed === null) return null;
|
|
186
|
+
const collector = typeof parsed.collector === 'string' && parsed.collector.trim()
|
|
187
|
+
? parsed.collector.trim().slice(0, 64)
|
|
188
|
+
: '';
|
|
189
|
+
if (!collector) return null;
|
|
190
|
+
return bound(`${typeof labels?.context === 'string' && labels.context
|
|
191
|
+
? labels.context
|
|
192
|
+
: DEFAULT_CONTEXT_LABEL} \u00b7 ${collector}`);
|
|
193
|
+
}
|
|
194
|
+
|
|
146
195
|
/** Bound one summary to the row's declared maximum. */
|
|
147
196
|
function bound(summary) {
|
|
148
197
|
if (!summary) return null;
|
|
@@ -206,6 +255,19 @@ function blockAt(text, cursor, labels) {
|
|
|
206
255
|
},
|
|
207
256
|
};
|
|
208
257
|
}
|
|
258
|
+
const context = delimited(text, cursor, tags.contextOpen, tags.contextClose);
|
|
259
|
+
if (context !== null) {
|
|
260
|
+
// Collected material the bot points at, so it precedes the question it
|
|
261
|
+
// belongs to; a body outside the block schema stays user text verbatim.
|
|
262
|
+
if (!isContextBlock(context.body)) return null;
|
|
263
|
+
return {
|
|
264
|
+
end: context.end,
|
|
265
|
+
block: {
|
|
266
|
+
position: 'before', form: 'notice', summary: contextSummary(context.body, labels),
|
|
267
|
+
text: text.slice(cursor, context.end),
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|
|
209
271
|
const reply = delimited(text, cursor, tags.replyOpen, tags.replyClose);
|
|
210
272
|
if (reply !== null) {
|
|
211
273
|
const summary = replySummary(reply.body, labels);
|