forked from liuup/claude-code-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompact.ts
More file actions
1705 lines (1581 loc) · 59.4 KB
/
Copy pathcompact.ts
File metadata and controls
1705 lines (1581 loc) · 59.4 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
import { feature } from 'bun:bundle'
import type { UUID } from 'crypto'
import uniqBy from 'lodash-es/uniqBy.js'
/* eslint-disable @typescript-eslint/no-require-imports */
const sessionTranscriptModule = feature('KAIROS')
? (require('../sessionTranscript/sessionTranscript.js') as typeof import('../sessionTranscript/sessionTranscript.js'))
: null
import { APIUserAbortError } from '@anthropic-ai/sdk'
import { markPostCompaction } from 'src/bootstrap/state.js'
import { getInvokedSkillsForAgent } from '../../bootstrap/state.js'
import type { QuerySource } from '../../constants/querySource.js'
import type { CanUseToolFn } from '../../hooks/useCanUseTool.js'
import type { Tool, ToolUseContext } from '../../Tool.js'
import type { LocalAgentTaskState } from '../../tasks/LocalAgentTask/LocalAgentTask.js'
import { FileReadTool } from '../../tools/FileReadTool/FileReadTool.js'
import {
FILE_READ_TOOL_NAME,
FILE_UNCHANGED_STUB,
} from '../../tools/FileReadTool/prompt.js'
import { ToolSearchTool } from '../../tools/ToolSearchTool/ToolSearchTool.js'
import type { AgentId } from '../../types/ids.js'
import type {
AssistantMessage,
AttachmentMessage,
HookResultMessage,
Message,
PartialCompactDirection,
SystemCompactBoundaryMessage,
SystemMessage,
UserMessage,
} from '../../types/message.js'
import {
createAttachmentMessage,
generateFileAttachment,
getAgentListingDeltaAttachment,
getDeferredToolsDeltaAttachment,
getMcpInstructionsDeltaAttachment,
} from '../../utils/attachments.js'
import { getMemoryPath } from '../../utils/config.js'
import { COMPACT_MAX_OUTPUT_TOKENS } from '../../utils/context.js'
import {
analyzeContext,
tokenStatsToStatsigMetrics,
} from '../../utils/contextAnalysis.js'
import { logForDebugging } from '../../utils/debug.js'
import { hasExactErrorMessage } from '../../utils/errors.js'
import { cacheToObject } from '../../utils/fileStateCache.js'
import {
type CacheSafeParams,
runForkedAgent,
} from '../../utils/forkedAgent.js'
import {
executePostCompactHooks,
executePreCompactHooks,
} from '../../utils/hooks.js'
import { logError } from '../../utils/log.js'
import { MEMORY_TYPE_VALUES } from '../../utils/memory/types.js'
import {
createCompactBoundaryMessage,
createUserMessage,
getAssistantMessageText,
getLastAssistantMessage,
getMessagesAfterCompactBoundary,
isCompactBoundaryMessage,
normalizeMessagesForAPI,
} from '../../utils/messages.js'
import { expandPath } from '../../utils/path.js'
import { getPlan, getPlanFilePath } from '../../utils/plans.js'
import {
isSessionActivityTrackingActive,
sendSessionActivitySignal,
} from '../../utils/sessionActivity.js'
import { processSessionStartHooks } from '../../utils/sessionStart.js'
import {
getTranscriptPath,
reAppendSessionMetadata,
} from '../../utils/sessionStorage.js'
import { sleep } from '../../utils/sleep.js'
import { jsonStringify } from '../../utils/slowOperations.js'
/* eslint-enable @typescript-eslint/no-require-imports */
import { asSystemPrompt } from '../../utils/systemPromptType.js'
import { getTaskOutputPath } from '../../utils/task/diskOutput.js'
import {
getTokenUsage,
tokenCountFromLastAPIResponse,
tokenCountWithEstimation,
} from '../../utils/tokens.js'
import {
extractDiscoveredToolNames,
isToolSearchEnabled,
} from '../../utils/toolSearch.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../analytics/growthbook.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../analytics/index.js'
import {
getMaxOutputTokensForModel,
queryModelWithStreaming,
} from '../api/claude.js'
import {
getPromptTooLongTokenGap,
PROMPT_TOO_LONG_ERROR_MESSAGE,
startsWithApiErrorPrefix,
} from '../api/errors.js'
import { notifyCompaction } from '../api/promptCacheBreakDetection.js'
import { getRetryDelay } from '../api/withRetry.js'
import { logPermissionContextForAnts } from '../internalLogging.js'
import {
roughTokenCountEstimation,
roughTokenCountEstimationForMessages,
} from '../tokenEstimation.js'
import { groupMessagesByApiRound } from './grouping.js'
import {
getCompactPrompt,
getCompactUserSummaryMessage,
getPartialCompactPrompt,
} from './prompt.js'
export const POST_COMPACT_MAX_FILES_TO_RESTORE = 5
export const POST_COMPACT_TOKEN_BUDGET = 50_000
export const POST_COMPACT_MAX_TOKENS_PER_FILE = 5_000
// Skills can be large (verify=18.7KB, claude-api=20.1KB). Previously re-injected
// unbounded on every compact → 5-10K tok/compact. Per-skill truncation beats
// dropping — instructions at the top of a skill file are usually the critical
// part. Budget sized to hold ~5 skills at the per-skill cap.
export const POST_COMPACT_MAX_TOKENS_PER_SKILL = 5_000
export const POST_COMPACT_SKILLS_TOKEN_BUDGET = 25_000
const MAX_COMPACT_STREAMING_RETRIES = 2
/**
* Strip image blocks from user messages before sending for compaction.
* Images are not needed for generating a conversation summary and can
* cause the compaction API call itself to hit the prompt-too-long limit,
* especially in CCD sessions where users frequently attach images.
* Replaces image blocks with a text marker so the summary still notes
* that an image was shared.
*
* Note: Only user messages contain images (either directly attached or within
* tool_result content from tools). Assistant messages contain text, tool_use,
* and thinking blocks but not images.
*/
export function stripImagesFromMessages(messages: Message[]): Message[] {
return messages.map(message => {
if (message.type !== 'user') {
return message
}
const content = message.message.content
if (!Array.isArray(content)) {
return message
}
let hasMediaBlock = false
const newContent = content.flatMap(block => {
if (block.type === 'image') {
hasMediaBlock = true
return [{ type: 'text' as const, text: '[image]' }]
}
if (block.type === 'document') {
hasMediaBlock = true
return [{ type: 'text' as const, text: '[document]' }]
}
// Also strip images/documents nested inside tool_result content arrays
if (block.type === 'tool_result' && Array.isArray(block.content)) {
let toolHasMedia = false
const newToolContent = block.content.map(item => {
if (item.type === 'image') {
toolHasMedia = true
return { type: 'text' as const, text: '[image]' }
}
if (item.type === 'document') {
toolHasMedia = true
return { type: 'text' as const, text: '[document]' }
}
return item
})
if (toolHasMedia) {
hasMediaBlock = true
return [{ ...block, content: newToolContent }]
}
}
return [block]
})
if (!hasMediaBlock) {
return message
}
return {
...message,
message: {
...message.message,
content: newContent,
},
} as typeof message
})
}
/**
* Strip attachment types that are re-injected post-compaction anyway.
* skill_discovery/skill_listing are re-surfaced by resetSentSkillNames()
* + the next turn's discovery signal, so feeding them to the summarizer
* wastes tokens and pollutes the summary with stale skill suggestions.
*
* No-op when EXPERIMENTAL_SKILL_SEARCH is off (the attachment types
* don't exist on external builds).
*/
export function stripReinjectedAttachments(messages: Message[]): Message[] {
if (feature('EXPERIMENTAL_SKILL_SEARCH')) {
return messages.filter(
m =>
!(
m.type === 'attachment' &&
(m.attachment.type === 'skill_discovery' ||
m.attachment.type === 'skill_listing')
),
)
}
return messages
}
export const ERROR_MESSAGE_NOT_ENOUGH_MESSAGES =
'Not enough messages to compact.'
const MAX_PTL_RETRIES = 3
const PTL_RETRY_MARKER = '[earlier conversation truncated for compaction retry]'
/**
* Drops the oldest API-round groups from messages until tokenGap is covered.
* Falls back to dropping 20% of groups when the gap is unparseable (some
* Vertex/Bedrock error formats). Returns null when nothing can be dropped
* without leaving an empty summarize set.
*
* This is the last-resort escape hatch for CC-1180 — when the compact request
* itself hits prompt-too-long, the user is otherwise stuck. Dropping the
* oldest context is lossy but unblocks them. The reactive-compact path
* (compactMessages.ts) has the proper retry loop that peels from the tail;
* this helper is the dumb-but-safe fallback for the proactive/manual path
* that wasn't migrated in bfdb472f's unification.
*/
export function truncateHeadForPTLRetry(
messages: Message[],
ptlResponse: AssistantMessage,
): Message[] | null {
// Strip our own synthetic marker from a previous retry before grouping.
// Otherwise it becomes its own group 0 and the 20% fallback stalls
// (drops only the marker, re-adds it, zero progress on retry 2+).
const input =
messages[0]?.type === 'user' &&
messages[0].isMeta &&
messages[0].message.content === PTL_RETRY_MARKER
? messages.slice(1)
: messages
const groups = groupMessagesByApiRound(input)
if (groups.length < 2) return null
const tokenGap = getPromptTooLongTokenGap(ptlResponse)
let dropCount: number
if (tokenGap !== undefined) {
let acc = 0
dropCount = 0
for (const g of groups) {
acc += roughTokenCountEstimationForMessages(g)
dropCount++
if (acc >= tokenGap) break
}
} else {
dropCount = Math.max(1, Math.floor(groups.length * 0.2))
}
// Keep at least one group so there's something to summarize.
dropCount = Math.min(dropCount, groups.length - 1)
if (dropCount < 1) return null
const sliced = groups.slice(dropCount).flat()
// groupMessagesByApiRound puts the preamble in group 0 and starts every
// subsequent group with an assistant message. Dropping group 0 leaves an
// assistant-first sequence which the API rejects (first message must be
// role=user). Prepend a synthetic user marker — ensureToolResultPairing
// already handles any orphaned tool_results this creates.
if (sliced[0]?.type === 'assistant') {
return [
createUserMessage({ content: PTL_RETRY_MARKER, isMeta: true }),
...sliced,
]
}
return sliced
}
export const ERROR_MESSAGE_PROMPT_TOO_LONG =
'Conversation too long. Press esc twice to go up a few messages and try again.'
export const ERROR_MESSAGE_USER_ABORT = 'API Error: Request was aborted.'
export const ERROR_MESSAGE_INCOMPLETE_RESPONSE =
'Compaction interrupted · This may be due to network issues — please try again.'
export interface CompactionResult {
boundaryMarker: SystemMessage
summaryMessages: UserMessage[]
attachments: AttachmentMessage[]
hookResults: HookResultMessage[]
messagesToKeep?: Message[]
userDisplayMessage?: string
preCompactTokenCount?: number
postCompactTokenCount?: number
truePostCompactTokenCount?: number
compactionUsage?: ReturnType<typeof getTokenUsage>
}
/**
* Diagnosis context passed from autoCompactIfNeeded into compactConversation.
* Lets the tengu_compact event disambiguate same-chain loops (H2) from
* cross-agent (H1/H5) and manual-vs-auto (H3) compactions without joins.
*/
export type RecompactionInfo = {
isRecompactionInChain: boolean
turnsSincePreviousCompact: number
previousCompactTurnId?: string
autoCompactThreshold: number
querySource?: QuerySource
}
/**
* Build the base post-compact messages array from a CompactionResult.
* This ensures consistent ordering across all compaction paths.
* Order: boundaryMarker, summaryMessages, messagesToKeep, attachments, hookResults
*/
export function buildPostCompactMessages(result: CompactionResult): Message[] {
return [
result.boundaryMarker,
...result.summaryMessages,
...(result.messagesToKeep ?? []),
...result.attachments,
...result.hookResults,
]
}
/**
* Annotate a compact boundary with relink metadata for messagesToKeep.
* Preserved messages keep their original parentUuids on disk (dedup-skipped);
* the loader uses this to patch head→anchor and anchor's-other-children→tail.
*
* `anchorUuid` = what sits immediately before keep[0] in the desired chain:
* - suffix-preserving (reactive/session-memory): last summary message
* - prefix-preserving (partial compact): the boundary itself
*/
export function annotateBoundaryWithPreservedSegment(
boundary: SystemCompactBoundaryMessage,
anchorUuid: UUID,
messagesToKeep: readonly Message[] | undefined,
): SystemCompactBoundaryMessage {
const keep = messagesToKeep ?? []
if (keep.length === 0) return boundary
return {
...boundary,
compactMetadata: {
...boundary.compactMetadata,
preservedSegment: {
headUuid: keep[0]!.uuid,
anchorUuid,
tailUuid: keep.at(-1)!.uuid,
},
},
}
}
/**
* Merges user-supplied custom instructions with hook-provided instructions.
* User instructions come first; hook instructions are appended.
* Empty strings normalize to undefined.
*/
export function mergeHookInstructions(
userInstructions: string | undefined,
hookInstructions: string | undefined,
): string | undefined {
if (!hookInstructions) return userInstructions || undefined
if (!userInstructions) return hookInstructions
return `${userInstructions}\n\n${hookInstructions}`
}
/**
* Creates a compact version of a conversation by summarizing older messages
* and preserving recent conversation history.
*/
export async function compactConversation(
messages: Message[],
context: ToolUseContext,
cacheSafeParams: CacheSafeParams,
suppressFollowUpQuestions: boolean,
customInstructions?: string,
isAutoCompact: boolean = false,
recompactionInfo?: RecompactionInfo,
): Promise<CompactionResult> {
try {
if (messages.length === 0) {
throw new Error(ERROR_MESSAGE_NOT_ENOUGH_MESSAGES)
}
const preCompactTokenCount = tokenCountWithEstimation(messages)
const appState = context.getAppState()
void logPermissionContextForAnts(appState.toolPermissionContext, 'summary')
context.onCompactProgress?.({
type: 'hooks_start',
hookType: 'pre_compact',
})
// Execute PreCompact hooks
context.setSDKStatus?.('compacting')
const hookResult = await executePreCompactHooks(
{
trigger: isAutoCompact ? 'auto' : 'manual',
customInstructions: customInstructions ?? null,
},
context.abortController.signal,
)
customInstructions = mergeHookInstructions(
customInstructions,
hookResult.newCustomInstructions,
)
const userDisplayMessage = hookResult.userDisplayMessage
// Show requesting mode with up arrow and custom message
context.setStreamMode?.('requesting')
context.setResponseLength?.(() => 0)
context.onCompactProgress?.({ type: 'compact_start' })
// 3P default: true — forked-agent path reuses main conversation's prompt cache.
// Experiment (Jan 2026) confirmed: false path is 98% cache miss, costs ~0.76% of
// fleet cache_creation (~38B tok/day), concentrated in ephemeral envs (CCR/GHA/SDK)
// with cold GB cache and 3P providers where GB is disabled. GB gate kept as kill-switch.
const promptCacheSharingEnabled = getFeatureValue_CACHED_MAY_BE_STALE(
'tengu_compact_cache_prefix',
true,
)
const compactPrompt = getCompactPrompt(customInstructions)
const summaryRequest = createUserMessage({
content: compactPrompt,
})
let messagesToSummarize = messages
let retryCacheSafeParams = cacheSafeParams
let summaryResponse: AssistantMessage
let summary: string | null
let ptlAttempts = 0
for (;;) {
summaryResponse = await streamCompactSummary({
messages: messagesToSummarize,
summaryRequest,
appState,
context,
preCompactTokenCount,
cacheSafeParams: retryCacheSafeParams,
})
summary = getAssistantMessageText(summaryResponse)
if (!summary?.startsWith(PROMPT_TOO_LONG_ERROR_MESSAGE)) break
// CC-1180: compact request itself hit prompt-too-long. Truncate the
// oldest API-round groups and retry rather than leaving the user stuck.
ptlAttempts++
const truncated =
ptlAttempts <= MAX_PTL_RETRIES
? truncateHeadForPTLRetry(messagesToSummarize, summaryResponse)
: null
if (!truncated) {
logEvent('tengu_compact_failed', {
reason:
'prompt_too_long' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
preCompactTokenCount,
promptCacheSharingEnabled,
ptlAttempts,
})
throw new Error(ERROR_MESSAGE_PROMPT_TOO_LONG)
}
logEvent('tengu_compact_ptl_retry', {
attempt: ptlAttempts,
droppedMessages: messagesToSummarize.length - truncated.length,
remainingMessages: truncated.length,
})
messagesToSummarize = truncated
// The forked-agent path reads from cacheSafeParams.forkContextMessages,
// not the messages param — thread the truncated set through both paths.
retryCacheSafeParams = {
...retryCacheSafeParams,
forkContextMessages: truncated,
}
}
if (!summary) {
logForDebugging(
`Compact failed: no summary text in response. Response: ${jsonStringify(summaryResponse)}`,
{ level: 'error' },
)
logEvent('tengu_compact_failed', {
reason:
'no_summary' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
preCompactTokenCount,
promptCacheSharingEnabled,
})
throw new Error(
`Failed to generate conversation summary - response did not contain valid text content`,
)
} else if (startsWithApiErrorPrefix(summary)) {
logEvent('tengu_compact_failed', {
reason:
'api_error' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
preCompactTokenCount,
promptCacheSharingEnabled,
})
throw new Error(summary)
}
// Store the current file state before clearing
const preCompactReadFileState = cacheToObject(context.readFileState)
// Clear the cache
context.readFileState.clear()
context.loadedNestedMemoryPaths?.clear()
// Intentionally NOT resetting sentSkillNames: re-injecting the full
// skill_listing (~4K tokens) post-compact is pure cache_creation with
// marginal benefit. The model still has SkillTool in its schema and
// invoked_skills attachment (below) preserves used-skill content. Ants
// with EXPERIMENTAL_SKILL_SEARCH already skip re-injection via the
// early-return in getSkillListingAttachments.
// Run async attachment generation in parallel
const [fileAttachments, asyncAgentAttachments] = await Promise.all([
createPostCompactFileAttachments(
preCompactReadFileState,
context,
POST_COMPACT_MAX_FILES_TO_RESTORE,
),
createAsyncAgentAttachmentsIfNeeded(context),
])
const postCompactFileAttachments: AttachmentMessage[] = [
...fileAttachments,
...asyncAgentAttachments,
]
const planAttachment = createPlanAttachmentIfNeeded(context.agentId)
if (planAttachment) {
postCompactFileAttachments.push(planAttachment)
}
// Add plan mode instructions if currently in plan mode, so the model
// continues operating in plan mode after compaction
const planModeAttachment = await createPlanModeAttachmentIfNeeded(context)
if (planModeAttachment) {
postCompactFileAttachments.push(planModeAttachment)
}
// Add skill attachment if skills were invoked in this session
const skillAttachment = createSkillAttachmentIfNeeded(context.agentId)
if (skillAttachment) {
postCompactFileAttachments.push(skillAttachment)
}
// Compaction ate prior delta attachments. Re-announce from the current
// state so the model has tool/instruction context on the first
// post-compact turn. Empty message history → diff against nothing →
// announces the full set.
for (const att of getDeferredToolsDeltaAttachment(
context.options.tools,
context.options.mainLoopModel,
[],
{ callSite: 'compact_full' },
)) {
postCompactFileAttachments.push(createAttachmentMessage(att))
}
for (const att of getAgentListingDeltaAttachment(context, [])) {
postCompactFileAttachments.push(createAttachmentMessage(att))
}
for (const att of getMcpInstructionsDeltaAttachment(
context.options.mcpClients,
context.options.tools,
context.options.mainLoopModel,
[],
)) {
postCompactFileAttachments.push(createAttachmentMessage(att))
}
context.onCompactProgress?.({
type: 'hooks_start',
hookType: 'session_start',
})
// Execute SessionStart hooks after successful compaction
const hookMessages = await processSessionStartHooks('compact', {
model: context.options.mainLoopModel,
})
// Create the compact boundary marker and summary messages before the
// event so we can compute the true resulting-context size.
const boundaryMarker = createCompactBoundaryMessage(
isAutoCompact ? 'auto' : 'manual',
preCompactTokenCount ?? 0,
messages.at(-1)?.uuid,
)
// Carry loaded-tool state — the summary doesn't preserve tool_reference
// blocks, so the post-compact schema filter needs this to keep sending
// already-loaded deferred tool schemas to the API.
const preCompactDiscovered = extractDiscoveredToolNames(messages)
if (preCompactDiscovered.size > 0) {
boundaryMarker.compactMetadata.preCompactDiscoveredTools = [
...preCompactDiscovered,
].sort()
}
const transcriptPath = getTranscriptPath()
const summaryMessages: UserMessage[] = [
createUserMessage({
content: getCompactUserSummaryMessage(
summary,
suppressFollowUpQuestions,
transcriptPath,
),
isCompactSummary: true,
isVisibleInTranscriptOnly: true,
}),
]
// Previously "postCompactTokenCount" — renamed because this is the
// compact API call's total usage (input_tokens ≈ preCompactTokenCount),
// NOT the size of the resulting context. Kept for event-field continuity.
const compactionCallTotalTokens = tokenCountFromLastAPIResponse([
summaryResponse,
])
// Message-payload estimate of the resulting context. The next iteration's
// shouldAutoCompact will see this PLUS ~20-40K for system prompt + tools +
// userContext (via API usage.input_tokens). So `willRetriggerNextTurn: true`
// is a strong signal; `false` may still retrigger when this is close to threshold.
const truePostCompactTokenCount = roughTokenCountEstimationForMessages([
boundaryMarker,
...summaryMessages,
...postCompactFileAttachments,
...hookMessages,
])
// Extract compaction API usage metrics
const compactionUsage = getTokenUsage(summaryResponse)
const querySourceForEvent =
recompactionInfo?.querySource ?? context.options.querySource ?? 'unknown'
logEvent('tengu_compact', {
preCompactTokenCount,
// Kept for continuity — semantically the compact API call's total usage
postCompactTokenCount: compactionCallTotalTokens,
truePostCompactTokenCount,
autoCompactThreshold: recompactionInfo?.autoCompactThreshold ?? -1,
willRetriggerNextTurn:
recompactionInfo !== undefined &&
truePostCompactTokenCount >= recompactionInfo.autoCompactThreshold,
isAutoCompact,
querySource:
querySourceForEvent as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryChainId: (context.queryTracking?.chainId ??
'') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryDepth: context.queryTracking?.depth ?? -1,
isRecompactionInChain: recompactionInfo?.isRecompactionInChain ?? false,
turnsSincePreviousCompact:
recompactionInfo?.turnsSincePreviousCompact ?? -1,
previousCompactTurnId: (recompactionInfo?.previousCompactTurnId ??
'') as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
compactionInputTokens: compactionUsage?.input_tokens,
compactionOutputTokens: compactionUsage?.output_tokens,
compactionCacheReadTokens: compactionUsage?.cache_read_input_tokens ?? 0,
compactionCacheCreationTokens:
compactionUsage?.cache_creation_input_tokens ?? 0,
compactionTotalTokens: compactionUsage
? compactionUsage.input_tokens +
(compactionUsage.cache_creation_input_tokens ?? 0) +
(compactionUsage.cache_read_input_tokens ?? 0) +
compactionUsage.output_tokens
: 0,
promptCacheSharingEnabled,
// analyzeContext walks every content block (~11ms on a 4.5K-message
// session) purely for this telemetry breakdown. Computed here, past
// the compaction-API await, so the sync walk doesn't starve the
// render loop before compaction even starts. Same deferral pattern
// as reactiveCompact.ts.
...(() => {
try {
return tokenStatsToStatsigMetrics(analyzeContext(messages))
} catch (error) {
logError(error as Error)
return {}
}
})(),
})
// Reset cache read baseline so the post-compact drop isn't flagged as a break
if (feature('PROMPT_CACHE_BREAK_DETECTION')) {
notifyCompaction(
context.options.querySource ?? 'compact',
context.agentId,
)
}
markPostCompaction()
// Re-append session metadata (custom title, tag) so it stays within
// the 16KB tail window that readLiteMetadata reads for --resume display.
// Without this, enough post-compaction messages push the metadata entry
// out of the window, causing --resume to show the auto-generated title
// instead of the user-set session name.
reAppendSessionMetadata()
// Write a reduced transcript segment for the pre-compaction messages
// (assistant mode only). Fire-and-forget — errors are logged internally.
if (feature('KAIROS')) {
void sessionTranscriptModule?.writeSessionTranscriptSegment(messages)
}
context.onCompactProgress?.({
type: 'hooks_start',
hookType: 'post_compact',
})
const postCompactHookResult = await executePostCompactHooks(
{
trigger: isAutoCompact ? 'auto' : 'manual',
compactSummary: summary,
},
context.abortController.signal,
)
const combinedUserDisplayMessage = [
userDisplayMessage,
postCompactHookResult.userDisplayMessage,
]
.filter(Boolean)
.join('\n')
return {
boundaryMarker,
summaryMessages,
attachments: postCompactFileAttachments,
hookResults: hookMessages,
userDisplayMessage: combinedUserDisplayMessage || undefined,
preCompactTokenCount,
postCompactTokenCount: compactionCallTotalTokens,
truePostCompactTokenCount,
compactionUsage,
}
} catch (error) {
// Only show the error notification for manual /compact.
// Auto-compact failures are retried on the next turn and the
// notification is confusing when compaction eventually succeeds.
if (!isAutoCompact) {
addErrorNotificationIfNeeded(error, context)
}
throw error
} finally {
context.setStreamMode?.('requesting')
context.setResponseLength?.(() => 0)
context.onCompactProgress?.({ type: 'compact_end' })
context.setSDKStatus?.(null)
}
}
/**
* Performs a partial compaction around the selected message index.
* Direction 'from': summarizes messages after the index, keeps earlier ones.
* Prompt cache for kept (earlier) messages is preserved.
* Direction 'up_to': summarizes messages before the index, keeps later ones.
* Prompt cache is invalidated since the summary precedes the kept messages.
*/
export async function partialCompactConversation(
allMessages: Message[],
pivotIndex: number,
context: ToolUseContext,
cacheSafeParams: CacheSafeParams,
userFeedback?: string,
direction: PartialCompactDirection = 'from',
): Promise<CompactionResult> {
try {
const messagesToSummarize =
direction === 'up_to'
? allMessages.slice(0, pivotIndex)
: allMessages.slice(pivotIndex)
// 'up_to' must strip old compact boundaries/summaries: for 'up_to',
// summary_B sits BEFORE kept, so a stale boundary_A in kept wins
// findLastCompactBoundaryIndex's backward scan and drops summary_B.
// 'from' keeps them: summary_B sits AFTER kept (backward scan still
// works), and removing an old summary would lose its covered history.
const messagesToKeep =
direction === 'up_to'
? allMessages
.slice(pivotIndex)
.filter(
m =>
m.type !== 'progress' &&
!isCompactBoundaryMessage(m) &&
!(m.type === 'user' && m.isCompactSummary),
)
: allMessages.slice(0, pivotIndex).filter(m => m.type !== 'progress')
if (messagesToSummarize.length === 0) {
throw new Error(
direction === 'up_to'
? 'Nothing to summarize before the selected message.'
: 'Nothing to summarize after the selected message.',
)
}
const preCompactTokenCount = tokenCountWithEstimation(allMessages)
context.onCompactProgress?.({
type: 'hooks_start',
hookType: 'pre_compact',
})
context.setSDKStatus?.('compacting')
const hookResult = await executePreCompactHooks(
{
trigger: 'manual',
customInstructions: null,
},
context.abortController.signal,
)
// Merge hook instructions with user feedback
let customInstructions: string | undefined
if (hookResult.newCustomInstructions && userFeedback) {
customInstructions = `${hookResult.newCustomInstructions}\n\nUser context: ${userFeedback}`
} else if (hookResult.newCustomInstructions) {
customInstructions = hookResult.newCustomInstructions
} else if (userFeedback) {
customInstructions = `User context: ${userFeedback}`
}
context.setStreamMode?.('requesting')
context.setResponseLength?.(() => 0)
context.onCompactProgress?.({ type: 'compact_start' })
const compactPrompt = getPartialCompactPrompt(customInstructions, direction)
const summaryRequest = createUserMessage({
content: compactPrompt,
})
const failureMetadata = {
preCompactTokenCount,
direction:
direction as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
messagesSummarized: messagesToSummarize.length,
}
// 'up_to' prefix hits cache directly; 'from' sends all (tail wouldn't cache).
// PTL retry breaks the cache prefix but unblocks the user (CC-1180).
let apiMessages = direction === 'up_to' ? messagesToSummarize : allMessages
let retryCacheSafeParams =
direction === 'up_to'
? { ...cacheSafeParams, forkContextMessages: messagesToSummarize }
: cacheSafeParams
let summaryResponse: AssistantMessage
let summary: string | null
let ptlAttempts = 0
for (;;) {
summaryResponse = await streamCompactSummary({
messages: apiMessages,
summaryRequest,
appState: context.getAppState(),
context,
preCompactTokenCount,
cacheSafeParams: retryCacheSafeParams,
})
summary = getAssistantMessageText(summaryResponse)
if (!summary?.startsWith(PROMPT_TOO_LONG_ERROR_MESSAGE)) break
ptlAttempts++
const truncated =
ptlAttempts <= MAX_PTL_RETRIES
? truncateHeadForPTLRetry(apiMessages, summaryResponse)
: null
if (!truncated) {
logEvent('tengu_partial_compact_failed', {
reason:
'prompt_too_long' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...failureMetadata,
ptlAttempts,
})
throw new Error(ERROR_MESSAGE_PROMPT_TOO_LONG)
}
logEvent('tengu_compact_ptl_retry', {
attempt: ptlAttempts,
droppedMessages: apiMessages.length - truncated.length,
remainingMessages: truncated.length,
path: 'partial' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
apiMessages = truncated
retryCacheSafeParams = {
...retryCacheSafeParams,
forkContextMessages: truncated,
}
}
if (!summary) {
logEvent('tengu_partial_compact_failed', {
reason:
'no_summary' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...failureMetadata,
})
throw new Error(
'Failed to generate conversation summary - response did not contain valid text content',
)
} else if (startsWithApiErrorPrefix(summary)) {
logEvent('tengu_partial_compact_failed', {
reason:
'api_error' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
...failureMetadata,
})
throw new Error(summary)
}
// Store the current file state before clearing
const preCompactReadFileState = cacheToObject(context.readFileState)
context.readFileState.clear()
context.loadedNestedMemoryPaths?.clear()
// Intentionally NOT resetting sentSkillNames — see compactConversation()
// for rationale (~4K tokens saved per compact event).
const [fileAttachments, asyncAgentAttachments] = await Promise.all([
createPostCompactFileAttachments(
preCompactReadFileState,
context,
POST_COMPACT_MAX_FILES_TO_RESTORE,
messagesToKeep,
),
createAsyncAgentAttachmentsIfNeeded(context),
])
const postCompactFileAttachments: AttachmentMessage[] = [
...fileAttachments,
...asyncAgentAttachments,
]
const planAttachment = createPlanAttachmentIfNeeded(context.agentId)
if (planAttachment) {
postCompactFileAttachments.push(planAttachment)
}
// Add plan mode instructions if currently in plan mode
const planModeAttachment = await createPlanModeAttachmentIfNeeded(context)
if (planModeAttachment) {
postCompactFileAttachments.push(planModeAttachment)
}
const skillAttachment = createSkillAttachmentIfNeeded(context.agentId)
if (skillAttachment) {
postCompactFileAttachments.push(skillAttachment)
}
// Re-announce only what was in the summarized portion — messagesToKeep
// is scanned, so anything already announced there is skipped.
for (const att of getDeferredToolsDeltaAttachment(
context.options.tools,
context.options.mainLoopModel,
messagesToKeep,
{ callSite: 'compact_partial' },
)) {
postCompactFileAttachments.push(createAttachmentMessage(att))
}
for (const att of getAgentListingDeltaAttachment(context, messagesToKeep)) {
postCompactFileAttachments.push(createAttachmentMessage(att))
}
for (const att of getMcpInstructionsDeltaAttachment(
context.options.mcpClients,
context.options.tools,
context.options.mainLoopModel,
messagesToKeep,
)) {
postCompactFileAttachments.push(createAttachmentMessage(att))
}
context.onCompactProgress?.({
type: 'hooks_start',
hookType: 'session_start',
})
const hookMessages = await processSessionStartHooks('compact', {
model: context.options.mainLoopModel,
})
const postCompactTokenCount = tokenCountFromLastAPIResponse([
summaryResponse,
])
const compactionUsage = getTokenUsage(summaryResponse)
logEvent('tengu_partial_compact', {
preCompactTokenCount,
postCompactTokenCount,
messagesKept: messagesToKeep.length,
messagesSummarized: messagesToSummarize.length,
direction:
direction as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
hasUserFeedback: !!userFeedback,
trigger:
'message_selector' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
compactionInputTokens: compactionUsage?.input_tokens,