@qwen-code/channel-base 0.23.2-preview.0 → 0.23.3-nightly.20260910.c46cb85cf2

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,6 +1,5 @@
1
1
  import { basename, join } from 'node:path';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { BlockStreamer } from './BlockStreamer.js';
4
3
  import { ChannelProactiveDeliveryError, isChannelProactiveDeliveryError, } from './ChannelProactiveDeliveryError.js';
5
4
  import { GroupGate } from './GroupGate.js';
6
5
  import { DmGate } from './DmGate.js';
@@ -12,7 +11,6 @@ import { NamedSessionManager, NamedSessionTaskError, } from './named-session-man
12
11
  import { getGlobalQwenDir } from './paths.js';
13
12
  import { sanitizeSenderName, sanitizeQuotedText, sanitizePromptText, sanitizePromptPath, sanitizeLogText, sanitizeDisplayText, truncateCodePoints, PROMPT_UNSAFE_INVISIBLES, } from './sanitize.js';
14
13
  import { ChannelLoopSkippedError } from './ChannelLoopScheduler.js';
15
- import { applyMessagePrefix } from './message-prefix.js';
16
14
  import { buildChannelWebhookDisplayText, buildChannelWebhookPrompt, resolveChannelWebhookTarget, } from './ChannelWebhookTask.js';
17
15
  import { parseChannelMemoryIntent, } from './channel-memory-intent.js';
18
16
  import { CHANNEL_MEMORY_RECALL_MAX_ENTRIES, createChannelMemoryRecallIndex, selectRelevantChannelMemory, selectRelevantChannelMemoryFromIndex, } from './channel-memory-recall.js';
