@@ -62,7 +62,15 @@ export function createPruningTool(
6262 return "None of the provided IDs were valid. Check the <prunable-tools> list for available IDs."
6363 }
6464
65- const tokensSaved = await calculateTokensSaved ( client , sessionId , prunedIds )
65+ // Fetch messages to calculate tokens and find current agent
66+ const messagesResponse = await client . session . messages ( {
67+ path : { id : sessionId } ,
68+ query : { limit : 200 }
69+ } )
70+ const messages = messagesResponse . data || messagesResponse
71+
72+ const currentAgent = findCurrentAgent ( messages )
73+ const tokensSaved = await calculateTokensSavedFromMessages ( messages , prunedIds )
6674
6775 const currentStats = state . stats . get ( sessionId ) ?? {
6876 totalToolsPruned : 0 ,
@@ -105,7 +113,7 @@ export function createPruningTool(
105113 toolMetadata,
106114 gcPending : null ,
107115 sessionStats
108- } )
116+ } , currentAgent )
109117
110118 toolTracker . skipNextIdle = true
111119
@@ -128,21 +136,29 @@ export function createPruningTool(
128136 } )
129137}
130138
139+ /**
140+ * Finds the current agent from messages (same logic as janitor.ts).
141+ */
142+ function findCurrentAgent ( messages : any [ ] ) : string | undefined {
143+ for ( let i = messages . length - 1 ; i >= 0 ; i -- ) {
144+ const msg = messages [ i ]
145+ const info = msg . info
146+ if ( info ?. role === 'user' ) {
147+ return info . agent || 'build'
148+ }
149+ }
150+ return undefined
151+ }
152+
131153/**
132154 * Calculates approximate tokens saved by pruning the given tool call IDs.
155+ * Uses pre-fetched messages to avoid duplicate API calls.
133156 */
134- async function calculateTokensSaved (
135- client : any ,
136- sessionId : string ,
157+ async function calculateTokensSavedFromMessages (
158+ messages : any [ ] ,
137159 prunedIds : string [ ]
138160) : Promise < number > {
139161 try {
140- const messagesResponse = await client . session . messages ( {
141- path : { id : sessionId } ,
142- query : { limit : 200 }
143- } )
144- const messages = messagesResponse . data || messagesResponse
145-
146162 const toolOutputs = new Map < string , string > ( )
147163 for ( const msg of messages ) {
148164 if ( msg . role === 'tool' && msg . tool_call_id ) {
0 commit comments