All files / src/messages converter.ts

86.41% Statements 299/346
73.72% Branches 188/255
91.66% Functions 33/36
86.47% Lines 294/340

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 7699x   9x 9x                           65x 2x   63x             3x 1x   2x     2x     2x 2x 2x           1x 1x 1x 1x 1x 1x             1x           25x     25x 25x     9x     341x 108x   233x 233x 233x 215x     18x     9x     18x     18x           18x       18x     18x 15x   3x   3x     3x     3x 3x                 26x   26x 26x 26x 9x     17x 17x                                                         9x     386x 386x 19x   367x     9x 24x 24x 24x 24x 25x 1x   24x 22x 22x 20x 20x   2x 2x 2x       2x       2x   2x 2x 2x                 24x         9x                   30x 6x   24x 43x         15x 15x       15x 15x                   15x 15x 15x 15x 20x 20x 6x   20x     15x     30x   15x     9x       144x   144x   184x           184x 184x 184x 184x   184x 192x 192x 7x 7x     185x 185x 13x       13x     172x 172x 164x 164x   8x 8x 7x 7x       7x   1x 1x         184x 7x 7x     7x                               184x 13x 13x 3x   13x             184x 184x   184x 163x 7x 7x 7x 7x 7x 7x   156x 156x   21x 1x       144x             9x       43x 43x 28x     15x 15x 15x                   15x         1x     14x     9x   764x 764x 764x 764x       764x                           9x   179x 179x 8x 8x 8x         171x 171x 9x 9x 9x       162x 162x 155x       7x 7x 7x                   9x     171x 171x 179x   170x     9x     129x 129x 163x   129x                               5x 5x 2x 2x 2x 2x     3x 3x 2x 2x 2x 2x     1x 1x 1x 1x       9x           6x                 6x 9x 9x   9x 10x 10x 10x   10x 10x   10x 2x 8x 2x 6x 1x   5x     5x 5x 1x 4x 2x   2x           6x     9x 15x 15x 15x 15x 15x 15x   15x           9x 324x 324x                                       12x 12x 12x 12x 12x 12x 12x                     9x     324x                 324x   434x               434x 421x   13x 25x 12x 13x 13x             434x 26x     434x 15x         324x               9x       11x 11x   6x 6x 3x     6x 6x 6x   6x 8x 8x 8x 1x   7x 7x           6x 6x 6x 6x 6x 8x                     8x                             8x   6x 1x     6x                   6x    
import { randomUUID } from "node:crypto";
 
import * as vscode from "vscode";
import { debugLog } from "../shared/logging";
import { JsonObject, NimChatMessage, NimContentPart, NimTool } from "../types";
 
export interface LegacyPart {
  type?: string;
  mimeType?: string;
  bytes?: Uint8Array | number[] | string;
  data?: Uint8Array | number[] | string;
  buffer?: ArrayBuffer;
  value?: string;
  [key: string]: unknown;
}
 
function asObjectRecord(value: unknown): Record<string, unknown> | undefined {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    return undefined;
  }
  return value as Record<string, unknown>;
}
 
function toUint8Array(
  data: Uint8Array | number[] | ArrayBuffer | string | undefined,
  options?: { allowBase64String?: boolean },
): Uint8Array | undefined {
  if (data instanceof Uint8Array && data.length > 0) {
    return data;
  }
  Iif (Array.isArray(data) && data.length > 0) {
    return new Uint8Array(data);
  }
  Iif (data instanceof ArrayBuffer && data.byteLength > 0) {
    return new Uint8Array(data);
  }
  if (typeof data === "string" && data.length > 0) {
    const trimmed = data.trim();
    if (
      options?.allowBase64String &&
      trimmed.length > 0 &&
      trimmed.length % 4 === 0 &&
      /^[A-Za-z0-9+/]+={0,2}$/.test(trimmed)
    ) {
      const decoded = Buffer.from(trimmed, "base64");
      if (decoded.length > 0) {
        try {
          const text = new TextDecoder().decode(decoded);
          if (!text.includes("\uFFFD") && !/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(text)) {
            return decoded;
          }
        } catch {
          // Fall back to treating the value as plain text.
        }
      }
    }
    return Buffer.from(data, "utf8");
  }
  return undefined;
}
 
