MCPcopy Create free account
hub / github.com/AnukarOP/claude-code-leaked / tokenCountWithEstimation

Function tokenCountWithEstimation

source code/utils/tokens.ts:228–263  ·  view source on GitHub ↗
(messages: readonly Message[])

Source from the content-addressed store, hash-verified

226 * so every interleaved tool_result is included in the rough estimate.
227 */
228export function tokenCountWithEstimation(messages: readonly Message[]): number {
229 let i = messages.length - 1
230 while (i >= 0) {
231 const message = messages[i]
232 const usage = message ? getTokenUsage(message) : undefined
233 if (message && usage) {
234 // Walk back past any earlier sibling records split from the same API
235 // response (same message.id) so interleaved tool_results between them
236 // are included in the estimation slice.
237 const responseId = getAssistantMessageId(message)
238 if (responseId) {
239 let j = i - 1
240 while (j >= 0) {
241 const prior = messages[j]
242 const priorId = prior ? getAssistantMessageId(prior) : undefined
243 if (priorId === responseId) {
244 // Earlier split of the same API response — anchor here instead.
245 i = j
246 } else if (priorId !== undefined) {
247 // Hit a different API response — stop walking.
248 break
249 }
250 // priorId === undefined: a user/tool_result/attachment message,
251 // possibly interleaved between splits — keep walking.
252 j--
253 }
254 }
255 return (
256 getTokenCountFromUsage(usage) +
257 roughTokenCountEstimationForMessages(messages.slice(i + 1))
258 )
259 }
260 i--
261 }
262 return roughTokenCountEstimationForMessages(messages)
263}

Callers 10

queryLoopFunction · 0.85
classifyYoloActionFunction · 0.85
runInProcessTeammateFunction · 0.85
compactConversationFunction · 0.85
shouldAutoCompactFunction · 0.85
shouldExtractMemoryFunction · 0.85
sessionMemory.tsFile · 0.85

Calls 4

getTokenUsageFunction · 0.85
getAssistantMessageIdFunction · 0.85
getTokenCountFromUsageFunction · 0.85

Tested by

no test coverage detected