All files / src/messages reasoning-router.ts

72.83% Statements 118/162
60.81% Branches 45/74
100% Functions 12/12
72.67% Lines 117/161

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 2757x   7x                 93x 93x 101x 3x     93x       142x   142x 710x 710x 3x 3x     142x       1x 1x 5x 5x 44x         1x                   7x           194x 194x 194x 194x 194x 194x 194x           194x 194x 194x 194x       17x       28x     28x 28x 1x 1x   28x 28x       198x     198x 198x 19x 19x   198x 165x     198x 182x 15x 14x   167x 14x 14x 14x 153x 118x 118x                     118x 118x   35x 24x 14x 10x 1x   9x     11x           178x                                       178x 7x     7x   7x 7x     178x       9x 9x 1x 1x 1x 1x   1x 1x     1x   8x 8x       14x 14x 14x 2x 2x 2x 2x 2x   2x 2x 2x     2x   12x               47x     47x 47x   47x 1x 1x                         1x 1x             1x     46x         246x 198x   48x 2x   46x 46x 1x   46x 46x      
import { filterThinkTagsFromChunk, flushThinkTagFilter, ThinkTagFilterState } from "./think-filter";
 
const ORPHANED_CLOSE_TAGS = [
  "</" + "think>",
  "</" + "mm:think>",
  "</" + "thought>",
  "[/" + "THINK]",
  "</" + "reasoning>",
];
 