function isIgnorableToolResultPart(part: vscode.LanguageModelInputPart | LegacyPart): boolean {
  Iif (typeof part !== "object" || part === null) {
    return false;
  }
  const mimeType = (part as { mimeType?: unknown }).mimeType;
  return typeof mimeType === "string" && mimeType.includes("cache_control");
}
 
export function getTextPartValue(
  part: vscode.LanguageModelInputPart | LegacyPart,
): string | undefined {
  if (part instanceof vscode.LanguageModelTextPart) {
    return part.value;
  }
  if (typeof part === "object" && part !== null) {
    const p = part as { value?: string };
    if (typeof p.value === "string") {
      return p.value;
    }
  }
  return undefined;
}
 
export function getDataPartTextValue(
  part: vscode.LanguageModelInputPart | LegacyPart,
): string | undefined {
  Iif (typeof part !== "object" || part === null) {
    return undefined;
  }
  const p = part as {
    mimeType?: unknown;
    data?: Uint8Array | number[] | string;
    bytes?: Uint8Array | number[] | string;
    buffer?: ArrayBuffer;
  };
  Iif (typeof p.mimeType !== "string") {
    return undefined;
  }
  const isTextMime =
    p.mimeType.startsWith("text/") ||
    p.mimeType === "application/json" ||
    p.mimeType.endsWith("+json");
  if (!isTextMime) {
    return undefined;
  }
  const allowBase64String = p.mimeType === "application/json" || p.mimeType.endsWith("+json");
  const bytes =
    toUint8Array(p.data, { allowBase64String }) ??
    toUint8Array(p.bytes, { allowBase64String }) ??
    toUint8Array(p.buffer);
  Iif (!bytes) {
    return undefined;
  }
  try {
    return new TextDecoder().decode(bytes);
  } catch {
    return undefined;
  }
}
 
function extractImageData(
  part: vscode.LanguageModelInputPart | LegacyPart,
): { mimeType: string; data: Uint8Array } | undefined {
  Iif (typeof part !== "object" || part === null) return undefined;
 
  const p = part as LegacyPart;
  const mimeType = typeof p.mimeType === "string" ? p.mimeType : undefined;
  if (!mimeType || !mimeType.startsWith("image/")) {
    return undefined;
  }
 
  if (p.data instanceof Uint8Array && p.data.length > 0) {
    return { mimeType, data: p.data };
  }
  Iif (p.bytes instanceof Uint8Array && p.bytes.length > 0) {
    return { mimeType, data: p.bytes };
  }
  Iif (p.buffer instanceof ArrayBuffer && p.buffer.byteLength > 0) {
    return { mimeType, data: new Uint8Array(p.buffer) };
  }
  Iif (Array.isArray(p.bytes) && p.bytes.length > 0) {
    return { mimeType, data: new Uint8Array(p.bytes) };
  }
  Iif (Array.isArray(p.data) && p.data.length > 0) {
    return { mimeType, data: new Uint8Array(p.data) };
  }
 
  Iif (typeof p.data === "string" && p.data.trim().length > 0) {
    const raw = p.data.trim();
    const payload = raw.startsWith("data:") ? raw.slice(raw.indexOf(",") + 1) : raw;
    Iif (/^[A-Za-z0-9+/\s]+={0,2}$/.test(payload)) {
      const decoded = Buffer.from(payload.replace(/\s/g, ""), "base64");
      Iif (decoded.length > 0) {
        return { mimeType, data: new Uint8Array(decoded) };
      }
    }
  }
 
  return undefined;
}
 
export function getToolCallInfo(
  part: vscode.LanguageModelInputPart | LegacyPart,
): { id?: string; name?: string; args?: Record<string, unknown> } | undefined {
  const p = part as { callId?: string; name?: string; input?: Record<string, unknown> };
  if (typeof p.callId === "string" && typeof p.name === "string") {
    return { id: p.callId, name: p.name, args: p.input };
  }
  return undefined;
}
 
