(text: string)
| 29 | |
| 30 | /** Parse one or more glued NDJSON stream objects from text. */ |
| 31 | export function parseStreamPartsText(text: string): { |
| 32 | parts: StreamPart[]; |
| 33 | rest: string; |
| 34 | } { |
| 35 | const parts: StreamPart[] = []; |
| 36 | let index = 0; |
| 37 | |
| 38 | while (index < text.length) { |
| 39 | while (index < text.length && text[index] !== "{") { |
| 40 | index++; |
| 41 | } |
| 42 | if (index >= text.length) { |
| 43 | break; |
| 44 | } |
| 45 | |
| 46 | let parsed: StreamPart | null = null; |
| 47 | let end = -1; |
| 48 | |
| 49 | for (let cursor = index + 1; cursor <= text.length; cursor++) { |
| 50 | if (text[cursor - 1] !== "}") { |
| 51 | continue; |
| 52 | } |
| 53 | try { |
| 54 | const candidate = JSON.parse(text.slice(index, cursor)) as StreamPart; |
| 55 | if ( |
| 56 | (candidate.kind === "reasoning" || candidate.kind === "content") && |
| 57 | typeof candidate.delta === "string" && |
| 58 | candidate.delta.length > 0 |
| 59 | ) { |
| 60 | parsed = candidate; |
| 61 | end = cursor; |
| 62 | break; |
| 63 | } |
| 64 | } catch { |
| 65 | // keep extending |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | if (!parsed || end === -1) { |
| 70 | return { parts, rest: text.slice(index) }; |
| 71 | } |
| 72 | |
| 73 | parts.push(parsed); |
| 74 | index = end; |
| 75 | } |
| 76 | |
| 77 | return { parts, rest: "" }; |
| 78 | } |
| 79 | |
| 80 | /** Split corrupted saved assistant text that contains NDJSON stream parts. */ |
| 81 | export function splitStoredStreamText(text: string): { |
no outgoing calls
no test coverage detected