@qwen-code/channel-base 0.19.3-nightly.20260701.a974594d7 → 0.19.4

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.
@@ -1,10 +1,13 @@
1
- import { basename } from 'node:path';
1
+ import { basename, join } from 'node:path';
2
2
  import { BlockStreamer } from './BlockStreamer.js';
3
3
  import { GroupGate } from './GroupGate.js';
4
+ import { GroupHistoryStore } from './group-history-store.js';
4
5
  import { SenderGate } from './SenderGate.js';
5
6
  import { PairingStore } from './PairingStore.js';
6
7
  import { SessionRouter } from './SessionRouter.js';
8
+ import { getGlobalQwenDir } from './paths.js';
7
9
  import { sanitizeSenderName, sanitizeQuotedText, sanitizePromptText, sanitizePromptPath, sanitizeLogText, } from './sanitize.js';
10
+ import { ChannelLoopSkippedError } from './ChannelLoopScheduler.js';
8
11
  /**
9
12
  * Max time /clear waits for a cancelled in-flight turn to wind down before
10
13
  * purging anyway. A wedged ACP child (stuck tool call, not reading stdin, or
@@ -14,6 +17,11 @@ import { sanitizeSenderName, sanitizeQuotedText, sanitizePromptText, sanitizePro
14
17
  * later is already invalidated.
15
18
  */
16
19
  export const CLEAR_CANCEL_TIMEOUT_MS = 3000;
20
+ const GROUP_HISTORY_CONTEXT_MARKER = '[Chat messages since your last reply - for context]';
21
+ const CURRENT_MESSAGE_MARKER = '[Current message - respond to this]';
22
+ const GROUP_HISTORY_ENTRY_TEXT_LIMIT = 1000;
23
+ const GROUP_HISTORY_ENTRY_METADATA_LIMIT = 256;
24
+ const LOOP_CANCEL_GRACE_MS = 5000;
17
25
  /**
18
26
  * Character class (sans the enclosing `[]`) for a slash-command token: alphanumerics
19
27
  * plus `_`, `:` and `-`, so hyphenated and namespaced agent commands (e.g.
@@ -25,6 +33,17 @@ const COMMAND_TOKEN_CHARS = 'a-zA-Z0-9_:-';
25
33
  const PARSE_COMMAND_RE = new RegExp(`^\\/([${COMMAND_TOKEN_CHARS}]+)(?:@\\S+)?\\s*(.*)`, 's');
26
34
  /** isSlashCommand: the first whitespace-delimited token alone must be a pure command token. */
27
35
  const COMMAND_TOKEN_RE = new RegExp(`^[${COMMAND_TOKEN_CHARS}]+(?:@\\S+)?$`);
