-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathSession.ts
More file actions
12527 lines (11894 loc) · 454 KB
/
Copy pathSession.ts
File metadata and controls
12527 lines (11894 loc) · 454 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { Buffer } from 'node:buffer';
import { randomUUID } from 'node:crypto';
import { realpathSync, statSync } from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import type {
Content,
FunctionCall,
GenerateContentResponseUsageMetadata,
Part,
} from '@google/genai';
import type {
Config,
GeminiChat,
ToolCallConfirmationDetails,
ToolConfirmationPayload,
ToolResult,
ToolResultDisplay,
ShellProgressData,
ChatRecord,
HistoryGap,
AgentEventEmitter,
StopHookOutput,
HookExecutionRequest,
HookExecutionResponse,
MessageBus,
StreamEvent,
ChatCompressionInfo,
AutoModeDecision,
AutoModeOutcome,
GoalRecord,
GoalRuntime,
GoalSnapshotV2,
GoalStateCause,
GoalTurnHost,
GoalTurnPermit,
ToolCallRequestInfo,
ToolCallResponseInfo,
ToolExecutionStatus,
LoopTickResult,
ToolArtifact,
VisionBridgeResult,
MemoryWriteCandidate,
CronTaskDelivery,
InvocationContextV1,
ChatRecordingService,
TurnResultRecordPayload,
WorkflowApproval,
BranchPoint,
} from '@qwen-code/qwen-code-core';
import {
AuthType,
ApprovalMode,
CompressionStatus,
detectLoopSentinel,
detectAutonomousSentinel,
LoopTickResolver,
convertToFunctionErrorResponse,
convertToFunctionResponse,
createDuplicateProviderToolCallResponse,
findPlanModeEntryBatchBoundaryIndex,
findRepeatedDuplicateProviderToolCall,
findRestorableAskUserQuestion,
restorableAskUserQuestionCallIds,
markDuplicateProviderToolCallResponseSent,
PLAN_MODE_ENTRY_SIBLING_SKIP_MESSAGE,
createDebugLogger,
DiscoveredMCPTool,
StreamEventType,
ToolConfirmationOutcome,
generatePromptSuggestion,
logPromptSuggestion,
logToolCall,
logUserPrompt,
PromptSuggestionEvent,
getErrorStatus,
UserPromptEvent,
readManyFiles,
getSpecificMimeType,
clampInlineMediaPart,
Storage,
Kind,
ToolNames,
ToolErrorType,
fireNotificationHook,
firePermissionRequestHook,
firePreToolUseHook,
firePostToolUseHook,
firePostToolUseFailureHook,
buildContextUsage,
injectPermissionRulesIfMissing,
NotificationType,
persistPermissionOutcome,
createHookOutput,
wrapUserPromptSubmitContext,
generateToolUseId,
MessageBusType,
MessageDisplayDispatcher,
getPlanModeSystemReminder,
getArenaSystemReminder,
getStartupContextLength,
isSystemReminderContent,
buildSessionRecoveryPlanFromApiHistory,
TURN_INTERRUPTION_HISTORY_TAIL_COUNT,
evaluatePermissionFlow,
buildPermissionCheckContext,
evaluateToolInvocationGuard,
getEffectivePermissionForConfirmation,
needsConfirmation,
isPlanModeBlocked,
decoratePlanModeShellConfirmation,
evaluatePlanModeShellPolicy,
validatePlanModeShellApproval,
validatePlanModeShellContext,
abortGoalForStopHookCap,
getStopHookContinuationReason,
formatStopHookBlockingCapWarning,
applyAutoModeDecision,
decorateClassifierUnavailableConfirmation,
evaluateAutoMode,
getAutoModePermissionDeniedReason,
isApproveOutcome,
isDenialFallbackReason,
MAX_TRANSCRIPT_MESSAGES,
formatDenialStateLog,
recordAllow,
recordFallbackApprove,
shouldFallback,
shouldClassifyAllShellForAutoMode,
finalizeToolResponses,
shouldForceAutoModeReviewForAllow,
shouldFirePermissionDeniedForAutoMode,
shouldRunAutoModeForCall,
extractDaemonTraceContext,
addAgentInputMessageAttributes,
AgentOutputMessageCapture,
getActiveInteractionSpan,
withInteractionSpan,
SessionWriterError,
startToolSpan,
endToolSpan,
addToolArgumentsAttributes,
addToolCallResultAttributes,
runInToolSpanContext,
startToolExecutionSpan,
endToolExecutionSpan,
isShellProgressData,
logConversationFinishedEvent,
ConversationFinishedEvent,
GLOBAL_DUPLICATE_THRESHOLD,
canonicalToolName,
getToolCallRepeatKey,
shouldHaltOnTurnToolCallCap,
logLoopDetected,
logRepeatedToolFailureGuard,
LoopDetectedEvent,
LoopType,
RepeatedToolFailureGuardEvent,
acquireSleepInhibitor,
didWriteProjectContextFile,
refreshMemoryAfterManagedWrite,
refreshMemoryInstruction,
GoalPersistenceUnavailableError,
goalTurnContext,
sessionIdContext,
promptIdContext,
todoWorkChainContext,
dedupeToolCallsById,
getFunctionCallFingerprint,
getProviderToolCallId,
isReplayOfHandledToolCall,
recordHandledToolCall,
parsePositiveIntegerEnv,
DEFAULT_TOKEN_LIMIT,
hasImageParts,
normalizeParts,
runVisionBridge,
bridgeToolResultImages,
shouldRunVisionBridge,
formatVisionBridgeNotice,
formatFullTurnVisionNotice,
getFullTurnVisionModelSelector,
splitImageParts,
approxBase64Bytes,
normalizeTurnResultError,
TURN_RESULT_CODE_TEXT_TRUNCATED,
TURN_RESULT_TEXT_MAX_CHARS,
runWithRuntimeContentGenerator,
observeToolResultBoundary,
toolResultBoundaryArtifact,
toolResultPartDiagnosticValues,
getInvocationContext,
runWithInvocationContext,
truncateNotificationLabel,
buildBackgroundEntryLabel,
collectSessionTurnState,
computeInitialTurnFromHistory as computeInitialTurnFromHistoryCore,
} from '@qwen-code/qwen-code-core';
import { NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE } from '@qwen-code/acp-bridge/bridgeErrors';
import { CHANNEL_PROMPT_META_KEY } from '@qwen-code/channel-base';
import { ENV_ACP_REPEATED_TOOL_FAILURE_GUARD } from '../../config/shared-env-keys.js';
// Single source of truth shared with the daemon-side answerer (BridgeClient),
// so a rename can't desync caller and answerer into a silent -32601 latch.
import {
type ActiveWorkHoldV1,
DAEMON_CHANNEL_DELIVERY_META_KEY,
DAEMON_ATTACHMENT_REFERENCES_META_KEY,
DAEMON_PERMISSION_CANCEL_REASON_META_KEY,
DAEMON_PROMPT_DISPLAY_TEXT_META_KEY,
DAEMON_RESTORE_ASK_USER_QUESTION_META_KEY,
MID_TURN_QUEUE_DRAIN_METHOD,
isValidTrustedModelPrompt,
TODO_STOP_GUARD_CONTINUATION_CLAIM_METHOD,
} from '@qwen-code/acp-bridge/bridgeTypes';
import type { SessionAttachmentReference } from '@qwen-code/acp-bridge/sessionAttachments';
import { SERVE_CONTROL_EXT_METHODS } from '@qwen-code/acp-bridge/status';
import { getCommandSubcommandNames } from '../../services/commandMetadata.js';
import { cleanupReviewWorktreeLeases } from '../../services/review-worktree-lease.js';
import { getEffectiveSupportedModes } from '../../services/commandUtils.js';
import { normalizeChannelDeliveryText } from '../../runtime/channel-delivery.js';
import {
CAPTURE_SCREEN_CONTEXT_TOOL_NAME,
CaptureScreenContextTool,
} from '../live/capture-screen-context.js';
import {
createLiveTaskTools,
type LiveTaskTool,
} from '../live/live-task-tools.js';
import {
SPEAK_TO_USER_TOOL_NAME,
SpeakToUserTool,
} from '../live/live-speak-to-user.js';
import {
LIVE_BACKEND_END_INSTRUCTIONS,
LIVE_BACKEND_START_INSTRUCTIONS,
} from '../live/live-backend-instructions.js';
import { readVoiceModel } from '../../services/voice-settings.js';
import {
MAX_AUDIO_BYTES,
sanitizeVoiceErrorMessage,
transcribeVoiceAudio,
} from '../../services/voice-transcriber.js';
import {
inactiveExtensionSkillRefs,
isInactiveExtensionSkill,
} from '../extension-skills.js';
import { RequestError } from '@agentclientprotocol/sdk';
import type {
AvailableCommand,
ContentBlock,
EmbeddedResourceResource,
PromptRequest,
PromptResponse,
RequestPermissionRequest,
RequestPermissionResponse,
SessionNotification,
SessionUpdate,
SetSessionModeRequest,
SetSessionModeResponse,
SetSessionModelRequest,
SetSessionModelResponse,
AgentSideConnection,
} from '@agentclientprotocol/sdk';
import { SettingScope, type LoadedSettings } from '../../config/settings.js';
import { insertAfterFunctionResponses } from '../../nonInteractive/nonInteractiveHelpers.js';
import { normalizePartList } from '../../utils/normalize-part-list.js';
import { prefixMidTurnUserMessageParts } from '../../utils/midTurnUserMessage.js';
import {
handleSlashCommand,
getAvailableCommands,
type NonInteractiveSlashCommandResult,
} from '../../nonInteractiveCliCommands.js';
import {
getSlashCommandFirstToken,
isSlashCommand,
} from '../../ui/utils/commandUtils.js';
import {
collectGoalStatusItemsFromRecords,
findGoalToRestore,
} from '../../ui/utils/restoreGoal.js';
import { CommandKind } from '../../ui/commands/types.js';
import { extractAtPathCommands } from '../../ui/hooks/atCommandProcessor.js';
import {
ACP_ROUTE_ID_PREFIX,
buildAcpModelOptions,
getCurrentAcpModelId,
parseAcpModelOption,
resolveAcpModelOption,
} from '../../utils/acpModelUtils.js';
import { classifyApiError } from '../../utils/classify-api-error.js';
import { getPersistScopeForModelSelection } from '../../config/modelProvidersScope.js';
import { writeStderrLine } from '../../utils/stdioHelpers.js';
import {
buildExtensionMentionContext,
EXTENSION_CONTEXT_BUDGET,
matchExtensionByRef,
parseExtensionRef,
} from '../../utils/extension-mention.js';
import {
buildMcpServerContextText,
matchMcpServerByRef,
parseMcpServerRef,
} from '../../utils/mcp-server-mention.js';
// Import modular session components
import type {
ApprovalModeValue,
CumulativeUsage,
SessionContext,
ToolCallStartParams,
} from './types.js';
import { HistoryReplayer } from './history-replayer.js';
import { projectAcpToolResultUpdate } from './acp-tool-result-text-projection.js';
import { observeAcpToolResultProjection } from '../../nonInteractive/tool-result-boundary-diagnostics.js';
import { ToolCallEmitter } from './emitters/tool-call-emitter.js';
import { ToolCallPreparationTracker } from './tool-call-preparation-tracker.js';
import { PlanEmitter } from './emitters/PlanEmitter.js';
import { MessageEmitter } from './emitters/MessageEmitter.js';
import type { HistoryItemGoalStatus } from '../../ui/types.js';
import {
goalPublicationKey,
renderPreparedGoalUpdate,
} from './recovered-goal-update.js';
import { SubAgentTracker } from './SubAgentTracker.js';
import {
buildPermissionRequestContent,
interactionMetaFields,
requestPermissionWithAbort,
resolvePermissionOutcome,
toPermissionOptions,
} from './permissionUtils.js';
import {
MessageRewriteMiddleware,
loadRewriteConfig,
} from './rewrite/index.js';
import {
DaemonTodoStopGuard,
type TodoStopGuardContinuation,
} from './daemon-todo-stop-guard.js';
import {
createRepeatedToolFailureGuardState,
reduceRepeatedToolFailureGuard,
REPEATED_TOOL_FAILURE_REMINDER,
REPEATED_TOOL_FAILURE_STOP_MESSAGE,
parseRepeatedToolFailureGuardMode,
type RepeatedToolFailureBatch,
type RepeatedToolFailureGuardMode,
type RepeatedToolFailureGuardDecision,
type RepeatedToolFailureGuardState,
} from './repeated-tool-failure-guard.js';
const debugLogger = createDebugLogger('SESSION');
const permissionRequestTails = new WeakMap<
AgentSideConnection,
Promise<void>
>();
const USER_CANCEL_ABORT_REASON = 'qwen:user-cancel';
const NEW_PROMPT_ABORT_REASON = 'qwen:new-prompt';
const SESSION_DISPOSE_ABORT_REASON = 'qwen:session-dispose';
const DAEMON_RETRY_META_KEY = 'qwen.daemon.retry';
const DAEMON_CONTINUE_META_KEY = 'qwen.daemon.continueLastTurn';
const MAX_DAEMON_ATTACHMENT_REFERENCES = 256;
function readDaemonAttachmentReferences(
value: unknown,
): SessionAttachmentReference[] | undefined {
if (
!Array.isArray(value) ||
value.length === 0 ||
value.length > MAX_DAEMON_ATTACHMENT_REFERENCES
) {
return undefined;
}
const references: SessionAttachmentReference[] = [];
for (const item of value) {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
return undefined;
}
const reference = item as Record<string, unknown>;
if (
(reference['type'] !== 'image' && reference['type'] !== 'resource') ||
typeof reference['attachmentId'] !== 'string' ||
reference['attachmentId'].length === 0 ||
reference['attachmentId'].length > 255 ||
typeof reference['mimeType'] !== 'string' ||
reference['mimeType'].length === 0 ||
reference['mimeType'].length > 128 ||
typeof reference['size'] !== 'number' ||
!Number.isSafeInteger(reference['size']) ||
reference['size'] < 0 ||
(reference['type'] === 'image' && reference['size'] === 0)
) {
return undefined;
}
references.push({
type: reference['type'],
attachmentId: reference['attachmentId'],
mimeType: reference['mimeType'],
size: reference['size'],
});
}
return references;
}
const TODO_STOP_GUARD_PROMPT_PREFIX = '[Todo Stop Guard] ';
const TODO_STOP_GUARD_PROMPT_BODY_SUFFIX =
' todo item(s) are still pending or in progress. Continue executing the current task now. Do not ask the user whether to continue. If progress requires user input, use the structured question or permission flow. If progress depends on external state, report the blocker explicitly.';
const TODO_STOP_GUARD_FINAL_PROMPT_SUFFIX =
' This is the final automatic continuation. Before ending, either complete/update the todos or report the completed progress and the exact blocker.';
// Content has no private metadata slot, so history cleanup recognizes only
// these exact templates; byte-identical user text is intentionally ambiguous.
function isTodoStopGuardPromptText(text: unknown): text is string {
if (typeof text !== 'string') return false;
if (!text.startsWith(TODO_STOP_GUARD_PROMPT_PREFIX)) return false;
const remainder = text.slice(TODO_STOP_GUARD_PROMPT_PREFIX.length);
const separator = remainder.indexOf(' ');
if (separator <= 0) return false;
const countText = remainder.slice(0, separator);
const count = Number(countText);
if (
!Number.isSafeInteger(count) ||
count <= 0 ||
String(count) !== countText
) {
return false;
}
const body = `${countText}${TODO_STOP_GUARD_PROMPT_BODY_SUFFIX}`;
return (
remainder === body ||
remainder === body + TODO_STOP_GUARD_FINAL_PROMPT_SUFFIX
);
}
function isCompressionFailureStatus(status: CompressionStatus): boolean {
return (
status === CompressionStatus.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT ||
status === CompressionStatus.COMPRESSION_FAILED_TOKEN_COUNT_ERROR ||
status === CompressionStatus.COMPRESSION_FAILED_EMPTY_SUMMARY ||
status === CompressionStatus.COMPRESSION_FAILED_OUTPUT_TRUNCATED
);
}
/** Finalizes preparations without allowing ACP cleanup to change the stream outcome. */
async function finalizeToolCallPreparations(
tracker: ToolCallPreparationTracker,
includeResolved: boolean,
streamName: string,
): Promise<void> {
try {
await tracker.discard(includeResolved);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
debugLogger.warn(
`Failed to discard tool preparations for ${streamName}; continuing stream: ${message}`,
);
}
}
function maskApiKeyForDisplay(apiKey: string | undefined): string {
const trimmed = apiKey?.trim() ?? '';
if (trimmed.length === 0) return '(not set)';
if (trimmed.length <= 6) return '***';
return `${trimmed.slice(0, 3)}...${trimmed.slice(-4)}`;
}
type AutoCompressionSendResult =
| { responseStream: AsyncGenerator<StreamEvent>; stopReason?: never }
| { responseStream: null; stopReason: PromptResponse['stopReason'] };
function getAbortAwareEndTurnStopReason(
signal: AbortSignal,
): PromptResponse['stopReason'] {
// Parent cancellation wins over a simultaneous terminal path.
return signal.aborted ? 'cancelled' : 'end_turn';
}
type RunToolResult = {
parts: Part[];
stopAfterPermissionCancel: boolean;
loopDetected?: boolean;
repeatedToolFailureBatch?: RepeatedToolFailureBatch;
memoryWriteCandidates?: MemoryWriteCandidate[];
};
type MidTurnDrainResult = {
parts: Part[];
hasQueuedPrompt: boolean;
reliable: boolean;
};
type TodoStopGuardClaimResult = 'claimed' | 'queued' | 'unavailable';
type NextMessageAfterToolRun = {
message: Content | null;
hadMidTurnUserInput: boolean;
stoppedByRepeatedToolFailure?: boolean;
};
type TodoStopGuardBackgroundBaseline = {
agents: Set<string>;
shells: Set<string>;
monitors: Set<string>;
wakeups: Set<string>;
};
type TodoStopGuardPromptPreparation = {
startsWorkChain: boolean;
drainSupersededAutomaticQueues: boolean;
};
type StopContinuationResult =
| { kind: 'natural_stop'; supersededAutomaticContinuation?: boolean }
| {
kind: 'terminal';
stopReason: PromptResponse['stopReason'];
supersededAutomaticContinuation?: boolean;
};
type BeforeModelSendDecision =
| { kind: 'send'; message: Part[] }
| { kind: 'stop'; stopReason: PromptResponse['stopReason'] };
type BeforeModelSendContext = {
compressionFailed: boolean;
};
interface AcpGoalTurn {
permit: GoalTurnPermit;
turnKey: string;
controller: AbortController;
origin: 'runtime' | 'user';
continuationContext: string;
verifierFeedback?: string;
modelStarted: boolean;
}
function sameGoalPermit(
left: GoalTurnPermit | undefined,
right: GoalTurnPermit,
): boolean {
return (
left?.goalId === right.goalId &&
left.revision === right.revision &&
left.turnId === right.turnId
);
}
function buildGoalContinuationParts(turn: AcpGoalTurn): Part[] {
return [
{
text: [
'Continue working on the active Goal.',
'Use get_goal for the authoritative objective and evidence state.',
"Follow the objective's requested output format exactly. Do not add progress, status, or completion commentary unless the objective asks for it.",
'If completion depends on content delivered in this turn, deliver only that content and call get_goal in the same response before update_goal.',
`Runtime continuation context: ${turn.continuationContext}`,
...(turn.verifierFeedback
? [`Verifier feedback: ${turn.verifierFeedback}`]
: []),
].join('\n'),
},
];
}
async function claimGoalTurn(
runtime: GoalRuntime,
turnKey: string,
signal: AbortSignal,
): Promise<GoalTurnPermit | undefined> {
// Checked before the immediate path, not only inside the wait: a prompt
// aborted while its preempted turn settles as a handoff would otherwise
// claim the permit the handoff just promoted to it, and then take
// `prompt()`'s aborted early-exit — which releases only when no goal
// turn was claimed. The permit would be held by nobody, forever.
if (signal.aborted) return undefined;
const immediate =
runtime.permitForTurn(turnKey) ?? runtime.beginTurn(turnKey);
if (immediate || runtime.getSnapshot().goal?.status !== 'active') {
return immediate;
}
return new Promise((resolve, reject) => {
let settled = false;
let unsubscribe = () => {};
const finish = (permit: GoalTurnPermit | undefined, error?: unknown) => {
if (settled) return;
settled = true;
unsubscribe();
signal.removeEventListener('abort', onAbort);
if (error !== undefined) reject(error);
else resolve(permit);
};
const inspect = () => {
try {
const permit = runtime.permitForTurn(turnKey);
if (permit || runtime.getSnapshot().goal?.status !== 'active') {
finish(permit);
}
} catch (error) {
finish(undefined, error);
}
};
const onAbort = () => finish(undefined);
unsubscribe = runtime.subscribe(inspect);
signal.addEventListener('abort', onAbort, { once: true });
if (signal.aborted) onAbort();
else inspect();
});
}
type PendingToolResultRecord = {
ordinal: number;
sequence: number;
callId: string;
toolName: string;
responseParts: Part[];
persistedOutputFiles?: string[];
policyToolName?: string;
toolType?: 'native' | 'mcp';
executionErrorType?: ToolErrorType;
providerDuplicate?: boolean;
/** Skip the durable JSONL write; the in-memory result is still produced. */
skipPersistence?: boolean;
metadata: Omit<Partial<ToolCallResponseInfo>, 'executionStatus'> & {
status: 'success' | 'error' | 'cancelled';
executionStatus: ToolExecutionStatus;
};
};
type QueueToolResultRecord = (
fc: FunctionCall,
record: Omit<PendingToolResultRecord, 'ordinal' | 'sequence'>,
) => void;
type HistoryMutationRunner = <T>(operation: () => Promise<T>) => Promise<T>;
export type DaemonToolLoopState = {
totalToolCalls: number;
invalidToolParamErrors: Map<string, number>;
/** Per-turn counts of identical (tool, args) calls, by repeat key. */
toolCallKeyCounts: Map<string, number>;
/** Highest repeat count of any single (tool, args) pair this turn. */
maxToolCallKeyRepeat: number;
loopDetected: boolean;
loopType?: LoopType;
repeatedToolFailureMode: RepeatedToolFailureGuardMode;
repeatedToolFailureState: RepeatedToolFailureGuardState;
};
const DAEMON_INVALID_TOOL_PARAMS_THRESHOLD = 3;
const PERMISSION_CANCEL_SKIP_MESSAGE =
'Skipped because a permission request was cancelled before the user answered; user input is required before continuing.';
const LOOP_DETECTED_SKIP_MESSAGE =
'Skipped because loop detection stopped the current turn before this tool call could run.';
const LOOP_DETECTED_CONTEXT_MESSAGE =
'System: this turn was terminated because the model exceeded tool-call safety limits. Try a different approach on the next turn.';
export const LOOP_DETECTED_TURN_ERROR_MESSAGE =
'Tool-call loop protection stopped this turn. The session is still available; send a more specific instruction to continue.';
const TOOL_EXECUTION_CANCELLED_MESSAGE = 'Tool execution was cancelled.';
const TOOL_POST_EXECUTION_CANCELLED_MESSAGE =
'The tool had already completed; its output was discarded.';
function createDaemonToolLoopState(
repeatedToolFailureMode: RepeatedToolFailureGuardMode,
): DaemonToolLoopState {
return {
totalToolCalls: 0,
invalidToolParamErrors: new Map(),
toolCallKeyCounts: new Map(),
maxToolCallKeyRepeat: 0,
loopDetected: false,
repeatedToolFailureMode,
repeatedToolFailureState: createRepeatedToolFailureGuardState(),
};
}
function repeatedToolFailureCountBucket(
count: number,
): '0' | '1-2' | '3-4' | '5-7' | '8+' {
if (count === 0) return '0';
if (count <= 2) return '1-2';
if (count <= 4) return '3-4';
if (count <= 7) return '5-7';
return '8+';
}
function repeatedToolFailureBatchBucket(count: number): '0' | '1' | '2' | '3+' {
if (count === 0) return '0';
if (count === 1) return '1';
if (count === 2) return '2';
return '3+';
}
function recordRepeatedToolFailureDecision(
promptId: string,
mode: RepeatedToolFailureGuardMode,
previousState: RepeatedToolFailureGuardState,
decision: RepeatedToolFailureGuardDecision,
batch: RepeatedToolFailureBatch,
): void {
if (mode === 'off' || decision.kind === 'none') {
return;
}
const countState = decision.kind === 'reset' ? previousState : decision.state;
const telemetryDecision =
decision.kind === 'warn'
? 'warned'
: decision.kind === 'stop'
? 'stopped'
: decision.kind;
const key = decision.kind === 'reset' ? undefined : decision.state.key;
const matchingToolTypes = new Set(
key
? batch.observations
.filter(
(observation) =>
!observation.providerDuplicate &&
observation.policyToolName === key.policyToolName &&
observation.executionErrorType === key.executionErrorType,
)
.map((observation) => observation.toolType)
.filter((toolType) => toolType !== undefined)
: [],
);
const toolType =
matchingToolTypes.size === 1 ? [...matchingToolTypes][0] : undefined;
logRepeatedToolFailureGuard(
new RepeatedToolFailureGuardEvent({
prompt_id: promptId,
route: 'acp_foreground',
mode,
phase_before: previousState.phase,
phase_after: decision.state.phase,
decision: telemetryDecision,
failure_count_bucket: repeatedToolFailureCountBucket(
countState.failureCount,
),
batch_count_bucket: repeatedToolFailureBatchBucket(countState.batchCount),
candidate_ordinal: countState.candidateOrdinal,
...(decision.kind === 'reset'
? { reset_reason: decision.reason }
: {
terminal_status: 'error',
execution_status: 'error',
execution_error_type: key?.executionErrorType,
tool_type: toolType,
}),
}),
);
}
function recordDaemonLoopDetected(
config: Config,
promptId: string,
loopType: LoopType,
message: string,
loopState: DaemonToolLoopState,
options: { recordToQwenLogger?: boolean } = {},
): true {
if (!loopState.loopDetected) {
loopState.loopDetected = true;
loopState.loopType = loopType;
debugLogger.warn(message);
try {
logLoopDetected(
config,
new LoopDetectedEvent(loopType, promptId),
options,
);
} catch (error) {
debugLogger.debug(
'[Session] Failed to record loop detection telemetry',
error,
);
}
}
return true;
}
function createLoopDetectedTurnError(
loopState: DaemonToolLoopState,
): RequestError {
return new RequestError(-32603, LOOP_DETECTED_TURN_ERROR_MESSAGE, {
code: 'LOOP_DETECTED',
errorKind: 'loop_detected',
...(loopState.loopType ? { loopType: loopState.loopType } : {}),
});
}
// Cancellation takes precedence when it races a loop-detected stop.
function cancelledOrThrowLoopDetected(
signal: AbortSignal,
loopState: DaemonToolLoopState,
): 'cancelled' {
if (signal.aborted) return 'cancelled';
throw createLoopDetectedTurnError(loopState);
}
function isLoopDetectedTurnError(error: unknown): boolean {
if (!(error instanceof RequestError)) return false;
const data = error.data;
return (
typeof data === 'object' &&
data !== null &&
(data as { code?: unknown }).code === 'LOOP_DETECTED'
);
}
function recordDaemonToolCalls(
config: Config,
promptId: string,
loopState: DaemonToolLoopState | undefined,
calls: readonly FunctionCall[],
): boolean {
if (!loopState || loopState.loopDetected)
return loopState?.loopDetected ?? false;
loopState.totalToolCalls += calls.length;
for (const call of calls) {
const key = getToolCallRepeatKey(call.name ?? '', call.args ?? {});
const count = (loopState.toolCallKeyCounts.get(key) ?? 0) + 1;
loopState.toolCallKeyCounts.set(key, count);
if (count > loopState.maxToolCallKeyRepeat) {
loopState.maxToolCallKeyRepeat = count;
}
}
// Same per-turn cap semantics as the core LoopDetectionService — the
// shouldHaltOnTurnToolCallCap predicate is shared with core's
// checkTurnToolCallCap so the two runtimes cannot drift (an explicit
// model.maxToolCallsPerTurn is a hard cap; the default is adaptive —
// past the soft cap a productive turn continues until the
// stuck-repetition signal or the hard backstop). Unlike core there is
// no in-session disable check — that flag is only set by the interactive
// loop-detection dialog, which has no ACP equivalent — and this runs
// once per batch, before execution: a batch that would cross the cap
// check is skipped whole, so a turn never executes past an explicit cap
// or the hard backstop (it can halt up to one batch short), while the
// adaptive soft cap is exceeded by design, up to the backstop. No retry
// rollback is needed for these counters: on RETRY / MODEL_FALLBACK the
// daemon stream loops discard the failed attempt's accumulated calls
// (functionCalls.length = 0) before re-streaming, so a failed attempt's
// calls never reach this function to be double-counted.
if (
shouldHaltOnTurnToolCallCap(
loopState.totalToolCalls,
loopState.maxToolCallKeyRepeat,
config.getMaxToolCallsPerTurn(),
config.isMaxToolCallsPerTurnExplicit(),
)
) {
return recordDaemonLoopDetected(
config,
promptId,
LoopType.TURN_TOOL_CALL_CAP,
`Stopping ACP turn after ${loopState.totalToolCalls} tool calls in one turn.`,
loopState,
);
}
// Mirror of core's checkGlobalDuplicate: the same (tool, args) pair
// repeated GLOBAL_DUPLICATE_THRESHOLD times anywhere in the turn halts
// it. Gated on skipLoopDetection exactly as in core — that detector class
// is the historically false-positive-prone one (long turns legitimately
// re-run the same build/test/read), so it ships off by default, and its
// false positives would land hardest on exactly the long turns this
// adaptive cap exists to enable. The cap's stuck signal above stays
// always-on regardless. "Off by default" depends on the CLI layer: core's
// Config defaults skipLoopDetection to false and loadCliConfig applies
// `?? true` (cli config.ts), so a Config constructed without that layer
// would ship this halt on.
if (
!config.getSkipLoopDetection() &&
loopState.maxToolCallKeyRepeat >= GLOBAL_DUPLICATE_THRESHOLD
) {
return recordDaemonLoopDetected(
config,
promptId,
LoopType.GLOBAL_TOOL_CALL_DUPLICATE,
`Stopping ACP turn after the same tool call repeated ${loopState.maxToolCallKeyRepeat} times.`,
loopState,
);
}
return false;
}
function recordDaemonInvalidToolParams(
config: Config,
promptId: string,
loopState: DaemonToolLoopState | undefined,
toolName: string,
error: Error,
): boolean {
if (!loopState || loopState.loopDetected)
return loopState?.loopDetected ?? false;
// Intentionally bucket by tool name only: repeated parameter errors for the
// same tool mean the model is stuck on that tool's schema.
const key = toolName;
const count = (loopState.invalidToolParamErrors.get(key) ?? 0) + 1;
loopState.invalidToolParamErrors.set(key, count);
if (count < DAEMON_INVALID_TOOL_PARAMS_THRESHOLD) return false;
return recordDaemonLoopDetected(
config,
promptId,
LoopType.INVALID_TOOL_PARAMS_STAGNATION,
`Stopping ACP turn after repeated tool parameter errors from ${toolName}: ${error.message}`,
loopState,
);
}
// The drain is served from an in-memory queue, so a conforming client answers
// near-instantly (or rejects with -32601). No response within this window
// means the client silently drops unknown methods; without a deadline the
// await would wedge the prompt turn forever.
const MID_TURN_QUEUE_DRAIN_TIMEOUT_MS = 2_000;
// Secondary deadline for recovering a drain whose response arrives AFTER the
// 2s race timeout: within this window the late answer is re-injected on the next
// batch; beyond it (e.g. degraded transport) it is dropped rather than pushed
// into an unrelated turn's context.
const MID_TURN_QUEUE_RECOVERY_TIMEOUT_MS = 30_000;
const MID_TURN_QUEUE_RESOLVE_TIMEOUT_MS = 10_000;
const MAX_MID_TURN_DRAIN_ITEMS = 10;
const MID_TURN_ATTACHMENT_PROCESSING_FAILURE_TEXT =
'[Attachment could not be processed]';
const MAX_MID_TURN_RESOURCE_TEXT_LENGTH = 100_000;
// Latch the drain off only after this many consecutive timeouts: one slow
// answer must not permanently disable mid-turn messages for a
// conforming-but-busy client, while a client that never answers stops
// costing a stall per tool batch after a few batches.
const MID_TURN_QUEUE_DRAIN_MAX_TIMEOUT_STRIKES = 3;
// fs codes that let a `dynamic` (self-paced) loop treat a THROWN loop.md
// sentinel-resolution as transient — degrade to a no-op re-arm tick so the loop
// survives — instead of re-throwing (which ends it: the firing wakeup is already
// consumed, so only an end-of-turn re-arm keeps it alive). readLoopTaskFile only
// re-throws EACCES/EIO/EBUSY/EPERM (it skips ENOENT/EISDIR/ENOTDIR/ELOOP/… to its
// own `missing` → no-op path); EISDIR/ENOTDIR stay here as defense-in-depth for
// the lstat→open TOCTOU race (path swapped to a dir/non-dir mid-read) should that
// internal skip ever narrow. ENOENT is omitted on purpose: "absent" is not a
// transient read failure and can never reach this catch.
const TRANSIENT_FS_CODES: readonly string[] = [
'EACCES',
'EIO',
'EBUSY',
'EPERM',
'EISDIR',
'ENOTDIR',
];
type DrainedMidTurnMessage =
| { kind: 'text'; message: string }
| {
kind: 'structured';
content: ContentBlock[];
displayText: string;
attachmentReferences?: SessionAttachmentReference[];
};
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object';
}
function isContentBlock(value: unknown): value is ContentBlock {
if (!isRecord(value) || typeof value['type'] !== 'string') return false;
switch (value['type']) {
case 'text':
return typeof value['text'] === 'string';
case 'image':
return (
typeof value['mimeType'] === 'string' &&
value['mimeType'].startsWith('image/') &&
typeof value['data'] === 'string'
);
case 'audio':
return (
typeof value['mimeType'] === 'string' &&
value['mimeType'].startsWith('audio/') &&
typeof value['data'] === 'string'
);
case 'resource_link':
return false;
case 'resource':
return isEmbeddedResourceResource(value['resource']);
default:
debugLogger.warn(`Unknown ContentBlock type: ${value['type']}`);
return false;
}
}
function isAudioPart(part: Part): boolean {
return (
typeof part.inlineData?.mimeType === 'string' &&