@@ -155,31 +155,52 @@ function getOpenAITextPhase(
155155 : null;
156156 }
157157
158+type StreamTextRoute = "skip" | "text" | "reasoning";
159+
160+function extractTextDelta(chunk: StreamTextChunk): string {
161+ if (typeof chunk.text === "string") return chunk.text;
162+ if (typeof chunk.textDelta === "string") return chunk.textDelta;
163+ if (typeof chunk.delta === "string") return chunk.delta;
164+ return "";
165+}
166+
158167 class StreamTextPhaseTracker {
159168 private phaseByTextPartId = new Map<string, "commentary" | "final_answer">();
160169
161- shouldEmit(chunk: StreamTextChunk): boolean {
170+ route(chunk: StreamTextChunk): StreamTextRoute {
162171 const textPartId = normalizeTextPartId(chunk.id);
163172 switch (chunk.type) {
164173 case "text-start": {
165174 const phase = getOpenAITextPhase(chunk);
166175 if (textPartId && phase) this.phaseByTextPartId.set(textPartId, phase);
167- return false;
176+ return "skip";
168177 }
169178 case "text-end": {
170179 if (textPartId) this.phaseByTextPartId.delete(textPartId);
171- return false;
180+ return "skip";
172181 }
173182 case "text-delta": {
174- if (!textPartId) return true;
175- return this.phaseByTextPartId.get(textPartId) !== "commentary";
183+ if (!textPartId) return "text";
184+ return this.phaseByTextPartId.get(textPartId) === "commentary"
185+ ? "reasoning"
186+ : "text";
176187 }
177188 default:
178- return true;
189+ return "text";
179190 }
180191 }
181192 }
182193
194+function mapCommentaryChunkToTurnEvent(
195+ chunk: StreamTextChunk,
196+): TurnEvent | null {
197+ if (chunk.type !== "text-delta") return null;
198+ return {
199+ type: "reasoning-delta",
200+ delta: extractTextDelta(chunk),
201+ };
202+}
203+
183204 class StreamToolCallTracker {
184205 private syntheticCount = 0;
185206 private pendingByTool = new Map<string, string[]>();
@@ -251,12 +272,15 @@ export async function* mapFullStreamToTurnEvents(
251272 const textPhaseTracker = new StreamTextPhaseTracker();
252273 for await (const originalChunk of stream) {
253274 const chunk = toolCallTracker.assign(originalChunk);
254- const shouldEmitChunk = textPhaseTracker.shouldEmit(chunk);
255- if (shouldEmitChunk && shouldLogStreamChunk(chunk)) {
275+ const route = textPhaseTracker.route(chunk);
276+ if (route !== "skip" && shouldLogStreamChunk(chunk)) {
256277 opts.onChunk?.(chunk);
257278 }
258- if (!shouldEmitChunk) continue;
259- const event = mapStreamChunkToTurnEvent(chunk);
279+ if (route === "skip") continue;
280+ const event =
281+ route === "reasoning"
282+ ? mapCommentaryChunkToTurnEvent(chunk)
283+ : mapStreamChunkToTurnEvent(chunk);
260284 if (event) yield event;
261285 }
262286 }