export function getToolResultTexts(part: vscode.LanguageModelInputPart | LegacyPart): string[] {
  const results: string[] = [];
  const p = part as { callId?: string; content?: unknown[] };
  if (typeof p.callId === "string" && Array.isArray(p.content)) {
    for (const inner of p.content) {
      if (isIgnorableToolResultPart(inner as vscode.LanguageModelInputPart | LegacyPart)) {
        continue;
      }
      if (typeof inner === "object" && inner !== null && "value" in inner) {
        const value = (inner as { value?: unknown }).value;
        if (typeof value === "string") {
          results.push(value);
          continue;
        }
        if (value !== undefined) {
          try {
            results.push(JSON.stringify(value));
          } catch {
            results.push(String(value));
          }
          continue;
        }
      }
      const tv =
        getTextPartValue(inner as vscode.LanguageModelInputPart | LegacyPart) ??
        getDataPartTextValue(inner as vscode.LanguageModelInputPart | LegacyPart);
      if (tv !== undefined) {
        results.push(tv);
        continue;
      }
      debugLog("Unhandled tool result part", inner);
      try {
        results.push(JSON.stringify(inner));
      } catch {
        results.push(String(inner));
      }
    }
    return results;
  }
  return results;
}
 
const AUXILIARY_REQUIRED_FIELDS = new Set([
  "goal",
  "explanation",
  "mode",
  "summary",
  "description",
  "isRegexp",
]);
 
function payloadRequiredFields(schema: Record<string, unknown> | undefined): string[] {
  if (!Array.isArray(schema?.required)) {
    return [];
  }
  return schema.required.filter(
    (item): item is string => typeof item === "string" && !AUXILIARY_REQUIRED_FIELDS.has(item),
  );
}
 
function toModelFacingSchema(inputSchema: unknown): JsonObject | undefined {
  const schema = asObjectRecord(inputSchema);
  Iif (!schema) {
    return inputSchema as JsonObject | undefined;
  }
 
  const required = payloadRequiredFields(schema);
  return {
    ...schema,
    ...(Array.isArray(schema.required) ? { required } : {}),
  };
}
 
function buildToolDescription(
  description: string | undefined,
  inputSchema: unknown,
): string | undefined {
  const schema = asObjectRecord(inputSchema);
  const required = payloadRequiredFields(schema);
  const properties = asObjectRecord(schema?.properties);
  const requiredHints = required.map((name) => {
    const propertySchema = asObjectRecord(properties?.[name]);
    const enumValues = Array.isArray(propertySchema?.enum)
      ? propertySchema.enum.filter((item): item is string => typeof item === "string")
      : [];
    return enumValues.length > 0 ? `${name} (${enumValues.join(", ")})` : name;
  });
 
  const parts = [
    typeof description === "string" ? description.trim() : "",
    requiredHints.length > 0 ? `Required: ${requiredHints.join(", ")}.` : "",
  ].filter((part) => part.length > 0);
 
  return parts.length > 0 ? parts.join(" ") : undefined;
}
 