function countCodeFenceParity(text: string): 0 | 1 {
  let count = 0;
  for (const line of text.split("\n")) {
    if (/^\s*```/.test(line)) {
      count++;
    }
  }
  return (count % 2) as 0 | 1;
}
 
function findOrphanedCloseTag(text: string): { index: number; tag: string } | undefined {
  let bestIndex = -1;
  let bestTag: string | undefined;
  for (const tag of ORPHANED_CLOSE_TAGS) {
    const idx = text.toLowerCase().indexOf(tag.toLowerCase());
    if (idx !== -1 && (bestIndex === -1 || idx < bestIndex)) {
      bestIndex = idx;
      bestTag = tag;
    }
  }
  return bestTag !== undefined ? { index: bestIndex, tag: bestTag } : undefined;
}
 
function findPartialCloseTagEnd(text: string): number {
  let bestMatch = -1;
  for (const tag of ORPHANED_CLOSE_TAGS) {
    const maxLen = Math.min(text.length, tag.length - 1);
    for (let len = maxLen; len > 0; len -= 1) {
      Iif (text.toLowerCase().endsWith(tag.slice(0, len).toLowerCase())) {
        bestMatch = Math.max(bestMatch, text.length - len);
      }
    }
  }
  return bestMatch;
}
 
export interface ReasoningStreamRouterOptions {
  reasoningIsolationExpected: boolean;
  onThinking: (text: string) => void;
  onText: (text: string) => void;
  onFirstResponse?: () => void;
}
 
export class ReasoningStreamRouter {
  private reasoningIsolationExpected: boolean;
  private onThinking: (text: string) => void;
  private onText: (text: string) => void;
  private onFirstResponse?: () => void;
 
  private seenReasoningContent = false;
  private reasoningContentFlushed = false;
  private contentStartedBeforeReasoning = false;
  private answerStarted = false;
  private reasoningBuffer = "";
  private contentBuffer = "";
  private thinkTagFilterState: ThinkTagFilterState = {
    insideThinkBlock: false,
    pendingText: "",
  };
 
  constructor(options: ReasoningStreamRouterOptions) {
    this.reasoningIsolationExpected = options.reasoningIsolationExpected;
    this.onThinking = options.onThinking;
    this.onText = options.onText;
    this.onFirstResponse = options.onFirstResponse;
  }
 
  public isAnswerStarted(): boolean {
    return this.answerStarted;
  }
 
  public handleReasoningContent(text: string): void {
    Iif (!text) {
      return;
    }
    this.onFirstResponse?.();
    if (this.contentBuffer && !this.seenReasoningContent) {
      this.emitReasoning(this.contentBuffer);
      this.contentBuffer = "";
    }
    this.seenReasoningContent = true;
    this.emitReasoning(text);
  }
 
  public handleContent(text: string): void {
    Iif (!text) {
      return;
    }
    this.onFirstResponse?.();
    if (this.seenReasoningContent && !this.reasoningContentFlushed) {
      this.flushReasoning(true);
      this.reasoningContentFlushed = true;
    }
    if (!this.seenReasoningContent) {
      this.contentStartedBeforeReasoning = true;
    }
 
    for (const segment of filterThinkTagsFromChunk(text, this.thinkTagFilterState)) {
      if (segment.type === "thinking") {
        if (!this.seenReasoningContent) {
          this.emitReasoning(segment.text);
        }
      } else if (this.thinkTagFilterState.closedThinkBlock) {
        this.thinkTagFilterState.closedThinkBlock = false;
        this.answerStarted = true;
        this.onText(segment.text);
      } else if (!this.reasoningIsolationExpected) {
        const closeMatch = findOrphanedCloseTag(segment.text);
        Iif (closeMatch) {
          const before = segment.text.slice(0, closeMatch.index);
          const after = segment.text.slice(closeMatch.index + closeMatch.tag.length);
          Iif (before) {
            this.emitReasoning(before);
          }
          this.answerStarted = true;
          Iif (after) {
            this.onText(after);
          }
        } else {
          this.answerStarted = true;
          this.onText(segment.text);
        }
      } else if (this.reasoningIsolationExpected && !this.answerStarted) {
        if (!this.seenReasoningContent) {
          this.bufferPossibleAnswer(segment.text);
        } else if (this.contentStartedBeforeReasoning) {
          this.emitReasoning(segment.text, true);
        } else {
          this.emitAnswerOrSplitCloseTag(segment.text);
        }
      } else {
        this.onText(segment.text);
      }
    }
  }
 
  public flush(): void {
    for (const segment of flushThinkTagFilter(this.thinkTagFilterState)) {
      if (segment.type === "thinking") {
        this.emitReasoning(segment.text);
      } else if (this.thinkTagFilterState.closedThinkBlock) {
        this.thinkTagFilterState.closedThinkBlock = false;
        this.answerStarted = true;
        this.onText(segment.text);
      } else if (this.reasoningIsolationExpected && !this.answerStarted) {
        if (!this.seenReasoningContent) {
          this.contentBuffer += segment.text;
        } else if (this.contentStartedBeforeReasoning) {
          this.emitReasoning(segment.text, true);
        } else {
          this.emitAnswerOrSplitCloseTag(segment.text);
        }
      } else {
        this.onText(segment.text);
      }
    }
 
    if (this.contentBuffer) {
      Iif (this.seenReasoningContent && this.contentStartedBeforeReasoning) {
        this.emitReasoning(this.contentBuffer);
      } else {
        this.onText(this.contentBuffer);
      }
      this.contentBuffer = "";
      this.answerStarted = true;
    }
 
    this.flushReasoning(true);
  }
 
  private emitAnswerOrSplitCloseTag(text: string): void {
    const closeMatch = findOrphanedCloseTag(text);
    if (closeMatch) {
      const before = text.slice(0, closeMatch.index);
      const after = text.slice(closeMatch.index + closeMatch.tag.length);
      if (before) {
        this.emitReasoning(before);
      }
      this.answerStarted = true;
      Iif (after) {
        this.onText(after);
      }
      return;
    }
    this.answerStarted = true;
    this.onText(text);
  }
 
  private bufferPossibleAnswer(text: string): void {
    this.contentBuffer += text;
    const closeMatch = findOrphanedCloseTag(this.contentBuffer);
    if (closeMatch) {
      const before = this.contentBuffer.slice(0, closeMatch.index);
      const after = this.contentBuffer.slice(closeMatch.index + closeMatch.tag.length);
      if (before) {
        this.emitReasoning(before);
        this.flushReasoning(true);
      }
      this.answerStarted = true;
      this.contentBuffer = "";
      Iif (after) {
        this.onText(after);
      }
      return;
    }
    Iif (this.contentBuffer.length > 150) {
      this.onText(this.contentBuffer);
      this.contentBuffer = "";
      this.answerStarted = true;
    }
  }
 
  private emitReasoning(text: string, checkOrphanedClose: boolean = false): void {
    Iif (!text) {
      return;
    }
    this.onFirstResponse?.();
    this.reasoningBuffer += text;
 
    if (checkOrphanedClose) {
      const closeMatch = findOrphanedCloseTag(this.reasoningBuffer);
      Iif (closeMatch) {
        const before = this.reasoningBuffer.slice(0, closeMatch.index);
        const after = this.reasoningBuffer.slice(closeMatch.index + closeMatch.tag.length);
        this.reasoningBuffer = before;
        this.flushReasoning(true);
        this.seenReasoningContent = true;
        this.answerStarted = true;
        Iif (after) {
          this.onText(after);
        }
        return;
      }
 
      const partialEnd = findPartialCloseTagEnd(this.reasoningBuffer);
      Iif (partialEnd !== -1) {
        const safePart = this.reasoningBuffer.slice(0, partialEnd);
        const partialPart = this.reasoningBuffer.slice(partialEnd);
        this.reasoningBuffer = safePart;
        this.flushReasoning(false);
        this.reasoningBuffer = partialPart;
      } else {
        this.flushReasoning(false);
      }
    } else {
      this.flushReasoning(false);
    }
  }
 
  private flushReasoning(force: boolean = false): void {
    if (!this.reasoningBuffer) {
      return;
    }
    if (!force && countCodeFenceParity(this.reasoningBuffer) === 1) {
      return;
    }
    let text = this.reasoningBuffer;
    if (countCodeFenceParity(text) === 1) {
      text += "\n```";
    }
    this.onThinking(text);
    this.reasoningBuffer = "";
  }
}