refactor: share tool result char estimation

This commit is contained in:
Peter Steinberger
2026-03-14 01:02:18 +00:00
parent 0db62fc6c5
commit 6e3f0f9fcb

View File

@@ -46,6 +46,20 @@ function getToolResultContent(msg: AgentMessage): unknown[] {
return Array.isArray(content) ? content : [];
}
function estimateContentBlockChars(content: unknown[]): number {
let chars = 0;
for (const block of content) {
if (isTextBlock(block)) {
chars += block.text.length;
} else if (isImageBlock(block)) {
chars += IMAGE_CHAR_ESTIMATE;
} else {
chars += estimateUnknownChars(block);
}
}
return chars;
}
export function getToolResultText(msg: AgentMessage): string {
const content = getToolResultContent(msg);
const chunks: string[] = [];
@@ -67,19 +81,10 @@ function estimateMessageChars(msg: AgentMessage): number {
if (typeof content === "string") {
return content.length;
}
let chars = 0;
if (Array.isArray(content)) {
for (const block of content) {
if (isTextBlock(block)) {
chars += block.text.length;
} else if (isImageBlock(block)) {
chars += IMAGE_CHAR_ESTIMATE;
} else {
chars += estimateUnknownChars(block);
}
}
return estimateContentBlockChars(content);
}
return chars;
return 0;
}
if (msg.role === "assistant") {
@@ -115,17 +120,8 @@ function estimateMessageChars(msg: AgentMessage): number {
}
if (isToolResultMessage(msg)) {
let chars = 0;
const content = getToolResultContent(msg);
for (const block of content) {
if (isTextBlock(block)) {
chars += block.text.length;
} else if (isImageBlock(block)) {
chars += IMAGE_CHAR_ESTIMATE;
} else {
chars += estimateUnknownChars(block);
}
}
let chars = estimateContentBlockChars(content);
const details = (msg as { details?: unknown }).details;
chars += estimateUnknownChars(details);
const weightedChars = Math.ceil(