All files / src/messages think-filter.ts

100% Statements 75/75
96.55% Branches 28/29
100% Functions 7/7
100% Lines 72/72

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                                8x                 954x 954x 954x   954x 5946x 32x       922x             186x   186x 930x 930x 11x       186x             207x     207x 1035x 1035x 21x 21x       207x                 8x       1055x 1055x 211x 211x   211x   211x 254x 47x 47x 47x 24x 24x 12x 12x     12x 2x   12x   24x     23x 11x   23x 23x 23x 23x 23x     207x 207x 186x 186x 175x 175x     11x 1x   11x   186x     21x 21x 3x   21x 21x 21x     1x     8x 181x 181x 1x   181x 181x 181x 181x    
export interface ThinkTagFilterState {
  insideThinkBlock: boolean;
  pendingText: string;
  closeTag?: string;
  closedThinkBlock?: boolean;
}
 
export type ThinkFilterSegment =
  | { type: "text"; text: string }
  | { type: "thinking"; text: string };
 
interface ThinkTagPair {
  open: string;
  close: string;
}
 
const THINK_TAG_PAIRS: ThinkTagPair[] = [
  { open: "<think>", close: "</think>" },
  { open: "<mm:think>", close: "</mm:think>" },
  { open: "<thought>", close: "</thought>" },
  { open: "[THINK]", close: "[/THINK]" },
  { open: "<reasoning>", close: "</reasoning>" },
];
 
function findTrailingCaseInsensitivePrefixStart(text: string, token: string): number {
  const normalizedText = text.toLowerCase();
  const normalizedToken = token.toLowerCase();
  const maxPrefixLength = Math.min(normalizedText.length, normalizedToken.length - 1);
 
  for (let prefixLength = maxPrefixLength; prefixLength > 0; prefixLength -= 1) {
    if (normalizedText.endsWith(normalizedToken.slice(0, prefixLength))) {
      return normalizedText.length - prefixLength;
    }
  }
 
  return -1;
}
 
function findTrailingCaseInsensitivePrefixStartAny(
  text: string,
  tokens: readonly string[],
): number {
  let bestMatch = -1;
 
  for (const token of tokens) {
    const matchIndex = findTrailingCaseInsensitivePrefixStart(text, token);
    if (matchIndex !== -1 && (bestMatch === -1 || matchIndex < bestMatch)) {
      bestMatch = matchIndex;
    }
  }
 
  return bestMatch;
}
 
function findEarliestCaseInsensitiveIndex(
  text: string,
  tokens: readonly string[],
): { index: number; token: string } | undefined {
  let bestIndex = -1;
  let bestToken: string | undefined;
 
  for (const token of tokens) {
    const idx = text.toLowerCase().indexOf(token.toLowerCase());
    if (idx !== -1 && (bestIndex === -1 || idx < bestIndex)) {
      bestIndex = idx;
      bestToken = token;
    }
  }
 
  return bestToken !== undefined ? { index: bestIndex, token: bestToken } : undefined;
}
 
/**
 * Split a streamed chunk into ordered text/thinking segments, capturing the
 * content inside `<think>`/`<mm:think>` blocks as `thinking` segments
 * instead of discarding it. Partial tags are buffered in `state.pendingText`
 * and resolved across chunks.
 */
export function filterThinkTagsFromChunk(
  text: string,
  state: ThinkTagFilterState,
): ThinkFilterSegment[] {
  const openTags = THINK_TAG_PAIRS.map((p) => p.open);
  const closeTagMap = new Map(THINK_TAG_PAIRS.map((p) => [p.open, p.close] as const));
  let remaining = state.pendingText + text;
  const segments: ThinkFilterSegment[] = [];
 
  state.pendingText = "";
 
  while (remaining.length > 0) {
    if (state.insideThinkBlock) {
      const closeTag = state.closeTag ?? "</think>";
      const closeIndex = remaining.toLowerCase().indexOf(closeTag.toLowerCase());
      if (closeIndex === -1) {
        const partialCloseIndex = findTrailingCaseInsensitivePrefixStart(remaining, closeTag);
        if (partialCloseIndex === -1) {
          if (remaining.length > 0) {
            segments.push({ type: "thinking", text: remaining });
          }
        } else {
          if (partialCloseIndex > 0) {
            segments.push({ type: "thinking", text: remaining.slice(0, partialCloseIndex) });
          }
          state.pendingText = remaining.slice(partialCloseIndex);
        }
        return segments;
      }
 
      if (closeIndex > 0) {
        segments.push({ type: "thinking", text: remaining.slice(0, closeIndex) });
      }
      remaining = remaining.slice(closeIndex + closeTag.length);
      state.insideThinkBlock = false;
      state.closeTag = undefined;
      state.closedThinkBlock = true;
      continue;
    }
 
    const openMatch = findEarliestCaseInsensitiveIndex(remaining, openTags);
    if (openMatch === undefined) {
      const partialOpenIndex = findTrailingCaseInsensitivePrefixStartAny(remaining, openTags);
      if (partialOpenIndex === -1) {
        if (remaining.length > 0) {
          segments.push({ type: "text", text: remaining });
        }
      } else {
        if (partialOpenIndex > 0) {
          segments.push({ type: "text", text: remaining.slice(0, partialOpenIndex) });
        }
        state.pendingText = remaining.slice(partialOpenIndex);
      }
      return segments;
    }
 
    const { index: openIndex, token: matchedOpenTag } = openMatch;
    if (openIndex > 0) {
      segments.push({ type: "text", text: remaining.slice(0, openIndex) });
    }
    remaining = remaining.slice(openIndex + matchedOpenTag.length);
    state.insideThinkBlock = true;
    state.closeTag = closeTagMap.get(matchedOpenTag);
  }
 
  return segments;
}
 
export function flushThinkTagFilter(state: ThinkTagFilterState): ThinkFilterSegment[] {
  const segments: ThinkFilterSegment[] = [];
  if (!state.insideThinkBlock && state.pendingText) {
    segments.push({ type: "text", text: state.pendingText });
  }
  state.pendingText = "";
  state.insideThinkBlock = false;
  state.closeTag = undefined;
  return segments;
}