MCPcopy Create free account
hub / github.com/claude-code-best/claude-code / approximateMessageTokens

Function approximateMessageTokens

src/utils/analyzeContext.ts:869–938  ·  view source on GitHub ↗
(
  messages: Message[],
)

Source from the content-addressed store, hash-verified

867}
868
869async function approximateMessageTokens(
870 messages: Message[],
871): Promise<MessageBreakdown> {
872 const microcompactResult = await microcompactMessages(messages)
873
874 // Initialize tracking
875 const breakdown: MessageBreakdown = {
876 totalTokens: 0,
877 toolCallTokens: 0,
878 toolResultTokens: 0,
879 attachmentTokens: 0,
880 assistantMessageTokens: 0,
881 userMessageTokens: 0,
882 toolCallsByType: new Map<string, number>(),
883 toolResultsByType: new Map<string, number>(),
884 attachmentsByType: new Map<string, number>(),
885 }
886
887 // Build a map of tool_use_id to tool_name for easier lookup
888 const toolUseIdToName = new Map<string, string>()
889 for (const msg of microcompactResult.messages) {
890 if (msg.type === 'assistant' && Array.isArray(msg.message!.content)) {
891 for (const block of msg.message!.content) {
892 if (
893 typeof block !== 'string' &&
894 'type' in block &&
895 block.type === 'tool_use'
896 ) {
897 const toolUseId = 'id' in block ? (block.id as string) : undefined
898 const toolName =
899 (('name' in block ? block.name : undefined) as
900 | string
901 | undefined) || 'unknown'
902 if (toolUseId) {
903 toolUseIdToName.set(toolUseId, toolName)
904 }
905 }
906 }
907 }
908 }
909
910 // Process each message for detailed breakdown
911 for (const msg of microcompactResult.messages) {
912 if (msg.type === 'assistant') {
913 processAssistantMessage(msg as AssistantMessage, breakdown)
914 } else if (msg.type === 'user') {
915 processUserMessage(msg as UserMessage, breakdown, toolUseIdToName)
916 } else if (msg.type === 'attachment') {
917 processAttachment(msg as AttachmentMessage, breakdown)
918 }
919 }
920
921 // Calculate total tokens using the API for accuracy
922 const approximateMessageTokens = await countTokensWithFallback(
923 normalizeMessagesForAPI(microcompactResult.messages).map(_ => {
924 if (_.type === 'assistant') {
925 return {
926 // Important: strip out fields like id, etc. -- the counting API errors if they're present

Callers 1

analyzeContextUsageFunction · 0.85

Calls 7

microcompactMessagesFunction · 0.85
processAssistantMessageFunction · 0.85
processUserMessageFunction · 0.85
processAttachmentFunction · 0.85
countTokensWithFallbackFunction · 0.85
normalizeMessagesForAPIFunction · 0.85
setMethod · 0.80

Tested by

no test coverage detected