The Open Framework for Building Agents
feat(eve): stream local tool generator results (#1679)
Casey Gowrief51f866cfa1e
diff --git a/.changeset/streamed-tool-results.md b/.changeset/streamed-tool-results.mdnew file mode 100644index 000000000..327d88302--- /dev/null+++ b/.changeset/streamed-tool-results.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Tools can now use async generators to stream preliminary output snapshots. eve publishes local snapshots as `action.partial` events before the final `action.result`, and the default client reducer exposes provisional output with `partial: true`.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex aa8dacac8..762b4fcb0 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -47,6 +47,7 @@ The stream is newline-delimited JSON (NDJSON), one event per line:| `message.received` | An inbound user message was accepted; carries flattened text plus structured text/file parts. || `step.started` | A model step began. || `actions.requested` | The model requested one or more actions, including tool calls; calls stream before execution. |+| `action.partial` | A locally executed tool generator yielded a preliminary output snapshot. || `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. |@@ -71,6 +72,8 @@ The stream is newline-delimited JSON (NDJSON), one event per line:`reasoning.appended` and `message.appended` stream incremental output as it arrives. When the durable stream writer is busy, eve may coalesce adjacent deltas of the same type; the text remains in source order, and any other event forms an ordering barrier. Each append carries both the new delta and the cumulative text for the current block. The finalized block shows up on `message.completed` and `reasoning.completed`, which is the compatibility path for clients that don't render incremental streaming.+`action.partial` carries one complete preliminary output snapshot from an authored async-generator tool. A later partial for the same `callId` replaces it, and `action.result` is the final snapshot. When the durable writer is busy, eve may keep only the newest adjacent partial for a call. Treat partials as last-write-wins: a durable step can retry and replay overlapping event runs. Provider-executed tool progress and MCP progress notifications are not projected as `action.partial` events.+Note: consider the privacy, confidentiality, and user-experience implications for displaying, storing, or transmitting reasoning events in your application.`message.completed` can fire more than once in a turn: the agent often emits interim assistant text before a tool call. To tell tool-call narration from a terminal reply, check `message.completed.data.finishReason`. `step.completed.data.finishReason` mirrors the step outcome, and usage lives on `step.completed`.diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex 4158e86af..915ec0432 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -99,6 +99,7 @@ The most common UI events are:| `reasoning.appended` | Render reasoning deltas when the model provides them. || `message.appended` | Render assistant text deltas. || `actions.requested` | Show tool calls as the model requests them, before execution. |+| `action.partial` | Update a generator tool's provisional output snapshot. || `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/docs/guides/hooks.md b/docs/guides/hooks.mdindex a54dbfb48..d99a54d18 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -26,7 +26,7 @@ The slug is the path-relative basename. `agent/hooks/audit.ts` becomes `"audit"``defineHook`, `HookDefinition`, and `HookContext` live on `eve/hooks`.-A hook file declares stream-event subscribers under the `events` map, keyed by event type, with `*` matching every event. Subscribe to any event in the runtime stream vocabulary documented in [Sessions, runs and streaming](../concepts/sessions-runs-and-streaming), including the lifecycle events `session.started`, `turn.completed`, `message.completed`, and `action.result`. Handlers are observe-only. They cannot inject model context. To contribute runtime model messages, use `defineDynamic` and `defineInstructions` in `agent/instructions/`.+A hook file declares stream-event subscribers under the `events` map, keyed by event type, with `*` matching every event. Subscribe to any event in the runtime stream vocabulary documented in [Sessions, runs and streaming](../concepts/sessions-runs-and-streaming), including the lifecycle events `session.started`, `turn.completed`, `message.completed`, `action.partial`, and `action.result`. Handlers are observe-only. They cannot inject model context. To contribute runtime model messages, use `defineDynamic` and `defineInstructions` in `agent/instructions/`.## Hook structure and contextdiff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex bfd8466f2..b1896c15b 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -28,10 +28,34 @@ A tool definition needs:- a filename slug under `agent/tools/`, the model-facing name.- a `description`: what the tool does, written for the model.- an `inputSchema`: a Zod schema (or any Standard Schema, or a plain JSON Schema object). Required. For no input, pass `z.object({})`. Zod and Standard Schema infer the `input` type in `execute`. Plain JSON Schema types it as `Record<string, unknown>`.-- an `execute(input, ctx)`: the implementation. May be sync or async.+- an `execute(input, ctx)`: the implementation. May be sync, async, or an async generator.When a tool returns structured data, add an optional `outputSchema`. With Zod or Standard Schema it also types the `execute` return.+### Stream preliminary tool results++An async generator lets a long-running tool stream complete output snapshots+before it finishes. Each `yield` replaces the previous snapshot; the final+yield is the normal tool result the model receives:++```ts title="agent/tools/build_report.ts"+export default defineTool({+ description: "Build a project report.",+ inputSchema: z.object({ project: z.string() }),+ async *execute({ project }) {+ yield { phase: "collecting", report: null };+ const report = await buildReport(project);+ yield { phase: "complete", report };+ },+});+```++eve publishes every earlier yield as an `action.partial` stream event. The+snapshot is visible to channels, hooks, and clients but never enters model+history or `toModelOutput`; only the final yield does. Treat snapshots as+last-write-wins by tool call id, not append-only progress. The durable runtime+can retry a step and replay overlapping snapshots.+### The `ctx` parameter`execute` gets a `ctx` carrying the runtime accessors:@@ -78,7 +102,7 @@ toModelOutput(output) {},```-`toModelOutput` receives the full, typed `execute` return and only affects the model. Channel event handlers and hooks still get the full output on `action.result`, so a channel can render rich platform output (Slack Block Kit, say) the model never sees. Return `{ type: "text", value }` for a summary, or `{ type: "json", value }` for a smaller object.+`toModelOutput` receives the final, typed `execute` return and only affects the model. Channel event handlers and hooks still get the full output on `action.result`, so a channel can render rich platform output (Slack Block Kit, say) the model never sees. Return `{ type: "text", value }` for a summary, or `{ type: "json", value }` for a smaller object.Tool outputs must be JSON-serializable. Return plain objects, arrays, strings, numbers, booleans, or `null`; convert values like `Date`, `Map`, `Set`, `NaN`, and cyclic objects before returning them from `execute` or from a `{ type: "json" }` `toModelOutput`.diff --git a/e2e/fixtures/agent-tools/agent/tools/streamed-action.ts b/e2e/fixtures/agent-tools/agent/tools/streamed-action.tsindex bdda3f476..ae563a880 100644--- a/e2e/fixtures/agent-tools/agent/tools/streamed-action.ts+++ b/e2e/fixtures/agent-tools/agent/tools/streamed-action.ts@@ -11,10 +11,17 @@ export default defineTool({inputSchema: z.object({label: z.string(),}),- async execute(input) {+ async *execute(input) {const executionStartedAt = Date.now();+ yield { executionStartedAt, label: input.label, phase: "waiting" as const };+await delay(500);- return { executionCompletedAt: Date.now(), executionStartedAt, label: input.label };+ yield {+ executionCompletedAt: Date.now(),+ executionStartedAt,+ label: input.label,+ phase: "complete" as const,+ };},});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.tsindex e1231924c..e5047ab65 100644--- a/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts+++ b/e2e/fixtures/agent-tools/evals/static-tools/streamed-action.eval.ts@@ -1,4 +1,8 @@-import type { ActionResultStreamEvent, MessageStreamEvent } from "eve/client";+import type {+ ActionPartialStreamEvent,+ ActionResultStreamEvent,+ MessageStreamEvent,+} from "eve/client";import { defineEval } from "eve/evals";const TOOL_NAME = "streamed-action";@@ -40,6 +44,41 @@ function streamedBeforeLocalExecutionCompletes(events: readonly MessageStreamEve);}+function streamsPreliminaryToolOutput(events: readonly MessageStreamEvent[]): 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,+ );+ });+ const [request] = matchingRequests;+ if (request === undefined || matchingRequests.length !== 1 || request.kind !== "tool-call") {+ return false;+ }++ const partialIndex = events.findIndex(+ (event): event is ActionPartialStreamEvent & MessageStreamEvent =>+ event.type === "action.partial" &&+ event.data.result.callId === request.callId &&+ event.data.result.toolName === TOOL_NAME,+ );+ const partial = events[partialIndex];+ const resultIndex = events.findIndex(+ (event) =>+ event.type === "action.result" &&+ event.data.result.kind === "tool-result" &&+ event.data.result.callId === request.callId,+ );+ return (+ partialIndex !== -1 &&+ partial !== undefined &&+ partial.type === "action.partial" &&+ hasPhase(partial.data.result.output, "waiting") &&+ partialIndex < resultIndex+ );+}+function parseTimestamp(value: string): number | undefined {const timestamp = Date.parse(value);return Number.isFinite(timestamp) ? timestamp : undefined;@@ -61,12 +100,23 @@ function readExecutionCompletedAt(output: unknown): number | undefined {: undefined;}+function hasPhase(output: unknown, phase: string): boolean {+ return (+ typeof output === "object" &&+ output !== null &&+ !Array.isArray(output) &&+ "phase" in output &&+ output.phase === phase+ );+}+// The AI SDK can begin local execution just before its tool-call stream part is// consumed. The tool waits before completing, so post-execution batch emission// still cannot satisfy this relation.export default defineEval({tags: ["real-model"],- description: "Static tools smoke: a local action request streams while execution is pending.",+ description:+ "Static tools smoke: a local generator streams preliminary output before its result.",async test(t) {const turn = await t.send(`Call the \`${TOOL_NAME}\` tool exactly once with label "${LABEL}". ` +@@ -83,5 +133,9 @@ export default defineEval({"local action request precedes execution completion",streamedBeforeLocalExecutionCompletes,);+ turn.eventsSatisfy(+ "local generator emits a preliminary tool-output snapshot",+ streamsPreliminaryToolOutput,+ );},});diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v6.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v6.tsnew file mode 100644index 000000000..02a61cf70--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v6.ts@@ -0,0 +1,10 @@+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";++export default defineDynamic({+ events: {+ "session.started": (_event, ctx) =>+ defineInstructions({+ markdown: `Use session ${ctx.session.id} when correlating evidence.`,+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v6.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v6.tsnew file mode 100644index 000000000..3c6e1498e--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v6.ts@@ -0,0 +1,11 @@+import { defineDynamic, defineSkill } from "#public/skills/index.js";++export default defineDynamic({+ events: {+ "turn.started": (_event, ctx) =>+ defineSkill({+ description: `Review evidence for session ${ctx.session.id}.`,+ markdown: "# Evidence review\n\nCheck every claim against its source.",+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v9.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v9.tsnew file mode 100644index 000000000..81c198d1a--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v9.ts@@ -0,0 +1,12 @@+import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "session.started": (_event, ctx) =>+ defineTool({+ description: "Return the active session identifier.",+ inputSchema: { type: "object", properties: {} },+ execute: () => ({ sessionId: ctx.session.id }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/hook/v7.ts b/packages/eve/extension-contracts/compatibility/hook/v7.tsnew file mode 100644index 000000000..38ecc7e06--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v7.ts@@ -0,0 +1,13 @@+import { defineHook } from "#public/hooks/index.js";++export default defineHook({+ events: {+ "subagent.completed"(event, ctx) {+ console.info("subagent completed", {+ output: event.data.output,+ sessionId: ctx.session.id,+ subagentName: event.data.subagentName,+ });+ },+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v6.ts b/packages/eve/extension-contracts/compatibility/tool/v6.tsnew file mode 100644index 000000000..4e6bdc067--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v6.ts@@ -0,0 +1,12 @@+import { defineTool } from "#public/tools/index.js";++export default defineTool({+ description: "Summarize a completed task.",+ inputSchema: { type: "object", properties: {} },+ async execute(_input, ctx) {+ return { callId: ctx.callId, summary: "Task completed." };+ },+ toModelOutput(output) {+ return { type: "text", value: output.summary };+ },+});diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v7.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v7.jsonnew file mode 100644index 000000000..90dcb2914--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v7.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicInstructions",+ "epoch": 7,+ "sha256": "21b997a3782ca550af622f02887bdad276145f4e5fb3988689117219bf0eb4c1",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v7.json b/packages/eve/extension-contracts/reports/dynamicSkill/v7.jsonnew file mode 100644index 000000000..83aad4fb7--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v7.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicSkill",+ "epoch": 7,+ "sha256": "21b997a3782ca550af622f02887bdad276145f4e5fb3988689117219bf0eb4c1",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v10.json b/packages/eve/extension-contracts/reports/dynamicTool/v10.jsonnew file mode 100644index 000000000..43360b41e--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v10.json@@ -0,0 +1,13 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 10,+ "sha256": "c9b16b2dd52b1f73c69ae7ab137fb1f0c15df403ff184fb6b3d2b808eecfc5aa",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v8.json b/packages/eve/extension-contracts/reports/hook/v8.jsonnew file mode 100644index 000000000..033a7ff87--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v8.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 8,+ "sha256": "0509469d75b0b882631932102f26d035dba7442c6ad91df838b28a4b80506954",+ "exports": ["defineHook"]+}diff --git a/packages/eve/extension-contracts/reports/tool/v7.json b/packages/eve/extension-contracts/reports/tool/v7.jsonnew file mode 100644index 000000000..8385b0358--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v7.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 7,+ "sha256": "79e9c26038a96722657db877ccfd8f6a8977dcd4e49d6153e00a636375e95c72",+ "exports": [+ "defineBashTool",+ "defineGlobTool",+ "defineGrepTool",+ "defineReadFileTool",+ "defineTool",+ "defineWriteFileTool",+ "disableTool",+ "experimental_workflow",+ "isDisabledToolSentinel",+ "isExperimentalWorkflowToolDefinition",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch"+ ]+}diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex eb36a2bfe..9b3fa995d 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -90,6 +90,7 @@ export type {// ---------------------------------------------------------------------------export type {+ ActionPartialStreamEvent,ActionResultStreamEvent,ActionsRequestedStreamEvent,AssistantStepFinishReason,diff --git a/packages/eve/src/client/message-reducer-types.ts b/packages/eve/src/client/message-reducer-types.tsindex 0a5f225a9..34d1be798 100644--- a/packages/eve/src/client/message-reducer-types.ts+++ b/packages/eve/src/client/message-reducer-types.ts@@ -125,6 +125,8 @@ export type EveAuthorizationPart = {* `"output-available"`, `"output-error"` (`errorText` set), or `"output-denied"`* (`approval.approved` is `false`). Which of `input`, `output`, `errorText`, and* `approval` are present depends on `state`, so narrow on `state` before reading them.+ * Preliminary generator output uses `"output-available"` with `partial: true`;+ * the terminal tool result clears that flag.* `toolName` and `toolMetadata.eve` ({@link EveMessageToolMetadata}) record call identity.*/export type EveDynamicToolPart = {@@ -182,6 +184,7 @@ export type EveDynamicToolPart = {readonly errorText?: never;readonly input: unknown;readonly output: unknown;+ readonly partial?: true;readonly state: "output-available";}| {diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.tsindex b6d258180..6d47aada8 100644--- a/packages/eve/src/client/message-reducer.test.ts+++ b/packages/eve/src/client/message-reducer.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import { defaultMessageReducer } from "#client/message-reducer.js";import { stampTestEvents } from "#internal/testing/events.js";import {+ createActionPartialEvent,createActionResultEvent,createActionsRequestedEvent,createAuthorizationCompletedEvent,@@ -31,6 +32,85 @@ function reduceServerEvents(}describe("defaultMessageReducer", () => {+ it("replaces tool-generator snapshots and ignores a late partial after the terminal result", () => {+ const reducer = defaultMessageReducer();+ let data = reduceServerEvents(reducer, reducer.initial(), [+ createActionsRequestedEvent({+ actions: [+ {+ callId: "call_1",+ input: { project: "eve" },+ kind: "tool-call",+ toolName: "build_report",+ },+ ],+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createActionPartialEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: { phase: "collecting" },+ toolName: "build_report",+ },+ sequence: 2,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createActionPartialEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: { phase: "writing" },+ toolName: "build_report",+ },+ sequence: 3,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ]);++ expect(findToolPart(data, "call_1")).toMatchObject({+ output: { phase: "writing" },+ partial: true,+ state: "output-available",+ });++ data = reduceServerEvents(reducer, data, [+ createActionResultEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: { phase: "complete" },+ toolName: "build_report",+ },+ sequence: 4,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ createActionPartialEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: { phase: "stale" },+ toolName: "build_report",+ },+ sequence: 5,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ]);++ const terminal = findToolPart(data, "call_1");+ expect(terminal).toMatchObject({+ output: { phase: "complete" },+ state: "output-available",+ });+ expect(terminal).not.toHaveProperty("partial");+ });+it("projects messages, reasoning, and actions into UIMessage-compatible parts", () => {const reducer = defaultMessageReducer();let data = reducer.initial();@@ -841,3 +921,12 @@ describe("defaultMessageReducer", () => {expect(userMessage?.parts).toEqual([{ state: "done", text: "hello there", type: "text" }]);});});++function findToolPart(+ data: ReturnType<ReturnType<typeof defaultMessageReducer>["initial"]>,+ toolCallId: string,+) {+ return data.messages+ .flatMap((message) => message.parts)+ .find((part) => part.type === "dynamic-tool" && part.toolCallId === toolCallId);+}diff --git a/packages/eve/src/client/message-reducer.ts b/packages/eve/src/client/message-reducer.tsindex a033a6085..abbd18971 100644--- a/packages/eve/src/client/message-reducer.ts+++ b/packages/eve/src/client/message-reducer.ts@@ -225,6 +225,35 @@ function reduceMessageData(data: EveMessageData, event: EveAgentReducerEvent): E);}+ case "action.partial": {+ const existing = findToolPart(data, event.data.result.callId);+ if (existing !== undefined && isSettledToolPart(existing)) {+ return data;+ }++ const descriptor = normalizeActionResult(event.data.result);+ const nextPart: EveDynamicToolPart = {+ approval: approvedApproval(existing),+ input: existing?.input,+ output: event.data.result.output,+ partial: true,+ state: "output-available",+ stepIndex: event.data.stepIndex,+ toolCallId: event.data.result.callId,+ toolMetadata: mergeToolMetadata(existing?.toolMetadata, createToolMetadata(descriptor)),+ toolName: existing?.toolName ?? descriptor.toolName,+ type: "dynamic-tool",+ };++ if (existing !== undefined) {+ return updateToolPart(data, event.data.result.callId, nextPart);+ }++ return updateAssistantMessage(data, event.data.turnId, (message) =>+ upsertPart(ensureStepStartPart(message, event.data.stepIndex), nextPart),+ );+ }+case "authorization.required":return updateAssistantMessage(data, event.data.turnId, (message) =>upsertPart(@@ -509,6 +538,14 @@ function findToolPart(data: EveMessageData, toolCallId: string): EveDynamicToolPreturn undefined;}+function isSettledToolPart(part: EveDynamicToolPart): boolean {+ return (+ part.state === "output-denied" ||+ part.state === "output-error" ||+ (part.state === "output-available" && part.partial !== true)+ );+}+function findLatestPendingAuthorizationPart(data: EveMessageData,name: string,diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 672273ebb..76ab3b337 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -21,14 +21,14 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },- tool: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },- dynamicTool: { current: 9, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9], dropped: {} },+ tool: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },+ dynamicTool: { current: 10, supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dropped: {} },connection: { current: 2, supported: [1, 2], dropped: {} },- hook: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },+ hook: { current: 8, supported: [1, 2, 3, 4, 5, 6, 7, 8], dropped: {} },skill: { current: 1, supported: [1], dropped: {} },- dynamicSkill: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },+ dynamicSkill: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },instructions: { current: 1, supported: [1], dropped: {} },- dynamicInstructions: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },+ dynamicInstructions: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },config: { current: 1, supported: [1], dropped: {} },state: { current: 2, supported: [1, 2], dropped: {} },} as const satisfies Record<string, ExtensionCapabilityContract>;diff --git a/packages/eve/src/execution/tool-auth.ts b/packages/eve/src/execution/tool-auth.tsindex d040ff465..c6b6640b1 100644--- a/packages/eve/src/execution/tool-auth.ts+++ b/packages/eve/src/execution/tool-auth.ts@@ -35,6 +35,7 @@ import {type ScopedAuthorization,} from "#runtime/connections/scoped-authorization.js";import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import { isAsyncIterable } from "#shared/async-iterable.js";/*** Wraps one authored tool's `execute` with a context that supports inline@@ -54,28 +55,50 @@ import type { ToolExecuteOptions } from "#shared/tool-definition.js";export function createToolExecuteWithAuth(input: {readonly scope: string;readonly execute: (toolInput: unknown, ctx: unknown) => unknown;-}): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown> {+}): (toolInput: unknown, options: ToolExecuteOptions) => Promise<unknown> | AsyncIterable<unknown> {const { scope, execute } = input;- return async (toolInput: unknown, options: ToolExecuteOptions): Promise<unknown> => {+ // An async wrapper would turn an async generator into Promise<AsyncIterable>,+ // which the AI SDK treats as one non-serializable terminal output.+ return (+ toolInput: unknown,+ options: ToolExecuteOptions,+ ): Promise<unknown> | AsyncIterable<unknown> => {const justAuthorizedScopes = new Set<string>();+ const ctx = buildToolContext({+ inlineAuthState: {},+ justAuthorizedScopes,+ options,+ scope,+ });try {- return await execute(- toolInput,- buildToolContext({- inlineAuthState: {},- justAuthorizedScopes,- options,- scope,- }),- );+ const output = execute(toolInput, ctx);+ if (isAsyncIterable(output)) {+ return handleToolIterableErrors(output);+ }+ return Promise.resolve(output).catch(handleToolError);} catch (err) {- if (isToolAuthorizationRequiredError(err)) {- return await handleAuthorizationRequests(err.requests);+ return handleToolError(err);+ }++ async function handleToolError(error: unknown): Promise<unknown> {+ if (isToolAuthorizationRequiredError(error)) {+ return await handleAuthorizationRequests(error.requests);}+ throw error;+ }- throw err;+ async function* handleToolIterableErrors(+ output: AsyncIterable<unknown>,+ ): AsyncIterable<unknown> {+ try {+ for await (const value of output) {+ yield value;+ }+ } catch (error) {+ yield await handleToolError(error);+ }}};}diff --git a/packages/eve/src/harness/emission-state.ts b/packages/eve/src/harness/emission-state.tsnew file mode 100644index 000000000..8bfc3be0d--- /dev/null+++ b/packages/eve/src/harness/emission-state.ts@@ -0,0 +1,54 @@+import type { HarnessSession, SessionStateMap } from "#harness/types.js";++/**+ * Tracks emission lifecycle state across harness step invocations.+ *+ * Persisted on `session.state` so the state survives when the durable+ * workflow runtime recreates the harness at each `"use step"` boundary.+ */+export interface HarnessEmissionState {+ readonly sessionStarted: boolean;+ readonly sequence: number;+ readonly stepIndex: number;+ readonly turnId: string;+}++const HARNESS_EMISSION_STATE_KEY = "eve.harness.emission";++const DEFAULT_EMISSION_STATE: HarnessEmissionState = {+ sessionStarted: false,+ sequence: 0,+ stepIndex: 0,+ turnId: "",+};++/** Reads the emission state, returning defaults when absent. */+export function getHarnessEmissionState(state: SessionStateMap | undefined): HarnessEmissionState {+ const emissionState = state?.[HARNESS_EMISSION_STATE_KEY] as HarnessEmissionState | undefined;+ return emissionState ?? DEFAULT_EMISSION_STATE;+}++/**+ * Returns `true` when the harness is between turns — either no turn has+ * started yet or the previous turn has emitted its epilogue and reset.+ *+ * The empty `turnId` sentinel distinguishes a fresh delivery from an in-flight+ * continuation. Callers should use this predicate instead of reading it.+ */+export function isHarnessBetweenTurns(session: HarnessSession): boolean {+ return getHarnessEmissionState(session.state).turnId === "";+}++/** Writes the emission state onto a new copy of the session. */+export function setHarnessEmissionState(+ session: HarnessSession,+ state: HarnessEmissionState,+): HarnessSession {+ return {+ ...session,+ state: {+ ...session.state,+ [HARNESS_EMISSION_STATE_KEY]: state,+ },+ };+}diff --git a/packages/eve/src/harness/emission.test.ts b/packages/eve/src/harness/emission.test.tsindex ba6917204..1cdb2fb59 100644--- a/packages/eve/src/harness/emission.test.ts+++ b/packages/eve/src/harness/emission.test.ts@@ -381,7 +381,7 @@ describe("emitStreamContent action requests", () => {});});- it("projects local and provider tool results at the same stream position", async () => {+ it("emits local preliminary results and drops provider preliminary results", async () => {const tools = new Map<string, HarnessToolDefinition>([["web_search",@@ -440,19 +440,31 @@ describe("emitStreamContent action requests", () => {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.partial","action.result","message.appended","message.completed",]);expect(localEvents[3]).toMatchObject({+ data: { result: { output: { results: ["partial"] } } },+ type: "action.partial",+ });+ expect(localEvents[4]).toMatchObject({data: { result: { output: { results: ["eve"] } } },type: "action.result",});+ expect(providerEvents.map((event) => event.type)).toEqual([+ "message.appended",+ "message.completed",+ "actions.requested",+ "action.result",+ "message.appended",+ "message.completed",+ ]);});it("projects local and provider tool failures at the same stream position", async () => {diff --git a/packages/eve/src/harness/emission.ts b/packages/eve/src/harness/emission.tsindex 4e0fe2634..2ea5e212a 100644--- a/packages/eve/src/harness/emission.ts+++ b/packages/eve/src/harness/emission.ts@@ -13,6 +13,7 @@ type InlineToolResultPart = Extract<ToolResponsePart, { type: "tool-result" }>;import type { AssistantStepFinishReason, RuntimeIdentity } from "#protocol/message.js";import {createActionsRequestedEvent,+ createActionPartialEvent,createActionResultEvent,createMessageAppendedEvent,createMessageCompletedEvent,@@ -52,80 +53,15 @@ import { normalizeModelStreamError } from "#harness/model-call-error.js";import { createOrderedStreamEmitter } from "#harness/ordered-stream-emitter.js";import { interruptStreamOnFailure } from "#harness/interruptible-stream.js";import { isInlineAuthorizationToolResult } from "#harness/inline-tool-authorization.js";-import type {- HarnessEmitFn,- HarnessSession,- HarnessToolMap,- SessionStateMap,- StepInput,-} from "#harness/types.js";--// ----------------------------------------------------------------------------// Emission state-// -----------------------------------------------------------------------------/**- * Tracks emission lifecycle state across harness step invocations.- *- * Persisted on `session.state` so the state survives when the durable- * workflow runtime recreates the harness at each `"use step"` boundary.- */-export interface HarnessEmissionState {- readonly sessionStarted: boolean;- readonly sequence: number;- readonly stepIndex: number;- readonly turnId: string;-}+import type { HarnessEmissionState } from "#harness/emission-state.js";+import type { HarnessEmitFn, HarnessToolMap, StepInput } from "#harness/types.js";-const HARNESS_EMISSION_STATE_KEY = "eve.harness.emission";--const DEFAULT_EMISSION_STATE: HarnessEmissionState = {- sessionStarted: false,- sequence: 0,- stepIndex: 0,- turnId: "",-};--/** Reads the emission state, returning defaults when absent. */-export function getHarnessEmissionState(state: SessionStateMap | undefined): HarnessEmissionState {- const emissionState = state?.[HARNESS_EMISSION_STATE_KEY] as HarnessEmissionState | undefined;- return emissionState ?? DEFAULT_EMISSION_STATE;-}--/**- * Returns `true` when the harness is **between turns** — either no turn- * has started yet (initial state) or the previous turn has emitted its- * epilogue (or recoverable failure cascade) and reset.- *- * Returns `false` while a turn is in progress, including during- * tool-loop continuations and runtime-action resumes within the same- * turn. Callers that gate per-turn work (eg. lifecycle hook dispatch)- * use this predicate to distinguish a fresh delivery from a- * continuation of an in-flight turn.- *- * Implemented over the empty-`turnId` sentinel that `emitTurnEpilogue`- * and `emitRecoverableFailedTurn` write — clients should never read- * `state.turnId` directly to make this distinction.- */-export function isHarnessBetweenTurns(session: HarnessSession): boolean {- return getHarnessEmissionState(session.state).turnId === "";-}--/**- * Writes the emission state onto a new copy of the session.- */-export function setHarnessEmissionState(- session: HarnessSession,- state: HarnessEmissionState,-): HarnessSession {- return {- ...session,- state: {- ...session.state,- [HARNESS_EMISSION_STATE_KEY]: state,- },- };-}+export {+ getHarnessEmissionState,+ isHarnessBetweenTurns,+ setHarnessEmissionState,+} from "#harness/emission-state.js";+export type { HarnessEmissionState } from "#harness/emission-state.js";// ---------------------------------------------------------------------------// Turn lifecycle helpers@@ -482,6 +418,17 @@ async function consumeStreamContent();};+ const emitActionPartial = async (result: RuntimeToolResultActionResult): Promise<void> => {+ await emitFn(+ createActionPartialEvent({+ result,+ sequence: state.sequence,+ stepIndex: state.stepIndex,+ turnId: state.turnId,+ }),+ );+ };+const emitToolCall = async (toolCall: TypedToolCall<ToolSet>): Promise<void> => {if (isInvalidToolCall(toolCall)) {invalidInputToolCallIds.add(toolCall.toolCallId);@@ -571,8 +518,10 @@ async function consumeStreamContent(}case "tool-result": {const inlineToolResult = part as TypedToolResult<ToolSet>;- // Preliminary chunks can be superseded by the terminal result.if (inlineToolResult.preliminary === true) {+ if (inlineToolResult.providerExecuted !== true) {+ await emitActionPartial(createRuntimeToolResultFromStepResult(inlineToolResult));+ }break;}if (inlineToolResult.providerExecuted === true) {diff --git a/packages/eve/src/harness/ordered-stream-emitter.test.ts b/packages/eve/src/harness/ordered-stream-emitter.test.tsindex 87cb6f947..0351417fe 100644--- a/packages/eve/src/harness/ordered-stream-emitter.test.ts+++ b/packages/eve/src/harness/ordered-stream-emitter.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it, vi } from "vitest";import { createOrderedStreamEmitter } from "#harness/ordered-stream-emitter.js";import {+ createActionPartialEvent,+ createActionResultEvent,createMessageAppendedEvent,createMessageCompletedEvent,createReasoningAppendedEvent,@@ -36,6 +38,15 @@ function reasoning(delta: string, soFar: string) {});}+function partial(callId: string, output: string) {+ return createActionPartialEvent({+ result: { callId, kind: "tool-result", output, toolName: "progress" },+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ });+}+describe("createOrderedStreamEmitter", () => {it("keeps consuming while a write is active and preserves the latest event payload", async () => {const firstWrite = deferred();@@ -92,6 +103,40 @@ describe("createOrderedStreamEmitter", () => {]);});+ it("keeps the newest adjacent partial for each call and preserves terminal barriers", async () => {+ const firstWrite = deferred();+ const events: UnstampedMessageStreamEvent[] = [];+ const emitFn = vi.fn(async (event: UnstampedMessageStreamEvent) => {+ events.push(event);+ if (events.length === 1) await firstWrite.promise;+ });+ const emitter = createOrderedStreamEmitter(emitFn);+ const result = createActionResultEvent({+ result: { callId: "call_1", kind: "tool-result", output: "done", toolName: "progress" },+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ });++ await emitter.emit(partial("call_1", "first"));+ await emitter.emit(partial("call_1", "second"));+ await emitter.emit(partial("call_2", "first"));+ await emitter.emit(partial("call_2", "second"));+ await emitter.emit(result);+ await emitter.emit(partial("call_1", "late"));++ firstWrite.resolve();+ await emitter.closeAndDrain();++ expect(events).toEqual([+ partial("call_1", "first"),+ partial("call_1", "second"),+ partial("call_2", "second"),+ result,+ partial("call_1", "late"),+ ]);+ });+it("surfaces sink failures from close and later emissions", async () => {const writeError = new Error("durable write failed");const emitter = createOrderedStreamEmitter(async () => {diff --git a/packages/eve/src/harness/ordered-stream-emitter.ts b/packages/eve/src/harness/ordered-stream-emitter.tsindex 10075178d..28d3635b9 100644--- a/packages/eve/src/harness/ordered-stream-emitter.ts+++ b/packages/eve/src/harness/ordered-stream-emitter.ts@@ -24,8 +24,9 @@ interface OrderedStreamEmitter {/*** Decouples model-stream consumption from the durable event sink while- * preserving FIFO dispatch. Adjacent append events waiting behind the active- * write are folded together; every other event remains an ordering barrier.+ * preserving FIFO dispatch. Adjacent append events and same-call tool partials+ * waiting behind the active write are folded together; every other event+ * remains an ordering barrier.* Coalescing before the durable writer keeps one Workflow chunk per emitted* event, so event-count reconnect cursors remain aligned with chunk indexes.*/@@ -133,7 +134,7 @@ export function createOrderedStreamEmitter(const lastIndex = pending.length - 1;const last = pending[lastIndex];const delta = appendDelta(event);- if (last === undefined || !mergeAdjacentAppends(last, event, messages)) {+ if (last === undefined || !mergeAdjacentEmissions(last, event, messages)) {pending.push({deltaCharacters: delta?.length ?? 0,event,@@ -161,7 +162,7 @@ export function createOrderedStreamEmitter(};}-function mergeAdjacentAppends(+function mergeAdjacentEmissions(left: PendingEmission,right: UnstampedMessageStreamEvent,messages: readonly import("ai").ModelMessage[] | undefined,@@ -184,6 +185,13 @@ function mergeAdjacentAppends(return true;}+ if (left.event.type === "action.partial" && right.type === "action.partial") {+ if (left.event.data.result.callId !== right.data.result.callId) return false;+ left.event = right;+ left.messages = messages;+ return true;+ }+return false;}diff --git a/packages/eve/src/harness/tool-interrupts.test.ts b/packages/eve/src/harness/tool-interrupts.test.tsindex a82f5b5cb..b608b3d85 100644--- a/packages/eve/src/harness/tool-interrupts.test.ts+++ b/packages/eve/src/harness/tool-interrupts.test.ts@@ -15,6 +15,7 @@ import {import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";import { readToolInterrupt, stashToolInterrupt } from "#harness/tool-interrupts.js";import { wrapToolExecute } from "#harness/tools.js";+import { ToolOutputSerializationError } from "#harness/tool-output-serialization.js";function signalWithVerifier(): AuthorizationSignal {return requestAuthorization([@@ -115,7 +116,87 @@ describe("wrapToolExecute", () => {expect(readToolInterrupt(ctx, "call_3")).toBeUndefined();});+ it("preserves generators and normalizes every yielded result", async () => {+ const wrapped = wrapToolExecute({+ ...baseDef,+ async *execute() {+ yield { phase: "starting" };+ yield { phase: "complete" };+ },+ })!;+ const ctx = new ContextContainer();++ const outputs = await contextStorage.run(ctx, async () => {+ const output = wrapped({}, { messages: [], toolCallId: "call_4" });+ if (!isAsyncIterable(output)) {+ throw new TypeError("Expected an async iterable.");+ }++ const values: unknown[] = [];+ for await (const value of output) values.push(value);+ return values;+ });++ expect(outputs).toEqual([{ phase: "starting" }, { phase: "complete" }]);+ });++ it("stashes authorization signals yielded from a generator", async () => {+ const signal = signalWithVerifier();+ const wrapped = wrapToolExecute({+ ...baseDef,+ async *execute() {+ yield signal;+ },+ })!;+ const ctx = new ContextContainer();++ const outputs = await contextStorage.run(ctx, async () => {+ const output = wrapped({}, { messages: [], toolCallId: "call_5" });+ if (!isAsyncIterable(output)) {+ throw new TypeError("Expected an async iterable.");+ }++ const values: unknown[] = [];+ for await (const value of output) values.push(value);+ return values;+ });++ expect(outputs).toEqual([modelFacingAuthorizationOutput(signal)]);+ expect(readToolInterrupt(ctx, "call_5")).toBe(signal);+ });++ it("applies execute serialization checks to every yielded result", async () => {+ const circular: { self?: unknown } = {};+ circular.self = circular;+ const wrapped = wrapToolExecute({+ ...baseDef,+ async *execute() {+ yield circular;+ },+ })!;+ const ctx = new ContextContainer();++ await expect(+ contextStorage.run(ctx, async () => {+ const output = wrapped({}, { messages: [], toolCallId: "call_6" });+ if (!isAsyncIterable(output)) {+ throw new TypeError("Expected an async iterable.");+ }+ for await (const _value of output) void _value;+ }),+ ).rejects.toBeInstanceOf(ToolOutputSerializationError);+ });+it("returns undefined for client-side tools (no execute)", () => {expect(wrapToolExecute(baseDef)).toBeUndefined();});});++function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {+ return (+ typeof value === "object" &&+ value !== null &&+ Symbol.asyncIterator in value &&+ typeof value[Symbol.asyncIterator] === "function"+ );+}diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.tsindex 7136187ad..145e7f652 100644--- a/packages/eve/src/harness/tools.test.ts+++ b/packages/eve/src/harness/tools.test.ts@@ -15,6 +15,7 @@ import {WEB_SEARCH_PARALLEL_OUTPUT_SCHEMA,} from "#runtime/framework-tools/web-search.js";import type { JsonObject } from "#shared/json.js";+import { isAsyncIterable } from "#shared/async-iterable.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { buildToolApproval, buildToolSet, buildToolSetWithProviderTools } from "#harness/tools.js";import type { HarnessToolMap } from "#harness/types.js";@@ -167,6 +168,54 @@ describe("buildToolSet", () => {expect(receivedSignal).toBe(abortController.signal);});+ it("preserves authored async generators for the AI SDK", async () => {+ const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([+ [+ "stream_progress",+ {+ description: "Stream progress.",+ execute: createToolExecuteWithAuth({+ async *execute() {+ yield { stage: "started" };+ yield { stage: "complete" };+ },+ scope: "stream_progress",+ }),+ inputSchema: jsonSchema({ type: "object" }),+ name: "stream_progress",+ },+ ],+ ]);+ const ctx = new ContextContainer();+ ctx.set(SessionKey, {+ auth: { current: null, initiator: null },+ sessionId: "session-1",+ turn: { id: "turn-1", sequence: 0 },+ });++ await contextStorage.run(ctx, async () => {+ const result = buildToolSet({ tools });+ const execute = (+ result.stream_progress as {+ readonly execute?: (+ input: unknown,+ options: ToolExecuteOptions,+ ) => Promise<unknown> | AsyncIterable<unknown>;+ }+ ).execute;+ expect(execute).toBeTypeOf("function");++ const output = execute!({}, { messages: [], toolCallId: "call_stream" });+ expect(isAsyncIterable(output)).toBe(true);++ const values: unknown[] = [];+ for await (const value of output as AsyncIterable<unknown>) {+ values.push(value);+ }+ expect(values).toEqual([{ stage: "started" }, { stage: "complete" }]);+ });+ });+it("supplies an inert abort signal when the SDK provides none", async () => {let receivedSignal: AbortSignal | undefined;const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex 27794dcae..4ed80c259 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -21,6 +21,7 @@ import {import { stashToolInterrupt } from "#harness/tool-interrupts.js";import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";import type { ToolExecuteOptions } from "#shared/tool-definition.js";+import { isAsyncIterable } from "#shared/async-iterable.js";type NativeApprovalStatus = Exclude<ApprovalStatus, boolean>;@@ -164,24 +165,55 @@ export function buildToolSetFromDefinitions(input: {*/export function wrapToolExecute(definition: HarnessToolDefinition,-): ((input: any, options: ToolExecuteOptions) => Promise<any>) | undefined {+): ((input: any, options: ToolExecuteOptions) => Promise<any> | AsyncIterable<any>) | undefined {const execute = definition.execute;if (execute === undefined) return undefined;- return async (input, options) => {- const output = await execute(input, options);- if (isAuthorizationSignal(output)) {- stashToolInterrupt(loadContext(), options.toolCallId, output);- return modelFacingAuthorizationOutput(output);++ return (input, options) => {+ let output: unknown;+ try {+ output = execute(input, options);+ } catch (error) {+ return Promise.reject(error);}- return normalizeToolJsonOutput({- boundary: "execute",- output,- toolCallId: options.toolCallId,- toolName: definition.name,- });++ if (isAsyncIterable(output)) {+ return normalizeToolExecuteIterable(output, definition.name, options);+ }++ return Promise.resolve(output).then((value) =>+ normalizeToolExecuteOutput(value, definition.name, options),+ );};}+async function* normalizeToolExecuteIterable(+ output: AsyncIterable<unknown>,+ toolName: string,+ options: ToolExecuteOptions,+): AsyncIterable<unknown> {+ for await (const value of output) {+ yield normalizeToolExecuteOutput(value, toolName, options);+ }+}++function normalizeToolExecuteOutput(+ output: unknown,+ toolName: string,+ options: ToolExecuteOptions,+): unknown {+ if (isAuthorizationSignal(output)) {+ stashToolInterrupt(loadContext(), options.toolCallId, output);+ return modelFacingAuthorizationOutput(output);+ }+ return normalizeToolJsonOutput({+ boundary: "execute",+ output,+ toolCallId: options.toolCallId,+ toolName,+ });+}+/*** Builds the AI SDK ToolSet for one harness step.*diff --git a/packages/eve/src/protocol/message.test.ts b/packages/eve/src/protocol/message.test.tsindex 3583ab171..3ccf07422 100644--- a/packages/eve/src/protocol/message.test.ts+++ b/packages/eve/src/protocol/message.test.ts@@ -5,6 +5,7 @@ import { encodeSandboxRef } from "#internal/attachments/sandbox-refs.js";import { serializeUrlFilePart } from "#internal/attachments/url-refs.js";import {EVE_MESSAGE_STREAM_VERSION,+ createActionPartialEvent,createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,@@ -22,7 +23,36 @@ import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";describe("message stream protocol", () => {it("pins the stream version for timed session events", () => {- expect(EVE_MESSAGE_STREAM_VERSION).toBe("20");+ expect(EVE_MESSAGE_STREAM_VERSION).toBe("21");+ });++ it("creates preliminary tool-result snapshots", () => {+ expect(+ createActionPartialEvent({+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: { phase: "collecting" },+ toolName: "build_report",+ },+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ ).toEqual({+ data: {+ result: {+ callId: "call_1",+ kind: "tool-result",+ output: { phase: "collecting" },+ toolName: "build_report",+ },+ sequence: 1,+ stepIndex: 0,+ turnId: "turn_1",+ },+ type: "action.partial",+ });});it("publishes the channel-local continuation token on session.waiting", () => {diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 3ac53b9b1..41de239cd 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -8,7 +8,11 @@ import {import { decodeSandboxRef, isSandboxRefUrl } from "#internal/attachments/sandbox-refs.js";import { createEventId } from "#protocol/event-id.js";import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";-import type { RuntimeActionRequest, RuntimeActionResult } from "#runtime/actions/types.js";+import type {+ RuntimeActionRequest,+ RuntimeActionResult,+ RuntimeToolResultActionResult,+} from "#runtime/actions/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";import { toChannelLocalContinuationToken } from "#shared/continuation-token.js";import type { JsonObject, JsonValue } from "#shared/json.js";@@ -19,7 +23,7 @@ export const EVE_STREAM_TAIL_INDEX_HEADER = "x-eve-stream-tail-index";export const EVE_STREAM_VERSION_HEADER = "x-eve-stream-version";export const EVE_MESSAGE_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";export const EVE_MESSAGE_STREAM_FORMAT = "ndjson";-export const EVE_MESSAGE_STREAM_VERSION = "20";+export const EVE_MESSAGE_STREAM_VERSION = "21";/*** eve-owned finish reason for one completed assistant step.@@ -254,6 +258,20 @@ export interface ActionResultStreamEvent {type: "action.result";}+/**+ * Stream event emitted for a preliminary snapshot from a locally executed+ * tool generator. The final snapshot is emitted as `action.result`.+ */+export interface ActionPartialStreamEvent {+ data: {+ result: RuntimeToolResultActionResult;+ sequence: number;+ stepIndex: number;+ turnId: string;+ };+ type: "action.partial";+}+/*** Stream event emitted when the parent workflow starts a child subagent session.*/@@ -631,6 +649,7 @@ export type UnstampedMessageStreamEvent =| SubagentStartedStreamEvent| ActionsRequestedStreamEvent| InputRequestedStreamEvent+ | ActionPartialStreamEvent| ActionResultStreamEvent| ReasoningCompletedStreamEvent| StepCompletedStreamEvent@@ -1082,6 +1101,24 @@ export function createActionResultEvent(input: {};}+/** Creates an `action.partial` event for one preliminary tool-result snapshot. */+export function createActionPartialEvent(input: {+ readonly result: RuntimeToolResultActionResult;+ readonly sequence: number;+ readonly stepIndex: number;+ readonly turnId: string;+}): ActionPartialStreamEvent {+ return {+ data: {+ result: input.result,+ sequence: input.sequence,+ stepIndex: input.stepIndex,+ turnId: input.turnId,+ },+ type: "action.partial",+ };+}+/*** Creates the `subagent.called` event for one started child workflow session.*/diff --git a/packages/eve/src/public/channels/discord/discordChannel.ts b/packages/eve/src/public/channels/discord/discordChannel.tsindex 6a110c916..efeff4d6c 100644--- a/packages/eve/src/public/channels/discord/discordChannel.ts+++ b/packages/eve/src/public/channels/discord/discordChannel.ts@@ -129,6 +129,7 @@ type DiscordSessionFailedHandler = (export interface DiscordChannelEvents {readonly "turn.started"?: DiscordEventHandler<"turn.started">;readonly "actions.requested"?: DiscordEventHandler<"actions.requested">;+ readonly "action.partial"?: DiscordEventHandler<"action.partial">;readonly "action.result"?: DiscordEventHandler<"action.result">;readonly "message.completed"?: DiscordEventHandler<"message.completed">;readonly "message.appended"?: DiscordEventHandler<"message.appended">;diff --git a/packages/eve/src/public/channels/github/githubChannel.ts b/packages/eve/src/public/channels/github/githubChannel.tsindex e2d91fed7..48abb061f 100644--- a/packages/eve/src/public/channels/github/githubChannel.ts+++ b/packages/eve/src/public/channels/github/githubChannel.ts@@ -132,6 +132,7 @@ type GitHubSessionFailedHandler = (* that key rather than running alongside it.*/export interface GitHubChannelEvents {+ readonly "action.partial"?: GitHubEventHandler<"action.partial">;readonly "action.result"?: GitHubEventHandler<"action.result">;readonly "actions.requested"?: GitHubEventHandler<"actions.requested">;readonly "authorization.completed"?: GitHubEventHandler<"authorization.completed">;diff --git a/packages/eve/src/public/channels/linear/linearChannel.ts b/packages/eve/src/public/channels/linear/linearChannel.tsindex 81dcf31dd..d6c020f2b 100644--- a/packages/eve/src/public/channels/linear/linearChannel.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.ts@@ -139,6 +139,7 @@ type LinearSessionFailedHandler = (export interface LinearChannelEvents {readonly "turn.started"?: LinearEventHandler<"turn.started">;readonly "actions.requested"?: LinearEventHandler<"actions.requested">;+ readonly "action.partial"?: LinearEventHandler<"action.partial">;readonly "action.result"?: LinearEventHandler<"action.result">;readonly "message.completed"?: LinearEventHandler<"message.completed">;readonly "message.appended"?: LinearEventHandler<"message.appended">;diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex e64566e71..dbfa0c5ab 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -450,6 +450,7 @@ export type SlackInboundResultOrPromise = SlackMentionResultOrPromise;export interface SlackChannelEvents {readonly "turn.started"?: SlackEventHandler<"turn.started">;readonly "actions.requested"?: SlackEventHandler<"actions.requested">;+ readonly "action.partial"?: SlackEventHandler<"action.partial">;readonly "action.result"?: SlackEventHandler<"action.result">;readonly "message.completed"?: SlackEventHandler<"message.completed">;readonly "message.appended"?: SlackEventHandler<"message.appended">;diff --git a/packages/eve/src/public/channels/teams/teamsChannel.ts b/packages/eve/src/public/channels/teams/teamsChannel.tsindex c79367ba2..6cf09d8a7 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.ts@@ -165,6 +165,7 @@ type TeamsSessionFailedHandler = (export interface TeamsChannelEvents {readonly "turn.started"?: TeamsEventHandler<"turn.started">;readonly "actions.requested"?: TeamsEventHandler<"actions.requested">;+ readonly "action.partial"?: TeamsEventHandler<"action.partial">;readonly "action.result"?: TeamsEventHandler<"action.result">;readonly "message.completed"?: TeamsEventHandler<"message.completed">;readonly "message.appended"?: TeamsEventHandler<"message.appended">;diff --git a/packages/eve/src/public/channels/telegram/telegramChannel.ts b/packages/eve/src/public/channels/telegram/telegramChannel.tsindex 9e6ab0976..90c169b46 100644--- a/packages/eve/src/public/channels/telegram/telegramChannel.ts+++ b/packages/eve/src/public/channels/telegram/telegramChannel.ts@@ -128,6 +128,7 @@ type TelegramSessionFailedHandler = (export interface TelegramChannelEvents {readonly "turn.started"?: TelegramEventHandler<"turn.started">;readonly "actions.requested"?: TelegramEventHandler<"actions.requested">;+ readonly "action.partial"?: TelegramEventHandler<"action.partial">;readonly "action.result"?: TelegramEventHandler<"action.result">;readonly "message.completed"?: TelegramEventHandler<"message.completed">;readonly "message.appended"?: TelegramEventHandler<"message.appended">;diff --git a/packages/eve/src/public/channels/twilio/twilioChannel.ts b/packages/eve/src/public/channels/twilio/twilioChannel.tsindex dac1dedbc..cf8f89dfd 100644--- a/packages/eve/src/public/channels/twilio/twilioChannel.ts+++ b/packages/eve/src/public/channels/twilio/twilioChannel.ts@@ -160,6 +160,7 @@ type TwilioSessionFailedHandler = (export interface TwilioChannelEvents {readonly "turn.started"?: TwilioEventHandler<"turn.started">;readonly "actions.requested"?: TwilioEventHandler<"actions.requested">;+ readonly "action.partial"?: TwilioEventHandler<"action.partial">;readonly "action.result"?: TwilioEventHandler<"action.result">;readonly "message.completed"?: TwilioEventHandler<"message.completed">;readonly "message.appended"?: TwilioEventHandler<"message.appended">;diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex c97edab3b..bc4c23d91 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -251,6 +251,7 @@ export interface ChannelEvents<TCtx = void> {readonly "compaction.completed"?: ChannelEventHandler<"compaction.completed", TCtx>;readonly "turn.started"?: ChannelEventHandler<"turn.started", TCtx>;readonly "actions.requested"?: ChannelEventHandler<"actions.requested", TCtx>;+ readonly "action.partial"?: ChannelEventHandler<"action.partial", TCtx>;readonly "action.result"?: ChannelEventHandler<"action.result", TCtx>;readonly "message.completed"?: ChannelEventHandler<"message.completed", TCtx>;readonly "message.appended"?: ChannelEventHandler<"message.appended", TCtx>;@@ -357,6 +358,7 @@ const channelEventTypes: Record<keyof ChannelEvents, null> = {"compaction.completed": null,"turn.started": null,"actions.requested": null,+ "action.partial": null,"action.result": null,"message.completed": null,"message.appended": null,diff --git a/packages/eve/src/public/definitions/exact.test.ts b/packages/eve/src/public/definitions/exact.test.tsindex 6d70b8185..a7c78bf5c 100644--- a/packages/eve/src/public/definitions/exact.test.ts+++ b/packages/eve/src/public/definitions/exact.test.ts@@ -17,7 +17,11 @@ import { defineInstrumentation } from "#public/definitions/instrumentation.js";import { defineSandbox } from "#public/definitions/sandbox.js";import { defineSchedule } from "#public/definitions/schedule.js";import { defineSkill } from "#public/definitions/skill.js";-import { defineTool, experimental_workflow } from "#public/definitions/tool.js";+import {+ defineTool,+ experimental_workflow,+ type ToolDefinition,+} from "#public/definitions/tool.js";describe("definition helper exact inputs", () => {it("preserves literal inference for valid definitions", () => {@@ -44,6 +48,21 @@ describe("definition helper exact inputs", () => {expect(schedule.cron).toBe("0 9 * * *");});+ it("accepts async-generator tool executors", () => {+ const streamedTool = defineTool({+ description: "Stream report progress.",+ inputSchema: { type: "object" },+ async *execute() {+ yield { phase: "collecting" };+ yield { phase: "complete" };+ },+ });++ expectTypeOf(streamedTool).toMatchTypeOf<+ ToolDefinition<Record<string, unknown>, { phase: string }>+ >();+ });+it("keeps the public hook event map aligned with runtime stream events", () => {expectTypeOf<keyof HookEventMap>().toEqualTypeOf<UnstampedMessageStreamEvent["type"]>();});diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.tsindex 3dfef0cf1..525a92756 100644--- a/packages/eve/src/public/definitions/hook.ts+++ b/packages/eve/src/public/definitions/hook.ts@@ -16,6 +16,7 @@ type ProtocolEvent<TType extends MessageStreamEvent["type"]> = Extract<* until eve exposes them here.*/export interface HookEventMap {+ readonly "action.partial": ProtocolEvent<"action.partial">;readonly "action.result": ProtocolEvent<"action.result">;readonly "actions.requested": ProtocolEvent<"actions.requested">;readonly "authorization.completed": ProtocolEvent<"authorization.completed">;diff --git a/packages/eve/src/public/definitions/tool.ts b/packages/eve/src/public/definitions/tool.tsindex fd43d69d0..16c08e78b 100644--- a/packages/eve/src/public/definitions/tool.ts+++ b/packages/eve/src/public/definitions/tool.ts@@ -118,7 +118,7 @@ export interface ToolDefinition<TInput = unknown, TOutput = unknown> extends PubTInput,TOutput> {- execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput;+ execute(input: TInput, ctx: ToolContext): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;/*** Optional per-tool approval gate. The return value determines whether* user approval is required before executing this tool.@@ -161,7 +161,8 @@ export function defineTool<ctx: ToolContext,):| Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>>- | StandardJSONSchemaV1.InferOutput<TOutputSchema>;+ | StandardJSONSchemaV1.InferOutput<TOutputSchema>+ | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>;approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TInputSchema>, unknown>["approval"];toModelOutput?: ToolDefinition<unknown,@@ -181,7 +182,7 @@ export function defineTool<execute(input: StandardJSONSchemaV1.InferOutput<TSchema>,ctx: ToolContext,- ): Promise<TOutput> | TOutput;+ ): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;approval?: ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, unknown>["approval"];toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];}): ToolDefinition<StandardJSONSchemaV1.InferOutput<TSchema>, TOutput>;@@ -196,7 +197,8 @@ export function defineTool<ctx: ToolContext,):| Promise<StandardJSONSchemaV1.InferOutput<TOutputSchema>>- | StandardJSONSchemaV1.InferOutput<TOutputSchema>;+ | StandardJSONSchemaV1.InferOutput<TOutputSchema>+ | AsyncIterable<StandardJSONSchemaV1.InferOutput<TOutputSchema>>;approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];toModelOutput?: ToolDefinition<unknown,@@ -207,7 +209,10 @@ export function defineTool<TOutput>(definition: {description: ToolDefinition<unknown, unknown>["description"];inputSchema: JsonObject;outputSchema?: JsonObject;- execute(input: Record<string, unknown>, ctx: ToolContext): Promise<TOutput> | TOutput;+ execute(+ input: Record<string, unknown>,+ ctx: ToolContext,+ ): Promise<TOutput> | TOutput | AsyncIterable<TOutput>;approval?: ToolDefinition<Record<string, unknown>, unknown>["approval"];toModelOutput?: ToolDefinition<unknown, TOutput>["toModelOutput"];}): ToolDefinition<Record<string, unknown>, TOutput>;diff --git a/packages/eve/src/shared/async-iterable.ts b/packages/eve/src/shared/async-iterable.tsnew file mode 100644index 000000000..758c1c9b2--- /dev/null+++ b/packages/eve/src/shared/async-iterable.ts@@ -0,0 +1,9 @@+/** Returns whether a value can produce values asynchronously. */+export function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T> {+ return (+ typeof value === "object" &&+ value !== null &&+ Symbol.asyncIterator in value &&+ typeof value[Symbol.asyncIterator] === "function"+ );+}diff --git a/packages/eve/src/shared/tool-definition.ts b/packages/eve/src/shared/tool-definition.tsindex 239a905af..6b65755b0 100644--- a/packages/eve/src/shared/tool-definition.ts+++ b/packages/eve/src/shared/tool-definition.ts@@ -11,7 +11,7 @@ export type ToolExecuteOptions = Omit<ToolExecutionOptions<unknown>, "context">;export type ToolExecuteFn<TInput = unknown, TOutput = unknown> = (input: TInput,options: ToolExecuteOptions,-) => Promise<TOutput> | TOutput;+) => Promise<TOutput> | TOutput | AsyncIterable<TOutput>;interface ToolDefinitionBase {readonly description: string;