export function convertMessages(
  messages: readonly vscode.LanguageModelChatMessage[],
  options?: { maxToolResultChars?: number; supportsVision?: boolean },
): NimChatMessage[] {
  const result: NimChatMessage[] = [];
 
  for (const msg of messages) {
    const role =
      msg.role === vscode.LanguageModelChatMessageRole.User
        ? "user"
        : msg.role === vscode.LanguageModelChatMessageRole.Assistant
          ? "assistant"
          : "system";
 
    const textParts: string[] = [];
    const imageParts: NimContentPart[] = [];
    const toolCalls: Array<{ id?: string; name?: string; args?: Record<string, unknown> }> = [];
    const toolResults: Array<{ callId: string; content: string }> = [];
 
    for (const part of msg.content) {
      const toolCallInfo = getToolCallInfo(part);
      if (toolCallInfo) {
        toolCalls.push(toolCallInfo);
        continue;
      }
 
      const toolResultPart = part as { callId?: unknown; content?: unknown[] };
      if (typeof toolResultPart.callId === "string" && Array.isArray(toolResultPart.content)) {
        toolResults.push({
          callId: toolResultPart.callId,
          content: getToolResultTexts(part).join("\n").trim(),
        });
        continue;
      }
 
      const tv = getTextPartValue(part) ?? getDataPartTextValue(part);
      if (tv !== undefined) {
        textParts.push(tv);
        continue;
      }
      const img = extractImageData(part);
      if (img && options?.supportsVision) {
        const base64 = Buffer.from(img.data).toString("base64");
        imageParts.push({
          type: "image_url",
          image_url: { url: `data:${img.mimeType};base64,${base64}` },
        });
        continue;
      }
      if (img) {
        continue;
      }
      debugLog("convertMessages", `Unrecognized message part: ${JSON.stringify(part)}`);
    }
 
    if (toolCalls.length > 0) {
      const assistantContent = textParts.join("");
      result.push({
        role: "assistant",
        content: assistantContent || "",
        tool_calls: toolCalls.map((tc) => ({
          id: tc.id ?? `call_${randomUUID()}`,
          type: "function",
          function: {
            name: tc.name ?? "unknown",
            arguments: JSON.stringify(tc.args ?? {}),
          },
        })),
        // A single space of reasoning_content prevents incomplete responses on
        // models that require the field (Kimi K2.5/2.6) without polluting the
        // actual output. Applied globally so the converted assistant turn stays
        // uniform across the adapter-specific messages workarounds.
        reasoning_content: " ",
      });
    }
 
    for (const tr of toolResults) {
      let content = tr.content || "";
      if (options?.maxToolResultChars && content.length > options.maxToolResultChars) {
        content = content.slice(0, options.maxToolResultChars) + "…";
      }
      result.push({
        role: "tool",
        tool_call_id: tr.callId,
        content,
      });
    }
 
    const hasTextOrImage = textParts.length > 0 || imageParts.length > 0;
    const isAssistantWithToolCalls = role === "assistant" && toolCalls.length > 0;
 
    if (hasTextOrImage && !isAssistantWithToolCalls) {
      if (imageParts.length > 0) {
        const contentParts: NimContentPart[] = [];
        const text = textParts.join("");
        if (text) contentParts.push({ type: "text", text });
        contentParts.push(...imageParts);
        const newMsg: NimChatMessage = { role, content: contentParts };
        result.push(newMsg);
      } else {
        const newMsg: NimChatMessage = { role, content: textParts.join("") || "(empty message)" };
        result.push(newMsg);
      }
    } else if (!isAssistantWithToolCalls && toolResults.length === 0 && !hasTextOrImage) {
      result.push({ role, content: "(empty message)" });
    }
  }
 
  return result;
}
 
/**
 * Convert VS Code language model tools to the NVIDIA NIM tool-call format.
 * Honors the Required tool mode by emitting an explicit tool_choice.
 */
export function convertTools(options: vscode.ProvideLanguageModelChatResponseOptions): {
  tools?: NimTool[];
  tool_choice?: "auto" | "required" | { type: "function"; function: { name: string } };
} {
  const toolsInput = options.tools ?? [];
  if (toolsInput.length === 0) {
    return {};
  }
 
  const tools: NimTool[] = toolsInput.map((tool) => {
    const parameters = toModelFacingSchema(tool.inputSchema);
    return {
      type: "function",
      function: {
        name: tool.name,
        description: buildToolDescription(tool.description, parameters ?? tool.inputSchema),
        ...(parameters ? { parameters } : {}),
      },
    };
  });
 
  if (
    options.toolMode ===
    (vscode as unknown as { LanguageModelChatToolMode?: { Required?: number } })
      .LanguageModelChatToolMode?.Required
  ) {
    return { tools, tool_choice: "required" };
  }
 
  return { tools, tool_choice: "auto" };
}
 
