@qwen-code/channel-base 0.27.2 → 0.27.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.
@@ -13,7 +13,7 @@ import { matchMessageRoute } from './message-routes.js';
13
13
  import { NamedSessionManager, NamedSessionTaskError, } from './named-session-manager.js';
14
14
  import { getGlobalQwenDir } from './paths.js';
15
15
  import { sanitizeSenderName, sanitizeQuotedText, sanitizePromptText, sanitizePromptPath, sanitizeLogText, sanitizeDisplayText, truncateCodePoints, PROMPT_UNSAFE_INVISIBLES, } from './sanitize.js';
16
- import { ChannelPromptCancelledError } from './ChannelAgentBridge.js';
16
+ import { BACKGROUND_WORKFLOW_APPROVAL_META_KEY, CHANNEL_WORKFLOW_ORIGIN_META_KEY, ChannelPromptCancelledError, parseChannelWorkflowOrigin, } from './ChannelAgentBridge.js';
17
17
  import { ChannelLoopSkippedError } from './ChannelLoopScheduler.js';
18
18
  import { buildChannelWebhookPrompt, resolveChannelWebhookTarget, } from './ChannelWebhookTask.js';
19
19
  import { parseChannelMemoryIntent, } from './channel-memory-intent.js';
@@ -226,6 +226,8 @@ export class ChannelBase {
226
226
  };
227
227
  pendingPermissions = new Map();
228
228
  pendingPermissionsByChat = new Map();
229
+ // A workflow may settle its approval while the named-task lookup awaits.
230
+ preparingWorkflowApprovals = new Set();
229
231
  channelLoopToolHandler = {
230
232
  canHandle: (sessionId) => this.router.getTarget(sessionId)?.channelName === this.name,
231
233
  create: (sessionId, input) => this.createLoopFromTool(sessionId, input),
@@ -257,17 +259,29 @@ export class ChannelBase {
257
259
  }
258
260
  this.onToolCall(chatId, event);
259
261
  }