@@ -68,6 +66,48 @@ const SENSITIVE_PAYLOAD_KEY_PATTERN = new RegExp([
68
66
  function isRecord(value) {
69
67
  return value !== null && typeof value === 'object' && !Array.isArray(value);
70
68
  }
69
+ const PERMISSION_COPY = {
70
+ en: {
71
+ toolUse: 'Tool use',
72
+ allowOnce: 'Allow once',
73
+ allowAlwaysProject: 'always allow for this project',
74
+ allowAlwaysUser: 'always allow for this user',
75
+ allowAlways: 'always allow',
76
+ deny: 'Deny',
77
+ required: 'Permission required to run a tool',
78
+ request: 'Request:',
79
+ tool: 'Tool:',
80
+ action: 'Action:',
81
+ parameters: 'Parameters:',
82
+ replyWith: 'Reply with:',
83
+ },
84
+ zh: {
85
+ toolUse: '工具调用',
86
+ allowOnce: '仅允许本次',
87
+ allowAlwaysProject: '始终允许此项目',
88
+ allowAlwaysUser: '始终允许此用户',
89
+ allowAlways: '始终允许',
90
+ deny: '拒绝',
91
+ required: '运行工具需要授权',
92
+ request: '请求:',
93
+ tool: '工具:',
94
+ action: '操作:',
95
+ parameters: '参数:',
96
+ replyWith: '回复以下命令:',
97
+ },
98
+ };
99
+ /**
100
+ * Translate the stock prefix of a scoped always-allow label, keeping the
101
+ * command/tool scope that exec and mcp confirmations append to it.
102
+ */
103
+ function localizedScopedAlwaysLabel(label, stockLabel, localizedLabel) {
104
+ if (label === stockLabel)
105
+ return localizedLabel;
106
+ const scopeSeparator = ': ';
107
+ if (!label.startsWith(stockLabel + scopeSeparator))
108
+ return undefined;
109
+ return `${localizedLabel}:${label.slice(stockLabel.length + scopeSeparator.length)}`;
110
+ }
71
111
  /**
72
112
  * Character class (sans the enclosing `[]`) for a slash-command token: alphanumerics
73
113
  * plus `_`, `:` and `-`, so hyphenated and namespaced agent commands (e.g.
@@ -115,6 +155,7 @@ export class ChannelBase {
115
155
  proxy;
116
156
  /** Adapter-owned persistent state directory, when supplied by the runtime. */
117
157
  stateDir;
158
+ locale;
118
159
  channelMemory;
119
160
  memoryIntentClassifier;
120
161
  channelMemoryRecallObserver;
@@ -128,9 +169,6 @@ export class ChannelBase {
128
169
  observedContacts;
129
170
  namedSessions;
130
171
  observedContactEnvelopes = new WeakSet();
131
- messagePrefix;
132
- messagePrefixCheckedEnvelopes = new WeakSet();
133
- messagePrefixRejectedEnvelopes = new WeakSet();
134
172
  instructedSessions = new Set();
135
173
  unattendedMemorySessions = new Set();
136
174
  channelMemoryReads = new Map();
@@ -276,7 +314,7 @@ export class ChannelBase {
276
314
  async handleBtw(envelope, sessionId, question, sourceLabel) {
277
315
  const target = this.router.getTarget(sessionId);
278
316
  if (!target || target.channelName !== this.name) {
279
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Could not resolve the current task for ${this.prefixedCommand('/btw')}.`, sourceLabel);
317
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Could not resolve the current task for /btw.`, sourceLabel);
280
318
  return;
281
319
  }
282
320
  const running = this.activeBtw.get(sessionId);
@@ -486,6 +524,10 @@ export class ChannelBase {
486
524
  if (presentation && (await presentation)) {
487
525
  return;
488
526
  }
527
+ const permissionPresentation = this.tryPresentPermission(pending);
528
+ if (permissionPresentation && (await permissionPresentation)) {
529
+ return;
530
+ }
489
531
  const text = this.formatPermissionRequest(pending);
490
532
  if (target.threadId !== undefined &&
491
533
  this.supportsProactiveSend() &&
@@ -576,6 +618,117 @@ export class ChannelBase {
576
618
  }
577
619
  })();
578
620
  }
621
+ tryPresentPermission(pending) {
622
+ const active = this.activePrompts.get(pending.sessionId);
623
+ const toolCall = pending.request.toolCall;
624
+ const meta = isRecord(toolCall['_meta']) ? toolCall['_meta'] : undefined;
625
+ const isUserQuestion = meta?.['qwenInteractionKind'] === 'user_question' ||
626
+ meta?.['toolName'] === 'ask_user_question' ||
627
+ toolCall['kind'] === 'ask_user_question';
628
+ const decisions = this.permissionPresentationDecisions(pending);
629
+ if (!active ||
630
+ active.loopPrompt ||
631
+ !active.owner ||
632
+ isUserQuestion ||
633
+ !decisions) {
634
+ return undefined;
635
+ }
636
+ const precedingSegment = this.closeOutputSegment(pending.sessionId, active, pending.target);
637
+ let respondInvoked = false;
638
+ const context = {
639
+ requestId: pending.requestId,
640
+ sessionId: pending.sessionId,
641
+ runId: active.runId,
642
+ owner: active.owner,
643
+ target: pending.target,
644
+ ...(precedingSegment
645
+ ? { precedingSegmentId: precedingSegment.segmentId }
646
+ : {}),
647
+ title: this.permissionTitle(pending.request.toolCall),
648
+ decisions,
649
+ onSettled: (listener) => {
650
+ if (pending.settled) {
651
+ listener(pending.settled);
652
+ return () => { };
653
+ }
654
+ pending.settlementListeners.add(listener);
655
+ return () => {
656
+ pending.settlementListeners.delete(listener);
657
+ };
658
+ },
659
+ respond: (decision) => {
660
+ const response = this.permissionPresentationResponse(pending, decision);
661
+ if (!response)
662
+ return Promise.resolve(false);
663
+ respondInvoked = true;
664
+ return this.respondToUserInput(pending, response);
665
+ },
666
+ };
667
+ pending.permissionPresented = true;
668
+ return (async () => {
669
+ try {
670
+ if (precedingSegment) {
671
+ await this.notifyOutputSegmentEnd(pending.target.chatId, pending.sessionId, precedingSegment, 'input_requested');
672
+ }
673
+ if (this.pendingPermissions.get(pending.requestId) !== pending) {
674
+ return true;
675
+ }
676
+ const result = await this.presentPermissionRequest(context);
677
+ if (this.pendingPermissions.get(pending.requestId) !== pending) {
678
+ return true;
679
+ }
680
+ if (result.kind === 'presented' ||
681
+ (result.kind === 'handled' && respondInvoked)) {
682
+ return true;
683
+ }
684
+ pending.permissionPresented = false;
685
+ return false;
686
+ }
687
+ catch (err) {
688
+ process.stderr.write(`[${this.name}] permission presentation failed for request ${sanitizeLogText(pending.requestId, 128)}: ${this.lifecycleError(err)}\n`);
689
+ if (this.pendingPermissions.get(pending.requestId) !== pending) {
690
+ return true;
691
+ }
692
+ pending.permissionPresented = false;
693
+ return false;
694
+ }
695
+ })();
696
+ }
697
+ permissionPresentationDecisions(pending) {
698
+ const allowOnce = this.approvalOption(pending);
699
+ if (!allowOnce)
700
+ return undefined;
701
+ const copy = PERMISSION_COPY[this.locale];
702
+ const allowAlways = this.approvalAlwaysOption(pending);
703
+ return [
704
+ {
705
+ kind: 'allow_once',
706
+ label: sanitizeQuotedText(this.permissionOptionLabel(allowOnce, copy.allowOnce), 80),
707
+ },
708
+ ...(allowAlways
709
+ ? [
710
+ {
711
+ kind: 'allow_always',
712
+ label: sanitizeQuotedText(allowAlways.label, 80),
713
+ },
714
+ ]
715
+ : []),
716
+ {
717
+ kind: 'deny',
718
+ label: sanitizeQuotedText(this.permissionOptionLabel(this.denialOption(pending), copy.deny), 80),
719
+ },
720
+ ];
721
+ }
722
+ permissionPresentationResponse(pending, decision) {
723
+ if (decision === 'deny')
724
+ return this.denialResponse(pending);
725
+ const optionId = decision === 'allow_once'
726
+ ? this.approvalOptionId(pending)
727
+ : this.approvalAlwaysOption(pending)?.optionId;
728
+ return optionId
729
+ ? { outcome: { outcome: 'selected', optionId } }
730
+ : undefined;
731
+ }
579
732
  normalizeUserQuestions(pending) {
580
733
  const toolCall = pending.request.toolCall;
581
734
  const meta = isRecord(toolCall['_meta']) ? toolCall['_meta'] : undefined;
@@ -639,7 +792,8 @@ export class ChannelBase {
639
792
  }
640
793
  async respondToUserInput(pending, response) {
641
794
  if (pending.responsePromise) {
642
- return pending.responsePromise;
795
+ await pending.responsePromise;
796
+ return false;
643
797
  }
644
798
  if (this.pendingPermissions.get(pending.requestId) !== pending ||
645
799
  !this.bridge.respondToPermission) {
@@ -691,14 +845,10 @@ export class ChannelBase {
691
845
  this.removePendingPermission(event.requestId, this.userInputSettlementReason(pending, event.outcome));
692
846
  }
693
847
  constructor(name, config, bridge, options) {
694
- if (config.messagePrefix !== undefined &&
695
- typeof config.messagePrefix !== 'string') {
696
- throw new Error(`Channel "${name}" field "messagePrefix" must be a string.`);
697
- }
698
848
  this.name = name;
699
849
  this.config = config;
700
- this.messagePrefix = config.messagePrefix?.trim() || undefined;
701
850
  this.bridge = bridge;
851
+ this.locale = options?.locale ?? 'en';
702
852
  this.proxy = options?.proxy;
703
853
  this.stateDir = options?.stateDir;
704
854
  this.identity = Object.freeze(this.resolveIdentity(name, config));
@@ -770,6 +920,9 @@ export class ChannelBase {
770
920
  async presentUserInputRequest(_context) {
771
921
  return { kind: 'unsupported' };
772
922
  }
923
+ async presentPermissionRequest(_context) {
924
+ return { kind: 'unsupported' };
925
+ }
773
926
  emitTaskLifecycle(event) {
774
927
  try {
775
928
  const result = this.onTaskLifecycle(event);
@@ -1734,7 +1887,6 @@ export class ChannelBase {
1734
1887
  return false;
1735
1888
  }
1736
1889
  active.cancelled = true;
1737
- this.stopActiveStreaming(active, sessionId, reason);
1738
1890
  this.dropCollectBuffer(sessionId);
1739
1891
  this.removePendingPermissionsForSession(sessionId, 'run_cancelled');
1740
1892
  this.emitTaskCancellation(active, sessionId, reason);
@@ -2058,51 +2210,47 @@ export class ChannelBase {
2058
2210
  canEnvelopeAnswerPendingPermission(envelope, pending) {
2059
2211
  return (pending.target.chatId === envelope.chatId &&
2060
2212
  pending.target.threadId === envelope.threadId &&
2061
- (!pending.userInputPresented ||
2213
+ ((!pending.userInputPresented && !pending.permissionPresented) ||
2062
2214
  pending.target.senderId === envelope.senderId) &&
2063
2215
  (this.isSharedSessionTarget(pending.target) ||
2064
2216
  pending.target.senderId === envelope.senderId));
2065
2217
  }
2066
2218
  formatPermissionRequest(pending) {
2067
2219
  const { toolCall } = pending.request;
2220
+ const copy = PERMISSION_COPY[this.locale];
2068
2221
  const parameters = this.permissionParameterSummary(toolCall);
2069
- const approveLabel = this.permissionOptionLabel(this.approvalOption(pending), 'allow once');
2222
+ const approveLabel = this.permissionOptionLabel(this.approvalOption(pending), copy.allowOnce.toLocaleLowerCase(this.locale));
2070
2223
  const alwaysOption = this.approvalAlwaysOption(pending);
2071
- const denyLabel = this.permissionOptionLabel(this.denialOption(pending), 'deny');
2224
+ const denyLabel = this.permissionOptionLabel(this.denialOption(pending), copy.deny.toLocaleLowerCase(this.locale));
2072
2225
  const requestSuffix = pending.taskName ? ` ${pending.requestId}` : '';
2073
2226
  const replyPadding = pending.taskName
2074
2227
  ? { approve: ' ', always: ' ', deny: ' ' }
2075
2228
  : { approve: ' ', always: ' ', deny: ' ' };
2076
2229
  const replies = [
2077
- `${this.prefixedCommand(`/approve${requestSuffix}`)}${replyPadding.approve}${approveLabel}`,
2230
+ `/approve${requestSuffix}${replyPadding.approve}${approveLabel}`,
2078
2231
  ...(alwaysOption
2079
2232
  ? [
2080
- `${this.prefixedCommand(`/approve-always${requestSuffix}`)}${replyPadding.always}${alwaysOption.label}`,
2233
+ `/approve-always${requestSuffix}${replyPadding.always}${alwaysOption.label}`,
2081
2234
  ]
2082
2235
  : []),
2083
- `${this.prefixedCommand(`/deny${requestSuffix}`)}${replyPadding.deny}${denyLabel}`,
2236
+ `/deny${requestSuffix}${replyPadding.deny}${denyLabel}`,
2084
2237
  ];
2085
2238
  return [
2086
- 'Permission required to run a tool',
2087
- ...(pending.taskName ? [`Request: ${pending.requestId}`] : []),
2239
+ copy.required,
2240
+ ...(pending.taskName ? [`${copy.request} ${pending.requestId}`] : []),
2088
2241
  '',
2089
- `Tool: ${this.permissionToolName(toolCall)}`,
2090
- `Action: ${this.permissionTitle(toolCall)}`,
2091
- ...(parameters ? [`Parameters: ${parameters}`] : []),
2242
+ `${copy.tool} ${this.permissionToolName(toolCall)}`,
2243
+ `${copy.action} ${this.permissionTitle(toolCall)}`,
2244
+ ...(parameters ? [`${copy.parameters} ${parameters}`] : []),
2092
2245
  '',
2093
- 'Reply with:',
2246
+ copy.replyWith,
2094
2247
  ...replies,
2095
2248
  ].join('\n');
2096
2249
  }
2097
- prefixedCommand(command) {
2098
- return this.messagePrefix ? `${this.messagePrefix} ${command}` : command;
2099
- }
2100
- configuredMessagePrefix() {
2101
- return this.messagePrefix;
2102
- }
2103
2250
  permissionTitle(toolCall) {
2104
2251
  const rawTitle = typeof toolCall.title === 'string' ? toolCall.title : undefined;
2105
- return sanitizeQuotedText(rawTitle || '', 160).trim() || 'Tool use';
2252
+ return (sanitizeQuotedText(rawTitle || '', 160).trim() ||
2253
+ PERMISSION_COPY[this.locale].toolUse);
2106
2254
  }
2107
2255
  permissionToolName(toolCall) {
2108
2256
  const rawToolCall = toolCall;
@@ -2146,7 +2294,31 @@ export class ChannelBase {
2146
2294
  permissionOptionLabel(option, fallback) {
2147
2295
  const rawLabel = typeof option?.name === 'string' ? option.name : '';
2148
2296
  const label = sanitizeQuotedText(rawLabel, 160).trim();
2149
- return label || fallback;
2297
+ if (!label)
2298
+ return fallback;
2299
+ return this.localizedPermissionOptionLabel(option, label) ?? label;
2300
+ }
2301
+ localizedPermissionOptionLabel(option, label) {
2302
+ if (this.locale !== 'zh')
2303
+ return undefined;
2304
+ const copy = PERMISSION_COPY[this.locale];
2305
+ if (option?.kind === 'allow_always') {
2306
+ if (option.optionId === 'proceed_always_project') {
2307
+ return localizedScopedAlwaysLabel(label, 'Always Allow in project', copy.allowAlwaysProject);
2308
+ }
2309
+ if (option.optionId === 'proceed_always_user') {
2310
+ return localizedScopedAlwaysLabel(label, 'Always Allow for user', copy.allowAlwaysUser);
2311
+ }
2312
+ if (option.optionId === 'proceed_always' && label === 'Allow All Edits') {
2313
+ return copy.allowAlways;
2314
+ }
2315
+ return undefined;
2316
+ }
2317
+ if (label === 'Allow' || label === 'Allow once')
2318
+ return copy.allowOnce;
2319
+ if (label === 'Deny' || label === 'Reject')
2320
+ return copy.deny;
2321
+ return undefined;
2150
2322
  }
2151
2323
  approvalOption(pending) {
2152
2324
  const options = pending.request.options;
@@ -2174,13 +2346,14 @@ export class ChannelBase {
2174
2346
  return options.find((option) => option.optionId === `proceed_always_${scope}`);
2175
2347
  }
2176
2348
  approvalAlwaysLabel(option) {
2349
+ const copy = PERMISSION_COPY[this.locale];
2177
2350
  if (option.optionId === 'proceed_always_project') {
2178
- return 'always allow for this project';
2351
+ return copy.allowAlwaysProject;
2179
2352
  }
2180
2353
  if (option.optionId === 'proceed_always_user') {
2181
- return 'always allow for this user';
2354
+ return copy.allowAlwaysUser;
2182
2355
  }
2183
- return 'always allow';
2356
+ return copy.allowAlways;
2184
2357
  }
2185
2358
  denialResponse(pending) {
2186
2359
  const option = this.denialOption(pending);
@@ -2224,7 +2397,7 @@ export class ChannelBase {
2224
2397
  return `- ${task}${sanitizeQuotedText(id, 128)}${title}`;
2225
2398
  })
2226
2399
  .join('\n');
2227
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Multiple permission requests are pending for this chat. Reply with ${this.prefixedCommand(`/${decision} <request-id>`)}.\n${requestList}`);
2400
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Multiple permission requests are pending for this chat. Reply with /${decision} <request-id>.\n${requestList}`);
2228
2401
  return true;
2229
2402
  }
2230
2403
  if (lookup.kind === 'none') {
@@ -2243,7 +2416,7 @@ export class ChannelBase {
2243
2416
  return true;
2244
2417
  }
2245
2418
  if (pending.userInputPresented && decision !== 'deny') {
2246
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Submit this question through its interactive card, or use ${this.prefixedCommand('/deny [request-id]')} to cancel it.`, pending.sourceLabel);
2419
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Submit this question through its interactive card, or use /deny [request-id] to cancel it.`, pending.sourceLabel);
2247
2420
  return true;
2248
2421
  }
2249
2422
  const response = (() => {
@@ -2265,9 +2438,10 @@ export class ChannelBase {
2265
2438
  }
2266
2439
  let accepted;
2267
2440
  try {
2268
- accepted = pending.userInputPresented
2269
- ? await this.respondToUserInput(pending, response)
2270
- : await this.bridge.respondToPermission(pending.requestId, response);
2441
+ accepted =
2442
+ pending.userInputPresented || pending.permissionPresented
2443
+ ? await this.respondToUserInput(pending, response)
2444
+ : await this.bridge.respondToPermission(pending.requestId, response);
2271
2445
  }
2272
2446
  catch (err) {
2273
2447
  this.removePendingPermission(pending.requestId);
@@ -2444,7 +2618,7 @@ export class ChannelBase {
2444
2618
  }
2445
2619
  const remedy = safeTaskName === undefined
2446
2620
  ? 'select this task first or close it'
2447
- : `select this task first or close it with ${this.prefixedCommand(`/session close ${safeTaskName}`)}`;
2621
+ : `select this task first or close it with /session close ${safeTaskName}`;
2448
2622
  return `${subject} ${problem}. Its files were not changed. Clearing now would reset the selected task instead, so ${remedy}.`;
2449
2623
  }
2450
2624
  async selectedTaskName(envelope) {
@@ -2475,7 +2649,7 @@ export class ChannelBase {
2475
2649
  return false;
2476
2650
  const normalized = args.trim().toLowerCase();
2477
2651
  if (normalized !== '' && normalized !== 'all') {
2478
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/sessions [all]')}`);
2652
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /sessions [all]`);
2479
2653
  return true;
2480
2654
  }
2481
2655
  try {
@@ -2509,7 +2683,7 @@ export class ChannelBase {
2509
2683
  const current = await namedSessions.current(owner);
2510
2684
  await this.sendThreadMessage(envelope.chatId, envelope.threadId, current
2511
2685
  ? `Current task: ${current.name} (${current.isolation})`
2512
- : `No task is currently selected. Use ${this.prefixedCommand('/session new <name>')} or ${this.prefixedCommand('/session use <name>')}.`);
2686
+ : `No task is currently selected. Use /session new <name> or /session use <name>.`);
2513
2687
  return true;
2514
2688
  }
2515
2689
  case 'new': {
@@ -2581,7 +2755,7 @@ export class ChannelBase {
2581
2755
  await this.sendNamedSessionError(envelope, error);
2582
2756
  return true;
2583
2757
  }
2584
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/session current')} | ${this.prefixedCommand('/session new <name> [--worktree]')} | ${this.prefixedCommand('/session use <name>')} | ${this.prefixedCommand('/session close <name>')} | ${this.prefixedCommand('/session cancel [<name>]')}`);
2758
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /session current | /session new <name> [--worktree] | /session use <name> | /session close <name> | /session cancel [<name>]`);
2585
2759
  return true;
2586
2760
  }
2587
2761
  /** Register shared slash commands. Called from constructor. */
@@ -2734,7 +2908,7 @@ export class ChannelBase {
2734
2908
  return true;
2735
2909
  }
2736
2910
  if (this.isSharedSession(envelope) && args.toLowerCase() !== 'confirm') {
2737
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `This clears the shared session for everyone who shares it. Re-send with "confirm" (e.g. ${this.prefixedCommand('/clear confirm')}) to proceed.`);
2911
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `This clears the shared session for everyone who shares it. Re-send with "confirm" (e.g. /clear confirm) to proceed.`);
2738
2912
  return true;
2739
2913
  }
2740
2914
  await doClear(envelope);
@@ -2794,24 +2968,24 @@ export class ChannelBase {
2794
2968
  this.registerCommand('help', async (envelope) => {
2795
2969
  const lines = [
2796
2970
  'Commands:',
2797
- `${this.prefixedCommand('/help')} — Show this help`,
2971
+ `/help — Show this help`,
2798
2972
  this.isSharedSession(envelope)
2799
- ? `${this.prefixedCommand('/clear confirm')} — Clear the shared session (aliases: ${this.prefixedCommand('/reset')}, ${this.prefixedCommand('/new')})`
2800
- : `${this.prefixedCommand('/clear')} — Clear your session (aliases: ${this.prefixedCommand('/reset')}, ${this.prefixedCommand('/new')})`,
2801
- `${this.prefixedCommand('/who')} — Show current session & workspace`,
2802
- `${this.prefixedCommand('/status')} — Show session info`,
2803
- `${this.prefixedCommand('/approve [request-id]')} — Approve a pending permission request`,
2804
- `${this.prefixedCommand('/approve-always [request-id]')} — Always approve a pending permission request`,
2805
- `${this.prefixedCommand('/deny [request-id]')} — Deny a pending permission request`,
2973
+ ? `/clear confirm — Clear the shared session (aliases: /reset, /new)`
2974
+ : `/clear — Clear your session (aliases: /reset, /new)`,
2975
+ `/who — Show current session & workspace`,
2976
+ `/status — Show session info`,
2977
+ `/approve [request-id] — Approve a pending permission request`,
2978
+ `/approve-always [request-id] — Always approve a pending permission request`,
2979
+ `/deny [request-id] — Deny a pending permission request`,
2806
2980
  ...(this.bridge.btw
2807
2981
  ? [
2808
- `${this.prefixedCommand('/btw <question>')} — Ask a side question without interrupting the current task`,
2982
+ `/btw <question> — Ask a side question without interrupting the current task`,
2809
2983
  ]
2810
2984
  : []),
2811
2985
  ...(this.namedSessions
2812
2986
  ? [
2813
- `${this.prefixedCommand('/sessions [all]')} — List your named tasks`,
2814
- `${this.prefixedCommand('/session current|new|use|close|cancel')} — Manage your named tasks`,
2987
+ `/sessions [all] — List your named tasks`,
2988
+ `/session current|new|use|close|cancel — Manage your named tasks`,
2815
2989
  ]
2816
2990
  : []),
2817
2991
  ];
@@ -2836,7 +3010,7 @@ export class ChannelBase {
2836
3010
  const platformCmds = [...this.commands.keys()].filter((c) => !sharedCmds.has(c));
2837
3011
  if (platformCmds.length > 0) {
2838
3012
  for (const cmd of platformCmds) {
2839
- lines.push(this.prefixedCommand(`/${cmd}`));
3013
+ lines.push(`/${cmd}`);
2840
3014
  }
2841
3015
  }
2842
3016
  const sessionId = await this.currentSessionId(envelope);
@@ -2850,12 +3024,10 @@ export class ChannelBase {
2850
3024
  if (agentCommands.length > 0) {
2851
3025
  lines.push('', 'Agent commands (forwarded to Qwen Code):');
2852
3026
  for (const cmd of agentCommands) {
2853
- lines.push(`${this.prefixedCommand(`/${cmd.name}`)} — ${cmd.description}`);
3027
+ lines.push(`/${cmd.name} — ${cmd.description}`);
2854
3028
  }
2855
3029
  }
2856
- lines.push('', this.messagePrefix
2857
- ? `Start each message with ${this.messagePrefix} to chat with the agent.`
2858
- : 'Send any text to chat with the agent.');
3030
+ lines.push('', 'Send any text to chat with the agent.');
2859
3031
  await this.sendThreadMessage(envelope.chatId, envelope.threadId, lines.join('\n'));
2860
3032
  return true;
2861
3033
  });
@@ -2906,7 +3078,7 @@ export class ChannelBase {
2906
3078
  case 'cancel':
2907
3079
  return this.handleLoopCancel(envelope, rest[0]);
2908
3080
  default:
2909
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/loop add "<cron>" <prompt>')} | ${this.prefixedCommand('/loop list')} | ${this.prefixedCommand('/loop inspect <id>')} | ${this.prefixedCommand('/loop cancel <id>')}`);
3081
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /loop add "<cron>" <prompt> | /loop list | /loop inspect <id> | /loop cancel <id>`);
2910
3082
  return true;
2911
3083
  }
2912
3084
  }
@@ -2923,7 +3095,7 @@ export class ChannelBase {
2923
3095
  }
2924
3096
  const parsed = parseLoopAddArgs(args);
2925
3097
  if (!parsed) {
2926
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/loop add "<cron>" <prompt>')}`);
3098
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /loop add "<cron>" <prompt>`);
2927
3099
  return true;
2928
3100
  }
2929
3101
  try {
@@ -3085,7 +3257,7 @@ export class ChannelBase {
3085
3257
  if (!this.loopController)
3086
3258
  return true;
3087
3259
  if (!id) {
3088
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/loop inspect <id>')}`);
3260
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /loop inspect <id>`);
3089
3261
  return true;
3090
3262
  }
3091
3263
  const jobs = await this.loopController.listForTarget(this.name, this.loopTargetFromEnvelope(envelope));
@@ -3146,7 +3318,7 @@ export class ChannelBase {
3146
3318
  if (!this.loopController)
3147
3319
  return true;
3148
3320
  if (!id) {
3149
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/loop cancel <id>')}`);
3321
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /loop cancel <id>`);
3150
3322
  return true;
3151
3323
  }
3152
3324
  const jobs = await this.loopController.listForTarget(this.name, this.loopTargetFromEnvelope(envelope));
@@ -3807,17 +3979,8 @@ export class ChannelBase {
3807
3979
  const active = this.activePrompts.get(sessionId);
3808
3980
  return active?.senderName || active?.senderId || target.senderId || 'agent';
3809
3981
  }
3810
- stopActiveStreaming(active, sessionId, reason) {
3811
- try {
3812
- active.stopStreaming?.();
3813
- }
3814
- catch (err) {
3815
- process.stderr.write(`[${this.name}] stopStreaming threw during ${reason} for session ${sessionId}: ${err instanceof Error ? err.message : err}\n`);
3816
- }
3817
- }
3818
3982
  /**
3819
- * Cancel the active turn and wait (bounded) for it to wind down. Stops the
3820
- * BlockStreamer so buffered text can't leak via the idle timer, then fires a
3983
+ * Cancel the active turn and wait (bounded) for it to wind down. Fires a
3821
3984
  * best-effort cancelSession (NOT awaited — a wedged child/daemon can leave the
3822
3985
  * request pending forever). Returns true if active.done settled first, false
3823
3986
  * if the CLEAR_CANCEL_TIMEOUT_MS bound won (the turn never wound down). Used by
@@ -3828,7 +3991,6 @@ export class ChannelBase {
3828
3991
  */
3829
3992
  async cancelAndAwaitActive(active, sessionId) {
3830
3993
  active.cancelled = true;
3831
- this.stopActiveStreaming(active, sessionId, 'cancel');
3832
3994
  // Fire-and-forget, but LOG the IPC failure: a swallowed reason leaves a
3833
3995
  // wedged turn undiagnosable (operator sees only the wind-down timeout below
3834
3996
  // with no cause).
@@ -4079,21 +4241,6 @@ export class ChannelBase {
4079
4241
  return `${GROUP_HISTORY_CONTEXT_MARKER}\n${formatted.join('\n')}\n\n${CURRENT_MESSAGE_MARKER}\n${promptText}`;
4080
4242
  }
4081
4243
  preflightInbound(envelope, options = {}) {
4082
- // Ahead of both pairing gates on purpose: a pairing request is a reply,
4083
- // and replying to every unprefixed message would be exactly the traffic
4084
- // the prefix exists to suppress. First contact carries the prefix too.
4085
- if (this.messagePrefixRejectedEnvelopes.has(envelope))
4086
- return false;
4087
- if (!this.messagePrefixCheckedEnvelopes.has(envelope)) {
4088
- this.messagePrefixCheckedEnvelopes.add(envelope);
4089
- if (!applyMessagePrefix(envelope, this.messagePrefix)) {
4090
- this.messagePrefixRejectedEnvelopes.add(envelope);
4091
- if (!(envelope.isGroup && !envelope.isMentioned && !envelope.isReplyToBot)) {
4092
- this.logPreflightRejected('message_prefix_mismatch');
4093
- }
4094
- return false;
4095
- }
4096
- }
4097
4244
  const groupResult = this.groupGate.check(envelope, {
4098
4245
  createPairingRequest: !options.deferPairingRequests,
4099
4246
  });
@@ -4157,9 +4304,6 @@ export class ChannelBase {
4157
4304
  logPreflightRejected(reason) {
4158
4305
  process.stderr.write(`[Channel:${this.name}] preflight rejected reason=${sanitizeLogText(reason, 80)}\n`);
4159
4306
  }
4160
- wasMessagePrefixRejected(envelope) {
4161
- return this.messagePrefixRejectedEnvelopes.has(envelope);
4162
- }
4163
4307
  logDebugPayload(platform, payload) {
4164
4308
  if (!isDebugPayloadEnabled(this.name))
4165
4309
  return;
@@ -4430,12 +4574,12 @@ export class ChannelBase {
4430
4574
  // same path it took before this interception existed.
4431
4575
  if (parsed.command === 'btw' && this.bridge.btw) {
4432
4576
  if (!this.isAuthorizedForSharedSession(envelope)) {
4433
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Only authorized members can use ${this.prefixedCommand('/btw')} in this shared session.`);
4577
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Only authorized members can use /btw in this shared session.`);
4434
4578
  return;
4435
4579
  }
4436
4580
  btwQuestion = parsed.args.trim();
4437
4581
  if (!btwQuestion) {
4438
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: ${this.prefixedCommand('/btw <question>')}`);
4582
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Usage: /btw <question>`);
4439
4583
  return;
4440
4584
  }
4441
4585
  if (btwQuestion.length > CHANNEL_BTW_MAX_INPUT_LENGTH) {
@@ -4443,7 +4587,7 @@ export class ChannelBase {
4443
4587
  return;
4444
4588
  }
4445
4589
  if (envelope.imageBase64 || envelope.attachments?.length) {
4446
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `${this.prefixedCommand('/btw')} supports text-only questions.`);
4590
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `/btw supports text-only questions.`);
4447
4591
  return;
4448
4592
  }
4449
4593
  }
@@ -4514,7 +4658,7 @@ export class ChannelBase {
4514
4658
  return;
4515
4659
  }
4516
4660
  if (!sessionId) {
4517
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `No task is currently selected. Use ${this.prefixedCommand('/session new <name>')} or ${this.prefixedCommand('/session use <name>')}.`);
4661
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `No task is currently selected. Use /session new <name> or /session use <name>.`);
4518
4662
  return;
4519
4663
  }
4520
4664
  }
@@ -4525,7 +4669,7 @@ export class ChannelBase {
4525
4669
  ? this.sourceLabelForTurn(sessionId, envelope)
4526
4670
  : undefined;
4527
4671
  if (this.namedSessions && !sourceLabel) {
4528
- await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Could not identify the selected task. Use ${this.prefixedCommand('/sessions')}, select it again, and retry.`);
4672
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, `Could not identify the selected task. Use /sessions, select it again, and retry.`);
4529
4673
  return;
4530
4674
  }
4531
4675
  if (btwQuestion !== undefined) {
@@ -4741,7 +4885,6 @@ export class ChannelBase {
4741
4885
  active.cancelled = true;
4742
4886
  if (firstCancellation) {
4743
4887
  process.stderr.write(`[${this.name}] steer: cancelled active turn for ${envelope.senderId} in session ${sessionId}\n`);
4744
- this.stopActiveStreaming(active, sessionId, 'steer');
4745
4888
  // Fire-and-forget, but LOG the IPC failure rather than swallow it, so a
4746
4889
  // best-effort cancel that fails isn't silently invisible to operators.
4747
4890
  void this.bridge.cancelSession(sessionId).catch((err) => {
@@ -4794,7 +4937,6 @@ export class ChannelBase {
4794
4937
  // keeps the generation captured when its buffer drained, so /clear cannot
4795
4938
  // resurrect it while preprocessing runs before this queue.
4796
4939
  const generation = namedTurn?.generation ?? this.sessionGenerations.get(sessionId) ?? 0;
4797
- const useBlockStreaming = this.config.blockStreaming === 'on';
4798
4940
  if (namedTurn) {
4799
4941
  namedTurn.claimed = true;
4800
4942
  }
@@ -4920,23 +5062,12 @@ export class ChannelBase {
4920
5062
  catch (err) {
4921
5063
  process.stderr.write(`[${this.name}] onPromptStart threw for session ${sessionId}: ${this.lifecycleError(err)}\n`);
4922
5064
  }
4923
- const streamer = useBlockStreaming
4924
- ? new BlockStreamer({
4925
- minChars: this.config.blockStreamingChunk?.minChars ?? 400,
4926
- maxChars: this.config.blockStreamingChunk?.maxChars ?? 1000,
4927
- idleMs: this.config.blockStreamingCoalesce?.idleMs ?? 1500,
4928
- send: (text) => this.sendResponseMessage(envelope.chatId, text, sessionId, sourceLabel),
4929
- })
4930
- : null;
4931
- promptState.stopStreaming = () => streamer?.stop();
4932
5065
  // Chunks arriving while a cancel is PENDING are held here: pushing them
4933
5066
  // to any visible sink could send output the cancel can't recall. On a
4934
5067
  // failed cancel they're replayed; on success, discarded.
4935
5068
  const heldChunks = [];
4936
- let hasStreamedText = false;
4937
5069
  const releaseHeldChunks = () => {
4938
5070
  for (const held of heldChunks.splice(0)) {
4939
- hasStreamedText = true;
4940
5071
  const segment = this.ensureOutputSegment(sessionId, promptState);
4941
5072
  this.emitTaskLifecycle({
4942
5073
  ...this.lifecycleBase(envelope.chatId, sessionId, envelope.messageId),
@@ -4944,7 +5075,6 @@ export class ChannelBase {
4944
5075
  chunk: held,
4945
5076
  });
4946
5077
  this.onResponseChunk(envelope.chatId, held, sessionId, segment);
4947
- streamer?.push(held);
4948
5078
  }
4949
5079
  };
4950
5080
  const onChunk = (sid, chunk) => {
@@ -4963,10 +5093,8 @@ export class ChannelBase {
4963
5093
  return;
4964
5094
  }
4965
5095
  heldChunks.length = 0;
4966
- hasStreamedText = false;
4967
5096
  const segment = this.closeOutputSegment(sessionId, promptState);
4968
5097
  void this.notifyOutputSegmentEnd(envelope.chatId, sessionId, segment, 'response_boundary');
4969
- streamer?.stop();
4970
5098
  };
4971
5099
  // Queue wait and memory recall can outlive a bridge crash. Capture the
4972
5100
  // bridge only after the latest recovery has restored session routing.
@@ -4988,18 +5116,10 @@ export class ChannelBase {
4988
5116
  // If cancelled, skip sending the response
4989
5117
  if (!promptState.cancelled && response) {
4990
5118
  promptState.deliveryStarted = true;
4991
- if (streamer) {
4992
- if (!hasStreamedText) {
4993
- streamer.push(response);
4994
- }
4995
- await streamer.flush();
4996
- }
4997
- else {
4998
- const segment = this.ensureOutputSegment(sessionId, promptState);
4999
- await this.onResponseComplete(envelope.chatId, response, sessionId, segment);
5000
- if (segment && promptState.activeSegmentId === segment.segmentId) {
5001
- promptState.activeSegmentId = undefined;
5002
- }
5119
+ const segment = this.ensureOutputSegment(sessionId, promptState);
5120
+ await this.onResponseComplete(envelope.chatId, response, sessionId, segment);
5121
+ if (segment && promptState.activeSegmentId === segment.segmentId) {
5122
+ promptState.activeSegmentId = undefined;
5003
5123
  }
5004
5124
  }
5005
5125
  // Once delivery started the turn's outcome is fixed — don't let a
@@ -5051,13 +5171,6 @@ export class ChannelBase {
5051
5171
  finally {
5052
5172
  promptBridge.off('textChunk', onChunk);
5053
5173
  promptBridge.off('responseBoundary', onResponseBoundary);
5054
- if (streamer) {
5055
- streamer.stop();
5056
- // Queued block sends belong to this turn: let them land before
5057
- // onPromptEnd settles turn-scoped adapter state, or a send racing
5058
- // the settle can recreate discarded state and leak unredacted text.
5059
- await streamer.drain();
5060
- }
5061
5174
  // Identity guard: a turn that wedged past /clear's bounded wait gets
5062
5175
  // EVICTED — /clear gives up on active.done, deletes activePrompts, and a
5063
5176
  // turn the user starts AFTER the clear can re-seed activePrompts (and own