export function estimateTokens(text: string): number {
  const cjkPattern =
    /[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff\u3000-\u303f\uff00-\uffef\uac00-\ud7af\u3040-\u309f\u30a0-\u30ff]/g;
  const cjkMatches = text.match(cjkPattern);
  const cjkCount = cjkMatches ? cjkMatches.length : 0;
  const otherCount = text.length - cjkCount;
  // CJK: ~1.5 chars/token → use 1.2 for conservative overestimate
  // Latin/digits/symbols: ~4 chars/token → use 3 for conservative overestimate
  // This improves context utilization while still keeping a safety margin.
  return Math.ceil(cjkCount / 1.2 + otherCount / 3);
}
 
/**
 * Estimate the token cost of a single message content part.
 *
 * Handles all part types VS Code passes in a heterogeneous `content` array:
 * {@link vscode.LanguageModelTextPart}, text-mime {@link vscode.LanguageModelDataPart},
 * {@link vscode.LanguageModelToolResultPart} (including structured/JSON/binary inner
 * content), and {@link vscode.LanguageModelToolCallPart}. Non-textable parts (images,
 * raw binary) use a size-aware heuristic. This is what VS Code calls to render the
 * context-window token breakdown, so under-counting any part type makes the breakdown
 * disappear for tool-heavy conversations.
 */
export function estimatePartTokens(part: vscode.LanguageModelInputPart | LegacyPart): number {
  // Tool call: assistant requesting a tool invocation.
  const toolCallInfo = getToolCallInfo(part);
  if (toolCallInfo) {
    const nameTokens = toolCallInfo.name ? estimateTokens(toolCallInfo.name) : 0;
    const argsTokens = toolCallInfo.args ? estimateTokens(JSON.stringify(toolCallInfo.args)) : 0;
    return nameTokens + argsTokens;
  }
 
  // Tool result: the outcome of a previous tool call. Its inner content array may hold
  // text parts, structured objects, JSON data parts, etc. Extract every textable piece.
  const toolResultPart = part as { callId?: unknown; content?: unknown[] };
  if (typeof toolResultPart.callId === "string" && Array.isArray(toolResultPart.content)) {
    const texts = getToolResultTexts(part);
    const joined = texts.join("\n").trim();
    return joined ? estimateTokens(joined) : 2;
  }
 
  // Text part or text-decodable data part.
  const tv = getTextPartValue(part) ?? getDataPartTextValue(part);
  if (tv !== undefined) {
    return estimateTokens(tv);
  }
 
  // Image / binary data part: size-aware heuristic (~750 bytes per token).
  const img = extractImageData(part);
  if (img) {
    return Math.max(4, Math.ceil(img.data.length / 750));
  }
 
  // Unknown part: rough placeholder so it still contributes to the breakdown.
  return 2;
}
 
/**
 * Estimate the token cost of a single chat message by summing its content parts.
 */
export function estimateMessageTokens(msg: {
  content: (vscode.LanguageModelInputPart | LegacyPart)[];
}): number {
  let total = 0;
  for (const part of msg.content) {
    total += estimatePartTokens(part);
  }
  return total;
}
 
export function estimateMessagesTokens(
  messages: readonly { content: (vscode.LanguageModelInputPart | LegacyPart)[] }[],
): number {
  let total = 0;
  for (const m of messages) {
    total += estimateMessageTokens(m);
  }
  return total;
}
 
export interface TokenCategoryBreakdown {
  system: number;
  user: number;
  assistant: number;
  toolCalls: number;
  toolResults: number;
  images: number;
}
 
function classifyPartTokens(
  part: vscode.LanguageModelInputPart | LegacyPart,
  breakdown: TokenCategoryBreakdown,
): void {
  const toolCallInfo = getToolCallInfo(part);
  if (toolCallInfo) {
    const nameTokens = toolCallInfo.name ? estimateTokens(toolCallInfo.name) : 0;
    const argsTokens = toolCallInfo.args ? estimateTokens(JSON.stringify(toolCallInfo.args)) : 0;
    breakdown.toolCalls += nameTokens + argsTokens;
    return;
  }
 
  const toolResultPart = part as { callId?: unknown; content?: unknown[] };
  if (typeof toolResultPart.callId === "string" && Array.isArray(toolResultPart.content)) {
    const texts = getToolResultTexts(part);
    const joined = texts.join("\n").trim();
    breakdown.toolResults += joined ? estimateTokens(joined) : 2;
    return;
  }
 
  const img = extractImageData(part);
  if (img) {
    breakdown.images += Math.max(4, Math.ceil(img.data.length / 750));
    return;
  }
}
 
