| 112 | const MAX_MARKER = Math.max(LLAMA_THINK_START.length, LLAMA_THINK_END.length); |
| 113 | |
| 114 | const callback = (token: string) => { |
| 115 | buf += token; |
| 116 | |
| 117 | while (buf.length > 0) { |
| 118 | if (state === 'scanning' || state === 'answering') { |
| 119 | const idx = buf.indexOf(LLAMA_THINK_START); |
| 120 | if (idx !== -1) { |
| 121 | // Emit everything before the marker as answer text |
| 122 | const before = buf.slice(0, idx); |
| 123 | if (before) onToken?.(before); |
| 124 | buf = buf.slice(idx + LLAMA_THINK_START.length); |
| 125 | state = 'thinking'; |
| 126 | } else { |
| 127 | // No marker yet — keep a tail in case the marker is split across tokens |
| 128 | const safe = buf.length > MAX_MARKER ? buf.slice(0, buf.length - MAX_MARKER) : ''; |
| 129 | if (safe) onToken?.(safe); |
| 130 | buf = buf.slice(safe.length); |
| 131 | break; |
| 132 | } |
| 133 | } else { |
| 134 | // state === 'thinking' |
| 135 | const idx = buf.indexOf(LLAMA_THINK_END); |
| 136 | if (idx !== -1) { |
| 137 | const reasoning = buf.slice(0, idx); |
| 138 | if (reasoning) onReasoningToken?.(reasoning); |
| 139 | buf = buf.slice(idx + LLAMA_THINK_END.length); |
| 140 | state = 'answering'; |
| 141 | } else { |
| 142 | const safe = buf.length > MAX_MARKER ? buf.slice(0, buf.length - MAX_MARKER) : ''; |
| 143 | if (safe) onReasoningToken?.(safe); |
| 144 | buf = buf.slice(safe.length); |
| 145 | break; |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | }; |
| 150 | |
| 151 | callback.flush = () => { |
| 152 | if (!buf) return; |