@qwen-code/channel-base 0.23.1-preview.2 → 0.23.2-nightly.20260909.2e212144d3

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,14 +1,13 @@
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';
7
6
  import { GroupHistoryStore } from './group-history-store.js';
8
7
  import { SenderGate } from './SenderGate.js';
9
8
  import { PairingStore } from './PairingStore.js';
10
- import { SessionRouter } from './SessionRouter.js';
11
- import { NamedSessionManager, } from './named-session-manager.js';
9
+ import { SessionRouter, readDaemonHttpErrorCode } from './SessionRouter.js';
10
+ import { NamedSessionManager, NamedSessionTaskError, } from './named-session-manager.js';
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';
@@ -68,6 +67,48 @@ const SENSITIVE_PAYLOAD_KEY_PATTERN = new RegExp([
68
67
  function isRecord(value) {
69
68
  return value !== null && typeof value === 'object' && !Array.isArray(value);
70
69
  }
70
+ const PERMISSION_COPY = {
71
+ en: {
72
+ toolUse: 'Tool use',
73
+ allowOnce: 'Allow once',
74
+ allowAlwaysProject: 'always allow for this project',
75
+ allowAlwaysUser: 'always allow for this user',
76
+ allowAlways: 'always allow',
77
+ deny: 'Deny',
78
+ required: 'Permission required to run a tool',
79
+ request: 'Request:',
80
+ tool: 'Tool:',
81
+ action: 'Action:',
82
+ parameters: 'Parameters:',
83
+ replyWith: 'Reply with:',
84
+ },
85
+ zh: {
86
+ toolUse: '工具调用',
87
+ allowOnce: '仅允许本次',
88
+ allowAlwaysProject: '始终允许此项目',
89
+ allowAlwaysUser: '始终允许此用户',
90
+ allowAlways: '始终允许',
91
+ deny: '拒绝',
92
+ required: '运行工具需要授权',
93
+ request: '请求:',
94
+ tool: '工具:',
95
+ action: '操作:',
96
+ parameters: '参数:',
97
+ replyWith: '回复以下命令:',
98
+ },
99
+ };
100
+ /**
101
+ * Translate the stock prefix of a scoped always-allow label, keeping the
102
+ * command/tool scope that exec and mcp confirmations append to it.
103
+ */
104
+ function localizedScopedAlwaysLabel(label, stockLabel, localizedLabel) {
105
+ if (label === stockLabel)
106
+ return localizedLabel;
107
+ const scopeSeparator = ': ';
108
+ if (!label.startsWith(stockLabel + scopeSeparator))
109
+ return undefined;
110
+ return `${localizedLabel}:${label.slice(stockLabel.length + scopeSeparator.length)}`;
111
+ }
71
112
  /**
72
113
  * Character class (sans the enclosing `[]`) for a slash-command token: alphanumerics
73
114
  * plus `_`, `:` and `-`, so hyphenated and namespaced agent commands (e.g.
@@ -115,6 +156,7 @@ export class ChannelBase {
115
156
  proxy;
116
157
  /** Adapter-owned persistent state directory, when supplied by the runtime. */
117
158
  stateDir;
159
+ locale;
118
160
  channelMemory;
119
161
  memoryIntentClassifier;
120
162
  channelMemoryRecallObserver;
@@ -168,6 +210,9 @@ export class ChannelBase {
168
210
  bridgeSessionDiedListener = (event) => {
169
211
  this.onSessionDied(event.sessionId);
170
212
  };
213
+ bridgeDisconnectedListener = () => {
214
+ this.onBridgeDisconnected();
215
+ };
171
216
  bridgePermissionRequestListener = (event) => {
172
217
  void this.dispatchPermissionRequest(event).catch((err) => {
173
218
  process.stderr.write(`[${this.name}] permission relay failed for request ${sanitizeLogText(event.requestId, 128)}: ${this.lifecycleError(err)}\n`);
@@ -483,6 +528,10 @@ export class ChannelBase {
483
528
  if (presentation && (await presentation)) {
484
529
  return;
485
530
  }
531
+ const permissionPresentation = this.tryPresentPermission(pending);
532
+ if (permissionPresentation && (await permissionPresentation)) {
533
+ return;
534
+ }
486
535
  const text = this.formatPermissionRequest(pending);
487
536
  if (target.threadId !== undefined &&
488
537
  this.supportsProactiveSend() &&
@@ -573,6 +622,117 @@ export class ChannelBase {
573
622
  }
574
623
  })();
575
624
  }
625
+ tryPresentPermission(pending) {
626
+ const active = this.activePrompts.get(pending.sessionId);
627
+ const toolCall = pending.request.toolCall;
628
+ const meta = isRecord(toolCall['_meta']) ? toolCall['_meta'] : undefined;
629
+ const isUserQuestion = meta?.['qwenInteractionKind'] === 'user_question' ||
630
+ meta?.['toolName'] === 'ask_user_question' ||
631
+ toolCall['kind'] === 'ask_user_question';
632
+ const decisions = this.permissionPresentationDecisions(pending);
633
+ if (!active ||
634
+ active.loopPrompt ||
635
+ !active.owner ||
636
+ isUserQuestion ||
637
+ !decisions) {
638
+ return undefined;
639
+ }
640
+ const precedingSegment = this.closeOutputSegment(pending.sessionId, active, pending.target);
641
+ let respondInvoked = false;
642
+ const context = {
643
+ requestId: pending.requestId,
644
+ sessionId: pending.sessionId,
645
+ runId: active.runId,
646
+ owner: active.owner,
647
+ target: pending.target,
648
+ ...(precedingSegment
649
+ ? { precedingSegmentId: precedingSegment.segmentId }
650
+ : {}),
651
+ title: this.permissionTitle(pending.request.toolCall),
652
+ decisions,
653
+ onSettled: (listener) => {
654
+ if (pending.settled) {
655
+ listener(pending.settled);
656
+ return () => { };
657
+ }
658
+ pending.settlementListeners.add(listener);
659
+ return () => {
660
+ pending.settlementListeners.delete(listener);
661
+ };
662
+ },
663
+ respond: (decision) => {
664
+ const response = this.permissionPresentationResponse(pending, decision);
665
+ if (!response)
666
+ return Promise.resolve(false);
667
+ respondInvoked = true;
668
+ return this.respondToUserInput(pending, response);
669
+ },
670
+ };
671
+ pending.permissionPresented = true;
672
+ return (async () => {
673
+ try {
674
+ if (precedingSegment) {
675
+ await this.notifyOutputSegmentEnd(pending.target.chatId, pending.sessionId, precedingSegment, 'input_requested');
676
+ }
677
+ if (this.pendingPermissions.get(pending.requestId) !== pending) {
678
+ return true;
679
+ }
680
+ const result = await this.presentPermissionRequest(context);
681
+ if (this.pendingPermissions.get(pending.requestId) !== pending) {
682
+ return true;
683
+ }
684
+ if (result.kind === 'presented' ||
685
+ (result.kind === 'handled' && respondInvoked)) {
686
+ return true;
687
+ }
688
+ pending.permissionPresented = false;
689
+ return false;
690
+ }
691
+ catch (err) {
692
+ process.stderr.write(`[${this.name}] permission presentation failed for request ${sanitizeLogText(pending.requestId, 128)}: ${this.lifecycleError(err)}\n`);
693
+ if (this.pendingPermissions.get(pending.requestId) !== pending) {
694
+ return true;
695
+ }
696
+ pending.permissionPresented = false;
697
+ return false;
698
+ }
699
+ })();
700
+ }
701
+ permissionPresentationDecisions(pending) {
702
+ const allowOnce = this.approvalOption(pending);
703
+ if (!allowOnce)
704
+ return undefined;
705
+ const copy = PERMISSION_COPY[this.locale];
706
+ const allowAlways = this.approvalAlwaysOption(pending);
707
+ return [
708
+ {
709
+ kind: 'allow_once',
710
+ label: sanitizeQuotedText(this.permissionOptionLabel(allowOnce, copy.allowOnce), 80),
711
+ },
712
+ ...(allowAlways
713
+ ? [
714
+ {
715
+ kind: 'allow_always',
716
+ label: sanitizeQuotedText(allowAlways.label, 80),
717
+ },
718
+ ]
719
+ : []),
720
+ {
721
+ kind: 'deny',
722
+ label: sanitizeQuotedText(this.permissionOptionLabel(this.denialOption(pending), copy.deny), 80),
723
+ },
724
+ ];
725
+ }
726
+ permissionPresentationResponse(pending, decision) {
727
+ if (decision === 'deny')
728
+ return this.denialResponse(pending);
729
+ const optionId = decision === 'allow_once'
730
+ ? this.approvalOptionId(pending)
731
+ : this.approvalAlwaysOption(pending)?.optionId;
732
+ return optionId
733
+ ? { outcome: { outcome: 'selected', optionId } }
734
+ : undefined;
735
+ }
576
736
  normalizeUserQuestions(pending) {
577
737
  const toolCall = pending.request.toolCall;
578
738
  const meta = isRecord(toolCall['_meta']) ? toolCall['_meta'] : undefined;
@@ -636,7 +796,8 @@ export class ChannelBase {
636
796
  }
637
797
  async respondToUserInput(pending, response) {
638
798
  if (pending.responsePromise) {
639
- return pending.responsePromise;
799
+ await pending.responsePromise;
800
+ return false;
640
801
  }
641
802
  if (this.pendingPermissions.get(pending.requestId) !== pending ||
642
803
  !this.bridge.respondToPermission) {
@@ -696,6 +857,7 @@ export class ChannelBase {
696
857
  this.config = config;
697
858
  this.messagePrefix = config.messagePrefix?.trim() || undefined;
698
859
  this.bridge = bridge;
860
+ this.locale = options?.locale ?? 'en';
699
861
  this.proxy = options?.proxy;
700
862
  this.stateDir = options?.stateDir;
701
863
  this.identity = Object.freeze(this.resolveIdentity(name, config));
@@ -767,6 +929,9 @@ export class ChannelBase {
767
929
  async presentUserInputRequest(_context) {
768
930
  return { kind: 'unsupported' };
769
931
  }
932
+ async presentPermissionRequest(_context) {
933
+ return { kind: 'unsupported' };
934
+ }
770
935
  emitTaskLifecycle(event) {
771
936
  try {
772
937
  const result = this.onTaskLifecycle(event);
@@ -1731,7 +1896,6 @@ export class ChannelBase {
1731
1896
  return false;
1732
1897
  }
1733
1898
  active.cancelled = true;
1734
- this.stopActiveStreaming(active, sessionId, reason);
1735
1899
  this.dropCollectBuffer(sessionId);
1736
1900
  this.removePendingPermissionsForSession(sessionId, 'run_cancelled');
1737
1901
  this.emitTaskCancellation(active, sessionId, reason);
@@ -1807,11 +1971,19 @@ export class ChannelBase {
1807
1971
  this.unattendedMemorySessions.delete(sessionId);
1808
1972
  this.removePendingPermissionsForSession(sessionId);
1809
1973
  }
1974
+ /**
1975
+ * Called when the standalone ACP bridge process exits. Its in-flight turns
1976
+ * never settle, but crash recovery restores the sessions on a fresh bridge,
1977
+ * so overrides must clear only turn-scoped transient state (never session
1978
+ * routing) and must not fabricate terminal outcomes for interrupted turns.
1979
+ */
1980
+ onBridgeDisconnected() { }
1810
1981
  onSessionRetiring(_sessionId) { }
1811
1982
  attachBridgeEvents(bridge) {
1812
1983
  bridge.on('toolCall', this.bridgeToolCallListener);
1813
1984
  bridge.on('backgroundResponse', this.bridgeBackgroundResponseListener);
1814
1985
  bridge.on('sessionDied', this.bridgeSessionDiedListener);
1986
+ bridge.on('disconnected', this.bridgeDisconnectedListener);
1815
1987
  bridge.on('permissionRequest', this.bridgePermissionRequestListener);
1816
1988
  bridge.on('permissionResolved', this.bridgePermissionResolvedListener);
1817
1989
  }
@@ -1819,6 +1991,7 @@ export class ChannelBase {
1819
1991
  bridge.off('toolCall', this.bridgeToolCallListener);
1820
1992
  bridge.off('backgroundResponse', this.bridgeBackgroundResponseListener);
1821
1993
  bridge.off('sessionDied', this.bridgeSessionDiedListener);
1994
+ bridge.off('disconnected', this.bridgeDisconnectedListener);
1822
1995
  bridge.off('permissionRequest', this.bridgePermissionRequestListener);
1823
1996
  bridge.off('permissionResolved', this.bridgePermissionResolvedListener);
1824
1997
  }
@@ -2046,17 +2219,18 @@ export class ChannelBase {
2046
2219
  canEnvelopeAnswerPendingPermission(envelope, pending) {
2047
2220
  return (pending.target.chatId === envelope.chatId &&
2048
2221
  pending.target.threadId === envelope.threadId &&
2049
- (!pending.userInputPresented ||
2222
+ ((!pending.userInputPresented && !pending.permissionPresented) ||
2050
2223
  pending.target.senderId === envelope.senderId) &&
2051
2224
  (this.isSharedSessionTarget(pending.target) ||
2052
2225
  pending.target.senderId === envelope.senderId));
2053
2226
  }
2054
2227
  formatPermissionRequest(pending) {
2055
2228
  const { toolCall } = pending.request;
2229
+ const copy = PERMISSION_COPY[this.locale];
2056
2230
  const parameters = this.permissionParameterSummary(toolCall);
2057
- const approveLabel = this.permissionOptionLabel(this.approvalOption(pending), 'allow once');
2231
+ const approveLabel = this.permissionOptionLabel(this.approvalOption(pending), copy.allowOnce.toLocaleLowerCase(this.locale));
2058
2232
  const alwaysOption = this.approvalAlwaysOption(pending);
2059
- const denyLabel = this.permissionOptionLabel(this.denialOption(pending), 'deny');
2233
+ const denyLabel = this.permissionOptionLabel(this.denialOption(pending), copy.deny.toLocaleLowerCase(this.locale));
2060
2234
  const requestSuffix = pending.taskName ? ` ${pending.requestId}` : '';
2061
2235
  const replyPadding = pending.taskName
2062
2236
  ? { approve: ' ', always: ' ', deny: ' ' }
@@ -2071,14 +2245,14 @@ export class ChannelBase {
2071
2245
  `${this.prefixedCommand(`/deny${requestSuffix}`)}${replyPadding.deny}${denyLabel}`,
2072
2246
  ];
2073
2247
  return [
2074
- 'Permission required to run a tool',
2075
- ...(pending.taskName ? [`Request: ${pending.requestId}`] : []),
2248
+ copy.required,
2249
+ ...(pending.taskName ? [`${copy.request} ${pending.requestId}`] : []),
2076
2250
  '',
2077
- `Tool: ${this.permissionToolName(toolCall)}`,
2078
- `Action: ${this.permissionTitle(toolCall)}`,
2079
- ...(parameters ? [`Parameters: ${parameters}`] : []),
2251
+ `${copy.tool} ${this.permissionToolName(toolCall)}`,
2252
+ `${copy.action} ${this.permissionTitle(toolCall)}`,
2253
+ ...(parameters ? [`${copy.parameters} ${parameters}`] : []),
2080
2254
  '',
2081
- 'Reply with:',
2255
+ copy.replyWith,
2082
2256
  ...replies,
2083
2257
  ].join('\n');
2084
2258
  }
@@ -2090,7 +2264,8 @@ export class ChannelBase {
2090
2264
  }
2091
2265
  permissionTitle(toolCall) {
2092
2266
  const rawTitle = typeof toolCall.title === 'string' ? toolCall.title : undefined;
2093
- return sanitizeQuotedText(rawTitle || '', 160).trim() || 'Tool use';
2267
+ return (sanitizeQuotedText(rawTitle || '', 160).trim() ||
2268
+ PERMISSION_COPY[this.locale].toolUse);
2094
2269
  }
2095
2270
  permissionToolName(toolCall) {
2096
2271
  const rawToolCall = toolCall;
@@ -2134,7 +2309,31 @@ export class ChannelBase {
2134
2309
  permissionOptionLabel(option, fallback) {
2135
2310
  const rawLabel = typeof option?.name === 'string' ? option.name : '';
2136
2311
  const label = sanitizeQuotedText(rawLabel, 160).trim();
2137
- return label || fallback;
2312
+ if (!label)
2313
+ return fallback;
2314
+ return this.localizedPermissionOptionLabel(option, label) ?? label;
2315
+ }
2316
+ localizedPermissionOptionLabel(option, label) {
2317
+ if (this.locale !== 'zh')
2318
+ return undefined;
2319
+ const copy = PERMISSION_COPY[this.locale];
2320
+ if (option?.kind === 'allow_always') {
2321
+ if (option.optionId === 'proceed_always_project') {
2322
+ return localizedScopedAlwaysLabel(label, 'Always Allow in project', copy.allowAlwaysProject);
2323
+ }
2324
+ if (option.optionId === 'proceed_always_user') {
2325
+ return localizedScopedAlwaysLabel(label, 'Always Allow for user', copy.allowAlwaysUser);
2326
+ }
2327
+ if (option.optionId === 'proceed_always' && label === 'Allow All Edits') {
2328
+ return copy.allowAlways;
2329
+ }
2330
+ return undefined;
2331
+ }
2332
+ if (label === 'Allow' || label === 'Allow once')
2333
+ return copy.allowOnce;
2334
+ if (label === 'Deny' || label === 'Reject')
2335
+ return copy.deny;
2336
+ return undefined;
2138
2337
  }
2139
2338
  approvalOption(pending) {
2140
2339
  const options = pending.request.options;
@@ -2162,13 +2361,14 @@ export class ChannelBase {
2162
2361
  return options.find((option) => option.optionId === `proceed_always_${scope}`);
2163
2362
  }
2164
2363
  approvalAlwaysLabel(option) {
2364
+ const copy = PERMISSION_COPY[this.locale];
2165
2365
  if (option.optionId === 'proceed_always_project') {
2166
- return 'always allow for this project';
2366
+ return copy.allowAlwaysProject;
2167
2367
  }
2168
2368
  if (option.optionId === 'proceed_always_user') {
2169
- return 'always allow for this user';
2369
+ return copy.allowAlwaysUser;
2170
2370
  }
2171
- return 'always allow';
2371
+ return copy.allowAlways;
2172
2372
  }
2173
2373
  denialResponse(pending) {
2174
2374
  const option = this.denialOption(pending);
@@ -2253,9 +2453,10 @@ export class ChannelBase {
2253
2453
  }
2254
2454
  let accepted;
2255
2455
  try {
2256
- accepted = pending.userInputPresented
2257
- ? await this.respondToUserInput(pending, response)
2258
- : await this.bridge.respondToPermission(pending.requestId, response);
2456
+ accepted =
2457
+ pending.userInputPresented || pending.permissionPresented
2458
+ ? await this.respondToUserInput(pending, response)
2459
+ : await this.bridge.respondToPermission(pending.requestId, response);
2259
2460
  }
2260
2461
  catch (err) {
2261
2462
  this.removePendingPermission(pending.requestId);
@@ -2319,6 +2520,21 @@ export class ChannelBase {
2319
2520
  binding.released = true;
2320
2521
  this.releaseQueuedTurn(binding.sessionId);
2321
2522
  }
2523
+ /**
2524
+ * Follow a task onto the session its reload healed to (a superseded
2525
+ * redirect). The queue reservation and the staleness generation are keyed
2526
+ * by session id, so both must move with the binding: leaving them behind
2527
+ * keeps the stale id "busy" forever and drops the turn on a generation the
2528
+ * replacement never had.
2529
+ */
2530
+ moveNamedTurnBinding(binding, sessionId) {
2531
+ if (binding.sessionId !== null) {
2532
+ this.releaseQueuedTurn(binding.sessionId);
2533
+ }
2534
+ binding.sessionId = sessionId;
2535
+ binding.generation = this.sessionGenerations.get(sessionId) ?? 0;
2536
+ this.reserveQueuedTurn(sessionId);
2537
+ }
2322
2538
  finishNamedTurnBinding(envelope) {
2323
2539
  const binding = this.namedTurnBindings.get(envelope);
2324
2540
  if (!binding)
@@ -2379,13 +2595,67 @@ export class ChannelBase {
2379
2595
  return true;
2380
2596
  }
2381
2597
  }
2598
+ /**
2599
+ * The actionable recovery message for a worktree task whose ownership state
2600
+ * the daemon refused to restore. Both codes come from the load/resume route
2601
+ * — the reset route resumes an interrupted transfer itself and reports a
2602
+ * broken marker as invalid state — so they surface on selection and on a
2603
+ * message, wrapped in the manager's generic load failure.
2604
+ *
2605
+ * Clearing always acts on the *selected* task, so pointing the user at a
2606
+ * clear is only safe when the task that failed is the selected one. Aimed at
2607
+ * any other task it would run a full ownership transfer against a healthy
2608
+ * one and destroy that conversation, so the alternative points at the close
2609
+ * that works on the broken task without loading it. Both name that task.
2610
+ */
2611
+ async worktreeRecoveryMessage(envelope, error) {
2612
+ const code = readDaemonHttpErrorCode(error);
2613
+ if (code !== 'worktree_reset_interrupted' &&
2614
+ code !== 'worktree_marker_missing') {
2615
+ return undefined;
2616
+ }
2617
+ const interrupted = code === 'worktree_reset_interrupted';
2618
+ const failedTaskName = error instanceof NamedSessionTaskError ? error.taskName : undefined;
2619
+ // This message bypasses the wrapper's sanitizeDisplayText, so bound the one
2620
+ // piece of interpolated text it adds.
2621
+ const safeTaskName = failedTaskName === undefined
2622
+ ? undefined
2623
+ : sanitizeDisplayText(failedTaskName, 32);
2624
+ const subject = safeTaskName === undefined ? 'The task' : `Task "${safeTaskName}"`;
2625
+ const problem = interrupted
2626
+ ? 'was interrupted while being reset'
2627
+ : 'cannot verify its worktree because its ownership marker is missing';
2628
+ if (safeTaskName !== undefined &&
2629
+ failedTaskName === (await this.selectedTaskName(envelope))) {
2630
+ return `${subject} ${problem}. Its files were not changed. ${interrupted
2631
+ ? 'Clear the task again to finish the reset.'
2632
+ : 'Clear the task to restart it in the same worktree, or close it.'}`;
2633
+ }
2634
+ const remedy = safeTaskName === undefined
2635
+ ? 'select this task first or close it'
2636
+ : `select this task first or close it with ${this.prefixedCommand(`/session close ${safeTaskName}`)}`;
2637
+ return `${subject} ${problem}. Its files were not changed. Clearing now would reset the selected task instead, so ${remedy}.`;
2638
+ }
2639
+ async selectedTaskName(envelope) {
2640
+ const namedSessions = this.namedSessions;
2641
+ if (!namedSessions)
2642
+ return undefined;
2643
+ try {
2644
+ return (await namedSessions.current(this.namedSessionOwner(envelope)))
2645
+ ?.name;
2646
+ }
2647
+ catch {
2648
+ return undefined;
2649
+ }
2650
+ }
2382
2651
  async sendNamedSessionError(envelope, error) {
2383
2652
  if (error instanceof Error && error.cause !== undefined) {
2384
2653
  process.stderr.write(`[${sanitizeLogText(this.name, 64)}] named-session operation failed: ${this.lifecycleError(error)} | cause: ${this.lifecycleError(error.cause)}\n`);
2385
2654
  }
2386
- const message = error instanceof Error
2387
- ? sanitizeDisplayText(error.message, 500)
2388
- : 'Named-session operation failed.';
2655
+ const message = (await this.worktreeRecoveryMessage(envelope, error)) ??
2656
+ (error instanceof Error
2657
+ ? sanitizeDisplayText(error.message, 500)
2658
+ : 'Named-session operation failed.');
2389
2659
  await this.sendThreadMessage(envelope.chatId, envelope.threadId, message || 'Named-session operation failed.');
2390
2660
  }
2391
2661
  async handleNamedSessionsCommand(envelope, args) {
@@ -2436,7 +2706,8 @@ export class ChannelBase {
2436
2706
  ? 'worktree'
2437
2707
  : 'shared';
2438
2708
  if ((isolation === 'shared' && parts.length !== 1) ||
2439
- (isolation === 'worktree' && parts.length !== 2)) {
2709
+ (isolation === 'worktree' && parts.length !== 2) ||
2710
+ parts[0]?.startsWith('-')) {
2440
2711
  break;
2441
2712
  }
2442
2713
  const created = await namedSessions.create(owner, parts[0], isolation);
@@ -2506,6 +2777,7 @@ export class ChannelBase {
2506
2777
  registerSharedCommands() {
2507
2778
  const doClear = async (envelope) => {
2508
2779
  let resetTaskName;
2780
+ let resetWorktreeKept = false;
2509
2781
  let removedIds;
2510
2782
  const retiringSessionId = this.namedSessions
2511
2783
  ? undefined
@@ -2516,9 +2788,20 @@ export class ChannelBase {
2516
2788
  try {
2517
2789
  const reset = await this.namedSessions.reset(this.namedSessionOwner(envelope));
2518
2790
  resetTaskName = reset?.name;
2791
+ resetWorktreeKept = reset?.worktreeKept ?? false;
2519
2792
  removedIds = reset ? [reset.previousSessionId] : [];
2520
2793
  }
2521
2794
  catch (error) {
2795
+ // The reset route's busy signal has its own wording; every other
2796
+ // typed failure goes through the shared named-session surface.
2797
+ const code = readDaemonHttpErrorCode(error);
2798
+ if (code !== undefined) {
2799
+ process.stderr.write(`[${sanitizeLogText(this.name, 64)}] worktree reset failed (${sanitizeLogText(code, 64)}): ${this.lifecycleError(error)}\n`);
2800
+ }
2801
+ if (code === 'worktree_reset_active') {
2802
+ await this.sendThreadMessage(envelope.chatId, envelope.threadId, 'Task is busy. Wait for the running prompt to finish (or cancel it), then try again.');
2803
+ return;
2804
+ }
2522
2805
  await this.sendNamedSessionError(envelope, error);
2523
2806
  return;
2524
2807
  }
@@ -2621,7 +2904,9 @@ export class ChannelBase {
2621
2904
  this.discardRetiredSession(this.bridge, id, 'cleared');
2622
2905
  }
2623
2906
  await this.sendThreadMessage(envelope.chatId, envelope.threadId, resetTaskName
2624
- ? `Task "${resetTaskName}" reset with a fresh conversation.`
2907
+ ? resetWorktreeKept
2908
+ ? `Task "${resetTaskName}" reset with a fresh conversation; its worktree and files were kept.`
2909
+ : `Task "${resetTaskName}" reset with a fresh conversation.`
2625
2910
  : 'Session cleared. The next message starts a fresh conversation.');
2626
2911
  }
2627
2912
  else {
@@ -3711,17 +3996,8 @@ export class ChannelBase {
3711
3996
  const active = this.activePrompts.get(sessionId);
3712
3997
  return active?.senderName || active?.senderId || target.senderId || 'agent';
3713
3998
  }
3714
- stopActiveStreaming(active, sessionId, reason) {
3715
- try {
3716
- active.stopStreaming?.();
3717
- }
3718
- catch (err) {
3719
- process.stderr.write(`[${this.name}] stopStreaming threw during ${reason} for session ${sessionId}: ${err instanceof Error ? err.message : err}\n`);
3720
- }
3721
- }
3722
3999
  /**
3723
- * Cancel the active turn and wait (bounded) for it to wind down. Stops the
3724
- * BlockStreamer so buffered text can't leak via the idle timer, then fires a
4000
+ * Cancel the active turn and wait (bounded) for it to wind down. Fires a
3725
4001
  * best-effort cancelSession (NOT awaited — a wedged child/daemon can leave the
3726
4002
  * request pending forever). Returns true if active.done settled first, false
3727
4003
  * if the CLEAR_CANCEL_TIMEOUT_MS bound won (the turn never wound down). Used by
@@ -3732,7 +4008,6 @@ export class ChannelBase {
3732
4008
  */
3733
4009
  async cancelAndAwaitActive(active, sessionId) {
3734
4010
  active.cancelled = true;
3735
- this.stopActiveStreaming(active, sessionId, 'cancel');
3736
4011
  // Fire-and-forget, but LOG the IPC failure: a swallowed reason leaves a
3737
4012
  // wedged turn undiagnosable (operator sees only the wind-down timeout below
3738
4013
  // with no cause).
@@ -4391,8 +4666,10 @@ export class ChannelBase {
4391
4666
  return;
4392
4667
  }
4393
4668
  try {
4394
- const resumed = await this.namedSessions.resumeReserved(this.namedSessionOwner(envelope), namedTurn.sessionId);
4395
- sessionId = resumed ? namedTurn.sessionId : undefined;
4669
+ sessionId = await this.namedSessions.resumeReserved(this.namedSessionOwner(envelope), namedTurn.sessionId);
4670
+ if (sessionId && sessionId !== namedTurn.sessionId) {
4671
+ this.moveNamedTurnBinding(namedTurn, sessionId);
4672
+ }
4396
4673
  }
4397
4674
  catch (error) {
4398
4675
  await this.sendNamedSessionError(envelope, error);
@@ -4643,7 +4920,6 @@ export class ChannelBase {
4643
4920
  active.cancelled = true;
4644
4921
  if (firstCancellation) {
4645
4922
  process.stderr.write(`[${this.name}] steer: cancelled active turn for ${envelope.senderId} in session ${sessionId}\n`);
4646
- this.stopActiveStreaming(active, sessionId, 'steer');
4647
4923
  // Fire-and-forget, but LOG the IPC failure rather than swallow it, so a
4648
4924
  // best-effort cancel that fails isn't silently invisible to operators.
4649
4925
  void this.bridge.cancelSession(sessionId).catch((err) => {
@@ -4696,7 +4972,6 @@ export class ChannelBase {
4696
4972
  // keeps the generation captured when its buffer drained, so /clear cannot
4697
4973
  // resurrect it while preprocessing runs before this queue.
4698
4974
  const generation = namedTurn?.generation ?? this.sessionGenerations.get(sessionId) ?? 0;
4699
- const useBlockStreaming = this.config.blockStreaming === 'on';
4700
4975
  if (namedTurn) {
4701
4976
  namedTurn.claimed = true;
4702
4977
  }
@@ -4822,23 +5097,12 @@ export class ChannelBase {
4822
5097
  catch (err) {
4823
5098
  process.stderr.write(`[${this.name}] onPromptStart threw for session ${sessionId}: ${this.lifecycleError(err)}\n`);
4824
5099
  }
4825
- const streamer = useBlockStreaming
4826
- ? new BlockStreamer({
4827
- minChars: this.config.blockStreamingChunk?.minChars ?? 400,
4828
- maxChars: this.config.blockStreamingChunk?.maxChars ?? 1000,
4829
- idleMs: this.config.blockStreamingCoalesce?.idleMs ?? 1500,
4830
- send: (text) => this.sendResponseMessage(envelope.chatId, text, sessionId, sourceLabel),
4831
- })
4832
- : null;
4833
- promptState.stopStreaming = () => streamer?.stop();
4834
5100
  // Chunks arriving while a cancel is PENDING are held here: pushing them
4835
5101
  // to any visible sink could send output the cancel can't recall. On a
4836
5102
  // failed cancel they're replayed; on success, discarded.
4837
5103
  const heldChunks = [];
4838
- let hasStreamedText = false;
4839
5104
  const releaseHeldChunks = () => {
4840
5105
  for (const held of heldChunks.splice(0)) {
4841
- hasStreamedText = true;
4842
5106
  const segment = this.ensureOutputSegment(sessionId, promptState);
4843
5107
  this.emitTaskLifecycle({
4844
5108
  ...this.lifecycleBase(envelope.chatId, sessionId, envelope.messageId),
@@ -4846,7 +5110,6 @@ export class ChannelBase {
4846
5110
  chunk: held,
4847
5111
  });
4848
5112
  this.onResponseChunk(envelope.chatId, held, sessionId, segment);
4849
- streamer?.push(held);
4850
5113
  }
4851
5114
  };
4852
5115
  const onChunk = (sid, chunk) => {
@@ -4865,10 +5128,8 @@ export class ChannelBase {
4865
5128
  return;
4866
5129
  }
4867
5130
  heldChunks.length = 0;
4868
- hasStreamedText = false;
4869
5131
  const segment = this.closeOutputSegment(sessionId, promptState);
4870
5132
  void this.notifyOutputSegmentEnd(envelope.chatId, sessionId, segment, 'response_boundary');
4871
- streamer?.stop();
4872
5133
  };
4873
5134
  // Queue wait and memory recall can outlive a bridge crash. Capture the
4874
5135
  // bridge only after the latest recovery has restored session routing.
@@ -4890,18 +5151,10 @@ export class ChannelBase {
4890
5151
  // If cancelled, skip sending the response
4891
5152
  if (!promptState.cancelled && response) {
4892
5153
  promptState.deliveryStarted = true;
4893
- if (streamer) {
4894
- if (!hasStreamedText) {
4895
- streamer.push(response);
4896
- }
4897
- await streamer.flush();
4898
- }
4899
- else {
4900
- const segment = this.ensureOutputSegment(sessionId, promptState);
4901
- await this.onResponseComplete(envelope.chatId, response, sessionId, segment);
4902
- if (segment && promptState.activeSegmentId === segment.segmentId) {
4903
- promptState.activeSegmentId = undefined;
4904
- }
5154
+ const segment = this.ensureOutputSegment(sessionId, promptState);
5155
+ await this.onResponseComplete(envelope.chatId, response, sessionId, segment);
5156
+ if (segment && promptState.activeSegmentId === segment.segmentId) {
5157
+ promptState.activeSegmentId = undefined;
4905
5158
  }
4906
5159
  }
4907
5160
  // Once delivery started the turn's outcome is fixed — don't let a
@@ -4953,13 +5206,6 @@ export class ChannelBase {
4953
5206
  finally {
4954
5207
  promptBridge.off('textChunk', onChunk);
4955
5208
  promptBridge.off('responseBoundary', onResponseBoundary);
4956
- if (streamer) {
4957
- streamer.stop();
4958
- // Queued block sends belong to this turn: let them land before
4959
- // onPromptEnd settles turn-scoped adapter state, or a send racing
4960
- // the settle can recreate discarded state and leak unredacted text.
4961
- await streamer.drain();
4962
- }
4963
5209
  // Identity guard: a turn that wedged past /clear's bounded wait gets
4964
5210
  // EVICTED — /clear gives up on active.done, deletes activePrompts, and a
4965
5211
  // turn the user starts AFTER the clear can re-seed activePrompts (and own