-
-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathjanitor.ts
More file actions
832 lines (714 loc) · 34.5 KB
/
janitor.ts
File metadata and controls
832 lines (714 loc) · 34.5 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
import { z } from "zod"
import type { Logger } from "./logger"
import type { PruningStrategy } from "./config"
import { buildAnalysisPrompt } from "./prompt"
import { selectModel, extractModelFromSession } from "./model-selector"
import { estimateTokensBatch, formatTokenCount } from "./tokenizer"
import { detectDuplicates, extractParameterKey } from "./deduplicator"
export interface SessionStats {
totalToolsPruned: number
totalTokensSaved: number
}
export interface PruningResult {
prunedCount: number
tokensSaved: number
deduplicatedIds: string[]
llmPrunedIds: string[]
deduplicationDetails: Map<string, any>
toolMetadata: Map<string, { tool: string, parameters?: any }>
sessionStats: SessionStats
}
export interface PruningOptions {
reason?: string
trigger: 'idle' | 'tool'
}
export class Janitor {
constructor(
private client: any,
private prunedIdsState: Map<string, string[]>,
private statsState: Map<string, SessionStats>,
private logger: Logger,
private toolParametersCache: Map<string, any>,
private protectedTools: string[],
private modelCache: Map<string, { providerID: string; modelID: string }>,
private configModel?: string, // Format: "provider/model"
private showModelErrorToasts: boolean = true, // Whether to show toast for model errors
private pruningSummary: "off" | "minimal" | "detailed" = "detailed", // UI summary display mode
private workingDirectory?: string // Current working directory for relative path display
) { }
/**
* Sends an ignored message to the session UI (user sees it, AI doesn't)
*/
private async sendIgnoredMessage(sessionID: string, text: string) {
try {
await this.client.session.prompt({
path: {
id: sessionID
},
body: {
noReply: true, // Don't wait for AI response
parts: [{
type: 'text',
text: text,
ignored: true
}]
}
})
} catch (error: any) {
this.logger.error("janitor", "Failed to send notification", {
error: error.message
})
}
}
/**
* Convenience method for idle-triggered pruning (sends notification automatically)
*/
async runOnIdle(sessionID: string, strategies: PruningStrategy[]): Promise<void> {
await this.runWithStrategies(sessionID, strategies, { trigger: 'idle' })
// Notification is handled inside runWithStrategies
}
/**
* Convenience method for tool-triggered pruning (returns result for tool output)
*/
async runForTool(
sessionID: string,
strategies: PruningStrategy[],
reason?: string
): Promise<PruningResult | null> {
return await this.runWithStrategies(sessionID, strategies, { trigger: 'tool', reason })
}
/**
* Core pruning method that accepts strategies and options
*/
async runWithStrategies(
sessionID: string,
strategies: PruningStrategy[],
options: PruningOptions
): Promise<PruningResult | null> {
try {
// Skip if no strategies configured
if (strategies.length === 0) {
return null
}
// Fetch session info and messages from OpenCode API
const [sessionInfoResponse, messagesResponse] = await Promise.all([
this.client.session.get({ path: { id: sessionID } }),
this.client.session.messages({ path: { id: sessionID }, query: { limit: 100 } })
])
const sessionInfo = sessionInfoResponse.data
// Handle the response format - it should be { data: Array<{info, parts}> } or just the array
const messages = messagesResponse.data || messagesResponse
// If there are no messages or very few, skip analysis
if (!messages || messages.length < 3) {
return null
}
// Extract tool call IDs from the session and track their output sizes
// Also track batch tool relationships and tool metadata
const toolCallIds: string[] = []
const toolOutputs = new Map<string, string>()
const toolMetadata = new Map<string, { tool: string, parameters?: any }>() // callID -> {tool, parameters}
const batchToolChildren = new Map<string, string[]>() // batchID -> [childIDs]
let currentBatchId: string | null = null
for (const msg of messages) {
if (msg.parts) {
for (const part of msg.parts) {
if (part.type === "tool" && part.callID) {
// Normalize tool call IDs to lowercase for consistent comparison
const normalizedId = part.callID.toLowerCase()
toolCallIds.push(normalizedId)
// Try to get parameters from cache first, fall back to part.parameters
// Cache might have either case, so check both
const cachedData = this.toolParametersCache.get(part.callID) || this.toolParametersCache.get(normalizedId)
const parameters = cachedData?.parameters || part.parameters
// Track tool metadata (name and parameters)
toolMetadata.set(normalizedId, {
tool: part.tool,
parameters: parameters
})
// Track the output content for size calculation
if (part.state?.status === "completed" && part.state.output) {
toolOutputs.set(normalizedId, part.state.output)
}
// Check if this is a batch tool by looking at the tool name
if (part.tool === "batch") {
currentBatchId = normalizedId
batchToolChildren.set(normalizedId, [])
}
// If we're inside a batch and this is a prt_ (parallel) tool call, it's a child
else if (currentBatchId && normalizedId.startsWith('prt_')) {
batchToolChildren.get(currentBatchId)!.push(normalizedId)
}
// If we hit a non-batch, non-prt_ tool, we're out of the batch
else if (currentBatchId && !normalizedId.startsWith('prt_')) {
currentBatchId = null
}
}
}
}
}
// Get already pruned IDs to filter them out
const alreadyPrunedIds = this.prunedIdsState.get(sessionID) ?? []
const unprunedToolCallIds = toolCallIds.filter(id => !alreadyPrunedIds.includes(id))
// If there are no unpruned tool calls, skip analysis
if (unprunedToolCallIds.length === 0) {
return null
}
// ============================================================
// PHASE 1: DUPLICATE DETECTION (if enabled)
// ============================================================
let deduplicatedIds: string[] = []
let deduplicationDetails = new Map<string, any>()
if (strategies.includes('deduplication')) {
const dedupeResult = detectDuplicates(toolMetadata, unprunedToolCallIds, this.protectedTools)
deduplicatedIds = dedupeResult.duplicateIds
deduplicationDetails = dedupeResult.deduplicationDetails
}
// Calculate candidates available for pruning (excludes protected tools)
const candidateCount = unprunedToolCallIds.filter(id => {
const metadata = toolMetadata.get(id)
return !metadata || !this.protectedTools.includes(metadata.tool)
}).length
// ============================================================
// PHASE 2: LLM ANALYSIS (if enabled)
// ============================================================
let llmPrunedIds: string[] = []
if (strategies.includes('ai-analysis')) {
// Filter out duplicates and protected tools
const protectedToolCallIds: string[] = []
const prunableToolCallIds = unprunedToolCallIds.filter(id => {
// Skip already deduplicated
if (deduplicatedIds.includes(id)) return false
// Skip protected tools
const metadata = toolMetadata.get(id)
if (metadata && this.protectedTools.includes(metadata.tool)) {
protectedToolCallIds.push(id)
return false
}
return true
})
// Run LLM analysis only if there are prunable tools
if (prunableToolCallIds.length > 0) {
// Select appropriate model with intelligent fallback
const cachedModelInfo = this.modelCache.get(sessionID)
const sessionModelInfo = extractModelFromSession(sessionInfo, this.logger)
const currentModelInfo = cachedModelInfo || sessionModelInfo
const modelSelection = await selectModel(currentModelInfo, this.logger, this.configModel, this.workingDirectory)
this.logger.info("janitor", `Model: ${modelSelection.modelInfo.providerID}/${modelSelection.modelInfo.modelID}`, {
source: modelSelection.source
})
// Show toast if we had to fallback from a failed model
if (modelSelection.failedModel && this.showModelErrorToasts) {
try {
await this.client.tui.showToast({
body: {
title: "DCP: Model fallback",
message: `${modelSelection.failedModel.providerID}/${modelSelection.failedModel.modelID} failed\nUsing ${modelSelection.modelInfo.providerID}/${modelSelection.modelInfo.modelID}`,
variant: "info",
duration: 5000
}
})
} catch (toastError: any) {
// Don't fail the whole operation if toast fails
}
}
// Lazy import - only load the 2.8MB ai package when actually needed
const { generateObject } = await import('ai')
// Replace already-pruned tool outputs to save tokens in janitor context
const allPrunedSoFar = [...alreadyPrunedIds, ...deduplicatedIds]
const sanitizedMessages = this.replacePrunedToolOutputs(messages, allPrunedSoFar)
// Build the prompt for analysis (pass reason if provided)
const analysisPrompt = buildAnalysisPrompt(
prunableToolCallIds,
sanitizedMessages,
allPrunedSoFar,
protectedToolCallIds,
options.reason
)
// Save janitor shadow context directly (auth providers may bypass globalThis.fetch)
await this.logger.saveWrappedContext(
"janitor-shadow",
[{ role: "user", content: analysisPrompt }],
{
sessionID,
modelProvider: modelSelection.modelInfo.providerID,
modelID: modelSelection.modelInfo.modelID,
candidateToolCount: prunableToolCallIds.length,
alreadyPrunedCount: allPrunedSoFar.length,
protectedToolCount: protectedToolCallIds.length,
trigger: options.trigger,
reason: options.reason
}
)
// Analyze which tool calls are obsolete
const result = await generateObject({
model: modelSelection.model,
schema: z.object({
pruned_tool_call_ids: z.array(z.string()),
reasoning: z.string(),
}),
prompt: analysisPrompt
})
// Filter LLM results to only include IDs that were actually candidates
// (LLM sometimes returns duplicate IDs that were already filtered out)
const rawLlmPrunedIds = result.object.pruned_tool_call_ids
llmPrunedIds = rawLlmPrunedIds.filter(id =>
prunableToolCallIds.includes(id.toLowerCase())
)
if (llmPrunedIds.length > 0) {
const reasoning = result.object.reasoning.replace(/\n+/g, ' ').replace(/\s+/g, ' ').trim()
this.logger.info("janitor", `LLM reasoning: ${reasoning.substring(0, 200)}${reasoning.length > 200 ? '...' : ''}`)
}
}
}
// ============================================================
// PHASE 3: COMBINE & EXPAND
// ============================================================
const newlyPrunedIds = [...deduplicatedIds, ...llmPrunedIds]
if (newlyPrunedIds.length === 0) {
return null
}
// Helper to expand batch tool IDs to include their children
const expandBatchIds = (ids: string[]): string[] => {
const expanded = new Set<string>()
for (const id of ids) {
const normalizedId = id.toLowerCase()
expanded.add(normalizedId)
// If this is a batch tool, add all its children
const children = batchToolChildren.get(normalizedId)
if (children) {
children.forEach(childId => expanded.add(childId))
}
}
return Array.from(expanded)
}
// Expand batch tool IDs to include their children
const expandedPrunedIds = new Set(expandBatchIds(newlyPrunedIds))
// Expand llmPrunedIds for UI display (so batch children show instead of "unknown metadata")
const expandedLlmPrunedIds = expandBatchIds(llmPrunedIds)
// Calculate which IDs are actually NEW (not already pruned)
const finalNewlyPrunedIds = Array.from(expandedPrunedIds).filter(id => !alreadyPrunedIds.includes(id))
// finalPrunedIds includes everything (new + already pruned) for logging
const finalPrunedIds = Array.from(expandedPrunedIds)
// ============================================================
// PHASE 4: CALCULATE STATS & NOTIFICATION
// ============================================================
// Calculate token savings once (used by both notification and log)
const tokensSaved = await this.calculateTokensSaved(finalNewlyPrunedIds, toolOutputs)
// Accumulate session stats (for showing cumulative totals in UI)
const currentStats = this.statsState.get(sessionID) ?? { totalToolsPruned: 0, totalTokensSaved: 0 }
const sessionStats: SessionStats = {
totalToolsPruned: currentStats.totalToolsPruned + finalNewlyPrunedIds.length,
totalTokensSaved: currentStats.totalTokensSaved + tokensSaved
}
this.statsState.set(sessionID, sessionStats)
// Determine notification mode based on which strategies ran
const hasLlmAnalysis = strategies.includes('ai-analysis')
if (hasLlmAnalysis) {
await this.sendSmartModeNotification(
sessionID,
deduplicatedIds,
deduplicationDetails,
expandedLlmPrunedIds,
toolMetadata,
tokensSaved,
sessionStats
)
} else {
await this.sendAutoModeNotification(
sessionID,
deduplicatedIds,
deduplicationDetails,
tokensSaved,
sessionStats
)
}
// ============================================================
// PHASE 5: STATE UPDATE
// ============================================================
// Merge newly pruned IDs with existing ones (using expanded IDs)
const allPrunedIds = [...new Set([...alreadyPrunedIds, ...finalPrunedIds])]
this.prunedIdsState.set(sessionID, allPrunedIds)
// Log final summary
// Format: "Pruned 5/5 tools (~4.2K tokens), 0 kept" or with breakdown if both duplicate and llm
const prunedCount = finalNewlyPrunedIds.length
const keptCount = candidateCount - prunedCount
const hasBoth = deduplicatedIds.length > 0 && llmPrunedIds.length > 0
const breakdown = hasBoth ? ` (${deduplicatedIds.length} duplicate, ${llmPrunedIds.length} llm)` : ""
// Build log metadata
const logMeta: Record<string, any> = { trigger: options.trigger }
if (options.reason) {
logMeta.reason = options.reason
}
this.logger.info("janitor", `Pruned ${prunedCount}/${candidateCount} tools${breakdown}, ${keptCount} kept (~${formatTokenCount(tokensSaved)} tokens)`, logMeta)
return {
prunedCount: finalNewlyPrunedIds.length,
tokensSaved,
deduplicatedIds,
llmPrunedIds: expandedLlmPrunedIds,
deduplicationDetails,
toolMetadata,
sessionStats
}
} catch (error: any) {
this.logger.error("janitor", "Analysis failed", {
error: error.message,
trigger: options.trigger
})
// Don't throw - this is a fire-and-forget background process
// Silently fail and try again on next idle event
return null
}
}
/**
* Helper function to shorten paths for display
*/
private shortenPath(input: string): string {
// Handle compound strings like: "pattern" in /absolute/path
// Extract and shorten just the path portion
const inPathMatch = input.match(/^(.+) in (.+)$/)
if (inPathMatch) {
const prefix = inPathMatch[1]
const pathPart = inPathMatch[2]
const shortenedPath = this.shortenSinglePath(pathPart)
return `${prefix} in ${shortenedPath}`
}
return this.shortenSinglePath(input)
}
/**
* Shorten a single path string
*/
private shortenSinglePath(path: string): string {
const homeDir = require('os').homedir()
// Strip working directory FIRST (before ~ replacement) for cleaner relative paths
if (this.workingDirectory) {
if (path.startsWith(this.workingDirectory + '/')) {
return path.slice(this.workingDirectory.length + 1)
}
// Exact match (the directory itself)
if (path === this.workingDirectory) {
return '.'
}
}
// Replace home directory with ~
if (path.startsWith(homeDir)) {
path = '~' + path.slice(homeDir.length)
}
// Shorten node_modules paths: show package + file only
const nodeModulesMatch = path.match(/node_modules\/(@[^\/]+\/[^\/]+|[^\/]+)\/(.*)/)
if (nodeModulesMatch) {
return `${nodeModulesMatch[1]}/${nodeModulesMatch[2]}`
}
// Try matching against ~ version of working directory (for paths already with ~)
if (this.workingDirectory) {
const workingDirWithTilde = this.workingDirectory.startsWith(homeDir)
? '~' + this.workingDirectory.slice(homeDir.length)
: null
if (workingDirWithTilde && path.startsWith(workingDirWithTilde + '/')) {
return path.slice(workingDirWithTilde.length + 1)
}
if (workingDirWithTilde && path === workingDirWithTilde) {
return '.'
}
}
return path
}
/**
* Replace pruned tool outputs with placeholder text to save tokens in janitor context
* This applies the same replacement logic as the global fetch wrapper, but for the
* janitor's shadow inference to avoid sending already-pruned content to the LLM
*/
private replacePrunedToolOutputs(messages: any[], prunedIds: string[]): any[] {
if (prunedIds.length === 0) return messages
const prunedIdsSet = new Set(prunedIds.map(id => id.toLowerCase()))
return messages.map(msg => {
if (!msg.parts) return msg
return {
...msg,
parts: msg.parts.map((part: any) => {
if (part.type === 'tool' &&
part.callID &&
prunedIdsSet.has(part.callID.toLowerCase()) &&
part.state?.output) {
// Replace with the same placeholder used by the global fetch wrapper
return {
...part,
state: {
...part.state,
output: '[Output removed to save context - information superseded or no longer needed]'
}
}
}
return part
})
}
})
}
/**
* Helper function to calculate token savings from tool outputs
*/
private async calculateTokensSaved(prunedIds: string[], toolOutputs: Map<string, string>): Promise<number> {
const outputsToTokenize: string[] = []
for (const prunedId of prunedIds) {
const output = toolOutputs.get(prunedId)
if (output) {
outputsToTokenize.push(output)
}
}
if (outputsToTokenize.length > 0) {
// Use batch tokenization for efficiency (lazy loads gpt-tokenizer)
const tokenCounts = await estimateTokensBatch(outputsToTokenize)
return tokenCounts.reduce((sum, count) => sum + count, 0)
}
return 0
}
/**
* Build a summary of tools by grouping them
* Uses shared extractParameterKey logic for consistent parameter extraction
*
* Note: prunedIds may be in original case (from LLM) but toolMetadata uses lowercase keys
*/
private buildToolsSummary(prunedIds: string[], toolMetadata: Map<string, { tool: string, parameters?: any }>): Map<string, string[]> {
const toolsSummary = new Map<string, string[]>()
// Helper function to truncate long strings
const truncate = (str: string, maxLen: number = 60): string => {
if (str.length <= maxLen) return str
return str.slice(0, maxLen - 3) + '...'
}
for (const prunedId of prunedIds) {
// Normalize ID to lowercase for lookup (toolMetadata uses lowercase keys)
const normalizedId = prunedId.toLowerCase()
const metadata = toolMetadata.get(normalizedId)
if (metadata) {
const toolName = metadata.tool
// Skip 'batch' tool in UI summary - it's a wrapper and its children are shown individually
if (toolName === 'batch') continue
if (!toolsSummary.has(toolName)) {
toolsSummary.set(toolName, [])
}
// Use shared parameter extraction logic
const paramKey = extractParameterKey(metadata)
if (paramKey) {
// Apply path shortening and truncation for display
const displayKey = truncate(this.shortenPath(paramKey), 80)
toolsSummary.get(toolName)!.push(displayKey)
} else {
// For tools with no extractable parameter key, add a placeholder
// This ensures the tool still shows up in the summary
toolsSummary.get(toolName)!.push('(default)')
}
}
}
return toolsSummary
}
/**
* Group deduplication details by tool type
* Shared helper used by notifications and tool output formatting
*/
private groupDeduplicationDetails(
deduplicationDetails: Map<string, any>
): Map<string, Array<{ count: number, key: string }>> {
const grouped = new Map<string, Array<{ count: number, key: string }>>()
for (const [_, details] of deduplicationDetails) {
const { toolName, parameterKey, duplicateCount } = details
// Skip 'batch' tool in UI summary - it's a wrapper and its children are shown individually
if (toolName === 'batch') continue
if (!grouped.has(toolName)) {
grouped.set(toolName, [])
}
grouped.get(toolName)!.push({
count: duplicateCount,
key: this.shortenPath(parameterKey)
})
}
return grouped
}
/**
* Format grouped deduplication results as lines
* Shared helper for building deduplication summaries
*/
private formatDeduplicationLines(
grouped: Map<string, Array<{ count: number, key: string }>>,
indent: string = ' '
): string[] {
const lines: string[] = []
for (const [toolName, items] of grouped.entries()) {
for (const item of items) {
const removedCount = item.count - 1
lines.push(`${indent}${toolName}: ${item.key} (${removedCount}× duplicate)`)
}
}
return lines
}
/**
* Format tool summary (from buildToolsSummary) as lines
* Shared helper for building LLM-pruned summaries
*/
private formatToolSummaryLines(
toolsSummary: Map<string, string[]>,
indent: string = ' '
): string[] {
const lines: string[] = []
for (const [toolName, params] of toolsSummary.entries()) {
if (params.length === 1) {
lines.push(`${indent}${toolName}: ${params[0]}`)
} else if (params.length > 1) {
lines.push(`${indent}${toolName} (${params.length}):`)
for (const param of params) {
lines.push(`${indent} ${param}`)
}
}
}
return lines
}
/**
* Send minimal summary notification (just tokens saved and count)
*/
private async sendMinimalNotification(
sessionID: string,
totalPruned: number,
tokensSaved: number,
sessionStats: SessionStats
) {
if (totalPruned === 0) return
const tokensFormatted = formatTokenCount(tokensSaved)
const toolText = totalPruned === 1 ? 'tool' : 'tools'
let message = `🧹 DCP: Saved ~${tokensFormatted} tokens (${totalPruned} ${toolText} pruned)`
// Add session totals if there's been more than one pruning run
if (sessionStats.totalToolsPruned > totalPruned) {
message += ` │ Session: ~${formatTokenCount(sessionStats.totalTokensSaved)} tokens, ${sessionStats.totalToolsPruned} tools`
}
await this.sendIgnoredMessage(sessionID, message)
}
/**
* Auto mode notification - shows only deduplication results
*/
private async sendAutoModeNotification(
sessionID: string,
deduplicatedIds: string[],
deduplicationDetails: Map<string, any>,
tokensSaved: number,
sessionStats: SessionStats
) {
if (deduplicatedIds.length === 0) return
// Check if notifications are disabled
if (this.pruningSummary === 'off') return
// Send minimal notification if configured
if (this.pruningSummary === 'minimal') {
await this.sendMinimalNotification(sessionID, deduplicatedIds.length, tokensSaved, sessionStats)
return
}
// Otherwise send detailed notification
const tokensFormatted = formatTokenCount(tokensSaved)
const toolText = deduplicatedIds.length === 1 ? 'tool' : 'tools'
let message = `🧹 DCP: Saved ~${tokensFormatted} tokens (${deduplicatedIds.length} duplicate ${toolText} removed)`
// Add session totals if there's been more than one pruning run
if (sessionStats.totalToolsPruned > deduplicatedIds.length) {
message += ` │ Session: ~${formatTokenCount(sessionStats.totalTokensSaved)} tokens, ${sessionStats.totalToolsPruned} tools`
}
message += '\n'
// Group by tool type using shared helper
const grouped = this.groupDeduplicationDetails(deduplicationDetails)
// Display grouped results (with UI-specific formatting: total dupes header, limit to 5)
for (const [toolName, items] of grouped.entries()) {
const totalDupes = items.reduce((sum, item) => sum + (item.count - 1), 0)
message += `\n${toolName} (${totalDupes} duplicate${totalDupes > 1 ? 's' : ''}):\n`
for (const item of items.slice(0, 5)) {
const dupeCount = item.count - 1
message += ` ${item.key} (${dupeCount}× duplicate)\n`
}
if (items.length > 5) {
message += ` ... and ${items.length - 5} more\n`
}
}
await this.sendIgnoredMessage(sessionID, message.trim())
}
/**
* Format pruning result for tool output (returned to AI)
* Uses shared helpers for consistency with UI notifications
*/
formatPruningResultForTool(result: PruningResult): string {
const lines: string[] = []
lines.push(`Context pruning complete. Pruned ${result.prunedCount} tool outputs.`)
lines.push('')
// Section 1: Deduplicated tools
if (result.deduplicatedIds.length > 0 && result.deduplicationDetails.size > 0) {
lines.push(`Duplicates removed (${result.deduplicatedIds.length}):`)
const grouped = this.groupDeduplicationDetails(result.deduplicationDetails)
lines.push(...this.formatDeduplicationLines(grouped))
lines.push('')
}
// Section 2: LLM-pruned tools
if (result.llmPrunedIds.length > 0) {
lines.push(`Semantically pruned (${result.llmPrunedIds.length}):`)
const toolsSummary = this.buildToolsSummary(result.llmPrunedIds, result.toolMetadata)
lines.push(...this.formatToolSummaryLines(toolsSummary))
}
return lines.join('\n').trim()
}
/**
* Smart mode notification - shows both deduplication and LLM analysis results
*/
private async sendSmartModeNotification(
sessionID: string,
deduplicatedIds: string[],
deduplicationDetails: Map<string, any>,
llmPrunedIds: string[],
toolMetadata: Map<string, any>,
tokensSaved: number,
sessionStats: SessionStats
) {
const totalPruned = deduplicatedIds.length + llmPrunedIds.length
if (totalPruned === 0) return
// Check if notifications are disabled
if (this.pruningSummary === 'off') return
// Send minimal notification if configured
if (this.pruningSummary === 'minimal') {
await this.sendMinimalNotification(sessionID, totalPruned, tokensSaved, sessionStats)
return
}
// Otherwise send detailed notification
const tokensFormatted = formatTokenCount(tokensSaved)
let message = `🧹 DCP: Saved ~${tokensFormatted} tokens (${totalPruned} tool${totalPruned > 1 ? 's' : ''} pruned)`
// Add session totals if there's been more than one pruning run
if (sessionStats.totalToolsPruned > totalPruned) {
message += ` │ Session: ~${formatTokenCount(sessionStats.totalTokensSaved)} tokens, ${sessionStats.totalToolsPruned} tools`
}
message += '\n'
// Section 1: Deduplicated tools
if (deduplicatedIds.length > 0 && deduplicationDetails) {
message += `\n📦 Duplicates removed (${deduplicatedIds.length}):\n`
const grouped = this.groupDeduplicationDetails(deduplicationDetails)
for (const [toolName, items] of grouped.entries()) {
message += ` ${toolName}:\n`
for (const item of items) {
const removedCount = item.count - 1 // Total occurrences minus the one we kept
message += ` ${item.key} (${removedCount}× duplicate)\n`
}
}
}
// Section 2: LLM-pruned tools
if (llmPrunedIds.length > 0) {
message += `\n🤖 LLM analysis (${llmPrunedIds.length}):\n`
const toolsSummary = this.buildToolsSummary(llmPrunedIds, toolMetadata)
for (const [toolName, params] of toolsSummary.entries()) {
if (params.length > 0) {
message += ` ${toolName} (${params.length}):\n`
for (const param of params) {
message += ` ${param}\n`
}
}
}
// Handle any tools that weren't found in metadata (edge case)
const foundToolNames = new Set(toolsSummary.keys())
const missingTools = llmPrunedIds.filter(id => {
const normalizedId = id.toLowerCase()
const metadata = toolMetadata.get(normalizedId)
return !metadata || !foundToolNames.has(metadata.tool)
})
if (missingTools.length > 0) {
message += ` (${missingTools.length} tool${missingTools.length > 1 ? 's' : ''} with unknown metadata)\n`
}
}
await this.sendIgnoredMessage(sessionID, message.trim())
}
}