The Open Framework for Building Agents
fix(eve): make repeated MCP input updates idempotent (#2990)
Colton Paddene82b8896d91d
diff --git a/.changeset/mcp-idempotent-input-updates.md b/.changeset/mcp-idempotent-input-updates.mdnew file mode 100644index 000000000..a6835b8d0--- /dev/null+++ b/.changeset/mcp-idempotent-input-updates.md@@ -0,0 +1,5 @@+---+"eve": patch+---++MCP `agent_update` now acknowledges a repeated answer that eve already accepted for the same input batch instead of returning a conflict, so a client that retries after a lost response converges on the current invocation state. `agent_get` also stops reporting `input_required` as soon as the answer is resolved rather than waiting for the next turn event.diff --git a/packages/eve/src/internal/invocation/workflow-execution.test.ts b/packages/eve/src/internal/invocation/workflow-execution.test.tsindex 1fdf6c812..dadd8cf31 100644--- a/packages/eve/src/internal/invocation/workflow-execution.test.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.test.ts@@ -306,6 +306,80 @@ describe("WorkflowAgentInvocationExecution", () => {expect(deliver).toHaveBeenCalledTimes(2);});+ it("stops reporting input_required once the answer is resolved", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ getReadable.mockReturnValue(+ eventStream([+ inputRequestedEvent("event_1", ["question"]),+ inputResolvedEvent("event_2", [{ optionId: "yes", requestId: "question" }]),+ ]),+ );++ await expect(+ execution().read({ auth, invocationId: "wrun_invocation" }),+ ).resolves.toMatchObject({ status: "working" });+ });++ it("acknowledges a repeated answer that eve already accepted", async () => {+ runsGet.mockResolvedValue(run({ status: "running" }));+ const requestId = invocationInputRequestId("event_1", "question");+ getReadable.mockImplementation(() =>+ eventStream([+ inputRequestedEvent("event_1", ["question"]),+ inputResolvedEvent("event_2", [{ optionId: "yes", requestId: "question" }]),+ ]),+ );++ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ optionId: "yes", requestId }],+ }),+ ).resolves.toMatchObject({ invocation: { status: "working" }, type: "success" });+ expect(deliver).not.toHaveBeenCalled();++ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ optionId: "no", requestId }],+ }),+ ).resolves.toEqual({ message: "Invocation is not waiting for input.", type: "conflict" });+ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ requestId, text: "yes" }],+ }),+ ).resolves.toMatchObject({ type: "conflict" });+ expect(deliver).not.toHaveBeenCalled();+ });++ it("acknowledges a repeated answer after the run completes", async () => {+ runsGet.mockResolvedValue(run({ status: "completed" }));+ returnValue.mockResolvedValue({ output: "done" });+ const requestId = invocationInputRequestId("event_1", "question");+ getReadable.mockImplementation(() =>+ eventStream([+ inputRequestedEvent("event_1", ["question"]),+ inputResolvedEvent("event_2", [{ requestId: "question", text: "go" }]),+ ]),+ );++ await expect(+ execution().update({+ auth,+ invocationId: "wrun_invocation",+ responses: [{ requestId, text: "go" }],+ }),+ ).resolves.toMatchObject({+ invocation: { result: "done", status: "completed" },+ type: "success",+ });+ expect(deliver).not.toHaveBeenCalled();+ });+it("projects and clears pending connection authorization", async () => {runsGet.mockResolvedValue(run({ status: "running" }));const required = {@@ -608,6 +682,27 @@ function inputRequestedEvent(id: string, requestIds: readonly string[]): HandleM};}+function inputResolvedEvent(+ id: string,+ responses: readonly { optionId?: string; requestId: string; text?: string }[],+): HandleMessageStreamEvent {+ return {+ data: {+ resolutions: responses.map((response) => ({+ kind: "question" as const,+ outcome: "answered" as const,+ requestId: response.requestId,+ response,+ })),+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ },+ meta: { at: "2026-07-20T00:00:01.000Z", id },+ type: "input.resolved",+ };+}+function eventStream(events: readonly unknown[],options: { readonly trailingNewline?: boolean } = {},diff --git a/packages/eve/src/internal/invocation/workflow-execution.ts b/packages/eve/src/internal/invocation/workflow-execution.tsindex 336bad830..2aa28c6bb 100644--- a/packages/eve/src/internal/invocation/workflow-execution.ts+++ b/packages/eve/src/internal/invocation/workflow-execution.ts@@ -22,7 +22,7 @@ import {} from "#internal/invocation/metadata.js";import type { RouteSessionCreator } from "#internal/nitro/routes/channel-route-context.js";import { getRun, getWorld } from "#internal/workflow/runtime.js";-import type { HandleMessageStreamEvent } from "#protocol/message.js";+import type { HandleMessageStreamEvent, InputResolution } from "#protocol/message.js";import type { InputRequest, InputResponse } from "#shared/input.js";import type { JsonObject, JsonValue } from "#shared/json.js";import { parseJsonValue } from "#shared/json.js";@@ -94,6 +94,12 @@ export class WorkflowAgentInvocationExecution {const current = await this.read(input);if (current === undefined) return { type: "not_found" };if (current.status !== "input_required") {+ // A retry after a lost response is the common case here: the answer+ // already landed, so acknowledge it instead of demanding a new one.+ const events = await readRecentPersistedEvents(input.invocationId);+ if (replaysResolvedBatch(events, input.responses)) {+ return { invocation: current, type: "success" };+ }return conflict("Invocation is not waiting for input.");}const run = await this.#readInvocationRun(input.invocationId, input.auth);@@ -218,15 +224,90 @@ function pendingInputBatch(return { id: event.meta.id, rawRequestIds, requests };}+/**+ * Removes resolved requests from a batch. The harness resolves a batch as a+ * whole today, but request-level bookkeeping keeps this correct if it ever+ * resolves them separately.+ */+function withoutResolved(+ batch: PendingInputBatch,+ resolutions: readonly InputResolution[],+): PendingInputBatch | undefined {+ const resolvedRawIds = new Set(resolutions.map((resolution) => resolution.requestId));+ const rawRequestIds: Record<string, string> = {};+ const requests: Record<string, InputRequest> = {};+ for (const [requestId, rawRequestId] of Object.entries(batch.rawRequestIds)) {+ if (resolvedRawIds.has(rawRequestId)) continue;+ rawRequestIds[requestId] = rawRequestId;+ const request = batch.requests[requestId];+ if (request !== undefined) requests[requestId] = request;+ }+ return Object.keys(rawRequestIds).length === 0+ ? undefined+ : { id: batch.id, rawRequestIds, requests };+}++interface ResolvedInputBatch {+ readonly batch: PendingInputBatch;+ readonly responses: ReadonlyMap<string, InputResponse | undefined>;+}++/**+ * Folds the event window into the currently pending batch and the most+ * recently resolved batch. Both are needed: the first to accept an answer,+ * the second to recognize a client re-sending an answer that already landed.+ */+function foldInputBatches(events: readonly HandleMessageStreamEvent[]): {+ readonly pending: PendingInputBatch | undefined;+ readonly resolved: ResolvedInputBatch | undefined;+} {+ let pending: PendingInputBatch | undefined;+ let requested: PendingInputBatch | undefined;+ let resolved: ResolvedInputBatch | undefined;+ for (const event of events) {+ if (event.type === "input.requested") {+ requested = pendingInputBatch(event);+ pending = requested;+ } else if (event.type === "input.resolved") {+ if (requested === undefined) continue;+ const responses = new Map<string, InputResponse | undefined>();+ for (const resolution of event.data.resolutions) {+ responses.set(resolution.requestId, resolution.response);+ }+ resolved = { batch: requested, responses };+ if (pending !== undefined) pending = withoutResolved(pending, event.data.resolutions);+ } else if (event.type === "turn.started") {+ pending = undefined;+ }+ }+ return { pending, resolved };+}+function latestPendingInputBatch(events: readonly HandleMessageStreamEvent[],): PendingInputBatch | undefined {- let batch: PendingInputBatch | undefined;- for (const event of events) {- if (event.type === "input.requested") batch = pendingInputBatch(event);- else if (event.type === "turn.started") batch = undefined;+ return foldInputBatches(events).pending;+}++/** True when `responses` exactly repeats the answers eve already accepted for the last batch. */+function replaysResolvedBatch(+ events: readonly HandleMessageStreamEvent[],+ responses: readonly InputResponse[],+): boolean {+ const resolved = foldInputBatches(events).resolved;+ if (resolved === undefined || responses.length !== resolved.responses.size) return false;+ const seen = new Set<string>();+ for (const response of responses) {+ const rawRequestId = resolved.batch.rawRequestIds[response.requestId];+ if (rawRequestId === undefined || seen.has(rawRequestId)) return false;+ seen.add(rawRequestId);+ if (!resolved.responses.has(rawRequestId)) return false;+ const accepted = resolved.responses.get(rawRequestId);+ if (accepted?.optionId !== response.optionId || accepted?.text !== response.text) {+ return false;+ }}- return batch;+ return true;}function projectNonterminal(@@ -241,6 +322,10 @@ function projectNonterminal(for (const event of events) {if (event.type === "input.requested") {inputBatch = pendingInputBatch(event);+ } else if (event.type === "input.resolved") {+ if (inputBatch !== undefined) {+ inputBatch = withoutResolved(inputBatch, event.data.resolutions);+ }} else if (event.type === "turn.started") {authorizations.clear();inputBatch = undefined;