All files / src/tools xml-tool-scanner.ts

72.92% Statements 229/314
54.54% Branches 90/165
100% Functions 18/18
72.84% Lines 228/313

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 61811x                                                                           11x                 11x 11x             11x 433x 154x     279x 279x 52x     227x 227x 227x     227x     227x 3x   224x     11x 1128x 1128x 1131x 1131x 1000x   131x 128x   3x           208x       155x 155x 53x   155x       76x 76x       339x 41x     298x 298x       298x 298x 15x 15x         298x 298x 222x     76x 76x     76x     76x 61x 33x 33x     33x 33x     33x 33x   28x 28x 28x 7x 7x         76x 76x     76x       76x                         19x 19x 28x 28x 2x     26x 26x 16x   10x 1x     9x                 1x       1x 1x 1x 1x 64x 64x 47x       47x       47x 5x   47x   17x 5x 5x   12x 2x 2x   10x 2x 2x 1x               1x 1x 1x 1x                                         1x 1x       1x 1x 1x       1x           1x 1x                 1x         104x       11x 11x     11x 1x   10x 1x     9x 9x     9x     9x             9x                     1x 1x     1x 1x 1x   1x                         11x 11x 11x 11x   11x 58x 58x 18x 18x 2x   16x 16x   16x 16x 16x     40x 40x       40x 1x 1x     1x     1x       1x       1x 1x     39x 39x     39x                 39x 14x 14x 14x 14x                               25x 18x 18x 18x   7x 7x 7x   7x 7x 7x                           9x 9x                 11x 188x 188x 460x 460x 175x   285x 49x 49x   236x 236x     236x 13x   223x         11x         13x 13x     13x     13x     13x 2x 2x     2x 1x   1x     11x                       11x 8x 8x     8x         11x 1x     1x 1x     1x         11x       11x     11x       1x 1x 1x 1x   1x 42x           42x           42x 42x             1x 1x 1x 1x 1x           41x 41x     1x    
import { jsonrepair } from "jsonrepair";
 
export type XmlToolKind =
  | "tool_calls"
  | "tool_call"
  | "function"
  | "invoke"
  | "parameter"
  | "tool_parameter";
 
export interface XmlScannedToolCall {
  name: string;
  args: Record<string, unknown>;
}
 
export type XmlScanResult =
  | {
      status: "complete";
      consumed: number;
      toolCall?: XmlScannedToolCall;
      extractedParams?: Record<string, unknown>;
    }
  | { status: "incomplete" }
  | { status: "not-a-tag"; skip: number };
 
interface ParsedXmlTag {
  kind: XmlToolKind;
  closing: boolean;
  name?: string;
  rawLength: number;
  incomplete: boolean;
}
 
interface StackFrame {
  kind: XmlToolKind;
  paramKey?: string;
}
 
const TOOL_KINDS = new Set<string>([
  "tool_calls",
  "tool_call",
  "function",
  "invoke",
  "parameter",
  "tool_parameter",
]);
 
const IDENT_RE = /^[a-zA-Z0-9_.-]+/;
const TAG_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_.-]*/;
 
/**
 * True when `index` sits inside a JS/TS string or regex literal, e.g.
 * `const token = "<tool_calls>";` or `/^\s*<\/tool_calls>/`.
 * Real Hermes/Anthropic tool tags sit on their own line after prose.
 */
