( messages: (UserMessage | AssistantMessage)[], limit: number, )
| 954 | * Strips oldest media first to preserve the most recent. |
| 955 | */ |
| 956 | export function stripExcessMediaItems( |
| 957 | messages: (UserMessage | AssistantMessage)[], |
| 958 | limit: number, |
| 959 | ): (UserMessage | AssistantMessage)[] { |
| 960 | let toRemove = 0 |
| 961 | for (const msg of messages) { |
| 962 | if (!Array.isArray(msg.message.content)) continue |
| 963 | for (const block of msg.message.content) { |
| 964 | if (isMedia(block)) toRemove++ |
| 965 | if (isToolResult(block) && Array.isArray(block.content)) { |
| 966 | for (const nested of block.content) { |
| 967 | if (isMedia(nested)) toRemove++ |
| 968 | } |
| 969 | } |
| 970 | } |
| 971 | } |
| 972 | toRemove -= limit |
| 973 | if (toRemove <= 0) return messages |
| 974 | |
| 975 | return messages.map(msg => { |
| 976 | if (toRemove <= 0) return msg |
| 977 | const content = msg.message.content |
| 978 | if (!Array.isArray(content)) return msg |
| 979 | |
| 980 | const before = toRemove |
| 981 | const stripped = content |
| 982 | .map(block => { |
| 983 | if ( |
| 984 | toRemove <= 0 || |
| 985 | !isToolResult(block) || |
| 986 | !Array.isArray(block.content) |
| 987 | ) |
| 988 | return block |
| 989 | const filtered = block.content.filter(n => { |
| 990 | if (toRemove > 0 && isMedia(n)) { |
| 991 | toRemove-- |
| 992 | return false |
| 993 | } |
| 994 | return true |
| 995 | }) |
| 996 | return filtered.length === block.content.length |
| 997 | ? block |
| 998 | : { ...block, content: filtered } |
| 999 | }) |
| 1000 | .filter(block => { |
| 1001 | if (toRemove > 0 && isMedia(block)) { |
| 1002 | toRemove-- |
| 1003 | return false |
| 1004 | } |
| 1005 | return true |
| 1006 | }) |
| 1007 | |
| 1008 | return before === toRemove |
| 1009 | ? msg |
| 1010 | : { |
| 1011 | ...msg, |
| 1012 | message: { ...msg.message, content: stripped }, |
| 1013 | } |
no test coverage detected