@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.
Files changed (33) hide show
  1. package/README.en.md +10 -2
  2. package/README.md +10 -2
  3. package/lib/client.js +7 -4
  4. package/lib/index.js +311 -306
  5. package/package.json +4 -3
  6. package/plugin-src/host/injected-context.mjs +13 -1
  7. package/plugin-src/host/modern-harness-api.mjs +10 -4
  8. package/src/channels/matrix/matrix-api.mjs +34 -0
  9. package/src/channels/matrix/matrix-config-store.mjs +50 -2
  10. package/src/channels/matrix/matrix-normalize.mjs +106 -14
  11. package/src/channels/matrix/matrix-room-history.mjs +240 -8
  12. package/src/channels/matrix/matrix-runtime.mjs +563 -3
  13. package/src/channels/qq/qq-bridge.mjs +147 -1
  14. package/src/channels/qq/state-store.mjs +89 -0
  15. package/src/channels/shared/context-enhancement.mjs +2 -0
  16. package/src/channels/shared/conversation/ambient-provider.mjs +115 -0
  17. package/src/channels/shared/conversation/context-builder.mjs +148 -0
  18. package/src/channels/shared/conversation/reply-context.mjs +95 -0
  19. package/src/channels/shared/conversation/root-context.mjs +101 -0
  20. package/src/channels/shared/conversation/route.mjs +71 -0
  21. package/src/channels/shared/conversation/semantic-message.mjs +75 -0
  22. package/src/channels/shared/conversation/trigger-policy.mjs +80 -0
  23. package/src/channels/shared/conversation-state-store.mjs +95 -1
  24. package/src/channels/shared/deferred-delivery-coordinator.mjs +5 -1
  25. package/src/channels/shared/harness-approval.mjs +19 -0
  26. package/src/channels/shared/harness-client.mjs +9 -1
  27. package/src/channels/shared/i18n-en/shared-a.mjs +2 -0
  28. package/src/channels/shared/i18n-en/shared-b.mjs +2 -0
  29. package/src/channels/shared/injected-context.mjs +64 -2
  30. package/src/channels/shared/prompt-failure-tracker.mjs +65 -0
  31. package/src/channels/shared/speaker-label.mjs +46 -0
  32. package/src/channels/shared/text-harness-bridge.mjs +504 -33
  33. package/src/channels/wecom/wecom-cards.mjs +1 -1
