Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

assistantStreaming.ts

306 lines11.5 KB

1import type { ResponseStreamingMode } from "@t3tools/contracts";
2import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
3​
4// List fences can open at any indentation; closers may be at most three spaces deeper.
5// A backtick fence's info string cannot contain a backtick, so "```npm test``` runs" is inline code.
6const MARKDOWN_FENCE_PATTERN = /^([ \t]*)(`{3,}(?![^`\r\n]*`)|~{3,})/;
7const LIST_MARKER_PATTERN = /[-*+]|\d{1,9}[.)]/y;
8// CommonMark blank lines contain only spaces and tabs.
9const BLANK_LINE_PATTERN = /^[ \t]*$/;
10// Require trailing space so partial list markers cannot match during streaming.
11const LIST_ITEM_START_PATTERN = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]/;
12const SECTION_TITLE_PATTERN = /^ {0,3}(?:#{1,6}(?:[ \t]|$)|\*\*(?:[^*]|\*(?!\*))+\*\*:?$)/;
13// Unindented ATX headings end preceding paragraphs and lists without blank lines; bold lines do not.
14const TOP_LEVEL_HEADING_PATTERN = /^#{1,6}(?:[ \t]|$)/;
15​
16// Matches LIST_ITEM_START_PATTERN on the trimmed partial line without copying it.
17const PARTIAL_LIST_ITEM_START_PATTERN = /[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t][ \t\r]*[^ \t\r]/y;
18​
19interface AssistantTextScan {
20 readonly text: string;
21 // Start of the partial line; every line before it has been scanned.
22 readonly lineStart: number;
23 readonly openFence: {
24 readonly marker: string;
25 readonly indent: number;
26 // A fence opened on a list item line ends with the item, at a line indented less than this.
27 readonly minIndent: number;
28 } | null;
29 readonly boundary: number;
30 readonly titleAwaitingContent: boolean;
32​
33const EMPTY_SCAN: AssistantTextScan = {
34 text: "",
35 lineStart: 0,
36 openFence: null,
37 boundary: -1,
38 titleAwaitingContent: false,
39};
40​
41function trimLineEnd(text: string, start: number, end: number): string {
42 while (end > start) {
43 const char = text.charCodeAt(end - 1);
44 if (char !== 32 && char !== 9 && char !== 13) break;
45 end--;
46 }
47 return text.slice(start, end);
49​
50// Skips spaces and tabs from `i`, counting columns with CommonMark's 4-column tab stops.
51function skipIndent(line: string, i: number, col: number): { i: number; col: number } {
52 for (; i < line.length; i++) {
53 const char = line.charCodeAt(i);
54 if (char === 32) col++;
55 else if (char === 9) col += 4 - (col % 4);
56 else break;
57 }
58 return { i, col };
60​
61const leadingIndent = (line: string) => skipIndent(line, 0, 0).col;
62​
63// A fence opened after list markers ("- ```", "1. - ~~~"); `indent` is its content column.
64function matchListItemFence(line: string): { marker: string; indent: number } | null {
65 let { i, col } = skipIndent(line, 0, 0);
66 let matched = false;
67 for (;;) {
68 LIST_MARKER_PATTERN.lastIndex = i;
69 const listMarker = LIST_MARKER_PATTERN.exec(line);
70 if (!listMarker) break;
71 const afterMarker = col + listMarker[0].length;
72 ({ i, col } = skipIndent(line, i + listMarker[0].length, afterMarker));
73 if (col === afterMarker || col - afterMarker > 4) return null;
74 matched = true;
75 }
76 if (!matched) return null;
77 const fence = MARKDOWN_FENCE_PATTERN.exec(line.slice(i));
78 return fence ? { marker: fence[2]!, indent: col } : null;
80​
81/** Scans the terminated lines of `text`, resuming after `previous` when `text` extends it. */
82function advanceScan(previous: AssistantTextScan, text: string): AssistantTextScan {
83 const resumed = text.startsWith(previous.text);
84 let { openFence, boundary, lineStart, titleAwaitingContent } = resumed ? previous : EMPTY_SCAN;
85 let searchFrom = resumed ? previous.text.length : 0;
86 if (resumed && text.charCodeAt(searchFrom - 1) === 13 && text.charCodeAt(searchFrom) === 10) {
87 if (boundary === lineStart) boundary++;
88 lineStart = ++searchFrom;
89 }
90 let nextLf = text.indexOf("\n", searchFrom);
91 let nextCr = text.indexOf("\r", searchFrom);
92 for (;;) {
93 let newline = nextLf === -1 ? nextCr : nextCr === -1 || nextLf < nextCr ? nextLf : nextCr;
94 if (newline === -1) break;
95 const line = trimLineEnd(text, lineStart, newline);
96 if (text.charCodeAt(newline) === 13 && text.charCodeAt(newline + 1) === 10) newline++;
97 if (
98 openFence !== null &&
99 openFence.minIndent > 0 &&
100 line.length > 0 &&
101 leadingIndent(line) < openFence.minIndent
102 ) {
103 openFence = null;
104 }
105 if (
106 openFence === null &&
107 lineStart > 0 &&
108 !titleAwaitingContent &&
109 LIST_ITEM_START_PATTERN.test(line)
110 ) {
111 boundary = lineStart;
112 }
113 const fenceMatch = MARKDOWN_FENCE_PATTERN.exec(line);
114 const listFenceMatch = openFence === null && !fenceMatch ? matchListItemFence(line) : null;
115 if (fenceMatch) {
116 const prefix = fenceMatch[1]!;
117 const indent = leadingIndent(prefix);
118 const marker = fenceMatch[2]!;
119 if (openFence === null) {
120 openFence = { marker, indent, minIndent: 0 };
121 titleAwaitingContent = false;
122 } else if (
123 marker[0] === openFence.marker[0] &&
124 marker.length >= openFence.marker.length &&
125 indent <= openFence.indent + 3 &&
126 line.length === prefix.length + marker.length
127 ) {
128 // CommonMark: a closing fence carries no info string.
129 openFence = null;
130 boundary = newline + 1;
131 }
132 } else if (listFenceMatch) {
133 openFence = {
134 marker: listFenceMatch.marker,
135 indent: listFenceMatch.indent,
136 minIndent: listFenceMatch.indent,
137 };
138 titleAwaitingContent = false;
139 } else if (openFence === null && BLANK_LINE_PATTERN.test(line) && lineStart > 0) {
140 if (!titleAwaitingContent) {
141 boundary = newline + 1;
142 }
143 } else if (openFence === null) {
144 if (lineStart > 0 && !titleAwaitingContent && TOP_LEVEL_HEADING_PATTERN.test(line)) {
145 boundary = lineStart;
146 }
147 titleAwaitingContent = SECTION_TITLE_PATTERN.test(line);
148 }
149 lineStart = newline + 1;
150 searchFrom = lineStart;
151 if (nextLf !== -1 && nextLf < searchFrom) nextLf = text.indexOf("\n", searchFrom);
152 if (nextCr !== -1 && nextCr < searchFrom) nextCr = text.indexOf("\r", searchFrom);
153 }
154 return { text, lineStart, openFence, boundary, titleAwaitingContent };
156​
157// The partial line may still change, so its list item start is checked here, not kept in the scan.
158function readyBoundary(scan: AssistantTextScan): number {
159 if (scan.openFence === null && scan.lineStart > 0 && !scan.titleAwaitingContent) {
160 PARTIAL_LIST_ITEM_START_PATTERN.lastIndex = scan.lineStart;
161 if (PARTIAL_LIST_ITEM_START_PATTERN.test(scan.text)) return scan.lineStart;
162 }
163 return scan.boundary;
165​
166/** Emit terminated lines only, except partial list-start lookahead for tight lists. Hold section titles until content follows. */
167export function splitBufferedAssistantText(text: string): { ready: string; rest: string } {
168 const boundary = readyBoundary(advanceScan(EMPTY_SCAN, text));
169 if (boundary === -1) {
170 return { ready: "", rest: text };
171 }
172 return { ready: text.slice(0, boundary), rest: text.slice(boundary) };
174​
175// Long enough to ride out normal gaps between chunks; short enough that text written before a
176// long tool call or background wait does not look lost.
177const ASSISTANT_IDLE_FLUSH_MS = 800;
178​
179type StreamedMessage = {
180 readonly id: string;
181 readonly text: string;
182 readonly streaming: boolean;
183};
184​
185interface StreamTrack {
186 readonly text: string;
187 readonly at: number;
188 // Latest snapshot whose text has not all been delivered yet.
189 readonly held: ProviderAdapter.ProviderAdapterV2Event | null;
190 readonly dueAt: number;
191 readonly scan: AssistantTextScan;
193​
194function streamedMessage(event: ProviderAdapter.ProviderAdapterV2Event): StreamedMessage | null {
195 if (event.type === "message.updated" && event.message.role === "assistant") return event.message;
196 if (
197 event.type === "turn_item.updated" &&
198 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
199 )
200 return event.turnItem;
201 return null;
203​
204function withText(
205 event: ProviderAdapter.ProviderAdapterV2Event,
206 text: string,
207): ProviderAdapter.ProviderAdapterV2Event {
208 if (event.type === "message.updated") return { ...event, message: { ...event.message, text } };
209 if (
210 event.type === "turn_item.updated" &&
211 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
212 )
213 return { ...event, turnItem: { ...event.turnItem, text } };
214 return event;
216​
217/**
218 * Paragraph mode delivers streamed text at Markdown boundaries, at most every 400ms. A snapshot
219 * held back that way is delivered whole once its message has been idle for `idleFlushMs`, so a
220 * provider that pauses mid-turn still shows everything it wrote.
221 */
222export function makeAssistantStreamingFilter(
223 mode: ResponseStreamingMode,
224 idleFlushMs = ASSISTANT_IDLE_FLUSH_MS,
225) {
226 const tracks = new Map<string, StreamTrack>();
227 // Earliest deadline of any held snapshot, or earlier: a newer snapshot only pushes its own
228 // deadline later, so the cache stays O(1) per event and is recomputed when it comes due.
229 let nextDueAt: number | null = null;
230 const track = (key: string, value: StreamTrack) => {
231 tracks.set(key, value);
232 if (value.held !== null && (nextDueAt === null || value.dueAt < nextDueAt))
233 nextDueAt = value.dueAt;
234 };
235 return {
236 filter(
237 event: ProviderAdapter.ProviderAdapterV2Event,
238 now: number,
239 ): ProviderAdapter.ProviderAdapterV2Event | null {
240 if (
241 event.type === "node.updated" &&
242 event.node.kind === "assistant_message" &&
243 event.node.status === "running"
244 )
245 return null;
246 const message = streamedMessage(event);
247 if (!message) return event;
248 const key = `${event.type}:${message.id}`;
249 if (!message.streaming) {
250 tracks.delete(key);
251 return event;
252 }
253 if (mode === "turn") return null;
254 const previous = tracks.get(key);
255 const delivered = previous?.text ?? "";
256 const hold = (scan = previous?.scan ?? EMPTY_SCAN) => {
257 track(key, {
258 text: delivered,
259 at: previous?.at ?? Number.NEGATIVE_INFINITY,
260 held: message.text !== delivered ? event : null,
261 dueAt: now + idleFlushMs,
262 scan,
263 });
264 return null;
265 };
266 if (previous && now - previous.at < 400) return hold();
267 const scan = advanceScan(previous?.scan ?? EMPTY_SCAN, message.text);
268 const boundary = readyBoundary(scan);
269 const ready = boundary === -1 ? "" : message.text.slice(0, boundary);
270 // An idle delivery may already show more than the next boundary; never shrink it. A
271 // provider rewrite or truncation is not a prefix and replaces it.
272 if (delivered.startsWith(ready)) return hold(scan);
273 track(key, {
274 text: ready,
275 at: now,
276 held: ready !== message.text ? event : null,
277 dueAt: now + idleFlushMs,
278 scan,
279 });
280 return withText(event, ready);
281 },
282 nextIdleFlushAt: (): number | null => nextDueAt,
283 /** Returns the held snapshots due by `now` and counts them as delivered. */
284 takeIdleFlushes(now: number): ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event> {
285 const due: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
286 nextDueAt = null;
287 for (const [key, current] of tracks) {
288 const event = current.held;
289 if (event === null) continue;
290 if (current.dueAt > now) {
291 if (nextDueAt === null || current.dueAt < nextDueAt) nextDueAt = current.dueAt;
292 continue;
293 }
294 due.push(event);
295 tracks.set(key, {
296 text: streamedMessage(event)?.text ?? current.text,
297 at: now,
298 held: null,
299 dueAt: now,
300 scan: current.scan,
301 });
302 }
303 return due;
304 },
305 };