Open History to see the last commit
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.
5const MARKDOWN_FENCE_PATTERN = /^( *)(`{3,}|~{3,})/;
6// CommonMark blank lines contain only spaces and tabs.
7const BLANK_LINE_PATTERN = /^[ \t]*$/;
8// Require trailing space so partial list markers cannot match during streaming.
9const LIST_ITEM_START_PATTERN = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]/;
10const SECTION_TITLE_PATTERN = /^ {0,3}(?:#{1,6}(?:[ \t]|$)|\*\*(?:[^*]|\*(?!\*))+\*\*:?$)/;
11// Unindented ATX headings end preceding paragraphs and lists without blank lines; bold lines do not.
12const TOP_LEVEL_HEADING_PATTERN = /^#{1,6}(?:[ \t]|$)/;
13
14/** Emit terminated lines only, except partial list-start lookahead for tight lists. Hold section titles until content follows. */
15export function splitBufferedAssistantText(text: string): { ready: string; rest: string } {
16 let openFence: { marker: string; indent: number } | null = null;
17 let boundary = -1;
18 let lineStart = 0;
19 let titleAwaitingContent = false;
20 for (;;) {
21 const newline = text.indexOf("\n", lineStart);
22 const line = text
23 .slice(lineStart, newline === -1 ? text.length : newline)
24 .replace(/[ \t\r]+$/, "");
25 if (
26 openFence === null &&
27 lineStart > 0 &&
28 !titleAwaitingContent &&
29 LIST_ITEM_START_PATTERN.test(line)
30 ) {
31 boundary = lineStart;
32 }
33 if (newline === -1) {
34 break;
35 }
36 const fenceMatch = MARKDOWN_FENCE_PATTERN.exec(line);
37 if (fenceMatch) {
38 const indent = fenceMatch[1]!.length;
39 const marker = fenceMatch[2]!;
40 if (openFence === null) {
41 openFence = { marker, indent };
42 titleAwaitingContent = false;
43 } else if (
44 marker[0] === openFence.marker[0] &&
45 marker.length >= openFence.marker.length &&
46 indent <= openFence.indent + 3 &&
47 line.length === indent + marker.length
48 ) {
49 // CommonMark: a closing fence carries no info string.
50 openFence = null;
51 boundary = newline + 1;
52 }
53 } else if (openFence === null && BLANK_LINE_PATTERN.test(line) && lineStart > 0) {
54 if (!titleAwaitingContent) {
55 boundary = newline + 1;
56 }
57 } else if (openFence === null) {
58 if (lineStart > 0 && !titleAwaitingContent && TOP_LEVEL_HEADING_PATTERN.test(line)) {
59 boundary = lineStart;
60 }
61 titleAwaitingContent = SECTION_TITLE_PATTERN.test(line);
62 }
63 lineStart = newline + 1;
64 }
65 if (boundary === -1) {
66 return { ready: "", rest: text };
67 }
68 return { ready: text.slice(0, boundary), rest: text.slice(boundary) };
69}
70
71// Long enough to ride out normal gaps between chunks; short enough that text written before a
72// long tool call or background wait does not look lost.
73const ASSISTANT_IDLE_FLUSH_MS = 800;
74
75type StreamedMessage = {
76 readonly id: string;
77 readonly text: string;
78 readonly streaming: boolean;
79};
80
81interface StreamTrack {
82 readonly text: string;
83 readonly at: number;
84 // Latest snapshot whose text has not all been delivered yet.
85 readonly held: ProviderAdapter.ProviderAdapterV2Event | null;
86 readonly dueAt: number;
87}
88
89function streamedMessage(event: ProviderAdapter.ProviderAdapterV2Event): StreamedMessage | null {
90 if (event.type === "message.updated" && event.message.role === "assistant") return event.message;
91 if (
92 event.type === "turn_item.updated" &&
93 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
94 )
95 return event.turnItem;
96 return null;
97}
98
99function withText(
100 event: ProviderAdapter.ProviderAdapterV2Event,
101 text: string,
102): ProviderAdapter.ProviderAdapterV2Event {
103 if (event.type === "message.updated") return { ...event, message: { ...event.message, text } };
104 if (
105 event.type === "turn_item.updated" &&
106 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
107 )
108 return { ...event, turnItem: { ...event.turnItem, text } };
109 return event;
110}
111
112/**
113 * Paragraph mode delivers streamed text at Markdown boundaries, at most every 400ms. A snapshot
114 * held back that way is delivered whole once its message has been idle for `idleFlushMs`, so a
115 * provider that pauses mid-turn still shows everything it wrote.
116 */
117export function makeAssistantStreamingFilter(
118 mode: ResponseStreamingMode,
119 idleFlushMs = ASSISTANT_IDLE_FLUSH_MS,
120) {
121 const tracks = new Map<string, StreamTrack>();
122 // Earliest deadline of any held snapshot, or earlier: a newer snapshot only pushes its own
123 // deadline later, so the cache stays O(1) per event and is recomputed when it comes due.
124 let nextDueAt: number | null = null;
125 const track = (key: string, value: StreamTrack) => {
126 tracks.set(key, value);
127 if (value.held !== null && (nextDueAt === null || value.dueAt < nextDueAt))
128 nextDueAt = value.dueAt;
129 };
130 return {
131 filter(
132 event: ProviderAdapter.ProviderAdapterV2Event,
133 now: number,
134 ): ProviderAdapter.ProviderAdapterV2Event | null {
135 if (
136 event.type === "node.updated" &&
137 event.node.kind === "assistant_message" &&
138 event.node.status === "running"
139 )
140 return null;
141 const message = streamedMessage(event);
142 if (!message) return event;
143 const key = `${event.type}:${message.id}`;
144 if (!message.streaming) {
145 tracks.delete(key);
146 return event;
147 }
148 if (mode === "turn") return null;
149 const previous = tracks.get(key);
150 const delivered = previous?.text ?? "";
151 const hold = () => {
152 track(key, {
153 text: delivered,
154 at: previous?.at ?? Number.NEGATIVE_INFINITY,
155 held: message.text !== delivered ? event : null,
156 dueAt: now + idleFlushMs,
157 });
158 return null;
159 };
160 if (previous && now - previous.at < 400) return hold();
161 const { ready } = splitBufferedAssistantText(message.text);
162 // An idle delivery may already show more than the next boundary; never shrink it. A
163 // provider rewrite or truncation is not a prefix and replaces it.
164 if (delivered.startsWith(ready)) return hold();
165 track(key, {
166 text: ready,
167 at: now,
168 held: ready !== message.text ? event : null,
169 dueAt: now + idleFlushMs,
170 });
171 return withText(event, ready);
172 },
173 nextIdleFlushAt: (): number | null => nextDueAt,
174 /** Returns the held snapshots due by `now` and counts them as delivered. */
175 takeIdleFlushes(now: number): ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event> {
176 const due: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
177 nextDueAt = null;
178 for (const [key, current] of tracks) {
179 const event = current.held;
180 if (event === null) continue;
181 if (current.dueAt > now) {
182 if (nextDueAt === null || current.dueAt < nextDueAt) nextDueAt = current.dueAt;
183 continue;
184 }
185 due.push(event);
186 tracks.set(key, {
187 text: streamedMessage(event)?.text ?? current.text,
188 at: now,
189 held: null,
190 dueAt: now,
191 });
192 }
193 return due;
194 },
195 };
196}