( messages: Message[], )
| 851 | } |
| 852 | |
| 853 | async function approximateMessageTokens( |
| 854 | messages: Message[], |
| 855 | ): Promise<MessageBreakdown> { |
| 856 | const microcompactResult = await microcompactMessages(messages) |
| 857 | |
| 858 | // Initialize tracking |
| 859 | const breakdown: MessageBreakdown = { |
| 860 | totalTokens: 0, |
| 861 | toolCallTokens: 0, |
| 862 | toolResultTokens: 0, |
| 863 | attachmentTokens: 0, |
| 864 | assistantMessageTokens: 0, |
| 865 | userMessageTokens: 0, |
| 866 | toolCallsByType: new Map<string, number>(), |
| 867 | toolResultsByType: new Map<string, number>(), |
| 868 | attachmentsByType: new Map<string, number>(), |
| 869 | } |
| 870 | |
| 871 | // Build a map of tool_use_id to tool_name for easier lookup |
| 872 | const toolUseIdToName = new Map<string, string>() |
| 873 | for (const msg of microcompactResult.messages) { |
| 874 | if (msg.type === 'assistant') { |
| 875 | for (const block of msg.message.content) { |
| 876 | if ('type' in block && block.type === 'tool_use') { |
| 877 | const toolUseId = 'id' in block ? block.id : undefined |
| 878 | const toolName = |
| 879 | ('name' in block ? block.name : undefined) || 'unknown' |
| 880 | if (toolUseId) { |
| 881 | toolUseIdToName.set(toolUseId, toolName) |
| 882 | } |
| 883 | } |
| 884 | } |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | // Process each message for detailed breakdown |
| 889 | for (const msg of microcompactResult.messages) { |
| 890 | if (msg.type === 'assistant') { |
| 891 | processAssistantMessage(msg, breakdown) |
| 892 | } else if (msg.type === 'user') { |
| 893 | processUserMessage(msg, breakdown, toolUseIdToName) |
| 894 | } else if (msg.type === 'attachment') { |
| 895 | processAttachment(msg, breakdown) |
| 896 | } |
| 897 | } |
| 898 | |
| 899 | // Calculate total tokens using the API for accuracy |
| 900 | const approximateMessageTokens = await countTokensWithFallback( |
| 901 | normalizeMessagesForAPI(microcompactResult.messages).map(_ => { |
| 902 | if (_.type === 'assistant') { |
| 903 | return { |
| 904 | // Important: strip out fields like id, etc. -- the counting API errors if they're present |
| 905 | role: 'assistant', |
| 906 | content: _.message.content, |
| 907 | } |
| 908 | } |
| 909 | return _.message |
| 910 | }), |
no test coverage detected