export function estimateMessagesTokensByCategory(
  messages: readonly {
    role: number;
    content: (vscode.LanguageModelInputPart | LegacyPart)[];
  }[],
): TokenCategoryBreakdown {
  const breakdown: TokenCategoryBreakdown = {
    system: 0,
    user: 0,
    assistant: 0,
    toolCalls: 0,
    toolResults: 0,
    images: 0,
  };
 
  for (const msg of messages) {
    const isUser = msg.role === vscode.LanguageModelChatMessageRole.User;
    const isAssistant = msg.role === vscode.LanguageModelChatMessageRole.Assistant;
 
    for (const part of msg.content) {
      const toolCallInfo = getToolCallInfo(part);
      const toolResultPart = part as { callId?: unknown; content?: unknown[] };
      const isToolCall = Boolean(toolCallInfo);
      const isToolResult =
        typeof toolResultPart.callId === "string" && Array.isArray(toolResultPart.content);
      const img = extractImageData(part);
 
      if (isToolCall) {
        classifyPartTokens(part, breakdown);
      } else if (isToolResult) {
        classifyPartTokens(part, breakdown);
      } else if (img) {
        classifyPartTokens(part, breakdown);
      } else {
        const tv = getTextPartValue(part) ?? getDataPartTextValue(part);
        // Unknown parts still contribute a placeholder so the category
        // breakdown stays consistent with estimatePartTokens().
        const tokens = tv !== undefined ? estimateTokens(tv) : 2;
        if (isUser) {
          breakdown.user += tokens;
        } else if (isAssistant) {
          breakdown.assistant += tokens;
        } else {
          breakdown.system += tokens;
        }
      }
    }
  }
 
  return breakdown;
}
 
export function estimateToolsTokens(tools: readonly NimTool[]): number {
  let total = 0;
  for (const tool of tools) {
    const name = tool.function.name;
    const description = tool.function.description ?? "";
    const params = JSON.stringify(tool.function.parameters ?? {});
    total += estimateTokens(name) + estimateTokens(description) + estimateTokens(params);
  }
  return total;
}
 
/**
 * Estimate token count for converted NimChatMessage[] (post-conversion).
 */
export function estimateNimMessagesTokens(messages: NimChatMessage[]): number {
  const breakdown = estimateNimMessagesTokensByCategory(messages);
  return (
    breakdown.system +
    breakdown.user +
    breakdown.assistant +
    breakdown.toolCalls +
    breakdown.toolResults +
    breakdown.images
  );
}
 
export interface NimTokenCategoryBreakdown {
  system: number;
  user: number;
  assistant: number;
  toolCalls: number;
  toolResults: number;
  images: number;
}
 
function estimateImageUrlTokens(url: string): number {
  if (url.startsWith("data:")) {
    const separatorIndex = url.indexOf(",");
    if (separatorIndex !== -1) {
      const payload = url.slice(separatorIndex + 1).replace(/\s/g, "");
      const isBase64 = url.slice(0, separatorIndex).toLowerCase().includes(";base64");
      const byteEstimate = isBase64 ? Math.ceil((payload.length * 3) / 4) : payload.length;
      return Math.max(4, Math.ceil(byteEstimate / 750));
    }
  }
  return Math.max(4, estimateTokens(url));
}
 
/**
 * Estimate categories from the exact converted payload sent to NIM. These
 * values remain estimates because the tokenizer is model-specific, but they
 * include tool calls, tool results, reasoning content, and image payloads.
 */