36
+ const LOOP_ADD_RE = /^"([^"]+)"\s+(.+)$/su;
37
+ const MAX_LOOP_JOBS_PER_TARGET = 10;
38
+ const MAX_LOOP_PROMPT_CHARS = 4000;
39
+ function parseLoopAddArgs(args) {
40
+ const match = args.trim().match(LOOP_ADD_RE);
41
+ if (!match)
42
+ return null;
43
+ const cron = match[1].trim();
44
+ const prompt = match[2].trim();
45
+ return cron && prompt ? { cron, prompt } : null;
46
+ }
28
47
  export class ChannelBase {
29
48
  config;
30
49
  bridge;
@@ -34,6 +53,9 @@ export class ChannelBase {
34
53
  name;
35
54
  /** Resolved proxy URL, available to subclasses for adapter-specific clients. */
36
55
  proxy;
56
+ channelMemory;
57
+ groupHistory;
58
+ loopController;
37
59
  instructedSessions = new Set();
38
60
  commands = new Map();
39
61
  /** Per-session promise chain to serialize prompt + send (followup mode). */
@@ -63,6 +85,10 @@ export class ChannelBase {
63
85
  this.config = config;
64
86
  this.bridge = bridge;
65
87
  this.proxy = options?.proxy;
88
+ this.channelMemory = options?.channelMemory;
89
+ this.groupHistory = new GroupHistoryStore(options?.groupHistoryPath ??
90
+ join(getGlobalQwenDir(), 'channels', `${encodeURIComponent(name)}-group-history.jsonl`));
91
+ this.loopController = options?.loopController;
66
92
  this.groupGate = new GroupGate(config.groupPolicy, config.groups);
67
93
  const pairingStore = config.senderPolicy === 'pairing' ? new PairingStore(name) : undefined;
68
94
  this.gate = new SenderGate(config.senderPolicy, config.allowedUsers, pairingStore);
@@ -78,6 +104,18 @@ export class ChannelBase {
78
104
  this.attachBridgeEvents(bridge);
79
105
  }
80
106
  }
107
+ supportsProactiveSend() {
108
+ return false;
109
+ }
110
+ supportsProactiveTarget(target) {
111
+ return target.threadId === undefined;
112
+ }
113
+ async pushProactive(target, text) {
114
+ if (target.threadId) {
115
+ throw new Error('Channel does not support proactive loop messages for threaded targets.');
116
+ }
117
+ await this.sendMessage(target.chatId, text);
118
+ }
81
119
  /** Replace the bridge instance (used after crash recovery restart). */
82
120
  setBridge(bridge) {
83
121
  if (this.registerBridgeEvents) {
@@ -89,6 +127,210 @@ export class ChannelBase {
89
127
  this.attachBridgeEvents(bridge);
90
128
  }
91
129
  }
130
+ async runLoopPrompt(job, options = {}) {
131
+ if (!this.supportsProactiveSend()) {
132
+ throw new Error('Channel does not support proactive loop messages.');
133
+ }
134
+ if (this.config.sessionScope === 'single') {
135
+ await this.loopController?.disable(job.id);
136
+ throw new Error('Loop messages are not supported with single session scope.');
137
+ }
138
+ if (job.channelName !== this.name) {
139
+ throw new Error(`Loop ${job.id} belongs to ${job.channelName}, not ${this.name}.`);
140
+ }
141
+ if (!this.supportsProactiveTarget(job.target)) {
142
+ throw new Error('Channel does not support proactive loop messages for this chat target.');
143
+ }
144
+ if (!this.isStoredLoopTargetAuthorized(job.target, job.createdBy)) {
145
+ await this.loopController?.disable(job.id);
146
+ throw new Error(`Loop ${job.id} target is no longer authorized.`);
147
+ }
148
+ const sessionId = await this.router.resolve(this.name, job.target.senderId, job.target.chatId, job.target.threadId, job.cwd);
149
+ const label = sanitizeQuotedText(job.label || job.id, 80);
150
+ const createdBy = sanitizeSenderName(job.createdBy || 'unknown');
151
+ let promptText = `[Loop "${label}" created by ${createdBy}]\n\n${sanitizePromptText(job.prompt)}`;
152
+ const shouldPrependSessionContext = !this.instructedSessions.has(sessionId);
153
+ const prev = this.sessionQueues.get(sessionId) ?? Promise.resolve();
154
+ const generation = this.sessionGenerations.get(sessionId) ?? 0;
155
+ const current = prev.then(async () => {
156
+ if ((this.sessionGenerations.get(sessionId) ?? 0) !== generation) {
157
+ process.stderr.write(`[${this.name}] dropped loop ${job.id} for session ${sessionId}: session was cleared before it ran\n`);
158
+ throw new ChannelLoopSkippedError('loop dropped because session was cleared before it ran');
159
+ }
160
+ if (options.shouldContinue && !(await options.shouldContinue())) {
161
+ throw new ChannelLoopSkippedError('loop dropped because it is no longer enabled');
162
+ }
163
+ let shouldClaimSessionContext = false;
164
+ if (shouldPrependSessionContext) {
165
+ const context = [];
166
+ let sessionContextReady = true;
167
+ if (this.channelMemory &&
168
+ this.isSenderAuthorizedForChannelMemory(job.target.senderId) &&
169
+ (!this.isSharedSessionTarget(job.target) ||
170
+ this.config.senderPolicy === 'allowlist')) {
171
+ try {
172
+ const memoryText = (await this.channelMemory.readChannelMemory({
173
+ channelName: this.name,
174
+ chatId: job.target.chatId,
175
+ threadId: job.target.threadId,
176
+ })).trim();
177
+ if (memoryText) {
178
+ context.push(`Channel memory for this chat:\n${sanitizePromptText(memoryText)}`);
179
+ }
180
+ }
181
+ catch (error) {
182
+ process.stderr.write(`[${this.name}] channel memory read failed for loop ${job.id} chat ${sanitizeLogText(job.target.chatId, 64)}: ${sanitizeLogText(this.channelMemoryErrorMessage(error), 200)}\n`);
183
+ this.instructedSessions.delete(sessionId);
184
+ sessionContextReady = false;
185
+ }
186
+ }
187
+ if (this.config.instructions) {
188
+ context.push(this.config.instructions);
189
+ }
190
+ if (context.length > 0) {
191
+ promptText = `${context.join('\n\n')}\n\n${promptText}`;
192
+ }
193
+ if (sessionContextReady) {
194
+ shouldClaimSessionContext = true;
195
+ }
196
+ }
197
+ if ((this.sessionGenerations.get(sessionId) ?? 0) !== generation) {
198
+ process.stderr.write(`[${this.name}] dropped loop ${job.id} for session ${sessionId}: session was cleared before it ran\n`);
199
+ throw new ChannelLoopSkippedError('loop dropped because session was cleared before it ran');
200
+ }
201
+ if (shouldClaimSessionContext) {
202
+ this.instructedSessions.add(sessionId);
203
+ }
204
+ let doneResolve = () => { };
205
+ const done = new Promise((resolve) => {
206
+ doneResolve = resolve;
207
+ });
208
+ const promptState = {
209
+ cancelled: false,
210
+ done,
211
+ resolve: doneResolve,
212
+ chatId: job.target.chatId,
213
+ messageId: job.id,
214
+ };
215
+ this.activePrompts.set(sessionId, promptState);
216
+ this.onPromptStart(job.target.chatId, sessionId);
217
+ const onChunk = (sid, chunk) => {
218
+ if (sid === sessionId && !promptState.cancelled) {
219
+ this.onResponseChunk(job.target.chatId, chunk, sessionId);
220
+ }
221
+ };
222
+ const promptBridge = this.bridge;
223
+ promptBridge.on('textChunk', onChunk);
224
+ try {
225
+ const response = await this.runLoopBridgePrompt(promptBridge, sessionId, promptText, promptState, job.id, options.timeoutMs);
226
+ if (promptState.cancelRequested && !promptState.cancelled) {
227
+ const cancelled = await promptState.cancelRequested;
228
+ if (cancelled) {
229
+ promptState.cancelled = true;
230
+ }
231
+ }
232
+ if (promptState.cancelled) {
233
+ throw new ChannelLoopSkippedError('loop cancelled before delivery');
234
+ }
235
+ if (options.shouldContinue && !(await options.shouldContinue())) {
236
+ throw new ChannelLoopSkippedError('loop dropped before delivery');
237
+ }
238
+ if (response) {
239
+ await this.pushProactive(job.target, response);
240
+ }
241
+ return response;
242
+ }
243
+ finally {
244
+ promptBridge.off('textChunk', onChunk);
245
+ const stillCurrent = this.activePrompts.get(sessionId) === promptState;
246
+ if (!promptState.clearEvicted) {
247
+ try {
248
+ this.onPromptEnd(job.target.chatId, sessionId);
249
+ }
250
+ catch (err) {
251
+ process.stderr.write(`[${this.name}] onPromptEnd threw in loop ${job.id} for session ${sessionId}: ${err instanceof Error ? err.message : err}\n`);
252
+ }
253
+ }
254
+ if (stillCurrent) {
255
+ this.activePrompts.delete(sessionId);
256
+ }
257
+ promptState.resolve();
258
+ const buffer = this.collectBuffers.get(sessionId);
259
+ if (stillCurrent && buffer && buffer.length > 0) {
260
+ this.collectBuffers.delete(sessionId);
261
+ const lost = buffer.length;
262
+ const coalesced = buffer.map((b) => b.text).join('\n\n');
263
+ const lastEnvelope = buffer[buffer.length - 1].envelope;
264
+ const syntheticEnvelope = {
265
+ ...lastEnvelope,
266
+ text: coalesced,
267
+ alreadyPrefixed: true,
268
+ referencedText: undefined,
269
+ attachments: undefined,
270
+ imageBase64: undefined,
271
+ imageMimeType: undefined,
272
+ };
273
+ this.handleInbound(syntheticEnvelope).catch((err) => {
274
+ process.stderr.write(`[${this.name}] dropped ${lost} buffered message(s) after loop ${job.id} for session ${sessionId} (last sender ${lastEnvelope.senderId}): ${err instanceof Error ? err.message : String(err)}\n`);
275
+ });
276
+ }
277
+ }
278
+ });
279
+ this.sessionQueues.set(sessionId, current.then(() => undefined).catch(() => { }));
280
+ return current;
281
+ }
282
+ async runLoopBridgePrompt(promptBridge, sessionId, promptText, promptState, jobId, timeoutMs) {
283
+ const prompt = promptBridge.prompt(sessionId, promptText, {});
284
+ prompt.catch(() => { });
285
+ if (timeoutMs === undefined) {
286
+ return prompt;
287
+ }
288
+ let timer;
289
+ try {
290
+ return await Promise.race([
291
+ prompt,
292
+ new Promise((_, reject) => {
293
+ timer = setTimeout(() => {
294
+ reject(new Error('loop timed out'));
295
+ }, timeoutMs);
296
+ timer.unref?.();
297
+ }),
298
+ ]);
299
+ }
300
+ catch (err) {
301
+ if (err instanceof Error && err.message === 'loop timed out') {
302
+ promptState.cancelled = true;
303
+ await this.cancelTimedOutLoopPrompt(promptBridge, sessionId, jobId);
304
+ }
305
+ throw err;
306
+ }
307
+ finally {
308
+ clearTimeout(timer);
309
+ }
310
+ }
311
+ async cancelTimedOutLoopPrompt(promptBridge, sessionId, jobId) {
312
+ let graceTimer;
313
+ try {
314
+ const cancelled = await Promise.race([
315
+ promptBridge.cancelSession(sessionId).then(() => true),
316
+ new Promise((resolve) => {
317
+ graceTimer = setTimeout(() => resolve(false), LOOP_CANCEL_GRACE_MS);
318
+ graceTimer.unref?.();
319
+ }),
320
+ ]);
321
+ if (!cancelled) {
322
+ this.router.removeSessionId(sessionId);
323
+ this.instructedSessions.delete(sessionId);
324
+ process.stderr.write(`[${this.name}] retired timed out loop ${jobId} session ${sessionId} after cancel did not settle\n`);
325
+ }
326
+ }
327
+ catch (cancelErr) {
328
+ process.stderr.write(`[${this.name}] cancelSession failed for timed out loop ${jobId} in session ${sessionId}: ${cancelErr instanceof Error ? cancelErr.message : cancelErr}\n`);
329
+ }
330
+ finally {
331
+ clearTimeout(graceTimer);
332
+ }
333
+ }
92
334
  onToolCall(_chatId, _event) { }
93
335
  onSessionDied(sessionId) {
94
336
  this.router.removeSessionId(sessionId);
@@ -178,6 +420,7 @@ export class ChannelBase {
178
420
  registerSharedCommands() {
179
421
  const doClear = async (envelope) => {
180
422
  const removedIds = this.router.removeSession(this.name, envelope.senderId, envelope.chatId, envelope.threadId);
423
+ this.clearPendingGroupHistory(envelope);
181
424
  if (removedIds.length > 0) {
182
425
  for (const id of removedIds) {
183
426
  // Audit: clearing a SHARED session wipes the conversation for every
@@ -320,6 +563,90 @@ export class ChannelBase {
320
563
  ].join('\n'));
321
564
  return true;
322
565
  });
566
+ this.registerCommand('remember-channel', async (envelope, args) => {
567
+ if (!(await this.ensureChannelMemoryAuthorized(envelope))) {
568
+ return true;
569
+ }
570
+ if (envelope.isGroup) {
571
+ await this.sendMessage(envelope.chatId, 'Channel memory cannot be changed in group chats.');
572
+ return true;
573
+ }
574
+ if (args.trim() === '') {
575
+ await this.sendMessage(envelope.chatId, 'Usage: /remember-channel <text>');
576
+ return true;
577
+ }
578
+ const channelMemory = await this.getChannelMemory(envelope);
579
+ if (!channelMemory) {
580
+ return true;
581
+ }
582
+ try {
583
+ await channelMemory.appendChannelMemory(this.channelMemoryTarget(envelope), args.trim());
584
+ }
585
+ catch (error) {
586
+ const message = this.channelMemoryErrorMessage(error);
587
+ this.logChannelMemoryError('save', envelope, message);
588
+ await this.sendMessage(envelope.chatId, `Failed to save channel memory: ${this.channelMemoryUserErrorMessage()}`);
589
+ return true;
590
+ }
591
+ this.invalidateSessionContext(envelope);
592
+ await this.sendMessage(envelope.chatId, 'Channel memory updated.');
593
+ return true;
594
+ });
595
+ this.registerCommand('channel-memory', async (envelope) => {
596
+ if (!(await this.ensureChannelMemoryAuthorized(envelope))) {
597
+ return true;
598
+ }
599
+ if (envelope.isGroup) {
600
+ await this.sendMessage(envelope.chatId, 'Channel memory cannot be shown in group chats.');
601
+ return true;
602
+ }
603
+ const channelMemory = await this.getChannelMemory(envelope);
604
+ if (!channelMemory) {
605
+ return true;
606
+ }
607
+ let text;
608
+ try {
609
+ text = (await channelMemory.readChannelMemory(this.channelMemoryTarget(envelope))).trim();
610
+ }
611
+ catch (error) {
612
+ const message = this.channelMemoryErrorMessage(error);
613
+ this.logChannelMemoryError('read', envelope, message);
614
+ await this.sendMessage(envelope.chatId, `Failed to read channel memory: ${this.channelMemoryUserErrorMessage()}`);
615
+ return true;
616
+ }
617
+ await this.sendMessage(envelope.chatId, text === '' ? 'No channel memory saved.' : sanitizePromptText(text));
618
+ return true;
619
+ });
620
+ this.registerCommand('forget-channel', async (envelope, args) => {
621
+ if (!(await this.ensureChannelMemoryAuthorized(envelope))) {
622
+ return true;
623
+ }
624
+ if (envelope.isGroup) {
625
+ await this.sendMessage(envelope.chatId, 'Channel memory cannot be changed in group chats.');
626
+ return true;
627
+ }
628
+ if (args.toLowerCase() !== 'confirm') {
629
+ await this.sendMessage(envelope.chatId, 'This clears channel memory for this chat. Re-send with "confirm" (e.g. /forget-channel confirm) to proceed.');
630
+ return true;
631
+ }
632
+ const channelMemory = await this.getChannelMemory(envelope);
633
+ if (!channelMemory) {
634
+ return true;
635
+ }
636
+ let result;
637
+ try {
638
+ result = await channelMemory.clearChannelMemory(this.channelMemoryTarget(envelope));
639
+ }
640
+ catch (error) {
641
+ const message = this.channelMemoryErrorMessage(error);
642
+ this.logChannelMemoryError('clear', envelope, message);
643
+ await this.sendMessage(envelope.chatId, `Failed to clear channel memory: ${this.channelMemoryUserErrorMessage()}`);
644
+ return true;
645
+ }
646
+ this.invalidateSessionContext(envelope);
647
+ await this.sendMessage(envelope.chatId, result.changed ? 'Channel memory cleared.' : 'No channel memory saved.');
648
+ return true;
649
+ });
323
650
  this.registerCommand('help', async (envelope) => {
324
651
  const lines = [
325
652
  'Commands:',
@@ -329,6 +656,9 @@ export class ChannelBase {
329
656
  : '/clear — Clear your session (aliases: /reset, /new)',
330
657
  '/who — Show current session & workspace',
331
658
  '/status — Show session info',
659
+ '/remember-channel <text> — Save memory for this chat',
660
+ '/channel-memory — Show memory for this chat',
661
+ '/forget-channel confirm — Clear memory for this chat',
332
662
  ];
333
663
  // Platform-specific commands (registered by adapters, not shared ones)
334
664
  const sharedCmds = new Set([
@@ -338,6 +668,9 @@ export class ChannelBase {
338
668
  'new',
339
669
  'who',
340
670
  'status',
671
+ 'remember-channel',
672
+ 'channel-memory',
673
+ 'forget-channel',
341
674
  ]);
342
675
  const platformCmds = [...this.commands.keys()].filter((c) => !sharedCmds.has(c));
343
676
  if (platformCmds.length > 0) {
@@ -376,6 +709,205 @@ export class ChannelBase {
376
709
  await this.sendMessage(envelope.chatId, lines.join('\n'));
377
710
  return true;
378
711
  });
712
+ this.registerCommand('loop', async (envelope, args) => this.handleLoopCommand(envelope, args));
713
+ }
714
+ async handleLoopCommand(envelope, args) {
715
+ if (!this.loopController) {
716
+ await this.sendMessage(envelope.chatId, 'Loops are not available.');
717
+ return true;
718
+ }
719
+ if (!this.isAuthorizedForSharedSession(envelope)) {
720
+ await this.sendMessage(envelope.chatId, 'Only authorized members can use loops in this shared session.');
721
+ return true;
722
+ }
723
+ const [subcommand = '', ...rest] = args.trim().split(/\s+/u);
724
+ switch (subcommand.toLowerCase()) {
725
+ case 'add':
726
+ return this.handleLoopAdd(envelope, rest.join(' '));
727
+ case 'list':
728
+ return this.handleLoopList(envelope);
729
+ case 'inspect':
730
+ return this.handleLoopInspect(envelope, rest[0]);
731
+ case 'cancel':
732
+ return this.handleLoopCancel(envelope, rest[0]);
733
+ default:
734
+ await this.sendMessage(envelope.chatId, 'Usage: /loop add "<cron>" <prompt> | /loop list | /loop inspect <id> | /loop cancel <id>');
735
+ return true;
736
+ }
737
+ }
738
+ async handleLoopAdd(envelope, args) {
739
+ if (!this.loopController)
740
+ return true;
741
+ if (!this.supportsProactiveSend()) {
742
+ await this.sendMessage(envelope.chatId, 'This channel does not support proactive loop messages.');
743
+ return true;
744
+ }
745
+ if (this.config.sessionScope === 'single') {
746
+ await this.sendMessage(envelope.chatId, 'Loops are not supported when sessionScope is single.');
747
+ return true;
748
+ }
749
+ const parsed = parseLoopAddArgs(args);
750
+ if (!parsed) {
751
+ await this.sendMessage(envelope.chatId, 'Usage: /loop add "<cron>" <prompt>');
752
+ return true;
753
+ }
754
+ try {
755
+ this.loopController.validateCron(parsed.cron);
756
+ }
757
+ catch (err) {
758
+ await this.sendMessage(envelope.chatId, `Invalid cron expression: ${err instanceof Error ? err.message : String(err)}`);
759
+ return true;
760
+ }
761
+ const target = this.loopTargetFromEnvelope(envelope);
762
+ if (!this.supportsProactiveTarget(target)) {
763
+ await this.sendMessage(envelope.chatId, 'This channel does not support proactive loop messages for this chat target.');
764
+ return true;
765
+ }
766
+ const prompt = sanitizePromptText(parsed.prompt.trim());
767
+ if (Array.from(prompt).length > MAX_LOOP_PROMPT_CHARS) {
768
+ await this.sendMessage(envelope.chatId, `Loop prompt is too long; keep it under ${MAX_LOOP_PROMPT_CHARS} characters.`);
769
+ return true;
770
+ }
771
+ const input = {
772
+ channelName: this.name,
773
+ target,
774
+ cwd: this.config.cwd,
775
+ cron: parsed.cron,
776
+ prompt,
777
+ label: truncateLoopLabel(prompt),
778
+ recurring: true,
779
+ createdBy: sanitizeSenderName(envelope.senderName || envelope.senderId || 'unknown'),
780
+ };
781
+ let job;
782
+ if (this.loopController.createForTarget) {
783
+ job = await this.loopController.createForTarget(input, MAX_LOOP_JOBS_PER_TARGET);
784
+ }
785
+ else {
786
+ const existingJobs = await this.loopController.listForTarget(this.name, target);
787
+ if (existingJobs.filter((existingJob) => existingJob.enabled).length <
788
+ MAX_LOOP_JOBS_PER_TARGET) {
789
+ job = await this.loopController.create(input);
790
+ }
791
+ }
792
+ if (!job) {
793
+ await this.sendMessage(envelope.chatId, `Too many loops for this chat. Cancel an existing loop before adding another.`);
794
+ return true;
795
+ }
796
+ await this.sendMessage(envelope.chatId, `Loop ${job.id}: ${job.cron}`);
797
+ return true;
798
+ }
799
+ async handleLoopList(envelope) {
800
+ if (!this.loopController)
801
+ return true;
802
+ const jobs = await this.loopController.listForTarget(this.name, this.loopTargetFromEnvelope(envelope));
803
+ if (jobs.length === 0) {
804
+ await this.sendMessage(envelope.chatId, 'No loops.');
805
+ return true;
806
+ }
807
+ await this.sendMessage(envelope.chatId, jobs.map((job) => this.formatLoopListLine(job)).join('\n'));
808
+ return true;
809
+ }
810
+ async handleLoopInspect(envelope, id) {
811
+ if (!this.loopController)
812
+ return true;
813
+ if (!id) {
814
+ await this.sendMessage(envelope.chatId, 'Usage: /loop inspect <id>');
815
+ return true;
816
+ }
817
+ const jobs = await this.loopController.listForTarget(this.name, this.loopTargetFromEnvelope(envelope));
818
+ const job = jobs.find((candidate) => candidate.id === id);
819
+ if (!job) {
820
+ await this.sendMessage(envelope.chatId, `No loop ${id}.`);
821
+ return true;
822
+ }
823
+ const lines = [
824
+ `Loop ${job.id}`,
825
+ `Status: ${job.enabled ? 'enabled' : 'disabled'}, last=${this.lastLoopStatus(job)}`,
826
+ `Cron: ${job.cron}`,
827
+ `Next: ${this.formatNextFireTime(job)}`,
828
+ `Runs: ${job.runCount}`,
829
+ `Created by: ${job.createdBy}`,
830
+ `Created: ${job.createdAt}`,
831
+ ];
832
+ if (job.lastFinishedAt) {
833
+ lines.push(`Last finished: ${job.lastFinishedAt}`);
834
+ }
835
+ if (job.lastError) {
836
+ lines.push(`Last error: ${job.lastError}`);
837
+ }
838
+ if (job.lastResultPreview) {
839
+ lines.push(`Last result: ${job.lastResultPreview}`);
840
+ }
841
+ lines.push(`Prompt: ${job.prompt}`);
842
+ await this.sendMessage(envelope.chatId, lines.join('\n'));
843
+ return true;
844
+ }
845
+ formatLoopListLine(job) {
846
+ const fields = [
847
+ job.id,
848
+ job.cron,
849
+ job.enabled ? 'enabled' : 'disabled',
850
+ `last=${this.lastLoopStatus(job)}`,
851
+ `next=${this.formatNextFireTime(job)}`,
852
+ `runs=${job.runCount}`,
853
+ ];
854
+ if (job.label)
855
+ fields.push(job.label);
856
+ return fields.join(' ');
857
+ }
858
+ lastLoopStatus(job) {
859
+ if (job.runningSince)
860
+ return 'running';
861
+ return job.lastStatus ?? 'never';
862
+ }
863
+ formatNextFireTime(job) {
864
+ try {
865
+ return this.loopController?.nextFireTime?.(job).toISOString() ?? 'n/a';
866
+ }
867
+ catch {
868
+ return 'invalid cron';
869
+ }
870
+ }
871
+ async handleLoopCancel(envelope, id) {
872
+ if (!this.loopController)
873
+ return true;
874
+ if (!id) {
875
+ await this.sendMessage(envelope.chatId, 'Usage: /loop cancel <id>');
876
+ return true;
877
+ }
878
+ const jobs = await this.loopController.listForTarget(this.name, this.loopTargetFromEnvelope(envelope));
879
+ const match = jobs.find((job) => job.id === id);
880
+ const disabled = match ? await this.loopController.disable(id) : false;
881
+ await this.sendMessage(envelope.chatId, disabled ? `Cancelled loop ${id}.` : `No loop ${id}.`);
882
+ return true;
883
+ }
884
+ loopTargetFromEnvelope(envelope) {
885
+ return {
886
+ channelName: this.name,
887
+ senderId: envelope.senderId,
888
+ chatId: envelope.chatId,
889
+ threadId: envelope.threadId,
890
+ isGroup: envelope.isGroup === true,
891
+ };
892
+ }
893
+ isStoredLoopTargetAuthorized(target, senderName) {
894
+ if (target.isGroup === undefined) {
895
+ return false;
896
+ }
897
+ const envelope = {
898
+ channelName: this.name,
899
+ senderId: target.senderId,
900
+ senderName,
901
+ chatId: target.chatId,
902
+ text: '',
903
+ threadId: target.threadId,
904
+ isGroup: target.isGroup === true,
905
+ isMentioned: true,
906
+ isReplyToBot: true,
907
+ };
908
+ return (this.groupGate.check(envelope).allowed &&
909
+ this.gate.isAllowed(target.senderId) &&
910
+ this.isAuthorizedForSharedSession(envelope));
379
911
  }
380
912
  /** Check if a message text matches a registered local command. */
381
913
  isLocalCommand(text) {
@@ -388,6 +920,66 @@ export class ChannelBase {
388
920
  ? sessionId
389
921
  : undefined;
390
922
  }
923
+ channelMemoryTarget(envelope) {
924
+ return {
925
+ channelName: this.name,
926
+ chatId: envelope.chatId,
927
+ threadId: envelope.threadId,
928
+ };
929
+ }
930
+ invalidateSessionContext(envelope) {
931
+ const sessionId = this.router.getSession(this.name, envelope.senderId, envelope.chatId, envelope.threadId);
932
+ if (sessionId) {
933
+ this.instructedSessions.delete(sessionId);
934
+ }
935
+ }
936
+ dropQueuedTurnIfStale(sessionId, generation, envelope) {
937
+ if ((this.sessionGenerations.get(sessionId) ?? 0) === generation) {
938
+ return false;
939
+ }
940
+ // Surface the drop — otherwise an unanswered queued message vanishes
941
+ // silently, making "my message was never answered" undiagnosable.
942
+ // envelope.text is attacker-controlled, so neutralize it with the shared
943
+ // log sanitizer: it renders newlines visibly and strips the C0/DEL controls
944
+ // PLUS PROMPT_UNSAFE_INVISIBLES — the C1 block (notably NEL U+0085, a line
945
+ // break that could forge an extra [channel] log line), the Unicode line/
946
+ // paragraph separators U+2028/U+2029, and the bidi overrides — any of which
947
+ // would otherwise inject, overwrite, or reorder an operator's audit line.
948
+ // Same helper as the QQ audit log, so the defense can't drift between sites.
949
+ const loggedText = sanitizeLogText(envelope.text, 80);
950
+ process.stderr.write(`[${this.name}] dropped queued turn from ${envelope.senderId} for session ${sessionId}: session was cleared before it ran (text: ${loggedText})\n`);
951
+ return true;
952
+ }
953
+ isAuthorizedForChannelMemory(envelope) {
954
+ return this.isSenderAuthorizedForChannelMemory(envelope.senderId);
955
+ }
956
+ isSenderAuthorizedForChannelMemory(senderId) {
957
+ return (this.config.allowedUsers.length > 0 &&
958
+ this.config.allowedUsers.includes(senderId));
959
+ }
960
+ async ensureChannelMemoryAuthorized(envelope) {
961
+ if (!this.isAuthorizedForChannelMemory(envelope)) {
962
+ await this.sendMessage(envelope.chatId, 'Only authorized members can manage channel memory.');
963
+ return false;
964
+ }
965
+ return true;
966
+ }
967
+ async getChannelMemory(envelope) {
968
+ if (!this.channelMemory) {
969
+ await this.sendMessage(envelope.chatId, 'Channel memory is not configured for this channel.');
970
+ return undefined;
971
+ }
972
+ return this.channelMemory;
973
+ }
974
+ channelMemoryErrorMessage(error) {
975
+ return error instanceof Error ? error.message : String(error);
976
+ }
977
+ channelMemoryUserErrorMessage() {
978
+ return 'An error occurred while accessing channel memory.';
979
+ }
980
+ logChannelMemoryError(action, envelope, message) {
981
+ process.stderr.write(`[${this.name}] channel memory ${action} failed for sender=${sanitizeLogText(envelope.senderId, 80)} chat=${sanitizeLogText(envelope.chatId, 80)} thread=${sanitizeLogText(envelope.threadId ?? '', 80)}: ${sanitizeLogText(message, 200)}\n`);
982
+ }
391
983
  /**
392
984
  * Whether the resolved session is SHARED across senders. `single` collapses
393
985
  * the whole channel to one `__single__` session for EVERY sender — group OR
@@ -397,8 +989,11 @@ export class ChannelBase {
397
989
  * and the host-shell (`!`) gate.
398
990
  */
399
991
  isSharedSession(envelope) {
992
+ return this.isSharedSessionTarget(envelope);
993
+ }
994
+ isSharedSessionTarget(target) {
400
995
  return (this.config.sessionScope === 'single' ||
401
- (envelope.isGroup && this.config.sessionScope === 'thread'));
996
+ (target.isGroup === true && this.config.sessionScope === 'thread'));
402
997
  }
403
998
  /**
404
999
  * Whether `envelope.senderId` may act on the resolved session's destructive or
@@ -567,10 +1162,104 @@ export class ChannelBase {
567
1162
  }
568
1163
  return bridge.availableCommands ?? [];
569
1164
  }
1165
+ groupHistoryKey(envelope) {
1166
+ return JSON.stringify([
1167
+ this.name,
1168
+ envelope.chatId,
1169
+ envelope.threadId ?? null,
1170
+ ]);
1171
+ }
1172
+ groupHistoryLimit(envelope) {
1173
+ if (!envelope.isGroup) {
1174
+ return 0;
1175
+ }
1176
+ const groupCfg = this.config.groups[envelope.chatId];
1177
+ const wildcardGroupCfg = this.config.groups['*'];
1178
+ const configured = groupCfg?.groupHistoryLimit ??
1179
+ wildcardGroupCfg?.groupHistoryLimit ??
1180
+ this.config.groupHistoryLimit ??
1181
+ 0;
1182
+ if (!Number.isFinite(configured) || configured <= 0) {
1183
+ return 0;
1184
+ }
1185
+ return Math.floor(configured);
1186
+ }
1187
+ recordPendingGroupHistory(envelope) {
1188
+ const limit = this.groupHistoryLimit(envelope);
1189
+ if (limit <= 0 || envelope.text.trim().length === 0) {
1190
+ return;
1191
+ }
1192
+ const senderId = truncateGroupHistoryField(envelope.senderId);
1193
+ if (!this.gate.isAllowed(senderId)) {
1194
+ return;
1195
+ }
1196
+ const entry = {
1197
+ senderId,
1198
+ senderName: truncateGroupHistoryField(envelope.senderName),
1199
+ text: envelope.text.slice(0, GROUP_HISTORY_ENTRY_TEXT_LIMIT),
1200
+ messageId: envelope.messageId === undefined
1201
+ ? undefined
1202
+ : truncateGroupHistoryField(envelope.messageId),
1203
+ timestamp: Date.now(),
1204
+ };
1205
+ try {
1206
+ this.groupHistory.record(this.groupHistoryKey(envelope), entry, limit);
1207
+ }
1208
+ catch (err) {
1209
+ process.stderr.write(`[${this.name}] failed to record group history for chat ${sanitizeLogText(envelope.chatId, 64)}: ${err instanceof Error ? err.message : err}\n`);
1210
+ }
1211
+ }
1212
+ drainPendingGroupHistory(envelope) {
1213
+ const limit = this.groupHistoryLimit(envelope);
1214
+ if (limit <= 0) {
1215
+ return [];
1216
+ }
1217
+ try {
1218
+ return this.groupHistory.drain(this.groupHistoryKey(envelope), limit);
1219
+ }
1220
+ catch (err) {
1221
+ process.stderr.write(`[${this.name}] failed to drain group history for chat ${sanitizeLogText(envelope.chatId, 64)}: ${err instanceof Error ? err.message : err}\n`);
1222
+ return [];
1223
+ }
1224
+ }
1225
+ clearPendingGroupHistory(envelope) {
1226
+ if (!envelope.isGroup && this.config.sessionScope !== 'single') {
1227
+ return;
1228
+ }
1229
+ try {
1230
+ if (this.config.sessionScope === 'single') {
1231
+ this.groupHistory.clearAll();
1232
+ }
1233
+ else {
1234
+ this.groupHistory.clear(this.groupHistoryKey(envelope));
1235
+ }
1236
+ }
1237
+ catch (err) {
1238
+ process.stderr.write(`[${this.name}] failed to clear group history for chat ${sanitizeLogText(envelope.chatId, 64)}: ${err instanceof Error ? err.message : err}\n`);
1239
+ }
1240
+ }
1241
+ prependGroupHistoryContext(promptText, entries) {
1242
+ if (entries.length === 0) {
1243
+ return promptText;
1244
+ }
1245
+ const lines = entries.filter((entry) => this.gate.isAllowed(entry.senderId));
1246
+ if (lines.length === 0) {
1247
+ return promptText;
1248
+ }
1249
+ const formatted = lines.map((entry) => {
1250
+ const who = sanitizeSenderName(entry.senderName || entry.senderId);
1251
+ const text = sanitizeQuotedText(entry.text, GROUP_HISTORY_ENTRY_TEXT_LIMIT);
1252
+ return `- [${who}] ${text}`;
1253
+ });
1254
+ return `${GROUP_HISTORY_CONTEXT_MARKER}\n${formatted.join('\n')}\n\n${CURRENT_MESSAGE_MARKER}\n${promptText}`;
1255
+ }
570
1256
  async handleInbound(envelope) {
571
1257
  // 1. Group gate: policy + allowlist + mention gating
572
1258
  const groupResult = this.groupGate.check(envelope);
573
1259
  if (!groupResult.allowed) {
1260
+ if (groupResult.reason === 'mention_required') {
1261
+ this.recordPendingGroupHistory(envelope);
1262
+ }
574
1263
  return; // silently drop — no pairing, no reply
575
1264
  }
576
1265
  // 2. Sender gate: allowlist / pairing / open
@@ -626,7 +1315,7 @@ export class ChannelBase {
626
1315
  const bridgeShellCommand = this.bridge.shellCommand;
627
1316
  if (cmd && bridgeShellCommand) {
628
1317
  try {
629
- const result = await this.bridge.shellCommand(sessionId, cmd);
1318
+ const result = await bridgeShellCommand(sessionId, cmd);
630
1319
  const longestRun = Math.max(0, ...Array.from((result.output || '').matchAll(/`+/g), (m) => m[0].length));
631
1320
  const fence = '`'.repeat(Math.max(3, longestRun + 1));
632
1321
  const output = result.output
@@ -643,6 +1332,8 @@ export class ChannelBase {
643
1332
  return;
644
1333
  }
645
1334
  }
1335
+ const recognizedSlashCommand = this.isSlashCommand(envelope.text) &&
1336
+ this.isRecognizedCommand(envelope.text, sessionId);
646
1337
  // Prepend referenced (quoted) message text for reply context
647
1338
  let promptText = envelope.text;
648
1339
  // Multiplayer attribution: when a session can carry multiple humans, tag each
@@ -668,8 +1359,7 @@ export class ChannelBase {
668
1359
  // list — see isRecognizedCommand for the no-await tradeoff.
669
1360
  if ((envelope.isGroup || this.config.sessionScope === 'single') &&
670
1361
  !envelope.alreadyPrefixed &&
671
- !(this.isSlashCommand(envelope.text) &&
672
- this.isRecognizedCommand(envelope.text, sessionId))) {
1362
+ !recognizedSlashCommand) {
673
1363
  const who = sanitizeSenderName(envelope.senderName || envelope.senderId || 'unknown');
674
1364
  promptText = `[${who}] ${sanitizePromptText(promptText)}`;
675
1365
  }
@@ -715,11 +1405,6 @@ export class ChannelBase {
715
1405
  promptText = promptText + '\n\n' + filePaths.join('\n');
716
1406
  }
717
1407
  }
718
- // Prepend channel instructions on first message of a session
719
- if (this.config.instructions && !this.instructedSessions.has(sessionId)) {
720
- promptText = `${this.config.instructions}\n\n${promptText}`;
721
- this.instructedSessions.add(sessionId);
722
- }
723
1408
  // Resolve dispatch mode: per-group override → channel config → default
724
1409
  const groupCfg = envelope.isGroup
725
1410
  ? this.config.groups[envelope.chatId] || this.config.groups['*']
@@ -819,6 +1504,10 @@ export class ChannelBase {
819
1504
  }
820
1505
  }
821
1506
  }
1507
+ let shouldPrependSessionContext = !this.instructedSessions.has(sessionId);
1508
+ if (shouldPrependSessionContext) {
1509
+ this.instructedSessions.add(sessionId);
1510
+ }
822
1511
  // Run the prompt with per-session serialization. followup AND steer both chain
823
1512
  // onto the existing queue tail; steer additionally best-effort cancelled the
824
1513
  // running turn above so the tail resolves sooner. Chaining (rather than seeding
@@ -839,20 +1528,46 @@ export class ChannelBase {
839
1528
  clearTimeout(steerWatchdog);
840
1529
  // A /clear (or reset/new) while we were queued bumps the generation; the
841
1530
  // captured session is cleared, so don't run the prompt against it.
842
- if ((this.sessionGenerations.get(sessionId) ?? 0) !== generation) {
843
- // Surface the drop — otherwise an unanswered queued message vanishes
844
- // silently, making "my message was never answered" undiagnosable.
845
- // envelope.text is attacker-controlled, so neutralize it with the shared
846
- // log sanitizer: it renders newlines visibly and strips the C0/DEL controls
847
- // PLUS PROMPT_UNSAFE_INVISIBLES — the C1 block (notably NEL U+0085, a line
848
- // break that could forge an extra [channel] log line), the Unicode line/
849
- // paragraph separators U+2028/U+2029, and the bidi overrides — any of which
850
- // would otherwise inject, overwrite, or reorder an operator's audit line.
851
- // Same helper as the QQ audit log, so the defense can't drift between sites.
852
- const loggedText = sanitizeLogText(envelope.text, 80);
853
- process.stderr.write(`[${this.name}] dropped queued turn from ${envelope.senderId} for session ${sessionId}: session was cleared before it ran (text: ${loggedText})\n`);
1531
+ if (this.dropQueuedTurnIfStale(sessionId, generation, envelope)) {
854
1532
  return;
855
1533
  }
1534
+ if (!shouldPrependSessionContext &&
1535
+ !this.instructedSessions.has(sessionId)) {
1536
+ shouldPrependSessionContext = true;
1537
+ this.instructedSessions.add(sessionId);
1538
+ }
1539
+ const sessionContext = [];
1540
+ if (shouldPrependSessionContext) {
1541
+ let memoryText;
1542
+ if (this.channelMemory &&
1543
+ this.isAuthorizedForChannelMemory(envelope) &&
1544
+ (!this.isSharedSession(envelope) ||
1545
+ this.config.senderPolicy === 'allowlist')) {
1546
+ try {
1547
+ memoryText = (await this.channelMemory.readChannelMemory(this.channelMemoryTarget(envelope)))?.trim();
1548
+ }
1549
+ catch (error) {
1550
+ this.logChannelMemoryError('read', envelope, this.channelMemoryErrorMessage(error));
1551
+ this.instructedSessions.delete(sessionId);
1552
+ }
1553
+ }
1554
+ if (memoryText) {
1555
+ sessionContext.push(`Channel memory for this chat:\n${sanitizePromptText(memoryText)}`);
1556
+ }
1557
+ if (this.config.instructions) {
1558
+ sessionContext.push(this.config.instructions);
1559
+ }
1560
+ }
1561
+ if (this.dropQueuedTurnIfStale(sessionId, generation, envelope)) {
1562
+ return;
1563
+ }
1564
+ const groupHistoryEntries = recognizedSlashCommand
1565
+ ? []
1566
+ : this.drainPendingGroupHistory(envelope);
1567
+ let promptToSend = this.prependGroupHistoryContext(promptText, groupHistoryEntries);
1568
+ if (sessionContext.length > 0) {
1569
+ promptToSend = `${sessionContext.join('\n\n')}\n\n${promptToSend}`;
1570
+ }
856
1571
  // Register this prompt as active
857
1572
  let doneResolve = () => { };
858
1573
  const done = new Promise((r) => {
@@ -888,12 +1603,15 @@ export class ChannelBase {
888
1603
  const promptBridge = this.bridge;
889
1604
  promptBridge.on('textChunk', onChunk);
890
1605
  try {
891
- const response = await promptBridge.prompt(sessionId, promptText, {
1606
+ const response = await promptBridge.prompt(sessionId, promptToSend, {
892
1607
  imageBase64,
893
1608
  imageMimeType,
894
1609
  });
895
1610
  if (promptState.cancelRequested && !promptState.cancelled) {
896
- promptState.cancelled = await promptState.cancelRequested;
1611
+ const cancelled = await promptState.cancelRequested;
1612
+ if (cancelled) {
1613
+ promptState.cancelled = true;
1614
+ }
897
1615
  }
898
1616
  // If cancelled, skip sending the response
899
1617
  if (!promptState.cancelled && response) {
@@ -997,4 +1715,11 @@ export class ChannelBase {
997
1715
  }
998
1716
  }
999
1717
  }
1718
+ function truncateGroupHistoryField(value) {
1719
+ return value.slice(0, GROUP_HISTORY_ENTRY_METADATA_LIMIT);
1720
+ }
1721
+ function truncateLoopLabel(prompt) {
1722
+ const chars = Array.from(prompt);
1723
+ return chars.length > 60 ? `${chars.slice(0, 57).join('')}...` : prompt;
1724
+ }
1000
1725
  //# sourceMappingURL=ChannelBase.js.map