Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): keep provider search answers in order and visible (#3966)

Andrew Barbae0ad9a02067b
diff --git a/.changeset/provider-search-replay-order.md b/.changeset/provider-search-replay-order.md
new file mode 100644
index 000000000..8b6864245
--- /dev/null
+++ b/.changeset/provider-search-replay-order.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Agents using AI Gateway web search no longer claim on the next turn that they answered before searching. When a reply continues after a search result in the same model call, eve now stores that text as its own assistant message, so AI Gateway replays it after the result instead of before the search.
diff --git a/.changeset/steering-wait-no-extra-step.md b/.changeset/steering-wait-no-extra-step.md
new file mode 100644
index 000000000..a83001655
--- /dev/null
+++ b/.changeset/steering-wait-no-extra-step.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+A message that interrupts a waiting tool call, such as a `sleep` or `task_wait`, no longer also interrupts the step that reads it. The stream no longer emits a stray `step.started` with no model call before the step that answers the message.
diff --git a/.changeset/tui-text-after-provider-tool.md b/.changeset/tui-text-after-provider-tool.md
new file mode 100644
index 000000000..9ae59c783
--- /dev/null
+++ b/.changeset/tui-text-after-provider-tool.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+The `eve dev` terminal UI now shows text the model writes after a provider-executed tool such as web search in the same model call. Before, the answer after a search was dropped from the transcript even though the agent sent it.
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/web-search-follow-up.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/web-search-follow-up.eval.ts
new file mode 100644
index 000000000..fd4d5b8bd
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/static-tools/web-search-follow-up.eval.ts
@@ -0,0 +1,37 @@
+import { defineEval } from "eve/evals";
+import { narratedWebSearchOrder, WEB_SEARCH_TOOL_NAME } from "./web-search-ordering";
+
+/**
+ * The first turn writes text, searches, then answers in one model call, so its
+ * history holds text after a provider-executed result. The follow-up replays
+ * that history to the provider and must search and answer again.
+ */
+export default defineEval({
+ tags: ["real-model"],
+ description: "Provider tools: a follow-up turn replays narrated web search history.",
+ async test(t) {
+ const first = await t.send(
+ [
+ "Important date context: the 2026 NBA Finals have absolutely already been played, and a champion has been crowned. Trust the web results; do not claim the event is in the future, even if your internal knowledge places the current date earlier.",
+ `Alice is catching up on basketball. Before calling \`${WEB_SEARCH_TOOL_NAME}\`, write one short visible sentence explaining that you will search.`,
+ `Then call \`${WEB_SEARCH_TOOL_NAME}\` exactly once to find out who won the 2026 NBA Finals.`,
+ "After the result returns, reply with the winning team name.",
+ ].join("\n"),
+ );
+ first.expectOk();
+ first.calledTool(WEB_SEARCH_TOOL_NAME, { count: 1 });
+ first.eventsSatisfy("the first turn answers after its narrated search", (events) =>
+ narratedWebSearchOrder(events),
+ );
+
+ const second = await first.session.send(
+ `Thanks! Bob asked who was named 2026 NBA Finals MVP. Please call \`${WEB_SEARCH_TOOL_NAME}\` once to check, then reply with the player's name.`,
+ );
+ second.expectOk();
+ second.calledTool(WEB_SEARCH_TOOL_NAME, { count: (count) => count >= 1 });
+ second.noFailedActions();
+ second.messageIncludes(/Brunson/iu);
+
+ t.succeeded();
+ },
+});
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index f2741d0be..c88930b1c 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -2688,6 +2688,80 @@ describe("EveTUIRunner reused step indexes", () => {
const completes = emitted.filter((event) => event.type === "assistant-complete");
expect(completes).toHaveLength(2);
});
+
+ it("renders the answer a model writes after a provider-executed tool in the same step", async () => {
+ // One model call: a preamble, a provider-executed web search, then the
+ // answer, all under the same `turnId:stepIndex` with no new `step.started`.
+ const prompts: Array<string | undefined> = ["who won the finals", undefined];
+ const emitted: AgentTUIStreamEvent[] = [];
+ const part = { sequence: 0, stepIndex: 0, turnId: "t0" };
+ const session = sessionYielding([
+ { type: "step.started", data: part },
+ { type: "message.appended", data: { ...part, messageDelta: "I'll look it up." } },
+ {
+ type: "message.completed",
+ data: { ...part, finishReason: "tool-calls", message: "I'll look it up." },
+ },
+ {
+ type: "actions.requested",
+ data: {
+ ...part,
+ actions: [
+ {
+ callId: "search-1",
+ input: { query: "finals winner" },
+ kind: "tool-call",
+ toolName: "web_search",
+ },
+ ],
+ },
+ },
+ {
+ type: "action.result",
+ data: {
+ ...part,
+ result: {
+ callId: "search-1",
+ kind: "tool-result",
+ output: { results: [] },
+ toolName: "web_search",
+ },
+ status: "completed",
+ },
+ },
+ { type: "message.appended", data: { ...part, messageDelta: "The Knicks won." } },
+ {
+ type: "message.completed",
+ data: { ...part, finishReason: "stop", message: "The Knicks won." },
+ },
+ { type: "step.completed", data: { ...part, usage: {} } },
+ { type: "turn.completed", data: { sequence: 0, turnId: "t0" } },
+ {
+ type: "session.waiting",
+ data: { continuationToken: "session-id", wait: "next-user-message" },
+ },
+ ]);
+ const renderer: AgentTUIRenderer = {
+ readPrompt: vi.fn(async () => prompts.shift()),
+ renderStream: vi.fn(async (result) => {
+ for await (const event of result.events as AsyncIterable<AgentTUIStreamEvent>) {
+ emitted.push(event);
+ }
+ }),
+ };
+
+ await new EveTUIRunner({ session, renderer, name: "Weather Agent" }).run();
+
+ const deltas = emitted.filter((event) => event.type === "assistant-delta");
+ expect(deltas.map((event) => event.delta)).toEqual(["I'll look it up.", "The Knicks won."]);
+ expect(deltas[0]?.id).not.toBe(deltas[1]?.id);
+ expect(emitted.map((event) => event.type)).toEqual(
+ expect.arrayContaining(["tool-call", "tool-result"]),
+ );
+ expect(emitted.findIndex((event) => event.type === "tool-result")).toBeLessThan(
+ emitted.findIndex((event) => event.type === "assistant-delta" && event.id === deltas[1]?.id),
+ );
+ });
});
describe("EveTUIRunner replay guards", () => {
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index 4f02469ea..e59cedc91 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -2184,12 +2184,13 @@ async function* eveEventsToTUIStream(
const toolNames = new Map<string, string>();
// Dropping re-delivered events here means every case below is a new emission.
const seenEvents = createEventDeduper();
- // Counts `step.started` events. The harness reuses `stepIndex` across the
- // model calls of one turn (e.g. the post-subagent call restarts at the same
- // index), so a part key alone cannot distinguish a new message under a
- // reused key from a re-emission. A fresh `step.started` since the part
- // completed is the discriminator.
- let stepEpoch = 0;
+ // Counts `step.started` and tool events. A part key alone cannot distinguish
+ // a new message from a re-emission: the harness reuses `stepIndex` across
+ // the model calls of one turn (e.g. the post-subagent call restarts at the
+ // same index), and one model call can write text, run a provider-executed
+ // tool, then write more text under the same key. A new step or tool event
+ // since the part completed is the discriminator.
+ let partEpoch = 0;
const knownToolCalls = new Set<string>();
const preparingToolCalls = new Set<string>();
// A task's `action.result` is only its start receipt, written for the
@@ -2229,15 +2230,15 @@ async function* eveEventsToTUIStream(
break;
case "step.started":
- stepEpoch += 1;
+ partEpoch += 1;
yield { type: "step-start", modelId: event.data.modelId };
break;
case "step.completed": {
const stepEvent = event as StepCompletedStreamEvent;
latestStepUsage = stepEvent.data.usage;
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
yield { type: "step-finish", usage: stepEvent.data.usage };
break;
}
@@ -2248,11 +2249,12 @@ async function* eveEventsToTUIStream(
const state = partStateFor(textParts, base);
if (state.completed) {
- // No intervening `step.started`: a retry of the same model call.
- if (stepEpoch <= state.completedEpoch) break;
+ // No intervening step or tool: a retry of the same model call.
+ if (partEpoch <= state.completedEpoch) break;
// A fresh model call reusing this part key (the harness restarts
- // `stepIndex` after a park/resume, e.g. post-subagent): open a new
- // message generation so it renders as its own block.
+ // `stepIndex` after a park/resume, e.g. post-subagent), or text
+ // after a tool in the same call: open a new message generation so
+ // it renders as its own block.
state.generation += 1;
state.text = "";
state.completed = false;
@@ -2272,12 +2274,12 @@ async function* eveEventsToTUIStream(
const message = event.data.message;
if (state.completed) {
- if (stepEpoch <= state.completedEpoch) break;
+ if (partEpoch <= state.completedEpoch) break;
// Channels that skip per-delta events: a new full message under a
// reused key after a fresh model call.
state.generation += 1;
state.text = message;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
yield {
type: "assistant-complete",
id: partGenerationId(base, state.generation),
@@ -2290,7 +2292,7 @@ async function* eveEventsToTUIStream(
if (state.text.length === 0) {
state.text = message;
state.completed = true;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
yield { type: "assistant-complete", id, text: message };
} else if (message.startsWith(state.text)) {
const suffix = message.slice(state.text.length);
@@ -2300,12 +2302,12 @@ async function* eveEventsToTUIStream(
}
state.text = message;
state.completed = true;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
yield { type: "assistant-complete", id };
} else {
state.text = message;
state.completed = true;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
yield { type: "assistant-complete", id, text: message };
}
break;
@@ -2317,7 +2319,7 @@ async function* eveEventsToTUIStream(
const state = partStateFor(reasoningParts, base);
if (state.completed) {
- if (stepEpoch <= state.completedEpoch) break;
+ if (partEpoch <= state.completedEpoch) break;
state.generation += 1;
state.text = "";
state.completed = false;
@@ -2337,10 +2339,10 @@ async function* eveEventsToTUIStream(
if (state.completed) {
if (next.length === 0) break;
- if (stepEpoch <= state.completedEpoch) break;
+ if (partEpoch <= state.completedEpoch) break;
state.generation += 1;
state.text = next;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
const id = partGenerationId(base, state.generation);
yield { type: "reasoning-delta", id, delta: next };
yield { type: "reasoning-complete", id };
@@ -2356,7 +2358,7 @@ async function* eveEventsToTUIStream(
state.generation += 1;
state.text = next;
state.completed = true;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
const replacementId = partGenerationId(base, state.generation);
yield { type: "reasoning-delta", id: replacementId, delta: next };
yield { type: "reasoning-complete", id: replacementId };
@@ -2364,7 +2366,7 @@ async function* eveEventsToTUIStream(
}
state.completed = true;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
yield { type: "reasoning-complete", id };
break;
}
@@ -2384,6 +2386,7 @@ async function* eveEventsToTUIStream(
action.kind === "tool-call" && !isTaskControlTool(action.toolName) ? [action] : [],
);
if (actions.length === 0) break;
+ partEpoch += 1;
for (const action of actions) {
toolNames.set(action.callId, action.toolName);
@@ -2488,6 +2491,7 @@ async function* eveEventsToTUIStream(
};
break;
}
+ partEpoch += 1;
switch (resultEvent.data.status) {
case "completed": {
const output = resultEvent.data.result.output;
@@ -2536,8 +2540,8 @@ async function* eveEventsToTUIStream(
const failure = toFailureEvent(event, emittedFailures, failureHintOverride);
if (failure) yield failure;
turnState.boundaryEvent = event.type;
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
yield {
type: "finish",
usage: latestStepUsage,
@@ -2549,8 +2553,8 @@ async function* eveEventsToTUIStream(
case "session.waiting":
case "session.completed":
turnState.boundaryEvent = event.type;
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
yield {
type: "finish",
usage: latestStepUsage,
@@ -2565,8 +2569,8 @@ async function* eveEventsToTUIStream(
break;
}
turnState.boundaryEvent = event.type;
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
yield {
type: "finish",
usage: latestStepUsage,
@@ -2576,16 +2580,16 @@ async function* eveEventsToTUIStream(
case "turn.completed":
visibleTurnCompleted = true;
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
break;
case "turn.cancelled":
// Explicit cooperative cancellation preserves the session.
// `session.waiting` follows and finishes the stream normally.
onTurnCancelled?.(event.data.turnId);
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
yield { type: "turn-cancelled" };
break;
@@ -2635,8 +2639,8 @@ async function* eveEventsToTUIStream(
}
if (!sentFinish) {
- yield* closeOpenParts(textParts, "assistant-complete", stepEpoch);
- yield* closeOpenParts(reasoningParts, "reasoning-complete", stepEpoch);
+ yield* closeOpenParts(textParts, "assistant-complete", partEpoch);
+ yield* closeOpenParts(reasoningParts, "reasoning-complete", partEpoch);
yield { type: "finish", usage: latestStepUsage };
}
}
@@ -2716,7 +2720,7 @@ type StreamPartState = {
/** Accumulated text of the current generation. */
text: string;
completed: boolean;
- /** Value of the step epoch when the current generation completed. */
+ /** Value of the part epoch when the current generation completed. */
completedEpoch: number;
};
@@ -2743,12 +2747,12 @@ function partGenerationId(base: string, generation: number): string {
function* closeOpenParts(
parts: Map<string, StreamPartState>,
type: "assistant-complete" | "reasoning-complete",
- stepEpoch: number,
+ partEpoch: number,
): Generator<AgentTUIStreamEvent> {
for (const [base, state] of parts) {
if (state.completed || state.text.length === 0) continue;
state.completed = true;
- state.completedEpoch = stepEpoch;
+ state.completedEpoch = partEpoch;
yield { type, id: partGenerationId(base, state.generation) };
}
}
diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.ts
index bc0c73a9f..89228af0c 100644
--- a/packages/eve/src/execution/session/turn.test.ts
+++ b/packages/eve/src/execution/session/turn.test.ts
@@ -775,6 +775,75 @@ describe("SessionExecution checkpoints", () => {
expect(publishTurnWaitingStep).toHaveBeenCalledTimes(1);
expect(publishTurnWaitingStep).toHaveBeenCalledWith(expect.objectContaining({ sessionState }));
});
+
+ it("does not let steering that woke a wait interrupt the step that reads it", async () => {
+ const base = state("");
+ const working = createTask(readTaskTable(undefined), {
+ callId: "task-call",
+ kind: "tool",
+ name: "research",
+ resumable: false,
+ turnId: "turn_0",
+ });
+ const sessionState: DurableSessionState = {
+ ...base,
+ snapshot: { session: writeTaskTable(base.snapshot.session, working.table) },
+ };
+ const steering: DeliverHookPayload = {
+ kind: "deliver",
+ payloads: [{ message: "Also check Bob's notes." }],
+ };
+ let signalDelivery: (payload: SessionInboxPayload) => void = () => {};
+ const inbox: SessionInbox = {
+ claimedTokens: [],
+ claimSessionHook: vi.fn(),
+ claimSessionHooks: vi.fn(),
+ drain: vi.fn(() => []),
+ hasPending: vi.fn(() => false),
+ whenPending: () => new Promise<void>(() => {}),
+ // The pump signals a delivery as it arrives, then the wait reads it.
+ next: vi.fn(async () => {
+ signalDelivery(steering);
+ return steering;
+ }),
+ onDelivery: vi.fn((handler) => {
+ signalDelivery = handler;
+ return () => {};
+ }),
+ onAgentStarted: () => () => {},
+ onInterrupt: vi.fn(() => () => {}),
+ restore: vi.fn(),
+ };
+ vi.mocked(dispatchCoordinationStep).mockReset().mockResolvedValue({
+ results: [],
+ serializedContext: {},
+ sessionState,
+ });
+ let continuation: { delivery?: DeliverHookPayload; steered?: boolean } = {};
+ vi.mocked(turnStep)
+ .mockReset()
+ .mockResolvedValueOnce({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["wait-call"],
+ pendingTaskToolCalls: [{ callId: "wait-call", kind: "task_wait" }],
+ serializedContext: {},
+ sessionState,
+ })
+ .mockImplementationOnce(async (input) => {
+ continuation = { delivery: input.input?.delivery, steered: input.steeringSignal?.aborted };
+ return { action: "done", output: "done", serializedContext: {}, sessionState };
+ });
+
+ await expect(
+ createExecution({ inbox, sessionState }).runTurn({
+ delivery: { kind: "deliver", payloads: [{ message: "Wait for the research." }] },
+ }),
+ ).resolves.toMatchObject({ kind: "done" });
+
+ expect(continuation).toEqual({ delivery: steering, steered: false });
+ });
});
function createExecution(input: {
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index 4c8848d41..e0a68c242 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -154,7 +154,6 @@ export class SessionExecution {
sessionState: result.sessionState,
});
await turn.admitBoundary();
- turn.resetSteering();
await this.handleAdmittedTaskEvents(turn);
if (result.action === "cancelled") return await this.finishCancelledTurn();
@@ -518,7 +517,7 @@ class ActiveTurn {
return this.steeringController.signal;
}
- resetSteering(): void {
+ private resetSteering(): void {
if (!this.steeringController.signal.aborted) return;
this.unsubscribeDelivery();
this.steeringController = new AbortController();
@@ -533,7 +532,11 @@ class ActiveTurn {
for (const payload of pending) await this.admit(payload);
}
- /** Steering admitted during this turn, routed to children first and coalesced. */
+ /**
+ * Steering admitted during this turn, routed to children first and coalesced.
+ * The next step reads it as input, so its signal must not interrupt that
+ * step; only deliveries still unread re-signal the next generation.
+ */
async takeSteering(): Promise<DeliverHookPayload | undefined> {
const steering: DeliverHookPayload[] = [];
while (true) {
@@ -547,6 +550,7 @@ class ActiveTurn {
}
if (routed.kind === "turn") steering.push(routed.delivery);
}
+ this.resetSteering();
if (steering.length === 0) return undefined;
const delivery = steering.length === 1 ? steering[0]! : coalesceDeliveries(steering);
if (delivery.caller !== undefined) this.caller = delivery.caller;
diff --git a/packages/eve/src/harness/provider-tool-history.test.ts b/packages/eve/src/harness/provider-tool-history.test.ts
index 33895a22e..9115629f6 100644
--- a/packages/eve/src/harness/provider-tool-history.test.ts
+++ b/packages/eve/src/harness/provider-tool-history.test.ts
@@ -142,6 +142,67 @@ describe("normalizeProviderToolHistory", () => {
expect(normalized.outcomeEndsResponse).toBe(true);
});
+ it("starts a new assistant message after native provider results so replay keeps the answer after them", () => {
+ const call = (toolCallId: string) =>
+ ({
+ type: "tool-call",
+ toolCallId,
+ toolName: "web_search",
+ input: { query: toolCallId },
+ providerExecuted: true,
+ }) as const;
+ const result = (toolCallId: string) =>
+ ({
+ type: "tool-result",
+ toolCallId,
+ toolName: "web_search",
+ output: { type: "json", value: { results: [toolCallId] } },
+ }) as const;
+ const reasoning = {
+ type: "reasoning",
+ text: "Search both.",
+ providerOptions: { anthropic: { signature: "sig" } },
+ } as const;
+ const messages: ModelMessage[] = [
+ {
+ role: "assistant",
+ content: [
+ reasoning,
+ { type: "text", text: "I'll look both up." },
+ call("search-1"),
+ call("search-2"),
+ result("search-1"),
+ result("search-2"),
+ { type: "text", text: "The Knicks and the Hurricanes won." },
+ ],
+ },
+ ];
+
+ const normalized = normalizeProviderToolHistory({
+ messages,
+ providerExecutedOutcomeIds: new Set(["search-1", "search-2"]),
+ });
+
+ expect(normalized.messages).toEqual([
+ {
+ role: "assistant",
+ content: [
+ reasoning,
+ { type: "text", text: "I'll look both up." },
+ call("search-1"),
+ call("search-2"),
+ result("search-1"),
+ result("search-2"),
+ ],
+ },
+ {
+ role: "assistant",
+ content: [{ type: "text", text: "The Knicks and the Hurricanes won." }],
+ },
+ ]);
+ expect(normalized.outcomeEndsResponse).toBe(false);
+ });
+
it("keeps local tool calls next to their results around provider-owned results", () => {
const messages: ModelMessage[] = [
{
diff --git a/packages/eve/src/harness/provider-tool-history.ts b/packages/eve/src/harness/provider-tool-history.ts
index d050cfa16..b7b4ebaef 100644
--- a/packages/eve/src/harness/provider-tool-history.ts
+++ b/packages/eve/src/harness/provider-tool-history.ts
@@ -7,11 +7,13 @@ import type { ModelMessage, ToolModelMessage } from "ai";
* message. Each matching call is rewritten as a normal call and consecutive
* results are moved into a tool message at their original position when the
* call lacks the matching marker or shares an assistant message with a local
- * tool call. Native provider-only call/result pairs remain untouched. Text
- * before a result remains before it; text after a result remains after it.
- * Local tool calls in a split message, with their approval requests, move to
- * its last assistant message, so the local results that follow the response
- * directly follow their calls.
+ * tool call. Native provider-only call/result pairs stay in the assistant
+ * message, but content after their results starts a new assistant message:
+ * AI Gateway replays a single message with a result followed by text as if
+ * the text came first. Text before a result remains before it; text after a
+ * result remains after it. Local tool calls in a split message, with their
+ * approval requests, move to its last assistant message, so the local results
+ * that follow the response directly follow their calls.
*/
export function normalizeProviderToolHistory(input: {
readonly messages: readonly ModelMessage[];
@@ -43,6 +45,7 @@ export function normalizeProviderToolHistory(input: {
let assistantContent: typeof message.content = [];
let toolContent: ToolModelMessage["content"] = [];
+ let afterProviderResult = false;
const localCallParts: typeof message.content = [];
const localCallIds = new Set<string>();
const splits = message.content.some(
@@ -79,6 +82,9 @@ export function normalizeProviderToolHistory(input: {
localCallParts.push(part);
} else {
flushTool();
+ // Parallel results stay together; anything else after them closes the message.
+ if (afterProviderResult && part.type !== "tool-result") flushAssistant();
+ afterProviderResult = part.type === "tool-result";
assistantContent.push(
part.type === "tool-call" && toolCallIdsToNormalize.has(part.toolCallId)
? { ...part, providerExecuted: false }