260
- async dispatchBackgroundResponse(sessionId, text, _context) {
262
+ async dispatchBackgroundResponse(sessionId, text, context) {
261
263
  if (text.trim().length === 0)
262
264
  return;
265
+ if (context?.kind === 'workflow') {
266
+ const origin = context.channelWorkflowOrigin;
267
+ if (!origin)
268
+ return;
269
+ const delivery = await this.resolveBackgroundResponseDelivery(sessionId, origin);
270
+ if (!delivery || !this.workflowTarget(sessionId, origin))
271
+ return;
272
+ await this.deliverBackgroundResponseToTarget(sessionId, text, delivery);
273
+ return;
274
+ }
263
275
  const delivery = await this.resolveBackgroundResponseDelivery(sessionId);
264
276
  if (!delivery || this.router.getTarget(sessionId) !== delivery.target) {
265
277
  return;
266
278
  }
267
279
  await this.deliverBackgroundResponseToTarget(sessionId, text, delivery);
268
280
  }
269
- getBackgroundResponseSourceLabel(sessionId) {
270
- const target = this.router.getTarget(sessionId);
281
+ getBackgroundResponseSourceLabel(sessionId, workflowOrigin) {
282
+ const target = workflowOrigin
283
+ ? this.workflowTarget(sessionId, workflowOrigin)
284
+ : this.router.getTarget(sessionId);
271
285
  const presentation = this.namedSessions?.presentation(sessionId);
272
286
  if (!target ||
273
287
  target.channelName !== this.name ||
@@ -279,14 +293,17 @@ export class ChannelBase {
279
293
  }
280
294
  return this.createSourceLabel(presentation, target);
281
295
  }
282
- async resolveBackgroundResponseDelivery(sessionId) {
283
- let target = this.router.getTarget(sessionId);
296
+ async resolveBackgroundResponseDelivery(sessionId, workflowOrigin) {
297
+ const getTarget = () => workflowOrigin
298
+ ? this.workflowTarget(sessionId, workflowOrigin)
299
+ : this.router.getTarget(sessionId);
300
+ let target = getTarget();
284
301
  if (!target || target.channelName !== this.name)
285
302
  return undefined;
286
303
  let sourceLabel;
287
304
  if (this.namedSessions) {
288
305
  const presentation = await this.namedSessions.resolvePresentation(sessionId);
289
- const currentTarget = this.router.getTarget(sessionId);
306
+ const currentTarget = getTarget();
290
307
  const currentPresentation = this.namedSessions.presentation(sessionId);
291
308
  if (!presentation ||
292
309
  presentation.status !== 'open' ||
@@ -302,10 +319,18 @@ export class ChannelBase {
302
319
  target = currentTarget;
303
320
  sourceLabel = this.createSourceLabel(presentation, target);
304
321
  }
305
- return { target, sourceLabel };
322
+ return {
323
+ target,
324
+ sourceLabel,
325
+ ...(workflowOrigin ? { workflowOrigin } : {}),
326
+ };
306
327
  }
307
328
  async deliverBackgroundResponseToTarget(sessionId, text, delivery) {
308
- const { target, sourceLabel } = delivery;
329
+ const { target, sourceLabel, workflowOrigin } = delivery;
330
+ if (workflowOrigin && !workflowOrigin.userInitiated) {
331
+ await this.pushProactive(target, text, sourceLabel);
332
+ return;
333
+ }
309
334
  if (this.supportsProactiveSend() && this.supportsProactiveTarget(target)) {
310
335
  if (sourceLabel) {
311
336
  await this.pushProactive(target, text, sourceLabel);
@@ -315,6 +340,10 @@ export class ChannelBase {
315
340
  }
316
341
  return;
317
342
  }
343
+ if (workflowOrigin) {
344
+ await this.sendThreadMessage(target.chatId, target.threadId, text, sourceLabel);
345
+ return;
346
+ }
318
347
  if (sourceLabel) {
319
348
  await this.deliverBackgroundReply(target.chatId, text, sessionId, sourceLabel);
320
349
  }
@@ -456,7 +485,18 @@ export class ChannelBase {
456
485
  request.controller.abort();
457
486
  }
458
487
  async dispatchPermissionRequest(event) {
459
- const target = this.permissionTargetForEvent(event);
488
+ const backgroundWorkflow = event.request.toolCall._meta?.[BACKGROUND_WORKFLOW_APPROVAL_META_KEY] ===
489
+ true;
490
+ const workflowOrigin = backgroundWorkflow
491
+ ? parseChannelWorkflowOrigin(event.request.toolCall._meta?.[CHANNEL_WORKFLOW_ORIGIN_META_KEY])
492
+ : undefined;
493
+ if (backgroundWorkflow && workflowOrigin?.channelName !== this.name) {
494
+ return;
495
+ }
496
+ const getTarget = () => workflowOrigin
497
+ ? this.workflowTarget(event.sessionId, workflowOrigin)
498
+ : this.permissionTargetForEvent(event.sessionId);
499
+ const target = getTarget();
460
500
  if (!target) {
461
501
  try {
462
502
  await this.bridge.respondToPermission?.(event.requestId, {
@@ -472,10 +512,14 @@ export class ChannelBase {
472
512
  let taskName;
473
513
  if (this.namedSessions) {
474
514
  let presentation;
515
+ if (backgroundWorkflow) {
516
+ this.preparingWorkflowApprovals.add(event.requestId);
517
+ }
475
518
  try {
476
519
  presentation = await this.namedSessions.resolvePresentation(event.sessionId);
477
520
  }
478
521
  catch (err) {
522
+ this.preparingWorkflowApprovals.delete(event.requestId);
479
523
  try {
480
524
  await this.bridge.respondToPermission?.(event.requestId, {
481
525
  outcome: { outcome: 'cancelled' },
@@ -486,7 +530,11 @@ export class ChannelBase {
486
530
  }
487
531
  throw err;
488
532
  }
489
- const currentTarget = this.permissionTargetForEvent(event);
533
+ if (backgroundWorkflow &&
534
+ !this.preparingWorkflowApprovals.delete(event.requestId)) {
535
+ return;
536
+ }
537
+ const currentTarget = getTarget();
490
538
  const currentPresentation = this.namedSessions.presentation(event.sessionId);
491
539
  if (!presentation ||
492
540
  presentation.status !== 'open' ||
@@ -507,7 +555,9 @@ export class ChannelBase {
507
555
  }
508
556
  return;
509
557
  }
510
- const active = this.activePrompts.get(event.sessionId);
558
+ const active = backgroundWorkflow
559
+ ? undefined
560
+ : this.activePrompts.get(event.sessionId);
511
561
  sourceLabel = active
512
562
  ? active.sourceLabel
513
563
  : this.createSourceLabel(presentation, target);
@@ -528,8 +578,11 @@ export class ChannelBase {
528
578
  const pending = {
529
579
  requestId: event.requestId,
530
580
  sessionId: event.sessionId,
531
- runId: this.activePrompts.get(event.sessionId)?.runId,
581
+ runId: backgroundWorkflow
582
+ ? undefined
583
+ : this.activePrompts.get(event.sessionId)?.runId,
532
584
  target,
585
+ ...(workflowOrigin ? { workflowOrigin } : {}),
533
586
  request: event.request,
534
587
  ...(sourceLabel ? { sourceLabel } : {}),
535
588
  ...(taskName ? { taskName } : {}),
@@ -541,13 +594,15 @@ export class ChannelBase {
541
594
  requestIds.push(event.requestId);
542
595
  this.pendingPermissionsByChat.set(chatKey, requestIds);
543
596
  try {
544
- const presentation = this.tryPresentUserInput(pending);
545
- if (presentation && (await presentation)) {
546
- return;
547
- }
548
- const permissionPresentation = this.tryPresentPermission(pending);
549
- if (permissionPresentation && (await permissionPresentation)) {
550
- return;
597
+ if (!backgroundWorkflow) {
598
+ const presentation = this.tryPresentUserInput(pending);
599
+ if (presentation && (await presentation)) {
600
+ return;
601
+ }
602
+ const permissionPresentation = this.tryPresentPermission(pending);
603
+ if (permissionPresentation && (await permissionPresentation)) {
604
+ return;
605
+ }
551
606
  }
552
607
  const text = this.formatPermissionRequest(pending);
553
608
  if (target.threadId !== undefined &&
@@ -833,12 +888,37 @@ export class ChannelBase {
833
888
  });
834
889
  return pending.responsePromise;
835
890
  }
836
- permissionTargetForEvent(event) {
837
- const routeTarget = this.router.getTarget(event.sessionId);
891
+ workflowTarget(sessionId, origin) {
892
+ const routed = this.router.getTarget(sessionId);
893
+ if (origin.channelName !== this.name ||
894
+ routed?.channelName !== this.name ||
895
+ (origin.messageRoute !== undefined &&
896
+ !this.messageRoutes.has(origin.messageRoute)) ||
897
+ !this.router.isSessionLive(sessionId)) {
898
+ return undefined;
899
+ }
900
+ if (this.namedSessions) {
901
+ return this.sameTaskOwner(origin, routed) ? origin : undefined;
902
+ }
903
+ if (this.router.getSession(this.name, origin.senderId, origin.chatId, origin.threadId, origin.messageRoute) === sessionId) {
904
+ return origin;
905
+ }
906
+ // Webhook sessions can have a synthetic routing key while retaining the
907
+ // actual delivery target.
908
+ if (!origin.userInitiated &&
909
+ this.sameTaskOwner(origin, routed) &&
910
+ origin.threadId === routed.threadId &&
911
+ origin.messageRoute === routed.messageRoute) {
912
+ return origin;
913
+ }
914
+ return undefined;
915
+ }
916
+ permissionTargetForEvent(sessionId) {
917
+ const routeTarget = this.router.getTarget(sessionId);
838
918
  if (!routeTarget || routeTarget.channelName !== this.name) {
839
919
  return undefined;
840
920
  }
841
- const active = this.activePrompts.get(event.sessionId);
921
+ const active = this.activePrompts.get(sessionId);
842
922
  if (!active) {
843
923
  return routeTarget;
844
924
  }
@@ -859,6 +939,7 @@ export class ChannelBase {
859
939
  return target;
860
940
  }
861
941
  dispatchPermissionResolved(event) {
942
+ this.preparingWorkflowApprovals.delete(event.requestId);
862
943
  const pending = this.pendingPermissions.get(event.requestId);
863
944
  if (!pending) {
864
945
  return;
@@ -1171,6 +1252,9 @@ export class ChannelBase {
1171
1252
  supportsProactiveWebhookTarget(target) {
1172
1253
  return this.supportsProactiveTarget(target);
1173
1254
  }
1255
+ canDeliverBackgroundWorkflow(_target) {
1256
+ return true;
1257
+ }
1174
1258
  async pushProactive(target, text, sourceLabel) {
1175
1259
  if (target.threadId) {
1176
1260
  throw new Error('Channel does not support proactive loop messages for threaded targets.');
@@ -1551,7 +1635,7 @@ export class ChannelBase {
1551
1635
  promptBridge.on('textChunk', onChunk);
1552
1636
  promptBridge.on('responseBoundary', onResponseBoundary);
1553
1637
  try {
1554
- const response = await this.runLoopBridgePrompt(promptBridge, sessionId, promptToSend, promptState, job.id, options.timeoutMs);
1638
+ const response = await this.runLoopBridgePrompt(promptBridge, sessionId, promptToSend, promptState, job.target, job.id, options.timeoutMs);
1555
1639
  await this.settleCancelRequested(promptState);
1556
1640
  if (promptState.cancelled) {
1557
1641
  throw new ChannelLoopSkippedError('loop cancelled before delivery', 'cancel_command');
@@ -1779,7 +1863,7 @@ export class ChannelBase {
1779
1863
  const promptBridge = this.bridge;
1780
1864
  promptBridge.on('textChunk', onChunk);
1781
1865
  try {
1782
- const response = await this.runLoopBridgePrompt(promptBridge, sessionId, promptToSend, promptState, taskId, options.timeoutMs);
1866
+ const response = await this.runLoopBridgePrompt(promptBridge, sessionId, promptToSend, promptState, target, taskId, options.timeoutMs);
1783
1867
  await this.settleCancelRequested(promptState);
1784
1868
  if (promptState.cancelled) {
1785
1869
  throw new ChannelLoopSkippedError('webhook task cancelled before delivery', 'cancel_command');
@@ -1853,9 +1937,10 @@ export class ChannelBase {
1853
1937
  webhookRoutingThreadId(task, target) {
1854
1938
  return `webhook:${task.source}:${target.threadId ?? target.chatId}`;
1855
1939
  }
1856
- async runLoopBridgePrompt(promptBridge, sessionId, promptText, promptState, jobId, timeoutMs) {
1940
+ async runLoopBridgePrompt(promptBridge, sessionId, promptText, promptState, workflowOrigin, jobId, timeoutMs) {
1857
1941
  const prompt = promptBridge.prompt(sessionId, promptText, {
1858
1942
  displayText: sanitizeDisplayText(promptText),
1943
+ workflowOrigin,
1859
1944
  });
1860
1945
  prompt.catch(() => { });
1861
1946
  if (timeoutMs === undefined) {
@@ -1965,7 +2050,9 @@ export class ChannelBase {
1965
2050
  }
1966
2051
  active.cancelled = true;
1967
2052
  this.dropCollectBuffer(sessionId);
1968
- this.removePendingPermissionsForSession(sessionId, 'run_cancelled');
2053
+ this.removePendingPermissionsForSession(sessionId, 'run_cancelled', {
2054
+ preserveBackgroundWorkflows: reason !== 'clear',
2055
+ });
1969
2056
  this.emitTaskCancellation(active, sessionId, reason);
1970
2057
  return true;
1971
2058
  });
@@ -2227,15 +2314,18 @@ export class ChannelBase {
2227
2314
  this.pendingPermissionsByChat.set(chatKey, remaining);
2228
2315
  }
2229
2316
  }
2230
- removePendingPermissionsForSession(sessionId, reason = 'cancelled') {
2317
+ removePendingPermissionsForSession(sessionId, reason = 'cancelled', options) {
2231
2318
  const requestIds = Array.from(this.pendingPermissions)
2232
- .filter(([, pending]) => pending.sessionId === sessionId)
2319
+ .filter(([, pending]) => pending.sessionId === sessionId &&
2320
+ (!options?.preserveBackgroundWorkflows ||
2321
+ pending.request.toolCall._meta?.[BACKGROUND_WORKFLOW_APPROVAL_META_KEY] !== true))
2233
2322
  .map(([requestId]) => requestId);
2234
2323
  for (const requestId of requestIds) {
2235
2324
  this.removePendingPermission(requestId, reason);
2236
2325
  }
2237
2326
  }
2238
2327
  clearPendingPermissions() {
2328
+ this.preparingWorkflowApprovals.clear();
2239
2329
  for (const requestId of Array.from(this.pendingPermissions.keys())) {
2240
2330
  this.removePendingPermission(requestId, 'cancelled');
2241
2331
  }
@@ -2302,7 +2392,15 @@ export class ChannelBase {
2302
2392
  return { kind: 'found', pending: matching[0] };
2303
2393
  }
2304
2394
  canEnvelopeAnswerPendingPermission(envelope, pending, requireOwner) {
2305
- if (requireOwner) {
2395
+ const origin = pending.workflowOrigin;
2396
+ if (origin) {
2397
+ if (!this.workflowTarget(pending.sessionId, origin) ||
2398
+ (requireOwner &&
2399
+ (!origin.userInitiated || origin.senderId !== envelope.senderId))) {
2400
+ return false;
2401
+ }
2402
+ }
2403
+ else if (requireOwner) {
2306
2404
  const active = this.activePrompts.get(pending.sessionId);
2307
2405
  if (!active ||
2308
2406
  pending.runId !== active.runId ||
@@ -5162,7 +5260,7 @@ export class ChannelBase {
5162
5260
  // turn at the channel level (cancelled is already set above), so
5163
5261
  // the event reflects that intent, not the bridge RPC outcome.
5164
5262
  this.emitTaskCancellation(active, sessionId, 'steer');
5165
- this.removePendingPermissionsForSession(sessionId, 'run_cancelled');
5263
+ this.removePendingPermissionsForSession(sessionId, 'run_cancelled', { preserveBackgroundWorkflows: true });
5166
5264
  }
5167
5265
  // Diagnostic watchdog: if the predecessor turn is STILL the active prompt
5168
5266
  // after the wind-down bound, this steered turn is wedged behind a hung
@@ -5389,7 +5487,22 @@ export class ChannelBase {
5389
5487
  if (!this.canStartInboundTurn()) {
5390
5488
  throw new ChannelPromptCancelledError();
5391
5489
  }
5490
+ const workflowTarget = {
5491
+ channelName: this.name,
5492
+ chatId: envelope.chatId,
5493
+ threadId: envelope.threadId,
5494
+ senderId: envelope.senderId,
5495
+ isGroup: envelope.isGroup,
5496
+ messageRoute: envelope.messageRoute,
5497
+ };
5392
5498
  let response = await promptBridge.prompt(sessionId, promptToSend, {
5499
+ workflowOrigin: {
5500
+ ...workflowTarget,
5501
+ userInitiated: true,
5502
+ ...(!this.canDeliverBackgroundWorkflow(workflowTarget)
5503
+ ? { backgroundWorkflowBlocked: true }
5504
+ : {}),
5505
+ },
5393
5506
  ...(this.config.outputMode === 'per_task'
5394
5507
  ? {
5395
5508
  outputMode: 'per_task',