Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): stream tool calls and results (#291)

Rui3865605c1e77
diff --git a/.changeset/stream-action-requests-early.md b/.changeset/stream-action-requests-early.md
new file mode 100644
index 000000000..287f68d4e
--- /dev/null
+++ b/.changeset/stream-action-requests-early.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Stream `actions.requested` as each model tool call arrives, before the tool finishes or a runtime action is dispatched.
diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.md
index 9d464f0f8..859df965c 100644
--- a/docs/concepts/sessions-runs-and-streaming.md
+++ b/docs/concepts/sessions-runs-and-streaming.md
@@ -40,7 +40,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:
| `turn.started` | A new turn began. |
| `message.received` | An inbound user message was accepted. |
| `step.started` | A model step began. |
-| `actions.requested` | The model requested tool calls. |
+| `actions.requested` | The model requested one or more actions, including tool calls; calls stream before execution. |
| `action.result` | A tool call returned. |
| `input.requested` | The run paused for human input ([HITL](/docs/human-in-the-loop) approval or `ask_question`); carries `requests`. |
| `subagent.called` | A subagent was delegated; carries `childSessionId` to attach to. |
diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdx
index b85dc0f21..4de31ec78 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -66,7 +66,7 @@ The most common UI events are:
| `message.received` | Confirm the user message landed. |
| `reasoning.appended` | Render reasoning deltas when the model provides them. |
| `message.appended` | Render assistant text deltas. |
-| `actions.requested` | Show tool calls requested by the model. |
+| `actions.requested` | Show tool calls as the model requests them, before execution. |
| `action.result` | Show tool call results. |
| `input.requested` | Pause the UI for approval or a question answer. |
| `result.completed` | Read structured output from an [output schema](./output-schema). |
diff --git a/e2e/fixtures/agent-tools/agent/channels/action-narration.ts b/e2e/fixtures/agent-tools/agent/channels/action-narration.ts
new file mode 100644
index 000000000..9b49a57b6
--- /dev/null
+++ b/e2e/fixtures/agent-tools/agent/channels/action-narration.ts
@@ -0,0 +1,109 @@
+import { defineChannel, POST } from "eve/channels";
+
+const STREAMED_ACTION_TOOL = "streamed-action";
+
+interface ActionNarrationState {
+ observedNarration: string | null;
+ pendingNarration: string | null;
+}
+
+interface ActionNarrationRequest {
+ readonly message: string;
+ readonly token: string;
+}
+
+function initialState(): ActionNarrationState {
+ return { observedNarration: null, pendingNarration: null };
+}
+
+function firstNonEmptyLine(message: string): string | null {
+ for (const line of message.split(/\r?\n/u)) {
+ const trimmed = line.trim();
+ if (trimmed.length > 0) return trimmed;
+ }
+ return null;
+}
+
+function readNonEmptyString(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function readRequestValue(body: unknown, key: string): unknown {
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return undefined;
+ return Reflect.get(body, key);
+}
+
+async function readRequest(request: Request): Promise<ActionNarrationRequest> {
+ const body = await request.json().catch(() => null);
+ const token = readNonEmptyString(readRequestValue(body, "token")) ?? crypto.randomUUID();
+ const message =
+ readNonEmptyString(readRequestValue(body, "message")) ??
+ "Reply with the single word: action-narration.";
+ return { message, token };
+}
+
+function continuationToken(token: string): string {
+ return `action-narration:${token}`;
+}
+
+/**
+ * Fixture channel that records the narration a channel handler can observe
+ * when a streamed action request arrives. The next turn exposes that durable
+ * observation through a dynamic tool so the eval can inspect it over HTTP.
+ */
+export default defineChannel({
+ state: initialState(),
+
+ context(state) {
+ return { state };
+ },
+
+ metadata(state) {
+ return { observedNarration: state.observedNarration };
+ },
+
+ routes: [
+ POST<ActionNarrationState>("/action-narration/start", async (request, { send }) => {
+ const input = await readRequest(request);
+ const session = await send(input.message, {
+ auth: null,
+ continuationToken: continuationToken(input.token),
+ state: initialState(),
+ });
+ return Response.json({ sessionId: session.id });
+ }),
+
+ POST<ActionNarrationState>("/action-narration/continue", async (request, { send }) => {
+ const input = await readRequest(request);
+ const session = await send(input.message, {
+ auth: null,
+ continuationToken: continuationToken(input.token),
+ state: initialState(),
+ });
+ return Response.json({ sessionId: session.id });
+ }),
+ ],
+
+ events: {
+ "turn.started"(_event, channel) {
+ channel.state.pendingNarration = null;
+ },
+
+ "message.completed"(event, channel) {
+ if (event.finishReason !== "tool-calls") return;
+ channel.state.pendingNarration = event.message ? firstNonEmptyLine(event.message) : null;
+ },
+
+ "actions.requested"(event, channel) {
+ const requestedStreamedAction = event.actions.some(
+ (action) => action.kind === "tool-call" && action.toolName === STREAMED_ACTION_TOOL,
+ );
+ if (!requestedStreamedAction) return;
+
+ channel.state.observedNarration = channel.state.pendingNarration;
+ channel.state.pendingNarration = null;
+ },
+ },
+});
diff --git a/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts b/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts
new file mode 100644
index 000000000..0e07f22b5
--- /dev/null
+++ b/e2e/fixtures/agent-tools/agent/tools/dynamic-channel-action-narration.ts
@@ -0,0 +1,33 @@
+import { isChannel } from "eve/channels";
+import { defineDynamic, defineTool } from "eve/tools";
+import { z } from "zod";
+
+import actionNarration from "../channels/action-narration.js";
+
+/**
+ * Exposes the previous turn's channel-side observation only after a streamed
+ * action request consumed pre-tool narration. The e2e eval drives a second
+ * turn to read this value through the real dynamic-tool lifecycle.
+ */
+export default defineDynamic({
+ events: {
+ "turn.started": (_event, ctx) => {
+ if (!isChannel(ctx.channel, actionNarration)) return null;
+
+ const narration = ctx.channel.metadata.observedNarration;
+ if (typeof narration !== "string" || narration.length === 0) return null;
+
+ return {
+ "read-channel-action-narration": defineTool({
+ description:
+ "Returns the narration the channel observed when the prior streamed action was requested. " +
+ "Only call when the user asks to inspect that channel observation.",
+ inputSchema: z.object({}),
+ async execute() {
+ return { narration };
+ },
+ }),
+ };
+ },
+ },
+});
diff --git a/e2e/fixtures/agent-tools/agent/tools/streamed-action.ts b/e2e/fixtures/agent-tools/agent/tools/streamed-action.ts
new file mode 100644
index 000000000..bdda3f476
--- /dev/null
+++ b/e2e/fixtures/agent-tools/agent/tools/streamed-action.ts
@@ -0,0 +1,20 @@
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+function delay(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+export default defineTool({
+ description:
+ "Test-only tool: records when local execution begins and ends, waiting before it returns. Only call when the user explicitly asks to use `streamed-action`.",
+ inputSchema: z.object({
+ label: z.string(),
+ }),
+ async execute(input) {
+ const executionStartedAt = Date.now();
+ await delay(500);
+
+ return { executionCompletedAt: Date.now(), executionStartedAt, label: input.label };
+ },
+});
diff --git a/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts b/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
new file mode 100644
index 000000000..d7f495125
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/channel-events/pre-tool-narration.eval.ts
@@ -0,0 +1,130 @@
+import { randomBytes } from "node:crypto";
+
+import type { HandleMessageStreamEvent } from "eve/client";
+import { defineEval, type EveEvalTargetHandle } from "eve/evals";
+
+const STREAMED_ACTION_TOOL = "streamed-action";
+const OBSERVATION_TOOL = "read-channel-action-narration";
+
+interface ChannelSessionResponse {
+ readonly sessionId: string;
+}
+
+function firstNonEmptyLine(message: string): string | undefined {
+ for (const line of message.split(/\r?\n/u)) {
+ const trimmed = line.trim();
+ if (trimmed.length > 0) return trimmed;
+ }
+ return undefined;
+}
+
+function preToolNarration(events: readonly HandleMessageStreamEvent[]): string | undefined {
+ const actionRequestIndex = events.findIndex(
+ (event) =>
+ event.type === "actions.requested" &&
+ event.data.actions.some(
+ (action) => action.kind === "tool-call" && action.toolName === STREAMED_ACTION_TOOL,
+ ),
+ );
+ if (actionRequestIndex < 0) return undefined;
+
+ for (let index = actionRequestIndex - 1; index >= 0; index -= 1) {
+ const event = events[index];
+ if (
+ event?.type === "message.completed" &&
+ event.data.finishReason === "tool-calls" &&
+ event.data.message !== null
+ ) {
+ return firstNonEmptyLine(event.data.message);
+ }
+ }
+ return undefined;
+}
+
+function observedNarration(events: readonly HandleMessageStreamEvent[]): string | undefined {
+ for (const event of events) {
+ if (event.type !== "action.result" || event.data.result.kind !== "tool-result") continue;
+ if (event.data.result.toolName !== OBSERVATION_TOOL) continue;
+
+ const output = event.data.result.output;
+ if (typeof output !== "object" || output === null || Array.isArray(output)) continue;
+ const narration = Reflect.get(output, "narration");
+ if (typeof narration === "string" && narration.length > 0) return narration;
+ }
+ return undefined;
+}
+
+async function postChannel(
+ target: EveEvalTargetHandle,
+ path: string,
+ body: Record<string, unknown>,
+): Promise<ChannelSessionResponse> {
+ const response = await target.fetch(path, {
+ body: JSON.stringify(body),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ });
+ const payload: unknown = await response.json().catch(() => null);
+ if (!response.ok) {
+ throw new Error(`POST ${path} failed (${response.status}): ${JSON.stringify(payload)}`);
+ }
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
+ throw new Error(`POST ${path} returned a non-object payload: ${JSON.stringify(payload)}`);
+ }
+
+ const sessionId = Reflect.get(payload, "sessionId");
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
+ throw new Error(`POST ${path} returned no sessionId: ${JSON.stringify(payload)}`);
+ }
+ return { sessionId };
+}
+
+/**
+ * End-to-end channel contract: the adapter receives the pre-tool completion
+ * before the matching action request, then preserves its observation across
+ * the next inbound channel turn.
+ */
+export default defineEval({
+ description: "Channel event smoke: pre-tool narration is visible when an action is requested.",
+ async test(t) {
+ const token = `channel-narration-${randomBytes(4).toString("hex")}`;
+ const started = await postChannel(t.target, "/action-narration/start", {
+ message:
+ "Before calling `streamed-action`, write one short plain-text sentence explaining the action. " +
+ `Then call it exactly once with label "${token}". After it returns, reply with the label verbatim.`,
+ token,
+ });
+ const firstTurn = await t.target.attachSession(started.sessionId);
+ const narration = preToolNarration(firstTurn.events);
+ if (narration === undefined) {
+ throw new Error(
+ "Expected a non-empty tool-calls message.completed event before the streamed-action request.",
+ );
+ }
+
+ const continued = await postChannel(t.target, "/action-narration/continue", {
+ message: `Call \`${OBSERVATION_TOOL}\` exactly once, then reply with the narration value it returned.`,
+ token,
+ });
+ if (continued.sessionId !== started.sessionId) {
+ throw new Error(
+ `Expected the channel continuation to resume ${started.sessionId}, received ${continued.sessionId}.`,
+ );
+ }
+
+ const secondTurn = await t.target.attachSession(continued.sessionId, {
+ startIndex: firstTurn.events.length,
+ });
+ const observed = observedNarration(secondTurn.events);
+ if (observed !== narration) {
+ throw new Error(
+ `Expected the channel to observe ${JSON.stringify(narration)}, received ${JSON.stringify(observed)}.`,
+ );
+ }
+
+ t.didNotFail();
+ t.completed();
+ t.calledTool(STREAMED_ACTION_TOOL, { isError: false, times: 1 });
+ t.calledTool(OBSERVATION_TOOL, { isError: false, times: 1 });
+ },
+});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts
new file mode 100644
index 000000000..4905058f5
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/static-tools/fanout-authored.eval.ts
@@ -0,0 +1,54 @@
+import { defineEval } from "eve/evals";
+
+import {
+ authoredFanoutExecutionsOverlap,
+ FANOUT_SIZE,
+ fanoutRequestsPrecedeFirstResult,
+ fanoutRequestsUseExpectedLabels,
+} from "./fanout.js";
+
+const TOOL_NAME = "streamed-action";
+const LABELS = [
+ "fanout-authored-01",
+ "fanout-authored-02",
+ "fanout-authored-03",
+ "fanout-authored-04",
+ "fanout-authored-05",
+ "fanout-authored-06",
+ "fanout-authored-07",
+ "fanout-authored-08",
+ "fanout-authored-09",
+ "fanout-authored-10",
+] as const;
+
+export default defineEval({
+ description: "Static tools smoke: ten authored tool calls begin concurrently.",
+ async test(t) {
+ const turn = await t.send(
+ [
+ `Call the \`${TOOL_NAME}\` tool exactly ${FANOUT_SIZE} separate times in one tool-use step.`,
+ `Use each label exactly once: ${LABELS.map((label) => `"${label}"`).join(", ")}.`,
+ "Start every call before waiting for any result. Do not use any other tool.",
+ "After every call returns, reply with exactly: authored fanout complete",
+ ].join("\n"),
+ );
+ turn.expectOk();
+
+ t.didNotFail();
+ t.completed();
+ t.calledTool(TOOL_NAME, { isError: false, times: FANOUT_SIZE });
+ t.noFailedActions();
+ t.event(
+ (events) => fanoutRequestsPrecedeFirstResult({ events, toolName: TOOL_NAME }),
+ "ten authored requests precede the first authored result",
+ );
+ t.event(
+ (events) => fanoutRequestsUseExpectedLabels({ events, labels: LABELS, toolName: TOOL_NAME }),
+ "ten authored requests use their distinct labels",
+ );
+ t.event(
+ (events) => authoredFanoutExecutionsOverlap({ events, toolName: TOOL_NAME }),
+ "ten authored executions overlap",
+ );
+ },
+});
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/fanout.ts b/e2e/fixtures/agent-tools/evals/static-tools/fanout.ts
new file mode 100644
index 000000000..e6cc89953
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/static-tools/fanout.ts
@@ -0,0 +1,110 @@
+import type { HandleMessageStreamEvent } from "eve/client";
+
+export const FANOUT_SIZE = 10;
+
+interface RequestedToolCall {
+ readonly callId: string;
+ readonly eventIndex: number;
+ readonly input: unknown;
+}
+
+/**
+ * Checks the visible fan-out boundary: every requested call must have reached
+ * the stream before the first matching result. This is the observable provider
+ * contract; the provider's own network execution is outside eve's process.
+ */
+export function fanoutRequestsPrecedeFirstResult(input: {
+ readonly events: readonly HandleMessageStreamEvent[];
+ readonly toolName: string;
+}): boolean {
+ const requests = requestedToolCalls(input);
+ const firstResultIndex = input.events.findIndex(
+ (event) =>
+ event.type === "action.result" &&
+ event.data.result.kind === "tool-result" &&
+ event.data.result.toolName === input.toolName,
+ );
+
+ return (
+ firstResultIndex >= 0 &&
+ requests.length === FANOUT_SIZE &&
+ new Set(requests.map((request) => request.callId)).size === FANOUT_SIZE &&
+ requests.every((request) => request.eventIndex < firstResultIndex)
+ );
+}
+
+export function fanoutRequestsUseExpectedLabels(input: {
+ readonly events: readonly HandleMessageStreamEvent[];
+ readonly labels: readonly string[];
+ readonly toolName: string;
+}): boolean {
+ const labels = requestedToolCalls(input)
+ .map((request) => readStringField(request.input, "label"))
+ .filter((label): label is string => label !== undefined);
+ const expectedLabels = new Set(input.labels);
+
+ return (
+ labels.length === FANOUT_SIZE &&
+ expectedLabels.size === FANOUT_SIZE &&
+ new Set(labels).size === FANOUT_SIZE &&
+ labels.every((label) => expectedLabels.has(label))
+ );
+}
+
+/**
+ * The fixture tool holds each invocation open. Requiring every interval to
+ * overlap rules out a serialized executor without relying on a clock-skew
+ * threshold.
+ */
+export function authoredFanoutExecutionsOverlap(input: {
+ readonly events: readonly HandleMessageStreamEvent[];
+ readonly toolName: string;
+}): boolean {
+ const intervals: Array<{ readonly completedAt: number; readonly startedAt: number }> = [];
+
+ for (const event of input.events) {
+ if (event.type !== "action.result" || event.data.result.kind !== "tool-result") continue;
+ if (event.data.result.toolName !== input.toolName) continue;
+
+ const startedAt = readFiniteNumberField(event.data.result.output, "executionStartedAt");
+ const completedAt = readFiniteNumberField(event.data.result.output, "executionCompletedAt");
+ if (startedAt === undefined || completedAt === undefined || startedAt >= completedAt) {
+ return false;
+ }
+ intervals.push({ completedAt, startedAt });
+ }
+
+ return (
+ intervals.length === FANOUT_SIZE &&
+ Math.max(...intervals.map((interval) => interval.startedAt)) <
+ Math.min(...intervals.map((interval) => interval.completedAt))
+ );
+}
+
+function requestedToolCalls(input: {
+ readonly events: readonly HandleMessageStreamEvent[];
+ readonly toolName: string;
+}): RequestedToolCall[] {
+ return input.events.flatMap((event, eventIndex) => {
+ if (event.type !== "actions.requested") return [];
+
+ return event.data.actions.flatMap((action) => {
+ if (action.kind !== "tool-call" || action.toolName !== input.toolName) return [];
+ return [{ callId: action.callId, eventIndex, input: action.input }];
+ });
+ });
+}
+
+function readFiniteNumberField(value: unknown, field: string): number | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
+
+ const candidate = Reflect.get(value, field);
+ return typeof candidate === "number" && Number.isFinite(candidate) ? candidate : undefined;
+}
+
+function readStringField(value: unknown, field: string): string | undefined {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
+
+ const candidate = Reflect.get(value, field);
+ return typeof candidate === "string" ? candidate : undefined;
+}
diff --git a/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts b/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts
new file mode 100644
index 000000000..2299e1e4c
--- /dev/null
+++ b/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts
@@ -0,0 +1,85 @@
+import type { ActionResultStreamEvent, HandleMessageStreamEvent } from "eve/client";
+import { defineEval } from "eve/evals";
+
+const TOOL_NAME = "streamed-action";
+const LABEL = "streaming-e2e";
+
+function streamedBeforeLocalExecution(events: readonly HandleMessageStreamEvent[]): boolean {
+ const matchingRequests = events.flatMap((event) => {
+ if (event.type !== "actions.requested") return [];
+
+ return event.data.actions
+ .filter((action) => action.kind === "tool-call" && action.toolName === TOOL_NAME)
+ .map((action) => ({ action, event }));
+ });
+ const [request] = matchingRequests;
+ if (
+ request === undefined ||
+ matchingRequests.length !== 1 ||
+ request.action.kind !== "tool-call"
+ ) {
+ return false;
+ }
+
+ const result = events.find(
+ (event): event is ActionResultStreamEvent =>
+ event.type === "action.result" &&
+ event.data.result.kind === "tool-result" &&
+ event.data.result.callId === request.action.callId,
+ );
+ if (result === undefined) {
+ return false;
+ }
+
+ const requestAt = parseTimestamp(request.event.meta?.at);
+ const executionStartedAt = readExecutionStartedAt(result.data.result.output);
+ return (
+ requestAt !== undefined && executionStartedAt !== undefined && requestAt <= executionStartedAt
+ );
+}
+
+function parseTimestamp(value: string | undefined): number | undefined {
+ if (value === undefined) return undefined;
+
+ const timestamp = Date.parse(value);
+ return Number.isFinite(timestamp) ? timestamp : undefined;
+}
+
+function readExecutionStartedAt(output: unknown): number | undefined {
+ if (
+ typeof output !== "object" ||
+ output === null ||
+ Array.isArray(output) ||
+ !("executionStartedAt" in output)
+ ) {
+ return undefined;
+ }
+
+ const executionStartedAt = output.executionStartedAt;
+ return typeof executionStartedAt === "number" && Number.isFinite(executionStartedAt)
+ ? executionStartedAt
+ : undefined;
+}
+
+// The runtime stamps meta.at immediately before persisting an event. The tool
+// records its start before waiting, so post-execution batch emission cannot
+// satisfy this relation.
+export default defineEval({
+ description: "Static tools smoke: a local action request streams before execution begins.",
+ async test(t) {
+ const turn = await t.send(
+ `Call the \`${TOOL_NAME}\` tool exactly once with label "${LABEL}". ` +
+ "After it returns, reply with the label verbatim.",
+ );
+ turn.expectOk();
+
+ t.didNotFail();
+ t.completed();
+ t.calledTool(TOOL_NAME, {
+ input: { label: LABEL },
+ isError: false,
+ times: 1,
+ });
+ t.event(streamedBeforeLocalExecution, "local action request precedes execution");
+ },
+});
diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.ts
index cde03bceb..74b621658 100644
--- a/packages/eve/src/cli/dev/tui/runner.test.ts
+++ b/packages/eve/src/cli/dev/tui/runner.test.ts
@@ -822,7 +822,7 @@ describe("EveTUIRunner reused step indexes", () => {
});
describe("EveTUIRunner replay guards", () => {
- it("ignores replayed tool batches and divergent text attempts in one turn", async () => {
+ it("deduplicates repeated call IDs and divergent text attempts in one turn", async () => {
const prompts: Array<string | undefined> = ["weather", undefined];
const emitted: AgentTUIStreamEvent[] = [];
const session = sessionYielding([
@@ -1002,15 +1002,57 @@ describe("EveTUIRunner replay guards", () => {
.map((event) => event.delta)
.join("");
- expect(toolCalls).toHaveLength(1);
- expect(toolCalls[0]).toMatchObject({ toolCallId: "call-original" });
- expect(toolResults).toHaveLength(1);
- expect(toolResults[0]).toMatchObject({ toolCallId: "call-original" });
+ expect(toolCalls.map((event) => event.toolCallId)).toEqual(["call-original", "call-replay"]);
+ expect(toolResults.map((event) => event.toolCallId)).toEqual(["call-original", "call-replay"]);
expect(assistantText).toBe("Using the first answer.");
expect(assistantText).not.toContain("retry");
expect(emitted.filter((event) => event.type === "finish")).toHaveLength(1);
});
+ it("renders every call in a 100-way bash fan-out with identical input", async () => {
+ const prompts: Array<string | undefined> = ["run the fan-out", undefined];
+ const emitted: AgentTUIStreamEvent[] = [];
+ const sentence = Array.from({ length: 100 }, (_, index) => `word-${index + 1}`).join(" ");
+ const command = `printf '%s\\n' '${sentence}'`;
+ const session = sessionYielding([
+ ...Array.from({ length: 100 }, (_, index) => ({
+ type: "actions.requested",
+ data: {
+ actions: [
+ {
+ callId: `bash-${index + 1}`,
+ input: { command },
+ kind: "tool-call",
+ toolName: "bash",
+ },
+ ],
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn_0",
+ },
+ })),
+ { type: "session.waiting", data: { 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);
+ }
+ }),
+ };
+
+ const runner = new EveTUIRunner({ session, renderer, name: "Weather Agent" });
+ await runner.run();
+
+ const toolCalls = emitted.filter((event) => event.type === "tool-call");
+ expect(toolCalls).toHaveLength(100);
+ expect(toolCalls.map((event) => event.toolCallId)).toEqual(
+ Array.from({ length: 100 }, (_, index) => `bash-${index + 1}`),
+ );
+ });
+
it("renders a known tool result that arrives after turn.completed", async () => {
const prompts: Array<string | undefined> = ["weather", undefined];
const emitted: AgentTUIStreamEvent[] = [];
diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.ts
index ac7daf84b..69b2d4bd1 100644
--- a/packages/eve/src/cli/dev/tui/runner.ts
+++ b/packages/eve/src/cli/dev/tui/runner.ts
@@ -1580,8 +1580,7 @@ async function* eveEventsToTUIStream(
// `step.started` since the part completed is the discriminator.
let stepEpoch = 0;
const knownToolCalls = new Set<string>();
- const ignoredToolCallIds = new Set<string>();
- const seenToolBatches = new Set<string>();
+ const seenInputRequestIds = new Set<string>();
// The harness reports one underlying failure as a cascade (`step.failed` →
// `turn.failed` → `session.failed`) with an identical payload on each
// event. Render it once, not three times.
@@ -1752,17 +1751,6 @@ async function* eveEventsToTUIStream(
const actions = data.actions.filter((action) => action.kind === "tool-call");
if (actions.length === 0) break;
- const batchKey = toolBatchKey("actions.requested", data.turnId, data.stepIndex, actions);
- if (seenToolBatches.has(batchKey)) {
- for (const action of actions) {
- if (!knownToolCalls.has(action.callId)) {
- ignoredToolCallIds.add(action.callId);
- }
- }
- break;
- }
- seenToolBatches.add(batchKey);
-
for (const action of actions) {
if (knownToolCalls.has(action.callId)) continue;
knownToolCalls.add(action.callId);
@@ -1781,17 +1769,6 @@ async function* eveEventsToTUIStream(
const requests = data.requests.filter((request) => request.action.kind === "tool-call");
if (requests.length === 0) break;
- const batchKey = inputRequestBatchKey(data.turnId, data.stepIndex, requests);
- if (seenToolBatches.has(batchKey)) {
- for (const request of requests) {
- if (!knownToolCalls.has(request.action.callId)) {
- ignoredToolCallIds.add(request.action.callId);
- }
- }
- break;
- }
- seenToolBatches.add(batchKey);
-
for (const request of requests) {
const toolCallId = request.action.callId;
@@ -1805,6 +1782,8 @@ async function* eveEventsToTUIStream(
};
}
+ if (seenInputRequestIds.has(request.requestId)) continue;
+ seenInputRequestIds.add(request.requestId);
pendingInputRequests.set(request.requestId, request);
if (isQuestionRequest(request)) {
@@ -1828,7 +1807,6 @@ async function* eveEventsToTUIStream(
break;
}
const callId = resultEvent.data.result.callId;
- if (ignoredToolCallIds.has(callId)) break;
if (!knownToolCalls.has(callId)) {
// Results for calls this turn never announced (e.g. subagent
// dispatches, which surface through the subagent section instead)
@@ -2080,62 +2058,6 @@ function isPostTurnVisibleEvent(event: HandleMessageStreamEvent): boolean {
}
}
-function toolBatchKey(
- type: string,
- turnId: string,
- stepIndex: number,
- actions: readonly { input: unknown; toolName: string }[],
-): string {
- return `${type}:${turnId}:${String(stepIndex)}:${stableStringify(
- actions.map((action) => ({
- input: action.input,
- toolName: action.toolName,
- })),
- )}`;
-}
-
-function inputRequestBatchKey(
- turnId: string,
- stepIndex: number,
- requests: readonly InputRequest[],
-): string {
- return toolBatchKey(
- "input.requested",
- turnId,
- stepIndex,
- requests.map((request) => ({
- input: request.action.input,
- toolName: request.action.toolName,
- })),
- );
-}
-
-function stableStringify(value: unknown): string {
- return JSON.stringify(toStableJson(value)) ?? "undefined";
-}
-
-function toStableJson(value: unknown, seen = new WeakSet<object>()): unknown {
- if (value === null || typeof value !== "object") {
- return value;
- }
-
- if (seen.has(value)) {
- return "[Circular]";
- }
- seen.add(value);
-
- if (Array.isArray(value)) {
- return value.map((item) => toStableJson(item, seen));
- }
-
- const object = value as Record<string, unknown>;
- const result: Record<string, unknown> = {};
- for (const key of Object.keys(object).sort()) {
- result[key] = toStableJson(object[key], seen);
- }
- return result;
-}
-
function formatActionResultError(event: ActionResultStreamEvent): string {
if (event.data.error?.message) return event.data.error.message;
const output = event.data.result.output;
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
index 4bfcf1668..a51fdd4fb 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts
@@ -179,6 +179,75 @@ describe("TerminalRenderer (inline scrollback)", () => {
expect(snapshot).toContain("It's 73°F in SF.");
});
+ it("renders interleaved tool lifecycles in arrival order", async () => {
+ const { screen, renderer } = makeRenderer();
+ await renderer.renderStream(
+ streamOf([
+ {
+ type: "tool-call",
+ toolCallId: "first",
+ toolName: "first_search",
+ input: { query: "first" },
+ },
+ { type: "tool-result", toolCallId: "first", output: { result: "first result" } },
+ {
+ type: "tool-call",
+ toolCallId: "second",
+ toolName: "second_search",
+ input: { query: "second" },
+ },
+ { type: "tool-result", toolCallId: "second", output: { result: "second result" } },
+ { type: "finish" },
+ ]),
+ { submittedPrompt: "run both searches", continueSession: false },
+ );
+
+ const snapshot = screen.snapshot();
+ expect(snapshot).toContain("✓ first_search");
+ expect(snapshot).toContain("first result");
+ expect(snapshot).toContain("✓ second_search");
+ expect(snapshot).toContain("second result");
+ expect(snapshot.indexOf("first_search")).toBeLessThan(snapshot.indexOf("second_search"));
+ renderer.shutdown();
+ });
+
+ it("renders a concurrent tool batch before any result arrives", async () => {
+ const { screen, renderer } = makeRenderer(120, 140);
+ let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
+ const rendering = renderer.renderStream(
+ {
+ events: new ReadableStream<AgentTUIStreamEvent>({
+ start(controller) {
+ streamController = controller;
+ },
+ }),
+ },
+ { submittedPrompt: "search the tri-state area", continueSession: true },
+ );
+
+ const controller = streamController;
+ expect(controller).toBeDefined();
+ controller?.enqueue({ type: "step-start" });
+ for (let index = 1; index <= 100; index += 1) {
+ controller?.enqueue({
+ type: "tool-call",
+ toolCallId: `search-${index}`,
+ toolName: "web_search",
+ input: { query: `tri-state-${index}` },
+ });
+ }
+
+ await screen.waitForText("tri-state-100");
+
+ const snapshot = screen.snapshot();
+ expect(snapshot.match(/web_search/g)).toHaveLength(100);
+ expect(snapshot).not.toContain("✓ web_search");
+
+ controller?.close();
+ await rendering;
+ renderer.shutdown();
+ });
+
it("omits the interrupt hint while waiting for the first stream event", async () => {
const { screen, renderer } = makeRenderer();
let streamController: ReadableStreamDefaultController<AgentTUIStreamEvent> | undefined;
diff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.ts
index 6bd22a3a8..b8f4c0233 100644
--- a/packages/eve/src/harness/emission.test.ts
+++ b/packages/eve/src/harness/emission.test.ts
@@ -1,4 +1,4 @@
-import type { TextStreamPart, ToolSet } from "ai";
+import { jsonSchema, type TextStreamPart, type ToolSet } from "ai";
import { describe, expect, it, vi } from "vitest";
import {
@@ -7,6 +7,7 @@ import {
type HarnessEmissionState,
setHarnessEmissionState,
} from "#harness/emission.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
import type { HarnessEmitFn, HarnessSession } from "#harness/types.js";
import { EMPTY_DELIVERY_SENTINEL } from "#shared/empty-delivery.js";
@@ -235,6 +236,198 @@ describe("emitStreamContent empty delivery", () => {
});
});
+describe("emitStreamContent action requests", () => {
+ it("completes pre-tool text before emitting a streamed action request", async () => {
+ const emit = createEmitStub();
+ const tools = new Map<string, HarnessToolDefinition>([
+ [
+ "delegate",
+ {
+ description: "Delegate work to a subagent.",
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "delegate",
+ runtimeAction: {
+ kind: "subagent-call",
+ nodeId: "subagents/researcher",
+ subagentName: "researcher",
+ },
+ },
+ ],
+ ]);
+
+ await emitStreamContent(
+ emit,
+ EMISSION_STATE,
+ streamOf([
+ { id: "message-1", text: "Checking the release notes.", type: "text-delta" },
+ {
+ input: { task: "research the release" },
+ toolCallId: "call-delegate",
+ toolName: "delegate",
+ type: "tool-call",
+ },
+ { finishReason: "tool-calls", type: "finish-step" },
+ ] as TextStreamPart<ToolSet>[]),
+ {
+ excludedActionToolNames: new Set(),
+ tools,
+ },
+ );
+
+ const events = vi.mocked(emit).mock.calls.map(([event]) => event);
+ expect(events.map((event) => event.type)).toEqual([
+ "message.appended",
+ "message.completed",
+ "actions.requested",
+ ]);
+ expect(events[1]).toMatchObject({
+ data: { finishReason: "tool-calls", message: "Checking the release notes." },
+ type: "message.completed",
+ });
+ });
+
+ it("projects local and provider tool results at the same stream position", async () => {
+ const tools = new Map<string, HarnessToolDefinition>([
+ [
+ "web_search",
+ {
+ description: "Search the web.",
+ execute: async () => ({ results: [] }),
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "web_search",
+ },
+ ],
+ ]);
+ const parts = (providerExecuted: boolean): TextStreamPart<ToolSet>[] => {
+ const providerExecution: { readonly providerExecuted?: true } = providerExecuted
+ ? { providerExecuted: true }
+ : {};
+ return [
+ { id: "text-1", text: "Searching now.", type: "text-delta" },
+ {
+ input: { query: "eve" },
+ ...providerExecution,
+ toolCallId: "call-1",
+ toolName: "web_search",
+ type: "tool-call",
+ },
+ {
+ output: { results: ["partial"] },
+ preliminary: true,
+ ...providerExecution,
+ toolCallId: "call-1",
+ toolName: "web_search",
+ type: "tool-result",
+ },
+ {
+ output: { results: ["eve"] },
+ ...providerExecution,
+ toolCallId: "call-1",
+ toolName: "web_search",
+ type: "tool-result",
+ },
+ { id: "text-2", text: "Done.", type: "text-delta" },
+ { finishReason: "stop", type: "finish-step" },
+ ] as TextStreamPart<ToolSet>[];
+ };
+ const localEmit = createEmitStub();
+ const providerEmit = createEmitStub();
+
+ await emitStreamContent(localEmit, EMISSION_STATE, streamOf(parts(false)), {
+ excludedActionToolNames: new Set(),
+ tools,
+ });
+ await emitStreamContent(providerEmit, EMISSION_STATE, streamOf(parts(true)), {
+ excludedActionToolNames: new Set(),
+ tools,
+ });
+
+ const localEvents = vi.mocked(localEmit).mock.calls.map(([event]) => event);
+ const providerEvents = vi.mocked(providerEmit).mock.calls.map(([event]) => event);
+
+ expect(localEvents).toEqual(providerEvents);
+ expect(localEvents.map((event) => event.type)).toEqual([
+ "message.appended",
+ "message.completed",
+ "actions.requested",
+ "action.result",
+ "message.appended",
+ "message.completed",
+ ]);
+ expect(localEvents[3]).toMatchObject({
+ data: { result: { output: { results: ["eve"] } } },
+ type: "action.result",
+ });
+ });
+
+ it("projects local and provider tool failures at the same stream position", async () => {
+ const tools = new Map<string, HarnessToolDefinition>([
+ [
+ "web_search",
+ {
+ description: "Search the web.",
+ execute: async () => ({ results: [] }),
+ inputSchema: jsonSchema({ type: "object" }),
+ name: "web_search",
+ },
+ ],
+ ]);
+ const parts = (providerExecuted: boolean): TextStreamPart<ToolSet>[] => {
+ const providerExecution: { readonly providerExecuted?: true } = providerExecuted
+ ? { providerExecuted: true }
+ : {};
+ return [
+ {
+ input: { query: "eve" },
+ ...providerExecution,
+ toolCallId: "call-1",
+ toolName: "web_search",
+ type: "tool-call",
+ },
+ {
+ error: new Error("Search failed"),
+ input: { query: "eve" },
+ ...providerExecution,
+ toolCallId: "call-1",
+ toolName: "web_search",
+ type: "tool-error",
+ },
+ { id: "text-1", text: "I could not find a result.", type: "text-delta" },
+ { finishReason: "stop", type: "finish-step" },
+ ] as TextStreamPart<ToolSet>[];
+ };
+ const localEmit = createEmitStub();
+ const providerEmit = createEmitStub();
+
+ await emitStreamContent(localEmit, EMISSION_STATE, streamOf(parts(false)), {
+ excludedActionToolNames: new Set(),
+ tools,
+ });
+ await emitStreamContent(providerEmit, EMISSION_STATE, streamOf(parts(true)), {
+ excludedActionToolNames: new Set(),
+ tools,
+ });
+
+ const localEvents = vi.mocked(localEmit).mock.calls.map(([event]) => event);
+ const providerEvents = vi.mocked(providerEmit).mock.calls.map(([event]) => event);
+
+ expect(localEvents).toEqual(providerEvents);
+ expect(localEvents.map((event) => event.type)).toEqual([
+ "actions.requested",
+ "action.result",
+ "message.appended",
+ "message.completed",
+ ]);
+ expect(localEvents[1]).toMatchObject({
+ data: {
+ result: { callId: "call-1", isError: true, output: "Search failed" },
+ status: "failed",
+ },
+ type: "action.result",
+ });
+ });
+});
+
describe("emitStreamContent error-part handling", () => {
it("preserves the original Error instance when the stream emits one", async () => {
const original = new TypeError("upstream rejected");
diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.ts
index 456190718..7ef0e1e75 100644
--- a/packages/eve/src/harness/emission.ts
+++ b/packages/eve/src/harness/emission.ts
@@ -38,12 +38,24 @@ import {
createRuntimeToolResultFromStepResult,
createRuntimeToolResultFromValue,
} from "#harness/action-result-helpers.js";
-import { resolveToolCallInputObject } from "#harness/runtime-actions.js";
-import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";
+import {
+ createRuntimeActionRequestFromToolCall,
+ resolveToolCallInputObject,
+} from "#harness/runtime-actions.js";
+import type {
+ RuntimeActionRequest,
+ RuntimeToolResultActionResult,
+} from "#runtime/actions/types.js";
import { isAuthorizationSignal, isPendingAuthorizationToolOutput } from "#harness/authorization.js";
import { contextStorage } from "#context/container.js";
import { readToolInterrupt } from "#harness/tool-interrupts.js";
-import type { HarnessEmitFn, HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";
+import type {
+ HarnessEmitFn,
+ HarnessSession,
+ HarnessToolMap,
+ SessionStateMap,
+ StepInput,
+} from "#harness/types.js";
// ---------------------------------------------------------------------------
// Emission state
@@ -311,54 +323,43 @@ export function normalizeAssistantStepFinishReason(
/**
* Result of consuming one step's `fullStream`.
*
- * `handledInlineToolResultCallIds` lists approval-resume tool-result
- * call ids the stream already handled inline — either emitted as
- * `action.result` events or routed to the authorization park path.
- * `emitStepActions` skips these to avoid double-emission.
- *
- * `inlineToolResultParts` holds the same tool-results in
- * `ToolResultPart` shape. The AI SDK omits them from
- * `stepResult.response.messages` on the approval-resume path, so the
- * harness splices them into persisted history to keep the prior turn's
- * `tool_use` block balanced with a matching `tool_result` on replay.
- *
- * `inlineAuthorizationResults` holds approval-resume tool-results whose
- * output is an {@link AuthorizationSignal}. These are surfaced into
- * `stepResult.toolResults` for the park detector instead of being emitted
- * as plain `action.result` events.
+ * Inline results avoid duplicate post-step events. Approval-resume results
+ * also repair persisted history or route authorization back to the park
+ * detector.
*/
interface EmittedStreamContent {
+ readonly emittedActionCallIds: ReadonlySet<string>;
readonly handledInlineToolResultCallIds: ReadonlySet<string>;
readonly inlineAuthorizationResults: readonly TypedToolResult<ToolSet>[];
readonly inlineToolResultParts: readonly InlineToolResultPart[];
}
+interface StreamActionEmissionOptions {
+ readonly excludedActionToolNames: ReadonlySet<string>;
+ readonly tools: HarnessToolMap;
+}
+
/**
* Consumes the AI SDK `fullStream` and emits real-time text and reasoning
* events.
*
- * `tool-result` parts that have no preceding `tool-call` in this stream
- * are emitted inline as `action.result` events. This is the
- * approval-resume path: when a previously-parked tool call is approved,
- * the AI SDK enqueues the executed tool-result onto the same step's
- * stream before the next LLM call. Emitting `action.result` inline keeps
- * it ahead of the message events that depend on it.
- *
- * Tool-call, tool-approval-request, and non-resumed tool-result events
- * are still emitted by `emitStepActions` from the `onStepFinish`
- * callback so the existing single-step batch ordering is preserved.
+ * Emits local and provider tool results in source order. A result without a
+ * streamed call resumes a call from an earlier step. `emitStepActions` emits
+ * the remaining events.
*/
export async function emitStreamContent(
emitFn: HarnessEmitFn,
state: HarnessEmissionState,
fullStream: AsyncIterable<TextStreamPart<ToolSet>>,
+ options?: StreamActionEmissionOptions,
): Promise<EmittedStreamContent> {
let currentReasoning = "";
let currentMessage = "";
let finishReason: AssistantStepFinishReason = "stop";
let streamError: Error | undefined;
const toolCallIdsSeenInStream = new Set<string>();
- const emittedProviderToolCallIds = new Set<string>();
+ const emittedActionCallIds = new Set<string>();
+ const emittedActionResultCallIds = new Set<string>();
const handledInlineToolResultCallIds = new Set<string>();
const inlineAuthorizationResults: TypedToolResult<ToolSet>[] = [];
const inlineToolResultParts: InlineToolResultPart[] = [];
@@ -379,17 +380,32 @@ export async function emitStreamContent(
currentMessage = "";
};
+ const emitActionRequest = async (action: RuntimeActionRequest): Promise<void> => {
+ if (emittedActionCallIds.has(action.callId)) {
+ return;
+ }
+
+ if (currentMessage.trim().length > 0) {
+ await flushCurrentMessage();
+ }
+
+ emittedActionCallIds.add(action.callId);
+ await emitFn(
+ createActionsRequestedEvent({
+ actions: [action],
+ sequence: state.sequence,
+ stepIndex: state.stepIndex,
+ turnId: state.turnId,
+ }),
+ );
+ };
+
const emitProviderToolCall = async (toolCall: {
readonly input?: unknown;
readonly toolCallId: string;
readonly toolName: string;
}): Promise<void> => {
- if (emittedProviderToolCallIds.has(toolCall.toolCallId)) {
- return;
- }
-
- emittedProviderToolCallIds.add(toolCall.toolCallId);
- const action = {
+ await emitActionRequest({
callId: toolCall.toolCallId,
input: resolveToolCallInputObject(toolCall.input, {
callId: toolCall.toolCallId,
@@ -397,10 +413,17 @@ export async function emitStreamContent(
}),
kind: "tool-call",
toolName: toolCall.toolName,
- } satisfies RuntimeToolCallActionRequest;
+ });
+ };
+
+ const emitActionResult = async (result: RuntimeToolResultActionResult): Promise<void> => {
+ if (emittedActionResultCallIds.has(result.callId)) {
+ return;
+ }
+ emittedActionResultCallIds.add(result.callId);
await emitFn(
- createActionsRequestedEvent({
- actions: [action],
+ createActionResultEvent({
+ result,
sequence: state.sequence,
stepIndex: state.stepIndex,
turnId: state.turnId,
@@ -408,6 +431,33 @@ export async function emitStreamContent(
);
};
+ const emitToolCall = async (toolCall: TypedToolCall<ToolSet>): Promise<void> => {
+ if (
+ options === undefined ||
+ toolCall.invalid === true ||
+ options.excludedActionToolNames.has(toolCall.toolName)
+ ) {
+ return;
+ }
+
+ try {
+ await emitActionRequest(
+ createRuntimeActionRequestFromToolCall({
+ toolCall,
+ tools: options.tools,
+ }),
+ );
+ } catch (error) {
+ // A malformed tool call can arrive before the SDK marks its final call
+ // invalid. Let the SDK's recovery path handle it instead of failing the
+ // whole step while projecting UI events.
+ if (error instanceof TypeError) {
+ return;
+ }
+ throw error;
+ }
+ };
+
for await (const part of fullStream) {
if (streamError !== undefined) {
continue;
@@ -455,59 +505,53 @@ export async function emitStreamContent(
toolCallIdsSeenInStream.add(toolCall.toolCallId);
if (toolCall.providerExecuted === true) {
await emitProviderToolCall(toolCall);
+ } else {
+ await emitToolCall(toolCall);
}
break;
}
case "tool-result": {
const inlineToolResult = part as TypedToolResult<ToolSet>;
+ // Preliminary chunks can be superseded by the terminal result.
+ if (inlineToolResult.preliminary === true) {
+ break;
+ }
if (inlineToolResult.providerExecuted === true) {
await emitProviderToolCall({
input: "input" in inlineToolResult ? inlineToolResult.input : undefined,
toolCallId: inlineToolResult.toolCallId,
toolName: inlineToolResult.toolName,
});
- await emitFn(
- createActionResultEvent({
- result: createRuntimeToolResultFromStepResult(inlineToolResult),
- sequence: state.sequence,
- stepIndex: state.stepIndex,
- turnId: state.turnId,
- }),
- );
- // Provider-executed results are already kept in the provider-owned
- // assistant response shape. Do not synthesize local `role: "tool"`
- // history for them; just surface the normal action result above.
+ await emitActionResult(createRuntimeToolResultFromStepResult(inlineToolResult));
+ // Provider results already live in the assistant response. Do not
+ // add a local tool message.
break;
}
- // Approval-resume: the AI SDK enqueues a previously-parked
- // tool's result onto the parent stream before re-entering the
- // LLM call. The tool-call itself was emitted on a prior step's
- // stream, so it is absent here. Surface `action.result`
- // inline so it precedes the message events that consume it.
if (toolCallIdsSeenInStream.has(part.toolCallId)) {
+ if (isInlineAuthorizationToolResult(inlineToolResult)) {
+ break;
+ }
+ if (emittedActionCallIds.has(part.toolCallId)) {
+ await emitActionResult(createRuntimeToolResultFromStepResult(inlineToolResult));
+ handledInlineToolResultCallIds.add(part.toolCallId);
+ }
break;
}
+
+ // An approved tool can resume with its result but no matching call in
+ // this step. Emit it before the message that consumes it.
await flushCurrentMessage();
if (isInlineAuthorizationToolResult(inlineToolResult)) {
- // Approval-resume auth: route to the park detector via
- // inlineAuthorizationResults instead of emitting a plain
- // action.result that the model would treat as a normal output.
+ // Keep authorization output for the park detector instead of
+ // emitting a normal tool result.
handledInlineToolResultCallIds.add(part.toolCallId);
inlineAuthorizationResults.push(inlineToolResult);
break;
}
- await emitFn(
- createActionResultEvent({
- result: createRuntimeToolResultFromStepResult(inlineToolResult),
- sequence: state.sequence,
- stepIndex: state.stepIndex,
- turnId: state.turnId,
- }),
- );
+ await emitActionResult(createRuntimeToolResultFromStepResult(inlineToolResult));
handledInlineToolResultCallIds.add(part.toolCallId);
- // Match AI SDK's `createToolModelOutput` shape (json for non-strings,
- // text for strings) so persisted history is shape-compatible.
+ // Preserve the SDK's text/json output shape in persisted history.
const rawOutput: unknown = inlineToolResult.output;
inlineToolResultParts.push({
type: "tool-result",
@@ -524,19 +568,24 @@ export async function emitStreamContent(
const toolError = part as TypedToolError<ToolSet>;
if (toolError.providerExecuted === true) {
await emitProviderToolCall(toolError);
- await emitFn(
- createActionResultEvent({
- result: createRuntimeToolResultFromValue({
- callId: toolError.toolCallId,
- isError: true,
- output: toError(toolError.error),
- toolName: toolError.toolName,
- }),
- sequence: state.sequence,
- stepIndex: state.stepIndex,
- turnId: state.turnId,
+ await emitActionResult(
+ createRuntimeToolResultFromValue({
+ callId: toolError.toolCallId,
+ isError: true,
+ output: toError(toolError.error),
+ toolName: toolError.toolName,
}),
);
+ } else if (emittedActionCallIds.has(toolError.toolCallId)) {
+ await emitActionResult(
+ createRuntimeToolResultFromValue({
+ callId: toolError.toolCallId,
+ isError: true,
+ output: toError(toolError.error),
+ toolName: toolError.toolName,
+ }),
+ );
+ handledInlineToolResultCallIds.add(toolError.toolCallId);
}
break;
}
@@ -596,7 +645,12 @@ export async function emitStreamContent(
);
}
- return { handledInlineToolResultCallIds, inlineAuthorizationResults, inlineToolResultParts };
+ return {
+ emittedActionCallIds,
+ handledInlineToolResultCallIds,
+ inlineAuthorizationResults,
+ inlineToolResultParts,
+ };
}
function isInlineAuthorizationToolResult(toolResult: TypedToolResult<ToolSet>): boolean {
diff --git a/packages/eve/src/harness/step-hooks.ts b/packages/eve/src/harness/step-hooks.ts
index ac36939c8..176d90053 100644
--- a/packages/eve/src/harness/step-hooks.ts
+++ b/packages/eve/src/harness/step-hooks.ts
@@ -190,15 +190,15 @@ export function buildStepHooks(input: StepHooksInput): StepHooks {
* arguments — the runtime event stream only sees successfully parsed
* tool calls.
*
- * `handledInlineToolResultCallIds` lists approval-resume tool-result
- * call ids the stream already handled inline (see `emitStreamContent`).
- * This skips them to avoid double-emission.
+ * `handledInlineToolResultCallIds` contains results emitted by
+ * `emitStreamContent` or sent to authorization. Skip them here.
*/
export async function emitStepActions(
emitFn: HarnessEmitFn,
state: HarnessEmissionState,
step: HarnessStepResult,
options: {
+ readonly emittedActionCallIds?: ReadonlySet<string>;
readonly excludedActionToolNames: ReadonlySet<string>;
readonly handledInlineToolResultCallIds?: ReadonlySet<string>;
readonly tools: ToolLoopHarnessConfig["tools"];
@@ -222,9 +222,14 @@ export async function emitStepActions(
const isExcluded = (toolCallId: string, toolName: string): boolean =>
excludedCallIds.has(toolCallId) || options.excludedActionToolNames.has(toolName);
- // actions.requested
+ // Streamed calls already emitted their request. The loop below emits their
+ // result.
const actions = (step.toolCalls as TypedToolCall<ToolSet>[])
- .filter((tc) => !isExcluded(tc.toolCallId, tc.toolName))
+ .filter(
+ (toolCall) =>
+ !isExcluded(toolCall.toolCallId, toolCall.toolName) &&
+ !options.emittedActionCallIds?.has(toolCall.toolCallId),
+ )
.map((toolCall) =>
createRuntimeActionRequestFromToolCall({
toolCall,
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index f4d13c237..28a114835 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -1957,9 +1957,19 @@ describe("createToolLoopHarness", () => {
expect(isHarnessBetweenTurns(result.session)).toBe(false);
});
- it("emits failed action.result from tool response messages when toolResults are missing", async () => {
+ it("emits failed action.result from tool response messages when the stream and toolResults omit it", async () => {
setupMockAgent({
finishReason: "tool-calls",
+ fullStreamParts: [
+ { id: "text-1", text: "Let me try that.", type: "text-delta" },
+ {
+ input: { city: "Vienna" },
+ toolCallId: "call-1",
+ toolName: "add",
+ type: "tool-call",
+ },
+ { finishReason: "tool-calls", type: "finish-step" },
+ ],
response: {
messages: [
{
@@ -2023,9 +2033,19 @@ describe("createToolLoopHarness", () => {
});
});
- it("does not duplicate action.result when toolResults and response messages both include it", async () => {
+ it("prefers toolResults over response messages when the stream omits the result", async () => {
setupMockAgent({
finishReason: "tool-calls",
+ fullStreamParts: [
+ { id: "text-1", text: "Let me try that.", type: "text-delta" },
+ {
+ input: { city: "Vienna" },
+ toolCallId: "call-1",
+ toolName: "add",
+ type: "tool-call",
+ },
+ { finishReason: "tool-calls", type: "finish-step" },
+ ],
response: {
messages: [
{
@@ -3232,6 +3252,7 @@ describe("createToolLoopHarness", () => {
"message.completed",
"actions.requested",
"action.result",
+ "message.completed",
"step.completed",
"turn.completed",
"session.waiting",
@@ -3240,9 +3261,16 @@ describe("createToolLoopHarness", () => {
expect(
events.filter((event) => event.type === "message.completed").map((event) => event.data),
).toEqual([
+ {
+ finishReason: "tool-calls",
+ message: "I'll search for that.",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn_0",
+ },
{
finishReason: "stop",
- message: "I'll search for that.The answer is 42.",
+ message: "The answer is 42.",
sequence: 0,
stepIndex: 0,
turnId: "turn_0",
@@ -3250,7 +3278,7 @@ describe("createToolLoopHarness", () => {
]);
});
- it("emits one stable parallel batch when streamed tool results interleave with later tool calls", async () => {
+ it("emits each streamed tool call before its later result", async () => {
setupMockAgent({
finishReason: "stop",
fullStreamParts: [
@@ -3385,31 +3413,19 @@ describe("createToolLoopHarness", () => {
"message.completed",
"actions.requested",
"action.result",
+ "actions.requested",
"action.result",
+ "message.completed",
"step.completed",
"turn.completed",
"session.waiting",
]);
- expect(events.find((event) => event.type === "actions.requested")?.data).toEqual({
- actions: [
- {
- callId: "call-1",
- input: { city: "New York" },
- kind: "tool-call",
- toolName: "get_weather",
- },
- {
- callId: "call-2",
- input: { city: "Los Angeles" },
- kind: "tool-call",
- toolName: "get_weather",
- },
- ],
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- });
+ expect(
+ events
+ .filter((event) => event.type === "actions.requested")
+ .map((event) => event.data.actions.map((action) => action.callId)),
+ ).toEqual([["call-1"], ["call-2"]]);
});
it("emits stream content before step actions", async () => {
@@ -4379,7 +4395,7 @@ describe("createToolLoopHarness", () => {
]);
});
- it("keeps the same parallel batch when tool calls arrive before results and preserves result arrival order", async () => {
+ it("emits parallel tool calls incrementally and preserves stream result order", async () => {
setupMockAgent({
finishReason: "stop",
fullStreamParts: [
@@ -4506,34 +4522,20 @@ describe("createToolLoopHarness", () => {
await runStep(session, { message: "Get the weather for two cities" });
- expect(events.find((event) => event.type === "actions.requested")?.data).toEqual({
- actions: [
- {
- callId: "call-1",
- input: { city: "New York" },
- kind: "tool-call",
- toolName: "get_weather",
- },
- {
- callId: "call-2",
- input: { city: "Los Angeles" },
- kind: "tool-call",
- toolName: "get_weather",
- },
- ],
- sequence: 0,
- stepIndex: 0,
- turnId: "turn_0",
- });
+ expect(
+ events
+ .filter((event) => event.type === "actions.requested")
+ .map((event) => event.data.actions.map((action) => action.callId)),
+ ).toEqual([["call-1"], ["call-2"]]);
expect(
events
.filter((event) => event.type === "action.result")
.map((event) => event.data.result.callId),
- ).toEqual(["call-1", "call-2"]);
+ ).toEqual(["call-2", "call-1"]);
});
- it("emits one stable action batch per assistant message when a turn contains multiple tool groups", async () => {
+ it("emits each tool call as it streams across multiple assistant groups", async () => {
setupMockAgent({
finishReason: "stop",
response: {
@@ -4650,7 +4652,10 @@ describe("createToolLoopHarness", () => {
"message.completed",
"actions.requested",
"action.result",
+ "message.completed",
+ "actions.requested",
"action.result",
+ "message.completed",
"step.completed",
"turn.completed",
"session.waiting",
@@ -4660,7 +4665,7 @@ describe("createToolLoopHarness", () => {
events
.filter((event) => event.type === "actions.requested")
.map((event) => event.data.actions.map((action) => action.callId)),
- ).toEqual([["call-1", "call-2"]]);
+ ).toEqual([["call-1"], ["call-2"]]);
});
it("emits input.requested for tool approval requests and parks without persisting unresolved messages", async () => {
@@ -4748,11 +4753,28 @@ describe("createToolLoopHarness", () => {
"message.received",
"step.started",
"message.completed",
+ "actions.requested",
"step.completed",
"input.requested",
"turn.completed",
"session.waiting",
]);
+ expect(events.find((event) => event.type === "actions.requested")).toEqual({
+ data: {
+ actions: [
+ {
+ callId: "call-1",
+ input: { command: "rm -rf /tmp/demo" },
+ kind: "tool-call",
+ toolName: "bash",
+ },
+ ],
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "turn_0",
+ },
+ type: "actions.requested",
+ });
expect(events.find((event) => event.type === "input.requested")).toEqual({
data: {
requests: [
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index a7db4a9bb..eb7e2114b 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -707,12 +707,17 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
const executeModelCall = async (): Promise<HarnessStepResult> => {
if (emit) {
+ const excludedActionToolNames = new Set([ASK_QUESTION_TOOL_NAME, FINAL_OUTPUT_TOOL_NAME]);
const streamResult = await agent.stream({ messages: callMessages });
const {
+ emittedActionCallIds,
handledInlineToolResultCallIds,
inlineAuthorizationResults,
inlineToolResultParts,
- } = await emitStreamContent(emit, emissionState, streamResult.fullStream);
+ } = await emitStreamContent(emit, emissionState, streamResult.fullStream, {
+ excludedActionToolNames,
+ tools: config.tools,
+ });
const stepResult = await hooks.stepResult;
if (
isEmptyModelResponse(stepResult) &&
@@ -722,7 +727,8 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {
throw new EmptyModelResponseError();
}
await emitStepActions(emit, emissionState, stepResult, {
- excludedActionToolNames: new Set([ASK_QUESTION_TOOL_NAME, FINAL_OUTPUT_TOOL_NAME]),
+ emittedActionCallIds,
+ excludedActionToolNames,
handledInlineToolResultCallIds,
tools: config.tools,
});
diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.ts
index f695a3279..85ffbe8a7 100644
--- a/packages/eve/src/protocol/message.ts
+++ b/packages/eve/src/protocol/message.ts
@@ -158,11 +158,12 @@ export interface MessageReceivedStreamEvent {
}
/**
- * Stream event emitted when the harness requests one stable runtime action
- * batch.
+ * Stream event emitted when the model requests one or more actions.
*
- * `data.actions.length === 1` is the serial case. `data.actions.length > 1`
- * is the parallel case for that assistant batch.
+ * A `tool-call` is one action kind, alongside `load-skill` and subagent calls.
+ * Calls may arrive incrementally before execution, so consumers must correlate
+ * action lifecycles by call ID rather than assume one event contains every call
+ * from an assistant step.
*/
export interface ActionsRequestedStreamEvent {
data: {
@@ -679,7 +680,8 @@ function summarizeUserContent(message: string | UserContent): string {
}
/**
- * Creates the `actions.requested` event for one stable execution batch.
+ * Creates the `actions.requested` event for one observed group of model action
+ * requests.
*/
export function createActionsRequestedEvent(input: {
readonly actions: readonly RuntimeActionRequest[];
diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.ts
index bc892ec4e..e50edad23 100644
--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts
+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts
@@ -324,6 +324,44 @@ describe("slackChannel() default event handlers", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
+ it("surfaces pre-tool assistant text when the following action is requested", async () => {
+ const adapter = withState(
+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
+ THREAD_STATE,
+ );
+ const ctx = buildAdapterContext(adapter, stubAccessor());
+
+ await callEvent(
+ adapter,
+ makeEvent("message.completed", {
+ finishReason: "tool-calls",
+ message: "\nChecking the issue context first.\nThen I will run a search.",
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ ctx,
+ );
+ await callEvent(
+ adapter,
+ makeEvent("actions.requested", {
+ actions: [{ callId: "call_1", input: {}, kind: "tool-call", toolName: "search" }],
+ sequence: 0,
+ stepIndex: 0,
+ turnId: "t1",
+ }),
+ ctx,
+ );
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(String(url)).toBe("https://slack.com/api/assistant.threads.setStatus");
+ expect(parseSlackRequestBody(init as RequestInit)).toMatchObject({
+ status: "Checking the issue context first.",
+ });
+ expect(ctx.state.pendingToolCallMessage).toBeNull();
+ });
+
it("message.completed clears typing without posting for empty delivery", async () => {
const adapter = withState(
getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),
diff --git a/packages/eve/src/runtime/actions/types.ts b/packages/eve/src/runtime/actions/types.ts
index c0ee6d004..8d30ac9dd 100644
--- a/packages/eve/src/runtime/actions/types.ts
+++ b/packages/eve/src/runtime/actions/types.ts
@@ -3,13 +3,15 @@ import { z } from "#compiled/zod/index.js";
import { jsonObjectSchema, jsonValueSchema } from "#shared/json-schemas.js";
/**
- * Runtime-owned authored tool-call request surfaced by a harness and executed
- * later by step-backed runtime code.
+ * Eve-owned `tool-call` action requested by the model.
+ *
+ * Depending on the tool definition, it can execute locally, be provider
+ * executed, or be handled later by the runtime.
*/
export type RuntimeToolCallActionRequest = z.infer<typeof runtimeToolCallActionRequestSchema>;
/**
- * Zod schema for one runtime-owned authored tool-call action request.
+ * Zod schema for one Eve-owned `tool-call` action request.
*/
export const runtimeToolCallActionRequestSchema = z
.object({
@@ -67,15 +69,12 @@ export const runtimeRemoteAgentCallActionRequestSchema = z
.strict();
/**
- * Runtime-owned action request surfaced by a harness.
- *
- * Harness-native capabilities such as `bash` do not cross the harness boundary
- * as runtime actions. Only runtime-executed requests use this taxonomy.
+ * Eve-owned `load-skill` action requested by the model.
*/
type RuntimeLoadSkillActionRequest = z.infer<typeof runtimeLoadSkillActionRequestSchema>;
/**
- * Zod schema for one runtime-owned load-skill action request.
+ * Zod schema for one Eve-owned `load-skill` action request.
*/
const runtimeLoadSkillActionRequestSchema = z
.object({
@@ -86,10 +85,10 @@ const runtimeLoadSkillActionRequestSchema = z
.strict();
/**
- * Runtime-owned action request surfaced by a harness.
+ * Eve-owned action request surfaced by the harness.
*
- * Harness-native capabilities such as `bash` do not cross the harness boundary
- * as runtime actions. Only runtime-executed requests use this taxonomy.
+ * A `tool-call` is one action kind, alongside control-plane work such as
+ * `load-skill` and runtime-dispatched subagent calls.
*/
export type RuntimeActionRequest =
| RuntimeLoadSkillActionRequest