@@ -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) {
@@ -16,6 +16,8 @@ export const INJECTED_CONTEXT_TAGS = Object.freeze({
16
16
  guidanceClose: '</dsh_im_source_guidance>',
17
17
  replyOpen: '<dsh_im_reply_to>',
18
18
  replyClose: '</dsh_im_reply_to>',
19
+ contextOpen: '<dsh_im_context>',
20
+ contextClose: '</dsh_im_context>',
19
21
  });
20
22
 
21
23
  /** Separator the producer joins prefix blocks with, and the splitter consumes. */
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Ambient context: the inferred-relation half of the context engine.
3
+ *
4
+ * Explicit relations (reply, thread root, bot-event binding) never need this
5
+ * module; it exists for the case where nobody replied, nobody opened a thread,
6
+ * yet a human reading the room obviously groups the messages anyway — a sender
7
+ * firing a burst of short messages right before addressing the bot. The
8
+ * provider reads the channel's bounded room history record (no second store),
9
+ * and a burst is a trailing same-sender run whose consecutive entries stay
10
+ * within `burstGapMs`; anything older or broken by the gap falls back to the
11
+ * bounded recent window. Entries the record already marked as injected are
12
+ * never re-offered, so ambient context is consumed at most once per entry.
13
+ */
14
+
15
+ function boundedInt(value, min, max, fallback) {
16
+ if (!Number.isSafeInteger(value) || value <= 0) return fallback;
17
+ return Math.min(Math.max(value, min), max);
18
+ }
19
+
20
+ export const DEFAULT_AMBIENT_BURST_GAP_MS = 90_000;
21
+ export const DEFAULT_AMBIENT_WINDOW_MS = 180_000;
22
+ export const DEFAULT_AMBIENT_RECENT_COUNT = 20;
23
+ export const DEFAULT_AMBIENT_MAX_CONTEXT_CHARS = 8_000;
24
+
25
+ export class WindowAmbientProvider {
26
+ #store;
27
+ #burstGapMs;
28
+ #windowMs;
29
+ #recentCount;
30
+ #maxContextChars;
31
+
32
+ constructor({
33
+ store,
34
+ burstGapMs = DEFAULT_AMBIENT_BURST_GAP_MS,
35
+ recentWindowMs = DEFAULT_AMBIENT_WINDOW_MS,
36
+ recentCount = DEFAULT_AMBIENT_RECENT_COUNT,
37
+ maxContextChars = DEFAULT_AMBIENT_MAX_CONTEXT_CHARS,
38
+ } = {}) {
39
+ this.#store = store && typeof store.search === 'function' ? store : null;
40
+ this.#burstGapMs = boundedInt(burstGapMs, 5_000, 3_600_000, DEFAULT_AMBIENT_BURST_GAP_MS);
41
+ this.#windowMs = boundedInt(recentWindowMs, 10_000, 86_400_000, DEFAULT_AMBIENT_WINDOW_MS);
42
+ this.#recentCount = boundedInt(recentCount, 1, 200, DEFAULT_AMBIENT_RECENT_COUNT);
43
+ this.#maxContextChars = boundedInt(maxContextChars, 200, 200_000, DEFAULT_AMBIENT_MAX_CONTEXT_CHARS);
44
+ }
45
+
46
+ /**
47
+ * Collect the ambient entries that may accompany one triggered message.
48
+ * @param {{roomId: string, senderId: string, threadId?: string|null, now?: number}} query
49
+ * — the optional `threadId` keeps the window inside one message list: the
50
+ * room's mainline (`null`) or the named thread, matching what members read
51
+ * in the current conversation.
52
+ * @returns {{burst: object[], recent: object[]}} both chronological; already-consumed and
53
+ * non-human entries are excluded, and the recent list never repeats a burst entry.
54
+ */
55
+ query({ roomId, senderId, threadId = null, now = Date.now() } = {}) {
56
+ if (!this.#store || !roomId || typeof senderId !== 'string' || !senderId) {
57
+ return { burst: [], recent: [] };
58
+ }
59
+ const wantedThread = typeof threadId === 'string' && threadId ? threadId : null;
60
+ const span = Math.max(this.#windowMs, this.#burstGapMs);
61
+ // The record answers newest-first; one extra slice covers the burst run on
62
+ // top of the recent budget before anything is filtered out.
63
+ const fetched = this.#store.search({
64
+ roomId,
65
+ from: now - span,
66
+ to: now,
67
+ limit: Math.min(500, Math.max(this.#recentCount * 4, 60)),
68
+ });
69
+ // The record keeps arrival order, which a replayed or seeded batch can leave
70
+ // out of timestamp order; the gap walk and the recency budgets need true time order.
71
+ const chronological = [...(Array.isArray(fetched) ? fetched : [])].sort((left, right) => left.ts - right.ts);
72
+ // The record's own notion of un-consumed human speech is the pending list;
73
+ // `search` answers over all retained entries, so intersect with it instead of
74
+ // trusting the per-entry flag, which is only the record's rendering of it.
75
+ const pendingIds = typeof this.#store.pending === 'function'
76
+ ? new Set(this.#store.pending({ roomId, limit: 5_000 }).map((entry) => entry.eventId))
77
+ : null;
78
+ const candidates = chronological.filter((entry) => entry.kind === 'human'
79
+ && entry.injected !== true
80
+ && (entry.threadId ?? null) === wantedThread
81
+ && (pendingIds === null || pendingIds.has(entry.eventId)));
82
+ const burst = [];
83
+ for (let index = candidates.length - 1; index >= 0; index -= 1) {
84
+ const entry = candidates[index];
85
+ if (entry.sender !== senderId) break;
86
+ const later = burst[burst.length - 1];
87
+ if (later && later.ts - entry.ts > this.#burstGapMs) break;
88
+ burst.push(entry);
89
+ }
90
+ burst.reverse();
91
+ const burstIds = new Set(burst.map((entry) => entry.eventId));
92
+ const recent = [];
93
+ let used = 0;
94
+ for (let index = candidates.length - 1; index >= 0 && recent.length < this.#recentCount; index -= 1) {
95
+ const entry = candidates[index];
96
+ if (burstIds.has(entry.eventId)) continue;
97
+ const cost = entry.text.length + (entry.name ? entry.name.length + 2 : 1);
98
+ if (used + cost > this.#maxContextChars) break;
99
+ used += cost;
100
+ recent.unshift(entry);
101
+ }
102
+ return { burst, recent };
103
+ }
104
+
105
+ /**
106
+ * Mark the offered entries as consumed so they are not offered again.
107
+ * @param {{roomId: string, entries: object[]}} consumed
108
+ * @returns {Promise<number>} the number newly marked; 0 when the record cannot mark.
109
+ */
110
+ async markConsumed({ roomId, entries } = {}) {
111
+ if (!this.#store || typeof this.#store.markInjected !== 'function') return 0;
112
+ if (!roomId || !Array.isArray(entries) || entries.length === 0) return 0;
113
+ return await this.#store.markInjected(roomId, entries.map((entry) => entry.eventId));
114
+ }
115
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Assembly of the collected context entries into injected context blocks that
3
+ * ride along with the triggering prompt.
4
+ *
5
+ * Each entry becomes one `<dsh_im_context>` block of the shared injected
6
+ * context grammar, so the Host's `agent/pre-step` listener splits every entry
7
+ * back out into its own plugin-sourced context message beside the untouched
8
+ * user text: what the human asked stays exactly what the human typed, and the
9
+ * collected material is separated by `source`, never spliced into the question.
10
+ * Entries sharing one event id merge into a single block whose `collector`
11
+ * names every role that hit the event (e.g. `thread-root+reply`), so the same
12
+ * message is never presented twice under two headings.
13
+ */
14
+
15
+ import { INJECTED_CONTEXT_SEPARATOR, INJECTED_CONTEXT_TAGS } from '../context-enhancement.mjs';
16
+ import { CONTEXT_NOTE } from '../injected-context.mjs';
17
+
18
+ /**
19
+ * @typedef {Object} ContextEntry
20
+ * @property {'thread-root'|'reply'|'ambient-burst'|'ambient-recent'|string} collector
21
+ * @property {string} roomId
22
+ * @property {?string} eventId
23
+ * @property {?string} sender
24
+ * @property {?string} name
25
+ * @property {?number} ts
26
+ * @property {string} text
27
+ */
28
+
29
+ const COLLECTOR_MAX = 64;
30
+ const ROOM_MAX = 256;
31
+ const EVENT_MAX = 256;
32
+ const SENDER_MAX = 300;
33
+ const CONTENT_MAX = 8_000;
34
+
35
+ const CONTROL_CHARACTERS = /[\u0000-\u0008\u000e-\u001f\u007f-\u009f]/gu;
36
+
37
+ function cleanField(value, limit) {
38
+ if (typeof value !== 'string') return undefined;
39
+ const cleaned = value.replace(CONTROL_CHARACTERS, '').trim();
40
+ if (!cleaned) return undefined;
41
+ return cleaned.length <= limit ? cleaned : cleaned.slice(0, limit);
42
+ }
43
+
44
+ function cleanContent(value) {
45
+ if (typeof value !== 'string') return undefined;
46
+ const normalized = value.replace(/\r\n?/gu, '\n').replace(CONTROL_CHARACTERS, '');
47
+ if (!normalized.trim()) return undefined;
48
+ return normalized.length <= CONTENT_MAX ? normalized : normalized.slice(0, CONTENT_MAX);
49
+ }
50
+
51
+ /**
52
+ * Merge entries that point at the same event into one entry, keeping the first
53
+ * occurrence's position, room, sender and stamp and naming every collector that
54
+ * referenced the event in first-seen order. Entries without an event id pass
55
+ * through unmerged; their collected text alone is what identifies them.
56
+ *
57
+ * @param {ContextEntry[]} entries
58
+ * @returns {ContextEntry[]} merged entries in assembly order
59
+ */
60
+ export function dedupeContextEntries(entries) {
61
+ if (!Array.isArray(entries)) return [];
62
+ const merged = [];
63
+ const byEvent = new Map();
64
+ for (const entry of entries) {
65
+ const eventId = cleanField(entry?.eventId, EVENT_MAX);
66
+ if (eventId === undefined) {
67
+ merged.push({ ...entry });
68
+ continue;
69
+ }
70
+ const existing = byEvent.get(eventId);
71
+ if (existing === undefined) {
72
+ const copy = { ...entry, collector: cleanField(entry?.collector, COLLECTOR_MAX) ?? '' };
73
+ byEvent.set(eventId, copy);
74
+ merged.push(copy);
75
+ continue;
76
+ }
77
+ const collector = cleanField(entry?.collector, COLLECTOR_MAX);
78
+ if (collector !== undefined) {
79
+ existing.collector = existing.collector ? `${existing.collector}+${collector}` : collector;
80
+ }
81
+ }
82
+ return merged;
83
+ }
84
+
85
+ /**
86
+ * Render one entry as a well-formed injected context block. The body is a
87
+ * plain object drawn from the block schema with `<>&` escaped, so the closing
88
+ * tag cannot be forged from collected values and the Host recognizes exactly
89
+ * the blocks this producer wrote.
90
+ *
91
+ * @param {ContextEntry} entry
92
+ * @returns {string} the block, or '' when the entry carries no renderable content.
93
+ */
94
+ export function contextBlockFor(entry) {
95
+ const content = cleanContent(entry?.text);
96
+ if (content === undefined) return '';
97
+ const body = {
98
+ note: CONTEXT_NOTE,
99
+ collector: cleanField(entry?.collector, COLLECTOR_MAX) ?? '?',
100
+ ...(cleanField(entry?.roomId, ROOM_MAX) !== undefined ? { room: cleanField(entry.roomId, ROOM_MAX) } : {}),
101
+ ...(cleanField(entry?.eventId, EVENT_MAX) !== undefined ? { event: cleanField(entry.eventId, EVENT_MAX) } : {}),
102
+ ...(() => {
103
+ const sender = cleanField(entry?.sender ?? entry?.name, SENDER_MAX);
104
+ return sender === undefined ? {} : { sender };
105
+ })(),
106
+ ...(Number.isSafeInteger(entry?.ts) && entry.ts > 0 ? { ts: entry.ts } : {}),
107
+ content,
108
+ };
109
+ const json = JSON.stringify(body).replace(/[<>&]/gu, (character) => ({
110
+ '<': '\\u003c',
111
+ '>': '\\u003e',
112
+ '&': '\\u0026',
113
+ })[character]);
114
+ return `${INJECTED_CONTEXT_TAGS.contextOpen}${json}${INJECTED_CONTEXT_TAGS.contextClose}`;
115
+ }
116
+
117
+ /**
118
+ * Render the whole block set: entries merge by event id, empty entries drop
119
+ * out, and the surviving blocks join in the order the collectors supplied
120
+ * (explicit collectors before ambient). Joined with the protocol separator the
121
+ * Host's splitter consumes, so the user text that follows is all the human
122
+ * actually wrote.
123
+ *
124
+ * @param {ContextEntry[]} entries
125
+ * @returns {string} the joined blocks, or '' when there is nothing to say.
126
+ */
127
+ export function renderContextEntries(entries) {
128
+ const blocks = [];
129
+ for (const entry of dedupeContextEntries(entries)) {
130
+ const block = contextBlockFor(entry);
131
+ if (block) blocks.push(block);
132
+ }
133
+ return blocks.join(INJECTED_CONTEXT_SEPARATOR);
134
+ }
135
+
136
+ /**
137
+ * Prepend the rendered blocks to the triggering prompt text, mirroring the
138
+ * enhancement producer's prefix pattern exactly so the splitter consumes the
139
+ * blocks and leaves the question verbatim.
140
+ *
141
+ * @param {{block: string, promptText: ?string}} parts
142
+ * @returns {string}
143
+ */
144
+ export function composeContextPrompt({ block, promptText } = {}) {
145
+ const text = typeof promptText === 'string' ? promptText : '';
146
+ if (typeof block !== 'string' || !block) return text;
147
+ return `${block}\n\n${text}`;
148
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Explicit-relation context: the reply ancestor chain.
3
+ *
4
+ * A reply is a fact the platform states, not a guess, so it never consults the
5
+ * ambient record: the channel injects a `fetch` that resolves one event id to
6
+ * its text (Matrix: CS API single-event lookup, Feishu: OpenAPI message get).
7
+ * The walk is depth-bounded and loop-guarded because reply relations are
8
+ * user-authored data; a cyclic chain terminates on the first repeat instead of
9
+ * spinning. The result is oldest-first so the prompt reads cause before effect.
10
+ */
11
+
12
+ /**
13
+ * @typedef {Object} ReplyChainNode
14
+ * @property {string} eventId
15
+ * @property {string} sender
16
+ * @property {string} name Display name when the channel knows one.
17
+ * @property {string} text
18
+ * @property {?number} ts
19
+ */
20
+
21
+ /**
22
+ * A tiny most-recent-used cache for single-event lookups so a burst of replies
23
+ * into one chain does not refetch shared ancestors. Insertion order is the LRU
24
+ * order; reading refreshes recency.
25
+ * @param {number} [capacity=256]
26
+ */
27
+ export function createEventLru(capacity = 256) {
28
+ const cap = Number.isSafeInteger(capacity) && capacity > 0 ? capacity : 256;
29
+ const entries = new Map();
30
+ return {
31
+ get size() {
32
+ return entries.size;
33
+ },
34
+ get(key) {
35
+ if (!entries.has(key)) return undefined;
36
+ const value = entries.get(key);
37
+ entries.delete(key);
38
+ entries.set(key, value);
39
+ return value;
40
+ },
41
+ set(key, value) {
42
+ if (entries.has(key)) entries.delete(key);
43
+ entries.set(key, value);
44
+ while (entries.size > cap) {
45
+ const oldest = entries.keys().next().value;
46
+ entries.delete(oldest);
47
+ }
48
+ return value;
49
+ },
50
+ delete(key) {
51
+ return entries.delete(key);
52
+ },
53
+ clear() {
54
+ entries.clear();
55
+ },
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Walk `startReplyTo` upward through the reply relations the platform reports.
61
+ * @param {Object} input
62
+ * @param {(eventId: string) => Promise<{sender?: string, name?: string, text: string, replyTo?: ?string, ts?: ?number}|null>} input.fetch
63
+ * Resolves one event, or null when it is gone, undecryptable, or not a message.
64
+ * @param {?string} input.startReplyTo The reply target of the triggering message.
65
+ * @param {number} [input.maxDepth=5]
66
+ * @returns {Promise<ReplyChainNode[]>} oldest ancestor first; empty when there is no chain.
67
+ */
68
+ export async function resolveReplyChain({ fetch, startReplyTo, maxDepth = 5 } = {}) {
69
+ const chain = [];
70
+ if (typeof fetch !== 'function') return chain;
71
+ const depth = Number.isSafeInteger(maxDepth) && maxDepth > 0 ? Math.min(maxDepth, 10) : 5;
72
+ const visited = new Set();
73
+ let cursor = typeof startReplyTo === 'string' && startReplyTo ? startReplyTo : null;
74
+ while (cursor && !visited.has(cursor) && chain.length < depth) {
75
+ visited.add(cursor);
76
+ let event = null;
77
+ try {
78
+ event = await fetch(cursor);
79
+ } catch {
80
+ // A channel lookup failure leaves the chain exactly as far as it reached;
81
+ // a partial explicit context still beats dropping the whole turn's context.
82
+ event = null;
83
+ }
84
+ if (!event || typeof event.text !== 'string' || !event.text) break;
85
+ chain.push({
86
+ eventId: cursor,
87
+ sender: typeof event.sender === 'string' ? event.sender : '',
88
+ name: typeof event.name === 'string' ? event.name : '',
89
+ text: event.text,
90
+ ts: Number.isSafeInteger(event.ts) && event.ts > 0 ? event.ts : null,
91
+ });
92
+ cursor = typeof event.replyTo === 'string' && event.replyTo ? event.replyTo : null;
93
+ }
94
+ return chain.reverse();
95
+ }