export function estimateNimMessagesTokensByCategory(
  messages: readonly NimChatMessage[],
): NimTokenCategoryBreakdown {
  const breakdown: NimTokenCategoryBreakdown = {
    system: 0,
    user: 0,
    assistant: 0,
    toolCalls: 0,
    toolResults: 0,
    images: 0,
  };
 
  for (const message of messages) {
    const category =
      message.role === "system"
        ? "system"
        : message.role === "assistant"
          ? "assistant"
          : message.role === "tool"
            ? "toolResults"
            : "user";
 
    if (typeof message.content === "string") {
      breakdown[category] += estimateTokens(message.content);
    } else {
      for (const part of message.content) {
        if (part.type === "image_url") {
          breakdown.images += estimateImageUrlTokens(part.image_url?.url ?? "image");
        } else if (typeof part.text === "string") {
          breakdown[category] += estimateTokens(part.text);
        } else E{
          breakdown[category] += estimateTokens(JSON.stringify(part));
        }
      }
    }
 
    if (message.reasoning_content) {
      breakdown.assistant += estimateTokens(message.reasoning_content);
    }
 
    for (const toolCall of message.tool_calls ?? []) {
      breakdown.toolCalls +=
        estimateTokens(toolCall.function.name) + estimateTokens(toolCall.function.arguments);
    }
  }
 
  return breakdown;
}
 
/**
 * Truncate converted messages to fit within a token budget.
 * Preserves all system messages + the most recent non-system messages.
 * Drops older messages from the middle.
 */
export function truncateMessagesForContext(
  messages: NimChatMessage[],
  maxTokens: number,
): NimChatMessage[] {
  const systemMessages = messages.filter((m) => m.role === "system");
  const nonSystemMessages = messages.filter((m) => m.role !== "system");
 
  let systemTokens = 0;
  for (const m of systemMessages) {
    systemTokens += estimateNimMessagesTokens([m]);
  }
 
  const budgetForNonSystem = Math.max(0, maxTokens - systemTokens);
  let kept: NimChatMessage[] = [];
  let usedTokens = 0;
 
  for (let i = nonSystemMessages.length - 1; i >= 0; i -= 1) {
    const msg = nonSystemMessages[i];
    const msgTokens = estimateNimMessagesTokens([msg]);
    if (usedTokens + msgTokens > budgetForNonSystem) {
      break;
    }
    kept.unshift(msg);
    usedTokens += msgTokens;
  }
 
  // Keep assistant tool-call messages paired with their tool results (and
  // vice versa). Sending an orphan `tool_call_id` is rejected by many
  // OpenAI-compatible endpoints even when the text budget itself fits.
  const selected = new Set(kept);
  let pairChanged = true;
  while (pairChanged) {
    pairChanged = false;
    for (const message of nonSystemMessages) {
      Iif (message.role === "tool" && selected.has(message) && message.tool_call_id) {
        const owner = nonSystemMessages.find(
          (candidate) =>
            candidate.role === "assistant" &&
            candidate.tool_calls?.some((call) => call.id === message.tool_call_id),
        );
        Iif (owner && !selected.has(owner)) {
          selected.add(owner);
          pairChanged = true;
        }
      }
      Iif (message.role === "assistant" && selected.has(message) && message.tool_calls?.length) {
        for (const result of nonSystemMessages) {
          Iif (
            result.role === "tool" &&
            result.tool_call_id &&
            message.tool_calls.some((call) => call.id === result.tool_call_id) &&
            !selected.has(result)
          ) {
            selected.add(result);
            pairChanged = true;
          }
        }
      }
    }
  }
  kept = nonSystemMessages.filter((message) => selected.has(message));
 
  if (kept.length === 0 && nonSystemMessages.length > 0) {
    kept.push(nonSystemMessages[nonSystemMessages.length - 1]);
  }
 
  const result: NimChatMessage[] = [
    {
      role: "system",
      content:
        "[Note: Earlier conversation context was truncated to fit the model's context window.]",
    },
    ...systemMessages,
    ...kept,
  ];
 
  return result;
}