export function isTokenInStringOrRegexLiteral(text: string, index: number): boolean {
  if (index <= 0) {
    return false;
  }
 
  const prev = text[index - 1];
  if (prev === "\\" || prev === '"' || prev === "'" || prev === "`" || prev === "/") {
    return true;
  }
 
  const lineStart = text.lastIndexOf("\n", index - 1) + 1;
  const prefix = text.slice(lineStart, index);
  Iif (/(?:^|[=:(,[{]\s*)["'][^"'\n]*$/.test(prefix)) {
    return true;
  }
  Iif (/(?:^|[=:(,[{]\s*)`[^`\n]*$/.test(prefix)) {
    return true;
  }
  if (/(?:^|[=:(,[{]\s*)\/(?:\^)?[^/\n]*$/.test(prefix)) {
    return true;
  }
  return false;
}
 
export function indexOfUnquoted(text: string, token: string, from = 0, contextPrefix = ""): number {
  let pos = from;
  while (pos < text.length) {
    const index = text.indexOf(token, pos);
    if (index === -1) {
      return -1;
    }
    if (!isTokenInStringOrRegexLiteral(contextPrefix + text, contextPrefix.length + index)) {
      return index;
    }
    pos = index + 1;
  }
  return -1;
}
 
function isWhitespace(char: string): boolean {
  return char === " " || char === "\n" || char === "\r" || char === "\t";
}
 
function skipWhitespace(text: string, index: number): number {
  let cursor = index;
  while (cursor < text.length && isWhitespace(text[cursor])) {
    cursor += 1;
  }
  return cursor;
}
 
function asToolKind(name: string): XmlToolKind | undefined {
  const normalized = name.toLowerCase();
  return TOOL_KINDS.has(normalized) ? (normalized as XmlToolKind) : undefined;
}
 
function readXmlTag(text: string, index: number): ParsedXmlTag | undefined {
  if (text[index] !== "<") {
    return undefined;
  }
 
  let cursor = index + 1;
  Iif (cursor >= text.length) {
    return { kind: "tool_call", closing: false, rawLength: 0, incomplete: true };
  }
 
  const closing = text[cursor] === "/";
  if (closing) {
    cursor += 1;
    Iif (cursor >= text.length) {
      return { kind: "tool_call", closing: true, rawLength: 0, incomplete: true };
    }
  }
 
  const nameMatch = text.slice(cursor).match(TAG_NAME_RE);
  if (!nameMatch) {
    return undefined;
  }
 
  const kind = asToolKind(nameMatch[0]);
  Iif (!kind) {
    return undefined;
  }
  cursor += nameMatch[0].length;
 
  let name: string | undefined;
  if (!closing) {
    if (text[cursor] === "=") {
      cursor += 1;
      Iif (cursor >= text.length) {
        return { kind, closing: false, rawLength: 0, incomplete: true };
      }
      const valueMatch = text.slice(cursor).match(IDENT_RE);
      Iif (!valueMatch) {
        return { kind, closing: false, rawLength: 0, incomplete: true };
      }
      name = valueMatch[0];
      cursor += name.length;
    } else {
      cursor = skipWhitespace(text, cursor);
      const attrMatch = text.slice(cursor).match(/^name\s*=\s*"([^"]*)"/i);
      if (attrMatch) {
        name = attrMatch[1];
        cursor += attrMatch[0].length;
      }
    }
  }
 
  cursor = skipWhitespace(text, cursor);
  Iif (cursor >= text.length) {
    return { kind, closing, name, rawLength: 0, incomplete: true };
  }
  Iif (text[cursor] !== ">") {
    return undefined;
  }
 
  return {
    kind,
    closing,
    name,
    rawLength: cursor + 1 - index,
    incomplete: false,
  };
}
 
function findParameterClose(
  text: string,
  startIndex: number,
): { index: number; length: number } | undefined {
  let cursor = startIndex;
  while (cursor < text.length) {
    const lt = text.indexOf("<", cursor);
    if (lt === -1) {
      return undefined;
    }
 
    const slice = text.slice(lt);
    if (/^<\/parameter>/i.test(slice)) {
      return { index: lt, length: "</parameter>".length };
    }
    if (/^<\/tool_parameter>/i.test(slice)) {
      return { index: lt, length: "</tool_parameter>".length };
    }
 
    cursor = lt + 1;
  }
  return undefined;
}
 
function readBalancedJsonObject(
  text: string,
  startIndex: number,
): { json: string; end: number } | { incomplete: true } | undefined {
  Iif (text[startIndex] !== "{") {
    return undefined;
  }
 
  let depth = 0;
  let inString = false;
  let escape = false;
  for (let cursor = startIndex; cursor < text.length; cursor += 1) {
    const char = text[cursor];
    if (inString) {
      Iif (escape) {
        escape = false;
        continue;
      }
      Iif (char === "\\") {
        escape = true;
        continue;
      }
      if (char === '"') {
        inString = false;
      }
      continue;
    }
    if (char === '"') {
      inString = true;
      continue;
    }
    if (char === "{") {
      depth += 1;
      continue;
    }
    if (char === "}") {
      depth -= 1;
      if (depth === 0) {
        return { json: text.slice(startIndex, cursor + 1), end: cursor + 1 };
      }
    }
  }
  return { incomplete: true };
}
 
function parseJsonObject(text: string): Record<string, unknown> | undefined {
  try {
    const parsed: unknown = JSON.parse(text);
    if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
      return parsed as Record<string, unknown>;
    }
  } catch {
    try {
      const repaired: unknown = JSON.parse(jsonrepair(text));
      Iif (typeof repaired === "object" && repaired !== null && !Array.isArray(repaired)) {
        return repaired as Record<string, unknown>;
      }
    } catch {
      return undefined;
    }
  }
  return undefined;
}
 
function mergeQwenJson(
  jsonText: string,
  args: Record<string, unknown>,
  setName: (name: string) => void,
  isValidName: (name: string) => boolean,
): void {
  const parsed = parseJsonObject(jsonText);
  Iif (!parsed) {
    return;
  }
 
  const name = String(parsed.name ?? parsed.tool ?? parsed.function ?? "");
  if (name && isValidName(name)) {
    setName(name);
  }
 
  const inner =
    typeof parsed.arguments === "object" && parsed.arguments !== null
      ? parsed.arguments
      : typeof parsed.parameters === "object" && parsed.parameters !== null
        ? parsed.parameters
        : parsed;
 
  if (typeof inner === "object" && inner !== null && !Array.isArray(inner)) {
    Iif (inner === parsed) {
      for (const [key, value] of Object.entries(parsed)) {
        Iif (key === "name" || key === "tool" || key === "function") {
          continue;
        }
        args[key] = value;
      }
      return;
    }
    Object.assign(args, inner);
  }
}
 
function isParameterKind(kind: XmlToolKind): boolean {
  return kind === "parameter" || kind === "tool_parameter";
}
 
function isPlausibleToolContinuation(text: string, afterTag: number): "yes" | "no" | "incomplete" {
  const cursor = skipWhitespace(text, afterTag);
  Iif (cursor >= text.length) {
    return "incomplete";
  }
  if (text[cursor] === "{") {
    return "yes";
  }
  if (text[cursor] !== "<") {
    return "no";
  }
 
  const next = readXmlTag(text, cursor);
  Iif (!next) {
    return "no";
  }
  Iif (next.incomplete) {
    return "incomplete";
  }
  if (
    isParameterKind(next.kind) ||
    next.kind === "function" ||
    next.kind === "tool_call" ||
    next.kind === "invoke" ||
    next.kind === "tool_calls"
  ) {
    return "yes";
  }
  return "no";
}
 
function scanParameterValue(
  text: string,
  startIndex: number,
  parseValue: (raw: string) => unknown,
  key: string | undefined,
): XmlScanResult {
  const close = findParameterClose(text, startIndex);
  Iif (!close) {
    return { status: "incomplete" };
  }
  const extractedParams: Record<string, unknown> = {};
  if (key) {
    extractedParams[key] = parseValue(text.slice(startIndex, close.index));
  }
  return {
    status: "complete",
    consumed: close.index + close.length,
    extractedParams,
  };
}
 
function scanToolRegion(
  text: string,
  firstTag: ParsedXmlTag,
  parseValue: (raw: string) => unknown,
  isValidName: (name: string) => boolean,
): XmlScanResult {
  const stack: StackFrame[] = [{ kind: firstTag.kind }];
  let cursor = firstTag.rawLength;
  let toolName = firstTag.name;
  const args: Record<string, unknown> = {};
 
  while (stack.length > 0) {
    const top = stack[stack.length - 1];
    if (isParameterKind(top.kind)) {
      const close = findParameterClose(text, cursor);
      if (!close) {
        return { status: "incomplete" };
      }
      if (top.paramKey) {
        args[top.paramKey] = parseValue(text.slice(cursor, close.index));
      }
      cursor = close.index + close.length;
      stack.pop();
      continue;
    }
 
    cursor = skipWhitespace(text, cursor);
    Iif (cursor >= text.length) {
      return { status: "incomplete" };
    }
 
    if (text[cursor] === "{") {
      const json = readBalancedJsonObject(text, cursor);
      Iif (!json) {
        return { status: "incomplete" };
      }
      Iif ("incomplete" in json) {
        return { status: "incomplete" };
      }
      mergeQwenJson(
        json.json,
        args,
        (name) => {
          toolName = name;
        },
        isValidName,
      );
      cursor = json.end;
      continue;
    }
 
    const tag = readXmlTag(text, cursor);
    Iif (tag?.incomplete) {
      return { status: "incomplete" };
    }
    Iif (!tag) {
      const nextLt = text.indexOf("<", cursor + 1);
      Iif (nextLt === -1) {
        return { status: "incomplete" };
      }
      cursor = nextLt;
      continue;
    }
 
    if (tag.closing) {
      if (tag.kind === top.kind) {
        stack.pop();
        cursor += tag.rawLength;
        continue;
      }
      Iif (tag.kind === "tool_call" || tag.kind === "invoke") {
        while (stack.length > 0 && stack[stack.length - 1].kind === "function") {
          stack.pop();
        }
        Iif (stack.length > 0 && stack[stack.length - 1].kind === tag.kind) {
          stack.pop();
          cursor += tag.rawLength;
          continue;
        }
      }
      cursor += tag.rawLength;
      continue;
    }
 
    if (isParameterKind(tag.kind)) {
      stack.push({ kind: tag.kind, paramKey: tag.name });
      cursor += tag.rawLength;
      continue;
    }
    if (tag.kind === "function") {
      if (tag.name) {
        toolName = tag.name;
      }
      stack.push({ kind: "function" });
      cursor += tag.rawLength;
      continue;
    }
    Iif (tag.kind === "tool_call" || tag.kind === "invoke") {
      Iif (tag.name) {
        toolName = tag.name;
      }
      stack.push({ kind: tag.kind });
      cursor += tag.rawLength;
      continue;
    }
 
    cursor += tag.rawLength;
  }
 
  if (toolName && isValidName(toolName)) {
    return {
      status: "complete",
      consumed: cursor,
      toolCall: { name: toolName, args },
    };
  }
  return { status: "complete", consumed: cursor };
}
 
export function findXmlConstructStart(text: string, contextPrefix = ""): number {
  let pos = 0;
  while (pos < text.length) {
    const lt = text.indexOf("<", pos);
    if (lt === -1) {
      return -1;
    }
    if (isTokenInStringOrRegexLiteral(contextPrefix + text, contextPrefix.length + lt)) {
      pos = lt + 1;
      continue;
    }
    const tag = readXmlTag(text, lt);
    Iif (tag?.incomplete) {
      return lt;
    }
    if (tag && !tag.closing) {
      return lt;
    }
    pos = lt + 1;
  }
  return -1;
}
 
export function scanXmlToolConstruct(
  text: string,
  parseValue: (raw: string) => unknown,
  isValidName: (name: string) => boolean,
): XmlScanResult {
  const tag = readXmlTag(text, 0);
  Iif (tag?.incomplete) {
    return { status: "incomplete" };
  }
  Iif (!tag) {
    return { status: "not-a-tag", skip: 1 };
  }
  Iif (tag.closing) {
    return { status: "complete", consumed: tag.rawLength };
  }
  if (tag.kind === "tool_calls") {
    const peek = isPlausibleToolContinuation(text, tag.rawLength);
    Iif (peek === "incomplete") {
      return { status: "incomplete" };
    }
    if (peek === "no") {
      return { status: "not-a-tag", skip: tag.rawLength };
    }
    return { status: "complete", consumed: tag.rawLength };
  }
 
  Iif (isParameterKind(tag.kind)) {
    const scanned = scanParameterValue(text, tag.rawLength, parseValue, tag.name);
    Iif (scanned.status !== "complete") {
      return scanned;
    }
    return {
      status: "complete",
      consumed: scanned.consumed,
      extractedParams: scanned.extractedParams,
    };
  }
 
  if (tag.kind === "tool_call" && !tag.name) {
    const peek = isPlausibleToolContinuation(text, tag.rawLength);
    Iif (peek === "incomplete") {
      return { status: "incomplete" };
    }
    Iif (peek === "no") {
      return { status: "not-a-tag", skip: tag.rawLength };
    }
  }
 
  if (tag.kind === "function") {
    Iif (!tag.name || !isValidName(tag.name)) {
      return { status: "not-a-tag", skip: tag.rawLength };
    }
    const peek = isPlausibleToolContinuation(text, tag.rawLength);
    Iif (peek === "incomplete") {
      return { status: "incomplete" };
    }
    Iif (peek === "no") {
      return { status: "not-a-tag", skip: tag.rawLength };
    }
  }
 
  Iif (tag.kind === "invoke" && (!tag.name || !isValidName(tag.name))) {
    return { status: "not-a-tag", skip: tag.rawLength };
  }
 
  return scanToolRegion(text, tag, parseValue, isValidName);
}
 
export function extractStandaloneXmlParameters(
  text: string,
  parseValue: (raw: string) => unknown,
): { cleanText: string; extractedParams: Record<string, unknown> } {
  const extractedParams: Record<string, unknown> = {};
  const cleanParts: string[] = [];
  let cursor = 0;
  let insideFence = false;
 
  while (cursor < text.length) {
    Iif (text.startsWith("```", cursor)) {
      insideFence = !insideFence;
      cleanParts.push("```");
      cursor += 3;
      continue;
    }
    Iif (insideFence) {
      cleanParts.push(text[cursor]);
      cursor += 1;
      continue;
    }
 
    const tag = readXmlTag(text, cursor);
    if (
      tag &&
      !tag.incomplete &&
      !tag.closing &&
      isParameterKind(tag.kind) &&
      !isTokenInStringOrRegexLiteral(text, cursor)
    ) {
      const scanned = scanParameterValue(text, cursor + tag.rawLength, parseValue, tag.name);
      if (scanned.status === "complete") {
        Object.assign(extractedParams, scanned.extractedParams);
        cursor = scanned.consumed;
        continue;
      }
      cleanParts.push(text.slice(cursor));
      break;
    }
 
    cleanParts.push(text[cursor]);
    cursor += 1;
  }
 
  return { cleanText: cleanParts.join(""), extractedParams };
}