The Open Framework for Building Agents
fix(eve): run messages as turns while tool approvals stay open (#1868)
Rui7dd64d3da0f6
diff --git a/.changeset/approvals-do-not-wedge-sessions.md b/.changeset/approvals-do-not-wedge-sessions.mdnew file mode 100644index 000000000..a523387d1--- /dev/null+++ b/.changeset/approvals-do-not-wedge-sessions.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Messages no longer wait behind pending tool approvals: a follow-up message now runs as an ordinary turn while the approval stays open and answerable, and a later structured answer still resolves the original tool call. Pending HITL batches are stored as an ordered collection, so a turn that runs while an approval is open can raise its own requests without overwriting it; multiple approval answers delivered together resume safely in order. Sessions wedged by the old deferral release the held message on their next delivery.diff --git a/.changeset/defer-task-approval-input.md b/.changeset/defer-task-approval-input.mdnew file mode 100644index 000000000..d79b139d2--- /dev/null+++ b/.changeset/defer-task-approval-input.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Keep task runs parked when unrelated messages arrive while tool approvals remain open, and resolve later text approval responses before replaying deferred messages. Invalid persisted input request kinds now fail closed.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 864c91ed3..c87eb7a05 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -150,13 +150,13 @@ curl -X POST http://127.0.0.1:2000/eve/v1/session/<sessionId> \The follow-up reuses the same durable session: same history, same state. Message sends default to cancellation-backed `"steer"`; if a turn is active, eve buffers the follow-up, cancels that turn, and starts the message under a new turn ID. Channels and TypeScript `Session.send(...)` calls can select `turnPolicy: "queue"` when active work should finish first. Structured `inputResponses` never steer.-If the session is waiting on a human-in-the-loop approval, a matching text reply such as `approve` or `cancel` answers the approval. Other follow-up text is held until the approval is answered, so an unrelated message does not implicitly deny the pending tool call.+If one pending batch is waiting on a human-in-the-loop approval, a matching text reply such as `approve` or `cancel` answers it. Unrelated text starts an ordinary turn immediately without denying the tool call; the approval stays pending and answerable. A later structured `inputResponses` answer keyed by its `requestId` still resumes the original tool call, even after intervening turns.-If the session is waiting on `ask_question`, a follow-up message clears that pending request before the model continues. An exact option match or permitted freeform response answers the question; any other message marks the question unanswered and starts the follow-up turn.+With one question-only batch, an exact option match or permitted freeform response answers `ask_question`. Any other follow-up marks the question unanswered and starts the new turn. With several approval or question batches pending, eve does not guess which batch plain text addresses: the message starts an ordinary turn and the batches stay open. Use structured responses to target requests unambiguously.-A response is stale when its request is no longer pending: the question or approval was already answered, cleared by a follow-up message, or cancelled. eve delivers a stale response to the model as a new user message, and the model decides whether the old selection still matters. A stale approval never authorizes the earlier tool call; the model must request the action and approval again if they are still needed.+A structured response matches any currently pending request by ID, not only the newest batch. It becomes stale only after that request was answered, cleared, or cancelled. eve delivers a stale response to the model as a new user message, and the model decides whether the old selection still matters. A stale approval never authorizes the earlier tool call; the model must request the action and approval again if they are still needed.-Responses match pending requests by request ID, so a response to an older request stays a plain user message even while a different question or approval is pending. Like any follow-up message, a stale response clears a pending question and is held while an approval is pending.+One delivery can answer requests from several batches. eve resumes approval-bearing batches in durable order and carries later answers forward until each batch can resume.Multiple replacement messages retain their durable arrival order and may be folded into the same replacement turn when they arrive before cancellation settles. See [message delivery and steering](./execution-model-and-durability#message-delivery-and-steering) for the current runtime contract.diff --git a/docs/guides/frontend/overview.mdx b/docs/guides/frontend/overview.mdxindex be0188b53..156867d2a 100644--- a/docs/guides/frontend/overview.mdx+++ b/docs/guides/frontend/overview.mdx@@ -113,20 +113,41 @@ received attachment as a `file` part on the user message. The part includes `med## Human-in-the-loop prompts-Tools opt into approval with `approval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `respond()`:+Tools opt into approval with `approval`, and the model can also ask a question with `ask_question` — see [Human-in-the-loop](/docs/human-in-the-loop) for the server-side model. Either way the stream emits an `input.requested` event, and the pending request rides on a `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest`. Scan every message because an unrelated turn can add newer messages while an approval stays open, then answer through the same session with `respond()`:```tsx-const request = agent.data.messages- .at(-1)- ?.parts.find((part) => part.type === "dynamic-tool" && part.toolMetadata?.eve?.inputRequest)- ?.toolMetadata?.eve?.inputRequest;--if (request) {- await agent.respond([{ requestId: request.requestId, optionId: "approve" }]);-}+const pendingRequests = agent.data.messages+ .flatMap((message) => message.parts)+ .flatMap((part) => {+ if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return [];+ const request = part.toolMetadata?.eve?.inputRequest;+ return request ? [request] : [];+ });++return pendingRequests.map((request) => (+ <fieldset key={request.requestId}>+ <legend>+ {request.kind === "tool-approval"+ ? "Approval required"+ : request.kind === "question"+ ? "Question"+ : "Session limit"}+ </legend>+ <p>{request.prompt}</p>+ {request.options?.map((option) => (+ <button+ key={option.id}+ onClick={() => void agent.respond([{ requestId: request.requestId, optionId: option.id }])}+ type="button"+ >+ {option.label}+ </button>+ ))}+ </fieldset>+));```-`request.prompt` and `request.options` give you what you need to render the approve and cancel UI. The default reducer marks the part as responded immediately, then updates it again once eve streams the resumed result.+For a question with `allowFreeform`, render a text input and send `{ requestId, text }`. The default reducer marks each matching part as responded immediately. Approved tools update again when eve streams their result.## Authorization promptsdiff --git a/docs/guides/frontend/use-eve-agent-svelte.mdx b/docs/guides/frontend/use-eve-agent-svelte.mdxindex b7cb1972e..f73a972e2 100644--- a/docs/guides/frontend/use-eve-agent-svelte.mdx+++ b/docs/guides/frontend/use-eve-agent-svelte.mdx@@ -77,26 +77,48 @@ await agent.send([## Human-in-the-loop prompts-A tool opts into approval with `approval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part of the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `agent.respond(inputResponses)`:+A tool opts into approval with `approval` ([Tools](../../tools)). When one fires, the pending request rides along on a `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest`. Scan every message because an unrelated turn can add newer messages while the approval stays open, then answer through the same session with `agent.respond(inputResponses)`:-```ts-import type { EveDynamicToolPart, EveMessagePart } from "eve/svelte";--const isDynamicToolPart = (part: EveMessagePart): part is EveDynamicToolPart =>- part.type === "dynamic-tool";+```svelte+<script lang="ts">+ import { useEveAgent } from "eve/svelte";-const request = agent.data.messages- .at(-1)- ?.parts.filter(isDynamicToolPart)- .map((part) => part.toolMetadata?.eve?.inputRequest)- .find((value) => value !== undefined);+ const agent = useEveAgent();+ const pendingRequests = $derived(+ agent.data.messages.flatMap((message) =>+ message.parts.flatMap((part) => {+ if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return [];+ const request = part.toolMetadata?.eve?.inputRequest;+ return request ? [request] : [];+ }),+ ),+ );+</script>-if (request) {- await agent.respond([{ requestId: request.requestId, optionId: "approve" }]);-}+{#each pendingRequests as request (request.requestId)}+ <fieldset>+ <legend>+ {request.kind === "tool-approval"+ ? "Approval required"+ : request.kind === "question"+ ? "Question"+ : "Session limit"}+ </legend>+ <p>{request.prompt}</p>+ {#each request.options ?? [] as option (option.id)}+ <button+ type="button"+ onclick={() =>+ void agent.respond([{ requestId: request.requestId, optionId: option.id }])}+ >+ {option.label}+ </button>+ {/each}+ </fieldset>+{/each}```-The find-and-answer flow is identical across frameworks. The [React hook reference](./overview) covers the longer walkthrough.+For a question with `allowFreeform`, bind a text input and send `{ requestId, text }`. The [React hook reference](./overview) covers the shared behavior.## Stop, reset, and resumediff --git a/docs/guides/frontend/use-eve-agent-vue.mdx b/docs/guides/frontend/use-eve-agent-vue.mdxindex 55053ec29..1b3553610 100644--- a/docs/guides/frontend/use-eve-agent-vue.mdx+++ b/docs/guides/frontend/use-eve-agent-vue.mdx@@ -88,28 +88,51 @@ async function onFileChange(event: Event) {## Human-in-the-loop prompts-A tool opts into approval with `approval` ([Tools](../../tools)). When it triggers, the pending request shows up as a `dynamic-tool` part on the latest message at `part.toolMetadata?.eve?.inputRequest`. Read it, then answer through the same session with `respond(inputResponses)`:+A tool opts into approval with `approval` ([Tools](../../tools)). When it triggers, the pending request shows up on a `dynamic-tool` part at `part.toolMetadata?.eve?.inputRequest`. Scan every message because an unrelated turn can add newer messages while the approval stays open, then answer through the same session with `respond(inputResponses)`:-```ts-import type { EveDynamicToolPart, EveMessagePart } from "eve/vue";+```vue+<script setup lang="ts">+import { computed } from "vue";+import { useEveAgent } from "eve/vue";const { data, respond } = useEveAgent();-const isDynamicToolPart = (part: EveMessagePart): part is EveDynamicToolPart =>- part.type === "dynamic-tool";--const request = data.value.messages- .at(-1)- ?.parts.filter(isDynamicToolPart)- .map((part) => part.toolMetadata?.eve?.inputRequest)- .find((value) => value !== undefined);+const pendingRequests = computed(() =>+ data.value.messages.flatMap((message) =>+ message.parts.flatMap((part) => {+ if (part.type !== "dynamic-tool" || part.state !== "approval-requested") return [];+ const request = part.toolMetadata?.eve?.inputRequest;+ return request ? [request] : [];+ }),+ ),+);+</script>-if (request) {- await respond([{ requestId: request.requestId, optionId: "approve" }]);-}+<template>+ <fieldset v-for="request in pendingRequests" :key="request.requestId">+ <legend>+ {{+ request.kind === "tool-approval"+ ? "Approval required"+ : request.kind === "question"+ ? "Question"+ : "Session limit"+ }}+ </legend>+ <p>{{ request.prompt }}</p>+ <button+ v-for="option in request.options ?? []"+ :key="option.id"+ type="button"+ @click="respond([{ requestId: request.requestId, optionId: option.id }])"+ >+ {{ option.label }}+ </button>+ </fieldset>+</template>```-The find-and-answer flow is the same across every framework. The [React hook reference](./overview) covers the longer walkthrough.+For a question with `allowFreeform`, bind a text input and send `{ requestId, text }`. The [React hook reference](./overview) covers the shared behavior.## Stop, reset, and resumediff --git a/docs/tools/human-in-the-loop.md b/docs/tools/human-in-the-loop.mdindex 6696a3e04..b33c92ed9 100644--- a/docs/tools/human-in-the-loop.md+++ b/docs/tools/human-in-the-loop.md@@ -109,7 +109,7 @@ semantics.The run picks back up exactly where it parked. Because the pause is durable, nothing is held in memory while it waits — the process can restart and the parked turn survives.-For approval requests, unrelated follow-up text does not deny the tool call. eve keeps the approval pending and holds that text until the approval is answered, then replays it as the next message in the session.+For approval requests, unrelated follow-up text does not deny the tool call — and it does not wait behind it either. The message runs as an ordinary turn while the approval stays pending and answerable; a later structured answer still resolves the original tool call. Text that exactly matches an option (like `approve`) still resolves the request directly.See [Sessions, runs & streaming](/docs/concepts/sessions-runs-and-streaming) for the full event and resume contract that this builds on.@@ -117,7 +117,7 @@ See [Sessions, runs & streaming](/docs/concepts/sessions-runs-and-streaming) forChannels turn requests into native UI: the Slack adapter renders approvals as buttons and questions as select menus, and writes the user's choice back as the answer. You get this for free on every [channel](/docs/channels/overview).-From your own frontend, read the pending request off the latest message and answer through the same session — see [Building a frontend](/docs/guides/frontend/overview#human-in-the-loop-prompts) for the client-side reducer and `inputResponses` shape.+From your own frontend, scan all messages for pending requests and answer through the same session — see [Building a frontend](/docs/guides/frontend/overview#human-in-the-loop-prompts) for the client-side reducer and `inputResponses` shape.## What to read nextdiff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.tsindex f4e8ce1c2..5d7af4bd5 100644--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.ts+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/authored-always-unrelated-input.eval.ts@@ -16,13 +16,16 @@ export default defineEval({toolName: TOOL_NAME,});- const unrelated = await t.send("Queue this unrelated note: ORBITAL-PINE-6C3R.");+ const unrelated = await t.send(+ "Note this unrelated marker and do not call any tools: ORBITAL-PINE-6C3R.",+ );+ // The unrelated message runs as an ordinary turn; the point of #533 is+ // that it must not replay or resolve the unresolved authored tool call.unrelated.expectOk();unrelated.notEvent("action.result", {data: { result: { toolName: TOOL_NAME } },});- unrelated.notEvent("step.started");unrelated.event("session.waiting", { count: 1 });const approved = await t.respond([diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.tsdeleted file mode 100644index 9570bf232..000000000--- a/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-queued.eval.ts+++ /dev/null@@ -1,52 +0,0 @@-import { defineEval } from "eve/evals";--import { GUARDED_ECHO_TOKEN } from "./shared";--/**- * HITL flow: unrelated text sent while an approval is pending must not deny- * the approval or disappear. The message is replayed after the approval- * receives an explicit terminal answer.- */-export default defineEval({- tags: ["real-model"],- description: "HITL smoke: unrelated message during approval is queued.",- async test(t) {- const parked = await t.send('Call the guarded-echo tool with note "queued-approval".');- parked.calledTool("guarded-echo", { status: "pending", count: 1 });- const request = t.requireInputRequest({- display: "confirmation",- toolName: "guarded-echo",- });-- const queued = await t.send(- "After the pending approval is resolved, reply with exactly QUEUED-HITL-OK.",- );- queued.expectOk();- queued.notEvent("action.result", {- data: { result: { toolName: "guarded-echo" }, status: "rejected" },- });- queued.event("session.waiting", { count: 1 });-- const approved = await t.respond([- {- requestId: request.requestId,- optionId: "approve",- },- ]);- approved.expectOk();- approved.event("action.result", {- data: {- result: {- kind: "tool-result",- output: new RegExp(GUARDED_ECHO_TOKEN),- toolName: "guarded-echo",- },- status: "completed",- },- count: 1,- });- approved.messageIncludes(/QUEUED-HITL-OK/i);-- t.succeeded();- },-});diff --git a/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-runs.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-runs.eval.tsnew file mode 100644index 000000000..62b7c8637--- /dev/null+++ b/e2e/fixtures/agent-tools-hitl/evals/hitl/unrelated-message-runs.eval.ts@@ -0,0 +1,62 @@+import { defineEval } from "eve/evals";++import { GUARDED_ECHO_TOKEN } from "./shared";++/**+ * HITL flow: unrelated text sent while an approval is pending must not deny+ * the approval and must not wait behind it. The message runs as an ordinary+ * turn, the approval stays answerable, and a later structured approval still+ * runs the original tool call exactly once.+ */+export default defineEval({+ tags: ["real-model"],+ description: "HITL smoke: unrelated message during approval runs immediately.",+ async test(t) {+ const parked = await t.send('Call the guarded-echo tool with note "open-approval".');+ parked.calledTool("guarded-echo", { status: "pending", count: 1 });+ const request = t.requireInputRequest({+ display: "confirmation",+ toolName: "guarded-echo",+ });++ // The message runs now; the approval is untouched.+ const message = await t.send(+ "Leave the pending approval alone. Do not call any tools. Reply with exactly OPEN-APPROVAL-MSG-OK.",+ );+ message.expectOk();+ message.event("message.received", { count: 1 });+ message.event("message.completed", { count: 1 });+ message.messageIncludes(/OPEN-APPROVAL-MSG-OK/i);+ // The parked call must not execute — and the intervening turn must not+ // run any tool of its own either.+ message.notEvent("action.result", {+ data: { result: { toolName: "guarded-echo" } },+ });+ message.usedNoTools();+ message.event("session.waiting", { count: 1 });++ // The approval still resolves afterwards and runs the tool once.+ const approved = await t.respond([+ {+ requestId: request.requestId,+ optionId: "approve",+ },+ ]);+ approved.expectOk();+ approved.event("action.result", {+ data: {+ result: {+ kind: "tool-result",+ output: new RegExp(GUARDED_ECHO_TOKEN),+ toolName: "guarded-echo",+ },+ status: "completed",+ },+ count: 1,+ });+ approved.event("session.waiting", { count: 1 });++ t.succeeded();+ t.calledTool("guarded-echo", { status: "completed", count: 1 });+ },+});diff --git a/packages/eve/src/client/message-reducer.test.ts b/packages/eve/src/client/message-reducer.test.tsindex 4138acdd0..5a0683055 100644--- a/packages/eve/src/client/message-reducer.test.ts+++ b/packages/eve/src/client/message-reducer.test.ts@@ -517,6 +517,58 @@ describe("defaultMessageReducer", () => {]);});+ it("keeps an older approval answerable after a later turn", () => {+ const reducer = defaultMessageReducer();+ let data = reduceServerEvents(reducer, reducer.initial(), [+ createInputRequestedEvent({+ requests: [+ {+ action: {+ callId: "call_1",+ input: { command: "pwd" },+ kind: "tool-call",+ toolName: "bash",+ },+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes", style: "primary" },+ { id: "cancel", label: "No", style: "danger" },+ ],+ prompt: "Approve tool call: bash",+ requestId: "approval_1",+ },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_1",+ }),+ {+ data: { message: "What time is it?", sequence: 0, turnId: "turn_2" },+ type: "message.received",+ },+ createMessageCompletedEvent({+ message: "It is noon.",+ sequence: 0,+ stepIndex: 0,+ turnId: "turn_2",+ }),+ ]);++ expect(data.messages.at(-1)?.id).toBe("turn_2:assistant");+ expect(findToolPart(data, "call_1")).toMatchObject({ state: "approval-requested" });++ data = reducer.reduce(data, {+ data: {+ createdAt: 1,+ responses: [{ optionId: "approve", requestId: "approval_1" }],+ },+ type: "client.input.responded",+ });++ expect(findToolPart(data, "call_1")).toMatchObject({ state: "approval-responded" });+ });+it("marks input requests as responded when the client submits a response", () => {const reducer = defaultMessageReducer();let data = reduceServerEvents(reducer, reducer.initial(), [diff --git a/packages/eve/src/execution/durable-session-store.test.ts b/packages/eve/src/execution/durable-session-store.test.tsindex 76862ab8f..0c032b99a 100644--- a/packages/eve/src/execution/durable-session-store.test.ts+++ b/packages/eve/src/execution/durable-session-store.test.ts@@ -8,6 +8,7 @@ import {type DurableSessionState,projectSessionState,readDurableSession,+ replaceDurableSessionSnapshot,} from "#execution/durable-session-store.js";import type { NextDriverAction } from "#execution/next-driver-action.js";import { projectToDurableSession } from "#execution/session.js";@@ -156,6 +157,32 @@ describe("durable-session-store cross-version contract", () => {});});+ it("replaces the session without dropping unknown snapshot fields", () => {+ const original = createDurableSessionState({+ session: buildSession({ continuationToken: "http:old", sessionId: "wrun_replace" }),+ });+ const state = {+ ...original,+ snapshot: {+ ...original.snapshot,+ futureSnapshotField: { owner: "newer deployment" },+ },+ } as DurableSessionState;+ const session = {+ ...state.snapshot!.session,+ continuationToken: "http:new",+ };++ const replaced = replaceDurableSessionSnapshot({ session, state });++ expect(replaced.continuationToken).toBe("http:new");+ expect(replaced.snapshot?.session).toBe(session);+ expect(+ (replaced.snapshot as DurableSessionSnapshot & { futureSnapshotField?: unknown })+ .futureSnapshotField,+ ).toEqual({ owner: "newer deployment" });+ });+it("reads an embedded snapshot without opening the legacy stream", async () => {const session = buildSession({continuationToken: "http:test",diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.tsindex 91256b07a..08ca4345c 100644--- a/packages/eve/src/execution/durable-session-store.ts+++ b/packages/eve/src/execution/durable-session-store.ts@@ -200,3 +200,23 @@ export function createDurableSessionState(input: {snapshot,};}++/** Replaces the embedded session while preserving additive snapshot fields. */+export function replaceDurableSessionSnapshot(input: {+ readonly session: DurableSession;+ readonly state: DurableSessionState;+}): DurableSessionState {+ return {+ ...input.state,+ continuationToken: input.session.continuationToken,+ emissionState: getHarnessEmissionState(input.session.state),+ hasProxyInputRequests: hasProxyInputRequests(input.session.state),+ sessionId: input.session.sessionId,+ version: DURABLE_SESSION_VERSION,+ snapshot: {+ ...input.state.snapshot,+ session: input.session,+ version: DURABLE_SESSION_VERSION,+ },+ };+}diff --git a/packages/eve/src/execution/parked-delivery-wait.test.ts b/packages/eve/src/execution/parked-delivery-wait.test.tsindex 1051dbf07..a4c369c83 100644--- a/packages/eve/src/execution/parked-delivery-wait.test.ts+++ b/packages/eve/src/execution/parked-delivery-wait.test.ts@@ -1,7 +1,8 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import type { DeliverHookPayload } from "#channel/types.js";import { nextTurnDelivery } from "#execution/parked-delivery-wait.js";+import { routeDeliverToChildren } from "#execution/route-child-delivery.js";import type {SessionCommandInbox,SessionInboxPayload,@@ -9,6 +10,10 @@ import type {} from "#execution/session-command-inbox.js";import type { DurableSessionState } from "#execution/durable-session-store.js";+vi.mock("./route-child-delivery.js", () => ({+ routeDeliverToChildren: vi.fn(),+}));+interface ScriptedRead {readonly result: IteratorResult<SessionInboxPayload>;readonly source: SessionInboxSource;@@ -101,6 +106,10 @@ function waitInput(inbox: SessionCommandInbox): Parameters<typeof nextTurnDelive}describe("nextTurnDelivery", () => {+ afterEach(() => {+ vi.mocked(routeDeliverToChildren).mockReset();+ });+it("surfaces an authorization callback as its own instruction", async () => {const inbox = createMockInbox([authorizationRead()]);@@ -174,4 +183,28 @@ describe("nextTurnDelivery", () => {).rejects.toThrow("Mock inbox exhausted.");expect(inbox.windowTransitions).toEqual([]);});++ it("carries retired proxy state through fully routed parked deliveries", async () => {+ const retiredState = { ...sessionState, hasProxyInputRequests: false };+ const inbox = createMockInbox([messageRead("child response"), messageRead("parent turn")]);+ vi.mocked(routeDeliverToChildren)+ .mockResolvedValueOnce({+ kind: "continue",+ remainder: undefined,+ sessionState: retiredState,+ })+ .mockResolvedValueOnce({+ kind: "continue",+ remainder: { message: "parent turn" },+ sessionState: retiredState,+ });++ const next = await nextTurnDelivery({+ ...waitInput(inbox),+ awaitAuthorizationCallbacks: false,+ });++ expect(vi.mocked(routeDeliverToChildren).mock.calls[1]?.[0].sessionState).toBe(retiredState);+ expect(next).toMatchObject({ kind: "turn", sessionState: retiredState });+ });});diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.tsindex fcabb2fb2..49086143f 100644--- a/packages/eve/src/execution/parked-delivery-wait.ts+++ b/packages/eve/src/execution/parked-delivery-wait.ts@@ -10,7 +10,7 @@ type NextSessionAction =| { readonly kind: "compact" }| { readonly kind: "expired" }| { readonly kind: "reset" }- | AuthorizationCallbackInstruction+ | Omit<AuthorizationCallbackInstruction, "sessionState">| {readonly delivery: DeliverHookPayload | null;readonly kind: "delivery";@@ -22,21 +22,23 @@ export interface AuthorizationCallbackInstruction {/** True when the authorization hook closed; no further callbacks can arrive. */readonly closed: boolean;readonly payloads: readonly DeliverPayload[];+ readonly sessionState: DurableSessionState;}/** What the parked driver should do with the next session activity. */export type NextTurnInstruction =- | { readonly kind: "clear" }- | { readonly kind: "compact" }- | { readonly kind: "expired" }- | { readonly kind: "reset" }- | { readonly kind: "closed" }- | { readonly kind: "cancel-turn" }+ | { readonly kind: "clear"; readonly sessionState: DurableSessionState }+ | { readonly kind: "compact"; readonly sessionState: DurableSessionState }+ | { readonly kind: "expired"; readonly sessionState: DurableSessionState }+ | { readonly kind: "reset"; readonly sessionState: DurableSessionState }+ | { readonly kind: "closed"; readonly sessionState: DurableSessionState }+ | { readonly kind: "cancel-turn"; readonly sessionState: DurableSessionState }| AuthorizationCallbackInstruction| {readonly kind: "turn";readonly deliver: DeliverHookPayload;readonly remainder: DeliverPayload;+ readonly sessionState: DurableSessionState;};/**@@ -81,6 +83,8 @@ async function awaitNextTurnDelivery(input: {readonly driverWritable: WritableStream<Uint8Array>;readonly sessionState: DurableSessionState;}): Promise<NextTurnInstruction> {+ let sessionState = input.sessionState;+while (true) {const nextAction = await waitForNextSessionAction({bufferedDeliveries: input.bufferedDeliveries,@@ -90,27 +94,28 @@ async function awaitNextTurnDelivery(input: {});if (nextAction.kind === "authorization") {- return nextAction;+ return { ...nextAction, sessionState };}if (nextAction.kind !== "delivery") {- return { kind: nextAction.kind };+ return { kind: nextAction.kind, sessionState };}const deliver = nextAction.delivery;if (deliver === null) {- return { kind: "closed" };+ return { kind: "closed", sessionState };}const routed = await routeDeliverToChildren({auth: deliver.auth,parentWritable: input.driverWritable,payloads: deliver.payloads,- sessionState: input.sessionState,+ sessionState,});+ sessionState = routed.sessionState;if (routed.kind === "cancel-turn") {- return { kind: "cancel-turn" };+ return { kind: "cancel-turn", sessionState };}if (routed.remainder === undefined) {@@ -118,7 +123,7 @@ async function awaitNextTurnDelivery(input: {continue;}- return { deliver, kind: "turn", remainder: routed.remainder };+ return { deliver, kind: "turn", remainder: routed.remainder, sessionState };}}diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.tsindex d3424fd66..9a5d3901c 100644--- a/packages/eve/src/execution/route-child-delivery.ts+++ b/packages/eve/src/execution/route-child-delivery.ts@@ -21,7 +21,7 @@ export async function routeDeliverToChildren(input: {}): Promise<RoutedDeliverResult> {const payload = coalesceDeliverPayloads(input.payloads);if (!input.sessionState.hasProxyInputRequests) {- return { kind: "continue", remainder: payload };+ return { kind: "continue", remainder: payload, sessionState: input.sessionState };}return await routeProxiedDeliverStep({diff --git a/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts b/packages/eve/src/execution/subagent-hitl-proxy.integration.test.tsindex bedae319b..6a1fda576 100644--- a/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts+++ b/packages/eve/src/execution/subagent-hitl-proxy.integration.test.ts@@ -242,6 +242,10 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #["req-approve-1",{+ batch: {+ approvalRequestIds: ["req-approve-1"],+ requestIds: ["req-approve-1"],+ },childContinuationToken: "subagent:parent:call-1",kind: "tool-approval",},@@ -310,6 +314,7 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #payload: {inputResponses: [{ optionId: "approve", requestId: "req-approve-1" }],},+ retireRequestIds: ["req-approve-1"],},]);});diff --git a/packages/eve/src/execution/subagent-hitl-proxy.test.ts b/packages/eve/src/execution/subagent-hitl-proxy.test.tsindex 72eff5413..a76cc51c3 100644--- a/packages/eve/src/execution/subagent-hitl-proxy.test.ts+++ b/packages/eve/src/execution/subagent-hitl-proxy.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vitest";-import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import {+ retireProxyInputRequests,+ upsertProxyInputRequests,+} from "#harness/proxy-input-requests.js";+import type { ProxyInputRequest } from "#harness/proxy-input-requests.js";import type { HarnessSession } from "#harness/types.js";import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";@@ -19,6 +23,26 @@ function createSession(state?: Record<string, unknown>): HarnessSession {};}+function addBatchRoutes(+ session: HarnessSession,+ requests: readonly { readonly kind: ProxyInputRequest["kind"]; readonly requestId: string }[],+): HarnessSession {+ const batch = {+ approvalRequestIds: requests.flatMap((request) =>+ request.kind === "tool-approval" ? [request.requestId] : [],+ ),+ requestIds: requests.map((request) => request.requestId),+ };+ return upsertProxyInputRequests({+ entries: requests.map((request) => [+ request.requestId,+ { batch, childContinuationToken: "child-a", kind: request.kind },+ ]),+ forChildContinuationToken: "child-a",+ session,+ });+}+describe("routeDeliverPayload", () => {it("routes responses to matching descendants and keeps unknown ones on forSelf", () => {const session = upsertProxyInputRequests({@@ -103,8 +127,81 @@ describe("routeDeliverPayload", () => {{childContinuationToken: "child-a",payload: { inputResponses: [{ optionId: "stop", requestId: "req-limit" }] },+ retireRequestIds: ["req-limit"],},]);expect(routed.parentAction).toEqual({ kind: "cancel-turn" });});++ it("retires an entire question batch after one answer", () => {+ const session = addBatchRoutes(createSession(), [+ { kind: "question", requestId: "question-1" },+ { kind: "question", requestId: "question-2" },+ ]);++ const routed = routeDeliverPayload({+ payload: { inputResponses: [{ requestId: "question-1", text: "answer" }] },+ state: session.state,+ });++ expect(new Set(routed.forChildren[0]?.retireRequestIds)).toEqual(+ new Set(["question-1", "question-2"]),+ );+ });++ it("retires a mixed batch when all of its approvals are answered", () => {+ const session = addBatchRoutes(createSession(), [+ { kind: "question", requestId: "question-1" },+ { kind: "tool-approval", requestId: "approval-1" },+ ]);++ const routed = routeDeliverPayload({+ payload: { inputResponses: [{ optionId: "approve", requestId: "approval-1" }] },+ state: session.state,+ });++ expect(new Set(routed.forChildren[0]?.retireRequestIds)).toEqual(+ new Set(["question-1", "approval-1"]),+ );+ });++ it("keeps unresolved approval routes across partial multi-approval responses", () => {+ let session = addBatchRoutes(createSession(), [+ { kind: "tool-approval", requestId: "approval-1" },+ { kind: "tool-approval", requestId: "approval-2" },+ ]);++ const partial = routeDeliverPayload({+ payload: { inputResponses: [{ optionId: "approve", requestId: "approval-1" }] },+ state: session.state,+ });+ expect(partial.forChildren[0]?.retireRequestIds).toEqual(["approval-1"]);++ session = retireProxyInputRequests(session, partial.forChildren[0]?.retireRequestIds ?? []);+ const completed = routeDeliverPayload({+ payload: { inputResponses: [{ optionId: "cancel", requestId: "approval-2" }] },+ state: session.state,+ });+ expect(new Set(completed.forChildren[0]?.retireRequestIds)).toEqual(+ new Set(["approval-1", "approval-2"]),+ );+ });++ it("keeps request-only retirement for legacy routes without batch metadata", () => {+ const session = upsertProxyInputRequests({+ entries: [+ ["question-1", { childContinuationToken: "child-a", kind: "question" }],+ ["question-2", { childContinuationToken: "child-a", kind: "question" }],+ ],+ forChildContinuationToken: "child-a",+ session: createSession(),+ });++ const routed = routeDeliverPayload({+ payload: { inputResponses: [{ requestId: "question-1", text: "answer" }] },+ state: session.state,+ });++ expect(routed.forChildren[0]?.retireRequestIds).toEqual(["question-1"]);+ });});diff --git a/packages/eve/src/execution/subagent-hitl-proxy.ts b/packages/eve/src/execution/subagent-hitl-proxy.tsindex 89b2e8a91..7cb379166 100644--- a/packages/eve/src/execution/subagent-hitl-proxy.ts+++ b/packages/eve/src/execution/subagent-hitl-proxy.ts@@ -69,6 +69,7 @@ export interface RoutedDeliverPayload {readonly forChildren: readonly {readonly childContinuationToken: string;readonly payload: { readonly inputResponses: readonly InputResponse[] };+ readonly retireRequestIds: readonly string[];}[];readonly forSelf: DeliverPayload | undefined;readonly parentAction: { readonly kind: "cancel-turn" } | undefined;@@ -82,7 +83,10 @@ export function routeDeliverPayload(input: {const entries = getProxyInputRequests(input.state);const inputResponses = input.payload.inputResponses ?? [];- const responsesByChild = new Map<string, InputResponse[]>();+ const responsesByChild = new Map<+ string,+ { responses: InputResponse[]; routes: ProxyInputRequest[] }+ >();const unroutedResponses: InputResponse[] = [];let parentAction: RoutedDeliverPayload["parentAction"];@@ -101,17 +105,36 @@ export function routeDeliverPayload(input: {const existing = responsesByChild.get(route.childContinuationToken);if (existing === undefined) {- responsesByChild.set(route.childContinuationToken, [response]);+ responsesByChild.set(route.childContinuationToken, {+ responses: [response],+ routes: [route],+ });} else {- existing.push(response);+ existing.responses.push(response);+ existing.routes.push(route);}}const forChildren: RoutedDeliverPayload["forChildren"] = [...responsesByChild.entries()].map(- ([childContinuationToken, responses]) => ({- childContinuationToken,- payload: { inputResponses: responses },- }),+ ([childContinuationToken, bucket]) => {+ const responseIds = new Set(bucket.responses.map((response) => response.requestId));+ const retireRequestIds = new Set(responseIds);++ for (const route of bucket.routes) {+ if (+ route.batch !== undefined &&+ batchResolves({ batch: route.batch, childContinuationToken, entries, responseIds })+ ) {+ for (const requestId of route.batch.requestIds) retireRequestIds.add(requestId);+ }+ }++ return {+ childContinuationToken,+ payload: { inputResponses: bucket.responses },+ retireRequestIds: [...retireRequestIds],+ };+ },);// Preserve every non-`inputResponses` field on the original payload@@ -135,3 +158,32 @@ export function routeDeliverPayload(input: {return { forChildren, forSelf, parentAction };}++function batchResolves(input: {+ readonly batch: NonNullable<ProxyInputRequest["batch"]>;+ readonly childContinuationToken: string;+ readonly entries: ReadonlyMap<string, ProxyInputRequest>;+ readonly responseIds: ReadonlySet<string>;+}): boolean {+ if (input.batch.approvalRequestIds.length === 0) return true;++ return input.batch.approvalRequestIds.every((requestId) => {+ const route = input.entries.get(requestId);+ if (route === undefined || !sameBatch(route, input)) return true;+ return input.responseIds.has(requestId);+ });+}++function sameBatch(+ route: ProxyInputRequest,+ input: {+ readonly batch: NonNullable<ProxyInputRequest["batch"]>;+ readonly childContinuationToken: string;+ },+): boolean {+ return (+ route.childContinuationToken === input.childContinuationToken &&+ route.batch?.requestIds.length === input.batch.requestIds.length &&+ route.batch.requestIds.every((requestId, index) => requestId === input.batch.requestIds[index])+ );+}diff --git a/packages/eve/src/execution/turn-workflow.test.ts b/packages/eve/src/execution/turn-workflow.test.tsindex 22d43af3a..5d69858d5 100644--- a/packages/eve/src/execution/turn-workflow.test.ts+++ b/packages/eve/src/execution/turn-workflow.test.ts@@ -746,6 +746,7 @@ describe("turnWorkflow", () => {createSessionState({ hasProxyInputRequests: true }),runningChildren,);+ const retiredProxyState = withRunningChildren(createSessionState(), runningChildren);const completedState = createSessionState();const requestId = "turn-token:inbox:delivery:0";installInbox([@@ -789,6 +790,7 @@ describe("turnWorkflow", () => {vi.mocked(routeDeliverToChildren).mockResolvedValue({kind: "continue",remainder: undefined,+ sessionState: retiredProxyState,});vi.mocked(turnStep).mockResolvedValueOnce({@@ -830,11 +832,13 @@ describe("turnWorkflow", () => {sessionState: proxyState,}),);+ expect(vi.mocked(turnStep).mock.calls[1]?.[0].sessionState).toBe(retiredProxyState);});it("lets the parent cancel after a descendant consumes a session-limit Stop response", async () => {const pendingState = createSessionState();const proxyState = createSessionState({ hasProxyInputRequests: true });+ const retiredProxyState = createSessionState();const requestId = "child-limit-request";installInbox([{@@ -864,6 +868,7 @@ describe("turnWorkflow", () => {});vi.mocked(routeDeliverToChildren).mockResolvedValue({kind: "cancel-turn",+ sessionState: retiredProxyState,});vi.mocked(turnStep).mockResolvedValueOnce({action: "park",@@ -883,7 +888,7 @@ describe("turnWorkflow", () => {expect(cancelDescendantTurnsStep).toHaveBeenCalledWith({serializedContext: { state: "proxied" },- sessionState: proxyState,+ sessionState: retiredProxyState,});expect(turnStep).toHaveBeenCalledOnce();expect(resumeHookMock).toHaveBeenCalledWith("turn-token", {@@ -891,7 +896,7 @@ describe("turnWorkflow", () => {cancelled: true,kind: "park",serializedContext: { state: "proxied" },- sessionState: proxyState,+ sessionState: retiredProxyState,},kind: "turn-result",});@@ -1077,6 +1082,7 @@ describe("turnWorkflow", () => {vi.mocked(routeDeliverToChildren).mockResolvedValue({kind: "continue",remainder: undefined,+ sessionState: pendingState,});vi.mocked(turnStep).mockResolvedValueOnce({diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.tsindex 4f1b7e004..005330869 100644--- a/packages/eve/src/execution/turn-workflow.ts+++ b/packages/eve/src/execution/turn-workflow.ts@@ -358,6 +358,7 @@ async function waitForRuntimeActionResults(input: {payloads: value.delivery.payloads,sessionState: input.cursor.sessionState,});+ await input.cursor.adopt(routed);if (routed.kind === "cancel-turn") {return routed.kind;}diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex e751f3d32..e2b12ab8f 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -58,9 +58,10 @@ vi.mock("./create-session-step.js", () => ({}));vi.mock("./route-child-delivery.js", () => ({- routeDeliverToChildren: vi.fn().mockImplementation(async ({ payloads }) => ({+ routeDeliverToChildren: vi.fn().mockImplementation(async ({ payloads, sessionState }) => ({kind: "continue",remainder: payloads[0],+ sessionState,})),}));@@ -1104,6 +1105,7 @@ describe("workflowEntry", () => {vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({kind: "continue",remainder: undefined,+ sessionState,});installHookMocks({deliveryHooks: [@@ -1131,6 +1133,40 @@ describe("workflowEntry", () => {expect(notifyTurnCallerStep).toHaveBeenCalledTimes(1);});+ it("adopts retired proxy state before the next parked driver turn", async () => {+ const sessionState = createBaseSessionState({ hasProxyInputRequests: true });+ const retiredState = createBaseSessionState({ hasProxyInputRequests: false });+ const completedState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ vi.mocked(routeDeliverToChildren).mockResolvedValueOnce({+ kind: "continue",+ remainder: undefined,+ sessionState: retiredState,+ });+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [+ { kind: "send", payload: { inputResponses: [] } },+ { kind: "send", payload: { message: "next parent turn" } },+ ],+ },+ ],+ turnControls: [+ turnResult({ action: "park", sessionState }),+ turnResult({ action: "done", output: "ok", sessionState: completedState }),+ ],+ });++ await workflowEntry({+ input: { message: "hello" },+ serializedContext: createSerializedContext(),+ });++ expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].sessionState).toBe(retiredState);+ });+it("runs concurrent caller deliveries as separate turns", async () => {const sessionState = createBaseSessionState();vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 0402be17b..bdf4fb39b 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -307,9 +307,14 @@ async function runDriverLoop(input: {readonly expectedAttemptIds: readonly string[];readonly sessionState: DurableSessionState;}): Promise<- | { readonly kind: "authorization-resume"; readonly payloads: DeliverPayload[] }+ | {+ readonly kind: "authorization-resume";+ readonly payloads: DeliverPayload[];+ readonly sessionState: DurableSessionState;+ }| Exclude<NextTurnInstruction, { kind: "authorization" }>> => {+ let sessionState = park.sessionState;const expectedAttemptIds = new Set(park.expectedAttemptIds);for (const attemptId of collectedAuthPayloads.keys()) {if (!expectedAttemptIds.has(attemptId)) collectedAuthPayloads.delete(attemptId);@@ -324,7 +329,7 @@ async function runDriverLoop(input: {(attemptId) => collectedAuthPayloads.get(attemptId)!,);collectedAuthPayloads.clear();- return { kind: "authorization-resume", payloads };+ return { kind: "authorization-resume", payloads, sessionState };}const next = await nextTurnDelivery({@@ -334,8 +339,9 @@ async function runDriverLoop(input: {commandInbox,deferDeliveries: input.mode === "task" && expectedAttemptIds.size > 0,driverWritable: input.driverWritable,- sessionState: park.sessionState,+ sessionState,});+ sessionState = next.sessionState;if (next.kind !== "authorization") return next;for (const payload of next.payloads) {@@ -353,7 +359,7 @@ async function runDriverLoop(input: {if (next.closed) {const payloads = [...collectedAuthPayloads.values()];collectedAuthPayloads.clear();- return { kind: "authorization-resume", payloads };+ return { kind: "authorization-resume", payloads, sessionState };}}};@@ -484,6 +490,8 @@ async function runDriverLoop(input: {expectedAttemptIds: action.authorizationAttemptIds ?? [],sessionState: action.sessionState,});+ action = { ...action, sessionState: next.sessionState };+ input.crashCleanupState.lastSessionState = action.sessionState;if (next.kind === "authorization-resume") {action = await runTurn({diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex e1e0261e9..053a9b0e6 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -20,8 +20,8 @@ import { setPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import { getAgentHandleStore } from "#harness/handles/store.js";import { requestTurnSleep } from "#harness/turn-sleep.js";import { getPendingAuthorization, setPendingAuthorization } from "#harness/authorization.js";-import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";-import { setPendingInputBatch } from "#harness/input-requests.js";+import { getProxyInputRequests, upsertProxyInputRequests } from "#harness/proxy-input-requests.js";+import { appendPendingInputBatch } from "#harness/input-requests.js";import type { HarnessSession, StepResult } from "#harness/types.js";import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";@@ -60,7 +60,9 @@ vi.mock("./durable-session-store.js", async (importOriginal) => {};});-function installSessionStoreMocks(sessions: HarnessSession[]): void {+function installSessionStoreMocks(+ sessions: Awaited<ReturnType<typeof readDurableSession>>[],+): void {// Each `readDurableSession` invocation pops the next prepared session// off the queue. Tests that exercise multiple harness steps stack// sessions in the order the step boundaries hit them.@@ -168,7 +170,9 @@ function createStubSession(overrides: Partial<HarnessSession> = {}): HarnessSess};}-function createSerializedContext(): Record<string, unknown> {+function createSerializedContext(+ mode: "conversation" | "task" = "conversation",+): Record<string, unknown> {const ctx = new ContextContainer();ctx.set(AuthKey, null);ctx.set(BundleKey, {@@ -191,7 +195,7 @@ function createSerializedContext(): Record<string, unknown> {} as never);ctx.set(ChannelKey, threadContextAdapter);ctx.set(ContinuationTokenKey, "http:thread-context");- ctx.set(ModeKey, "conversation");+ ctx.set(ModeKey, mode);ctx.set(SessionIdKey, "session-1");return serializeContext(ctx);}@@ -215,7 +219,10 @@ describe("routeProxiedDeliverStep", () => {principalType: "user",};const session = upsertProxyInputRequests({- entries: [["request-1", { childContinuationToken: "child-token", kind: "tool-approval" }]],+ entries: [+ ["request-1", { childContinuationToken: "child-token", kind: "tool-approval" }],+ ["request-2", { childContinuationToken: "child-token", kind: "tool-approval" }],+ ],forChildContinuationToken: "child-token",session: createStubSession({continuationToken: "parent-token",@@ -224,20 +231,24 @@ describe("routeProxiedDeliverStep", () => {});installSessionStoreMocks([session]);- await expect(- routeProxiedDeliverStep({- auth,- parentWritable: createTestWritable(),- payload: {- inputResponses: [{ optionId: "approve", requestId: "request-1" }],- },- sessionState: createStubSessionState({- continuationToken: "parent-token",- hasProxyInputRequests: true,- sessionId: "parent-session",- }),+ const result = await routeProxiedDeliverStep({+ auth,+ parentWritable: createTestWritable(),+ payload: {+ inputResponses: [{ optionId: "approve", requestId: "request-1" }],+ },+ sessionState: createStubSessionState({+ continuationToken: "parent-token",+ hasProxyInputRequests: true,+ sessionId: "parent-session",}),- ).resolves.toEqual({ kind: "continue", remainder: undefined });+ });++ expect(result).toMatchObject({ kind: "continue", remainder: undefined });+ expect(result.sessionState.hasProxyInputRequests).toBe(true);+ expect([...getProxyInputRequests(result.sessionState.snapshot?.session.state)]).toEqual([+ ["request-2", { childContinuationToken: "child-token", kind: "tool-approval" }],+ ]);expect(resumeHookMock).toHaveBeenCalledWith("child-token", {auth,@@ -250,6 +261,88 @@ describe("routeProxiedDeliverStep", () => {requestId: undefined,});});++ it("does not retire before forwarding succeeds and ignores a stale retry after retirement", async () => {+ const session = upsertProxyInputRequests({+ entries: [["request-1", { childContinuationToken: "child-token", kind: "session-limit" }]],+ forChildContinuationToken: "child-token",+ session: createStubSession(),+ });+ installSessionStoreMocks([session]);+ const initialState = createDurableSessionState({ session });+ resumeHookMock.mockRejectedValueOnce(new Error("temporary forward failure"));++ await expect(+ routeProxiedDeliverStep({+ parentWritable: createTestWritable(),+ payload: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },+ sessionState: initialState,+ }),+ ).rejects.toThrow("temporary forward failure");+ expect(initialState.hasProxyInputRequests).toBe(true);++ installSessionStoreMocks([session]);+ const forwarded = await routeProxiedDeliverStep({+ parentWritable: createTestWritable(),+ payload: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },+ sessionState: initialState,+ });+ expect(forwarded.kind).toBe("cancel-turn");+ expect(forwarded.sessionState.hasProxyInputRequests).toBe(false);++ resumeHookMock.mockClear();+ const retiredSession = forwarded.sessionState.snapshot?.session;+ if (retiredSession === undefined) throw new Error("Expected a routed session snapshot.");+ installSessionStoreMocks([retiredSession]);+ const stale = await routeProxiedDeliverStep({+ parentWritable: createTestWritable(),+ payload: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },+ sessionState: forwarded.sessionState,+ });++ expect(stale).toEqual({+ kind: "continue",+ remainder: { inputResponses: [{ optionId: "stop", requestId: "request-1" }] },+ sessionState: forwarded.sessionState,+ });+ expect(resumeHookMock).not.toHaveBeenCalled();+ });++ it("replays multi-child forwarding in the same order when a later child fails", async () => {+ const session = upsertProxyInputRequests({+ entries: [+ ["request-a", { childContinuationToken: "child-a", kind: "question" }],+ ["request-b", { childContinuationToken: "child-b", kind: "question" }],+ ],+ forChildContinuationToken: "child-a",+ session: createStubSession(),+ });+ installSessionStoreMocks([session]);+ const initialState = createDurableSessionState({ session });+ resumeHookMock+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("child-b down"));+ const input = {+ parentWritable: createTestWritable(),+ payload: {+ inputResponses: [+ { requestId: "request-a", text: "a" },+ { requestId: "request-b", text: "b" },+ ],+ },+ sessionState: initialState,+ };++ await expect(routeProxiedDeliverStep(input)).rejects.toThrow("child-b down");+ expect(resumeHookMock.mock.calls.map(([token]) => token)).toEqual(["child-a", "child-b"]);+ expect(initialState.snapshot?.session.state).toEqual(session.state);++ resumeHookMock.mockReset();+ installSessionStoreMocks([session]);+ await routeProxiedDeliverStep(input);++ expect(resumeHookMock.mock.calls.map(([token]) => token)).toEqual(["child-a", "child-b"]);+ });});describe("dispatchTurnStep", () => {@@ -1016,6 +1109,45 @@ describe("dispatchRuntimeActionsStep", () => {});describe("turnStep", () => {+ it("rejects task completion while input requests remain pending", async () => {+ const session = appendPendingInputBatch({+ requests: [+ {+ action: {+ callId: "call-pending-approval",+ input: {},+ kind: "tool-call",+ toolName: "confirm",+ },+ kind: "tool-approval",+ prompt: "Approve?",+ requestId: "request-pending-approval",+ },+ ],+ responseMessages: [],+ session: createStubSession(),+ });+ installSessionStoreMocks([session]);+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {+ return async (stepSession): Promise<StepResult> => ({+ next: { done: true, output: "must not complete" },+ session: stepSession,+ });+ });++ await expect(+ turnStep({+ input: {+ kind: "deliver",+ payloads: [{ message: "unrelated message" }],+ },+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext("task"),+ sessionState: createStubSessionState(),+ }),+ ).rejects.toThrow("Task mode cannot complete while input requests remain pending.");+ });+it("uses the selected dynamic subagent model for execution identity", async () => {const session = createStubSession();installSessionStoreMocks([session]);@@ -1194,6 +1326,50 @@ describe("turnStep", () => {});});+ it("carries a settled turn while an older input batch remains pending", async () => {+ const session = appendPendingInputBatch({+ requests: [+ {+ action: {+ callId: "call-existing-input",+ input: {},+ kind: "tool-call",+ toolName: "confirm",+ },+ kind: "question",+ prompt: "Continue?",+ requestId: "request-existing-input",+ },+ ],+ responseMessages: [],+ session: createStubSession(),+ });+ installSessionStoreMocks([session]);+ vi.mocked(createExecutionNodeStep).mockImplementation(() => {+ return async (stepSession): Promise<StepResult> => ({+ next: null,+ session: stepSession,+ settledTurn: { output: "settled while approval remains open" },+ });+ });++ const result = await turnStep({+ input: {+ kind: "deliver",+ payloads: [{ message: "unrelated message" }],+ },+ parentWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(result).toMatchObject({+ action: "park",+ hasPendingInputBatch: true,+ settled: { output: "settled while approval remains open" },+ });+ });+it.each([{name: "authorization",@@ -1218,7 +1394,7 @@ describe("turnStep", () => {{name: "input batch",withPending: (session: HarnessSession): HarnessSession =>- setPendingInputBatch({+ appendPendingInputBatch({requests: [{action: {@@ -1253,14 +1429,13 @@ describe("turnStep", () => {session,}),},- ])("does not attach settled output while a $name remains pending", async ({ withPending }) => {+ ])("does not infer settled output from a pending $name", async ({ withPending }) => {const session = createStubSession();installSessionStoreMocks([session]);vi.mocked(createExecutionNodeStep).mockImplementation(() => {return async (stepSession): Promise<StepResult> => ({next: null,session: withPending(stepSession),- settledTurn: { output: "must stay gated" },});});diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex bbcc2913e..bcda76f5f 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -68,6 +68,7 @@ import {createDurableSessionState,type DurableSessionState,readDurableSession,+ replaceDurableSessionSnapshot,} from "#execution/durable-session-store.js";import {createTurnWorkflowInput,@@ -76,6 +77,7 @@ import {} from "#execution/durable-session-migrations/turn-workflow.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";import { routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";+import { retireProxyInputRequests } from "#harness/proxy-input-requests.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import { recordSubagentUsageSpans } from "#execution/subagent-usage-span.js";import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";@@ -90,6 +92,9 @@ import {} from "#execution/workflow-runtime.js";import { resumeHook } from "#internal/workflow/runtime.js";+const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE =+ "Task mode cannot complete while input requests remain pending.";+/*** Result of one durable harness step, consumed by the turn workflow.*@@ -463,6 +468,10 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResutypeof stepResult.next === "object" &&"done" in stepResult.next) {+ if (mode === "task" && hasPendingInputBatch(stepResult.session.state)) {+ writer.releaseLock();+ throw new Error(TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE);+ }await writer.close();const sessionTotals = getTurnUsageState(stepResult.session.state)?.session;return {@@ -498,21 +507,11 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst pending = derivePendingState(stepResult.session);- // A park is idle when the turn stopped because it finished, not because- // it is blocked on an authorization grant, a queued input batch, or- // runtime-action dispatch.- const isIdlePark =- !pending.hasPendingAuthorization &&- !pending.hasPendingInputBatch &&- (pending.pendingRuntimeActionKeys?.length ?? 0) === 0;-- // A settled answer crosses the park boundary only at an idle park: the- // driver forwards it to the delegated caller (notify-then-park), and- // forwarding from a blocked park would report the turn as finished while- // it still waits on pending work. `usage` carries only this turn's- // delta: the take marks the totals reported, so the next settled turn- // of a persistent child never re-reports earlier spend.- if (isIdlePark && stepResult.settledTurn !== undefined) {+ // `settledTurn` is the harness's explicit settlement verdict. Pending+ // state may predate this turn, while newly created parks omit the verdict.+ // `usage` carries only this turn's delta: the take marks the totals+ // reported, so a persistent child never re-reports earlier spend.+ if (stepResult.settledTurn !== undefined) {const { delta, session: reportedSession } = takeSessionUsageDelta(stepResult.session);return {action: "park",@@ -610,17 +609,20 @@ export function resolveEffectiveOutputSchema(input: {export type RoutedDeliverResult =| {readonly kind: "cancel-turn";+ readonly sessionState: DurableSessionState;}| {readonly kind: "continue";/** `undefined` when the entire payload was routed to descendants. */readonly remainder: DeliverPayload | undefined;+ readonly sessionState: DurableSessionState;};/*** Splits an inbound deliver payload into parent-local and* proxied-child buckets and forwards the child buckets via- * `resumeHook`. Read-only: never appends a snapshot.+ * `resumeHook`. Successfully forwarded request IDs are retired in the+ * returned snapshot so later deliveries cannot route through stale entries.*/export async function routeProxiedDeliverStep(input: {readonly auth?: SessionAuthContext | null;@@ -630,7 +632,7 @@ export async function routeProxiedDeliverStep(input: {}): Promise<RoutedDeliverResult> {"use step";- const durableSession = await readDurableSession(input.sessionState);+ let durableSession = await readDurableSession(input.sessionState);const routed = routeDeliverPayload({payload: input.payload,state: durableSession.state,@@ -643,9 +645,17 @@ export async function routeProxiedDeliverStep(input: {forChild.childContinuationToken,sendCommandToDelivery({ auth: input.auth, kind: "send", payload: forChild.payload }),);+ durableSession = retireProxyInputRequests(durableSession, forChild.retireRequestIds);}- return routed.parentAction ?? { kind: "continue", remainder: routed.forSelf };+ const sessionState =+ routed.forChildren.length === 0+ ? input.sessionState+ : replaceDurableSessionSnapshot({ session: durableSession, state: input.sessionState });++ return routed.parentAction === undefined+ ? { kind: "continue", remainder: routed.forSelf, sessionState }+ : { ...routed.parentAction, sessionState };}/** Starts a per-turn child workflow for the current driver session. */diff --git a/packages/eve/src/harness/hitl/approval-input-requests.ts b/packages/eve/src/harness/hitl/approval-input-requests.tsnew file mode 100644index 000000000..22ddc24ad--- /dev/null+++ b/packages/eve/src/harness/hitl/approval-input-requests.ts@@ -0,0 +1,295 @@+import type { ModelMessage } from "ai";++import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";+import type { InputRequest, InputResponse } from "#runtime/input/types.js";+import { isApprovalRequest } from "#harness/input-request-class.js";+import type { PendingInputBatch } from "#harness/pending-input-batches.js";+import {+ queueDeferredStepInput,+ removePendingInputBatches,+} from "#harness/pending-input-batches.js";+import {+ appendResolvedBatchTranscript,+ compactStepInput,+ finishResolvedInput,+ responsesForBatches,+} from "#harness/hitl/pending-input-resolution.js";+import type {+ InputDomainResolverInput,+ ResolvedInputActionBatch,+ ResolvePendingInputResult,+ ToolResponsePart,+} from "#harness/hitl/pending-input-resolution.js";+import {+ buildQuestionToolResponsePart,+ findAnsweredQuestionBatches,+ resolveQuestionBatches,+} from "#harness/hitl/question-input-requests.js";+import type { QuestionInputRequest } from "#harness/hitl/question-input-requests.js";+import type { HarnessSession } from "#harness/types.js";++const APPROVED_TOOLS_KEY = "eve.runtime.hitl.approvedTools";+const IGNORED_INPUT_REASON = "Ignored because the user continued without responding.";+const TOOL_EXECUTION_DENIED_CODE = "TOOL_EXECUTION_DENIED";+const TOOL_EXECUTION_DENIED_MESSAGE = "Tool execution was denied.";+const TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE = "Invalid approval response.";++type ApprovalTerminalStatus = "approved" | "denied" | "ignored" | "invalid";+type ToolApprovalInputRequest = InputRequest & { readonly kind: "tool-approval" };++export type RejectedActionBatch = ResolvedInputActionBatch;++export function hasAnsweredApprovalBatch(+ batches: readonly PendingInputBatch[],+ responses: readonly InputResponse[],+): boolean {+ const responseIds = new Set(responses.map((response) => response.requestId));+ return batches.some((batch) =>+ batch.requests.every(+ (request) => !isApprovalRequest(request) || responseIds.has(request.requestId),+ ),+ );+}++export function resolveApprovalInputBatches(+ input: InputDomainResolverInput & {+ readonly approvalBatches: readonly PendingInputBatch[];+ readonly questionBatches: readonly PendingInputBatch[];+ readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;+ },+): ResolvePendingInputResult {+ const responseIds = new Set(input.responses.map((response) => response.requestId));+ const answeredApprovalBatches = new Set(+ input.approvalBatches.filter((batch) =>+ batch.requests.every(+ (request) => !isApprovalRequest(request) || responseIds.has(request.requestId),+ ),+ ),+ );+ const answeredQuestionBatches = new Set(+ findAnsweredQuestionBatches(input.questionBatches, input.responses),+ );+ let resolvedBatches = input.batches.filter(+ (batch) => answeredApprovalBatches.has(batch) || answeredQuestionBatches.has(batch),+ );+ const firstApprovalIndex = resolvedBatches.findIndex((batch) =>+ batch.requests.some((request) => isApprovalRequest(request)),+ );+ if (firstApprovalIndex >= 0) {+ // Anything after this batch would hide its approval response from AI+ // SDK's tail-tool-message scan. Its responses replay on the next step.+ resolvedBatches = resolvedBatches.slice(0, firstApprovalIndex + 1);+ }++ const openBatches = input.batches.filter((batch) => !resolvedBatches.includes(batch));+ const leftoverResponses = responsesForBatches(input.responses, openBatches);++ if (resolvedBatches.length === 0) {+ if (input.resolvedStepInput?.message === undefined) {+ return {+ outcome: "unresolved",+ messages: [...input.baseHistory],+ session: queueDeferredStepInput(input.session, compactStepInput(input.resolvedStepInput)),+ };+ }++ const session =+ leftoverResponses.length === 0+ ? input.session+ : queueDeferredStepInput(input.session, { inputResponses: leftoverResponses });+ return {+ consumedMessage: input.resolvedStepInput.messageConsumed,+ outcome: "continue",+ messages: [...input.baseHistory],+ session,+ };+ }++ const approvalBatch = resolvedBatches.find((batch) =>+ batch.requests.some((request) => isApprovalRequest(request)),+ );+ const questionBatches = resolvedBatches.filter((batch) => batch !== approvalBatch);+ const questions = resolveQuestionBatches({+ batches: questionBatches,+ messages: [...input.baseHistory],+ responses: input.responses,+ });+ const approval =+ approvalBatch === undefined+ ? { messages: questions, session: input.session }+ : resolveApprovalBatch({+ batch: approvalBatch,+ messages: questions,+ resolveApprovalKey: input.resolveApprovalKey,+ responses: input.responses,+ session: input.session,+ });++ return finishResolvedInput({+ deferTurnInput: approvalBatch !== undefined || input.deferTurnInput,+ leftoverResponses,+ messages: approval.messages,+ rejectedActions: approval.rejectedActions,+ resolvedStepInput: input.resolvedStepInput,+ session: removePendingInputBatches(approval.session, resolvedBatches),+ });+}++/** Returns tool approval keys recorded during this session. */+export function getApprovedTools(session: HarnessSession): ReadonlySet<string> {+ const value = session.state?.[APPROVED_TOOLS_KEY];+ return Array.isArray(value) ? new Set(value as string[]) : new Set();+}++function resolveApprovalBatch(input: {+ readonly batch: PendingInputBatch;+ readonly messages: ModelMessage[];+ readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;+ readonly responses: readonly InputResponse[];+ readonly session: HarnessSession;+}): ResolvedApprovalBatch {+ const session = recordApprovedTools({+ pendingBatch: input.batch,+ resolveApprovalKey: input.resolveApprovalKey,+ responses: input.responses,+ session: input.session,+ });+ const toolParts = buildApprovalBatchToolResponseParts(input.batch, input.responses);+ appendResolvedBatchTranscript(input.messages, input.batch, toolParts);+ const rejected = buildRejectedActionBatch(input.batch, input.responses);++ return {+ messages: input.messages,+ rejectedActions: rejected === undefined ? undefined : [rejected],+ session,+ };+}++type ResolvedApprovalBatch = {+ readonly messages: ModelMessage[];+ readonly rejectedActions?: readonly RejectedActionBatch[];+ readonly session: HarnessSession;+};++function recordApprovedTools(input: {+ readonly pendingBatch: PendingInputBatch;+ readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;+ readonly responses: readonly InputResponse[];+ readonly session: HarnessSession;+}): HarnessSession {+ const approvedIds = new Set(+ input.responses.filter((response) => response.optionId === "approve").map((r) => r.requestId),+ );+ const newKeys = input.pendingBatch.requests+ .filter((request) => isApprovalRequest(request) && approvedIds.has(request.requestId))+ .map((request) => input.resolveApprovalKey?.(request) ?? request.action.toolName);++ if (newKeys.length === 0) return input.session;++ const state = { ...input.session.state };+ state[APPROVED_TOOLS_KEY] = [...new Set([...getApprovedTools(input.session), ...newKeys])];+ return { ...input.session, state };+}++function resolveApprovalOutcome(response: InputResponse | undefined): {+ readonly approved: boolean;+ readonly reason: string | undefined;+ readonly status: ApprovalTerminalStatus;+} {+ if (response === undefined) {+ return { approved: false, reason: IGNORED_INPUT_REASON, status: "ignored" };+ }+ if (response.optionId === "approve") {+ return { approved: true, reason: undefined, status: "approved" };+ }+ if (response.optionId === "cancel") {+ return { approved: false, reason: TOOL_EXECUTION_DENIED_MESSAGE, status: "denied" };+ }+ return {+ approved: false,+ reason: TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE,+ status: "invalid",+ };+}++function buildRejectedActionBatch(+ batch: PendingInputBatch,+ responses: readonly InputResponse[],+): RejectedActionBatch | undefined {+ if (batch.event === undefined) return undefined;++ const responseMap = new Map(responses.map((response) => [response.requestId, response]));+ const results: RuntimeToolResultActionResult[] = [];+ for (const request of batch.requests) {+ if (!isApprovalRequest(request)) continue;++ const { approved, reason, status } = resolveApprovalOutcome(responseMap.get(request.requestId));+ if (approved) continue;++ results.push({+ callId: request.action.callId,+ isError: true,+ kind: "tool-result",+ output: {+ approval: { requestId: request.requestId, status },+ code: TOOL_EXECUTION_DENIED_CODE,+ message: reason ?? TOOL_EXECUTION_DENIED_MESSAGE,+ tool: { result: "not_run" },+ },+ toolName: request.action.toolName,+ });+ }++ return results.length > 0 ? { event: batch.event, results } : undefined;+}++function buildApprovalBatchToolResponseParts(+ batch: PendingInputBatch,+ responses: readonly InputResponse[],+): ToolResponsePart[] {+ const responseMap = new Map(responses.map((response) => [response.requestId, response]));+ const parts: ToolResponsePart[] = [];+ for (const request of batch.requests) {+ const response = responseMap.get(request.requestId);+ switch (request.kind) {+ case "tool-approval":+ parts.push(+ ...buildApprovalToolResponseParts(request as ToolApprovalInputRequest, response),+ );+ break;+ case "question":+ parts.push(buildQuestionToolResponsePart(request as QuestionInputRequest, response));+ break;+ case "session-limit":+ throw new TypeError(+ "Session-limit pending input batches must contain only session-limit requests.",+ );+ default: {+ const unhandled: never = request.kind;+ throw new TypeError(`Unhandled pending input request kind: ${String(unhandled)}`);+ }+ }+ }+ return parts;+}++function buildApprovalToolResponseParts(+ request: ToolApprovalInputRequest,+ response: InputResponse | undefined,+): ToolResponsePart[] {+ const { approved, reason } = resolveApprovalOutcome(response);+ const parts: ToolResponsePart[] = [+ { approvalId: request.requestId, approved, reason, type: "tool-approval-response" },+ ];+ // Persist an explicit denial result because AI SDK strips historical+ // approval responses during provider prompt conversion.+ if (!approved) {+ parts.push({+ output: { type: "execution-denied", reason },+ toolCallId: request.action.callId,+ toolName: request.action.toolName,+ type: "tool-result",+ });+ }+ return parts;+}diff --git a/packages/eve/src/harness/hitl/pending-input-resolution.ts b/packages/eve/src/harness/hitl/pending-input-resolution.tsnew file mode 100644index 000000000..a2726a2d3--- /dev/null+++ b/packages/eve/src/harness/hitl/pending-input-resolution.ts@@ -0,0 +1,133 @@+import type { ModelMessage } from "ai";++import type { RuntimeToolResultActionResult } from "#runtime/actions/types.js";+import type { InputResponse } from "#runtime/input/types.js";+import type { PendingInputBatch, PendingInputBatchEvent } from "#harness/pending-input-batches.js";+import { queueDeferredStepInput } from "#harness/pending-input-batches.js";+import type { HarnessSession, StepInput } from "#harness/types.js";++export type ToolResponsePart = Extract<ModelMessage, { role: "tool" }>["content"][number];++/** Action results from one resolved batch, attributed to their originating turn. */+export interface ResolvedInputActionBatch {+ readonly event: PendingInputBatchEvent;+ readonly results: readonly RuntimeToolResultActionResult[];+}++export type ResolvedStepInput = StepInput & { readonly messageConsumed?: boolean };++export type InputDomainResolverInput = {+ readonly baseHistory: ModelMessage[];+ readonly batches: readonly PendingInputBatch[];+ readonly deferTurnInput: boolean;+ readonly resolvedStepInput: ResolvedStepInput | undefined;+ readonly responses: readonly InputResponse[];+ readonly session: HarnessSession;+};++export type ResolvePendingInputResult = {+ readonly consumedMessage?: boolean;+ readonly deferredContext?: boolean;+ readonly deferredMessage?: boolean;+ /** Present when a session-limit continuation prompt was resolved. */+ readonly limitContinuation?: { readonly granted: boolean };+ readonly outcome: "resolved" | "continue" | "unresolved";+ readonly messages: ModelMessage[];+ readonly rejectedActions?: readonly ResolvedInputActionBatch[];+ readonly session: HarnessSession;+};++export function responsesForBatches(+ responses: readonly InputResponse[],+ batches: readonly PendingInputBatch[],+): readonly InputResponse[] {+ return responses.filter((response) =>+ batches.some((batch) =>+ batch.requests.some((request) => request.requestId === response.requestId),+ ),+ );+}++export function appendResolvedBatchTranscript(+ messages: ModelMessage[],+ batch: PendingInputBatch,+ toolParts: readonly ToolResponsePart[],+): void {+ messages.push(...batch.responseMessages);+ if (toolParts.length > 0) {+ messages.push({ content: [...toolParts], role: "tool" });+ }+}++export function finishResolvedInput(input: {+ readonly deferTurnInput: boolean;+ readonly leftoverResponses: readonly InputResponse[];+ readonly limitContinuation?: { readonly granted: boolean };+ readonly messages: ModelMessage[];+ readonly rejectedActions?: readonly ResolvedInputActionBatch[];+ readonly resolvedStepInput: ResolvedStepInput | undefined;+ readonly session: HarnessSession;+}): ResolvePendingInputResult {+ // AI SDK collects approval responses only from the tail tool message. Turn+ // input must replay after that isolated approval response.+ const deferredInput: {+ context?: StepInput["context"];+ inputResponses?: StepInput["inputResponses"];+ message?: StepInput["message"];+ } = {};+ if (input.leftoverResponses.length > 0) {+ deferredInput.inputResponses = input.leftoverResponses;+ }+ if (input.deferTurnInput) {+ if ((input.resolvedStepInput?.context?.length ?? 0) > 0) {+ deferredInput.context = input.resolvedStepInput?.context;+ }+ if (input.resolvedStepInput?.message !== undefined) {+ deferredInput.message = input.resolvedStepInput.message;+ }+ }++ if (Object.keys(deferredInput).length > 0) {+ return {+ consumedMessage: input.resolvedStepInput?.messageConsumed,+ deferredContext: deferredInput.context === undefined ? undefined : true,+ deferredMessage: deferredInput.message === undefined ? undefined : true,+ limitContinuation: input.limitContinuation,+ outcome: "resolved",+ messages: input.messages,+ rejectedActions: input.rejectedActions,+ session: queueDeferredStepInput(input.session, deferredInput),+ };+ }++ return {+ consumedMessage: input.resolvedStepInput?.messageConsumed,+ limitContinuation: input.limitContinuation,+ outcome: "resolved",+ messages: input.messages,+ rejectedActions: input.rejectedActions,+ session: input.session,+ };+}++export function compactStepInput(input: ResolvedStepInput | undefined): ResolvedStepInput {+ if (input === undefined) {+ return {};+ }++ const result: {+ context?: StepInput["context"];+ inputResponses?: StepInput["inputResponses"];+ message?: StepInput["message"];+ messageConsumed?: boolean;+ outputSchema?: StepInput["outputSchema"];+ } = {};++ if ((input.context?.length ?? 0) > 0) result.context = input.context;+ if ((input.inputResponses?.length ?? 0) > 0) result.inputResponses = input.inputResponses;+ if (input.message !== undefined) result.message = input.message;+ if (input.messageConsumed === true) result.messageConsumed = true;+ if (input.outputSchema !== undefined) result.outputSchema = input.outputSchema;++ return result;+}diff --git a/packages/eve/src/harness/hitl/question-input-requests.ts b/packages/eve/src/harness/hitl/question-input-requests.tsnew file mode 100644index 000000000..321badd42--- /dev/null+++ b/packages/eve/src/harness/hitl/question-input-requests.ts@@ -0,0 +1,127 @@+import type { ModelMessage } from "ai";++import type { InputRequest, InputResponse } from "#runtime/input/types.js";+import type { PendingInputBatch } from "#harness/pending-input-batches.js";+import {+ queueDeferredStepInput,+ removePendingInputBatches,+} from "#harness/pending-input-batches.js";+import {+ appendResolvedBatchTranscript,+ compactStepInput,+ finishResolvedInput,+ responsesForBatches,+} from "#harness/hitl/pending-input-resolution.js";+import type {+ InputDomainResolverInput,+ ResolvePendingInputResult,+ ToolResponsePart,+} from "#harness/hitl/pending-input-resolution.js";++export type QuestionInputRequest = InputRequest & { readonly kind: "question" };++export function resolveQuestionOnlyInputBatches(+ input: InputDomainResolverInput,+): ResolvePendingInputResult {+ const resolvedBatches = findAnsweredQuestionBatches(input.batches, input.responses);+ const openBatches = input.batches.filter((batch) => !resolvedBatches.includes(batch));+ const leftoverResponses = responsesForBatches(input.responses, openBatches);++ if (resolvedBatches.length === 0) {+ if (input.resolvedStepInput?.message === undefined) {+ return {+ outcome: "unresolved",+ messages: [...input.baseHistory],+ session: queueDeferredStepInput(input.session, compactStepInput(input.resolvedStepInput)),+ };+ }++ const sole = input.batches.length === 1 ? input.batches[0] : undefined;+ if (sole === undefined) {+ const session =+ leftoverResponses.length === 0+ ? input.session+ : queueDeferredStepInput(input.session, { inputResponses: leftoverResponses });+ return {+ consumedMessage: input.resolvedStepInput.messageConsumed,+ outcome: "continue",+ messages: [...input.baseHistory],+ session,+ };+ }++ // One question-only batch keeps the dismiss-and-continue behavior.+ const messages = resolveQuestionBatches({+ batches: [sole],+ messages: [...input.baseHistory],+ responses: [],+ });+ return {+ consumedMessage: input.resolvedStepInput.messageConsumed,+ outcome: "resolved",+ messages,+ session: removePendingInputBatches(input.session, [sole]),+ };+ }++ const messages = resolveQuestionBatches({+ batches: resolvedBatches,+ messages: [...input.baseHistory],+ responses: input.responses,+ });++ return finishResolvedInput({+ deferTurnInput: input.deferTurnInput,+ leftoverResponses,+ messages,+ resolvedStepInput: input.resolvedStepInput,+ session: removePendingInputBatches(input.session, resolvedBatches),+ });+}++export function findAnsweredQuestionBatches(+ batches: readonly PendingInputBatch[],+ responses: readonly InputResponse[],+): PendingInputBatch[] {+ const responseIds = new Set(responses.map((response) => response.requestId));+ return batches.filter((batch) =>+ batch.requests.some((request) => responseIds.has(request.requestId)),+ );+}++export function resolveQuestionBatches(input: {+ readonly batches: readonly PendingInputBatch[];+ readonly messages: ModelMessage[];+ readonly responses: readonly InputResponse[];+}): ModelMessage[] {+ const responseMap = new Map(input.responses.map((response) => [response.requestId, response]));+ for (const batch of input.batches) {+ const toolParts = batch.requests.map((request) =>+ buildQuestionToolResponsePart(+ request as QuestionInputRequest,+ responseMap.get(request.requestId),+ ),+ );+ appendResolvedBatchTranscript(input.messages, batch, toolParts);+ }++ return input.messages;+}++export function buildQuestionToolResponsePart(+ request: QuestionInputRequest,+ response: InputResponse | undefined,+): ToolResponsePart {+ return {+ output: {+ type: "json",+ value:+ response !== undefined+ ? { optionId: response.optionId, text: response.text, status: "answered" }+ : { status: "ignored" },+ },+ toolCallId: request.action.callId,+ toolName: request.action.toolName,+ type: "tool-result",+ };+}diff --git a/packages/eve/src/harness/hitl/session-limit-input-requests.ts b/packages/eve/src/harness/hitl/session-limit-input-requests.tsnew file mode 100644index 000000000..eccc6e9e1--- /dev/null+++ b/packages/eve/src/harness/hitl/session-limit-input-requests.ts@@ -0,0 +1,85 @@+import type { PendingInputBatch } from "#harness/pending-input-batches.js";+import {+ getPendingInputBatches,+ queueDeferredStepInput,+ removePendingInputBatches,+} from "#harness/pending-input-batches.js";+import {+ appendResolvedBatchTranscript,+ compactStepInput,+ finishResolvedInput,+ responsesForBatches,+} from "#harness/hitl/pending-input-resolution.js";+import type {+ InputDomainResolverInput,+ ResolvePendingInputResult,+} from "#harness/hitl/pending-input-resolution.js";+import {+ isSessionLimitContinuationRequest,+ resolveSessionLimitContinuation,+} from "#harness/session-limit-continuation.js";+import type { HarnessSession } from "#harness/types.js";++const SESSION_LIMIT_BATCH_INVARIANT_MESSAGE =+ "Session-limit pending input batches must contain only session-limit requests.";++/** Returns whether this is a valid session-limit batch and rejects mixed ownership. */+export function isSessionLimitInputBatch(batch: PendingInputBatch): boolean {+ const hasSessionLimit = batch.requests.some((request) => request.kind === "session-limit");+ if (hasSessionLimit && batch.requests.some((request) => request.kind !== "session-limit")) {+ throw new TypeError(SESSION_LIMIT_BATCH_INVARIANT_MESSAGE);+ }+ return hasSessionLimit;+}++export function resolveSessionLimitInput(+ input: InputDomainResolverInput & { readonly pendingBatch: PendingInputBatch },+): ResolvePendingInputResult {+ const responseIds = new Set(input.responses.map((response) => response.requestId));+ const answered =+ input.pendingBatch.requests.some((request) => responseIds.has(request.requestId)) &&+ input.pendingBatch.requests.every((request) => responseIds.has(request.requestId));+ if (!answered) {+ return {+ deferredMessage: true,+ outcome: "unresolved",+ messages: [...input.baseHistory],+ session: queueDeferredStepInput(input.session, compactStepInput(input.resolvedStepInput)),+ };+ }++ const openBatches = input.batches.filter((batch) => batch !== input.pendingBatch);+ const leftoverResponses = responsesForBatches(input.responses, openBatches);+ const limitBlocked = openBatches.some((batch) =>+ batch.requests.some((request) => isSessionLimitContinuationRequest(request)),+ );+ const messages = [...input.baseHistory];+ appendResolvedBatchTranscript(messages, input.pendingBatch, []);+ const session = removePendingInputBatches(input.session, [input.pendingBatch]);+ const limitContinuation = resolveSessionLimitContinuation({+ requests: input.pendingBatch.requests,+ responses: input.responses,+ });++ return finishResolvedInput({+ deferTurnInput: input.deferTurnInput || limitBlocked,+ leftoverResponses,+ limitContinuation,+ messages,+ resolvedStepInput: input.resolvedStepInput,+ session,+ });+}++/** Drops only harness-authored session-limit prompts from a parked session. */+export function clearPendingSessionLimitPrompt(session: HarnessSession): HarnessSession {+ const dropped = getPendingInputBatches(session.state).filter(+ (batch) =>+ batch.requests.length > 0 &&+ batch.requests.every((request) => isSessionLimitContinuationRequest(request)),+ );+ if (dropped.length === 0) {+ return session;+ }+ return removePendingInputBatches(session, dropped);+}diff --git a/packages/eve/src/harness/input-requests.test.ts b/packages/eve/src/harness/input-requests.test.tsindex d4a36c44f..af06722b8 100644--- a/packages/eve/src/harness/input-requests.test.ts+++ b/packages/eve/src/harness/input-requests.test.ts@@ -11,10 +11,12 @@ import {consumeDeferredStepInput,createRuntimeToolCallActionFromToolCall,getApprovedTools,+ getPendingInputRequestIds,hasDeferredStepInput,+ hasPendingInputBatch,hasStepInput,resolvePendingInput,- setPendingInputBatch,+ appendPendingInputBatch,} from "#harness/input-requests.js";import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";import { buildToolApproval, buildToolSet } from "#harness/tools.js";@@ -119,7 +121,7 @@ describe("createRuntimeToolCallActionFromToolCall", () => {describe("resolvePendingInput", () => {it("keeps approvals pending when another request is answered first", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -196,7 +198,7 @@ describe("resolvePendingInput", () => {});it("resolves freeform question input from a follow-up message", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -257,7 +259,7 @@ describe("resolvePendingInput", () => {});it("defers a follow-up message until after tool approvals are resolved", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -325,7 +327,7 @@ describe("resolvePendingInput", () => {});it("defers channel context until after tool approvals are resolved", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -385,7 +387,7 @@ describe("resolvePendingInput", () => {});it("resolves approval when follow-up text matches an option", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -450,7 +452,7 @@ describe("resolvePendingInput", () => {});it("records compound approval key when resolveApprovalKey is provided", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -517,7 +519,7 @@ describe("resolvePendingInput", () => {* unmatched. The harness must emit the matching tool-result* itself so persisted history is replay-safe.*/- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -586,7 +588,7 @@ describe("resolvePendingInput", () => {});it("returns a rejected action for an explicitly denied approval", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },requests: [{@@ -619,32 +621,34 @@ describe("resolvePendingInput", () => {});expect(result.outcome).toBe("resolved");- expect(result.rejectedActions).toEqual({- event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },- results: [- {- callId: "approval-call",- isError: true,- kind: "tool-result",- output: {- approval: {- requestId: "approval-1",- status: "denied",- },- code: "TOOL_EXECUTION_DENIED",- message: "Tool execution was denied.",- tool: {- result: "not_run",+ expect(result.rejectedActions).toEqual([+ {+ event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },+ results: [+ {+ callId: "approval-call",+ isError: true,+ kind: "tool-result",+ output: {+ approval: {+ requestId: "approval-1",+ status: "denied",+ },+ code: "TOOL_EXECUTION_DENIED",+ message: "Tool execution was denied.",+ tool: {+ result: "not_run",+ },},+ toolName: "bash",},- toolName: "bash",- },- ],- });+ ],+ },+ ]);});it("does not return a rejected action when an approval is granted", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },requests: [{@@ -680,8 +684,55 @@ describe("resolvePendingInput", () => {expect(result.rejectedActions).toBeUndefined();});- it("keeps a pending approval and queues an unrelated follow-up message", () => {- const session = setPendingInputBatch({+ it("does not retain approval when a deferred response is superseded", () => {+ const approval = (requestId: string, callId: string): InputRequest => ({+ action: { callId, input: { command: "pwd" }, kind: "tool-call", toolName: "bash" },+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId,+ });+ const session = appendPendingInputBatch({+ event: { sequence: 5, stepIndex: 1, turnId: "turn_0" },+ requests: [approval("approval-1", "call-1"), approval("approval-2", "call-2")],+ responseMessages: [],+ session: createHarnessSession(),+ });++ const partial = resolvePendingInput({+ session,+ stepInput: { inputResponses: [{ requestId: "approval-1", optionId: "approve" }] },+ });+ const deferred = consumeDeferredStepInput({+ input: {+ inputResponses: [+ { requestId: "approval-1", optionId: "cancel" },+ { requestId: "approval-2", optionId: "approve" },+ ],+ },+ session: partial.session,+ });+ const result = resolvePendingInput({+ resolveApprovalKey: (request) => request.requestId,+ session: deferred.session,+ stepInput: deferred.input,+ });++ expect(getApprovedTools(result.session)).toEqual(new Set(["approval-2"]));+ expect(result.rejectedActions?.[0]?.results).toEqual([+ expect.objectContaining({+ callId: "call-1",+ }),+ ]);+ });++ it("keeps a pending approval open while an unrelated follow-up message continues", () => {+ const session = appendPendingInputBatch({event: { sequence: 7, stepIndex: 2, turnId: "turn_1" },requests: [{@@ -711,19 +762,45 @@ describe("resolvePendingInput", () => {session,});- expect(result.outcome).toBe("unresolved");+ // The message runs as an ordinary turn; the approval stays answerable.+ expect(result.outcome).toBe("continue");expect(result.rejectedActions).toBeUndefined();expect(result.messages).toEqual([{ content: "previous", role: "user" }]);- expect(hasDeferredStepInput(result.session)).toBe(true);+ expect(hasDeferredStepInput(result.session)).toBe(false);+ expect(getPendingInputRequestIds(result.session.state)).toEqual(new Set(["approval-1"]));+ });- const deferred = consumeDeferredStepInput({ session: result.session });- expect(deferred.input).toEqual({- message: "Never mind, do something else.",+ it("preserves context-only input while a pending batch stays open", () => {+ const session = appendPendingInputBatch({+ requests: [+ {+ action: {+ callId: "approval-call",+ input: { command: "pwd" },+ kind: "tool-call",+ toolName: "bash",+ },+ kind: "tool-approval",+ prompt: "Approve tool call: bash",+ requestId: "approval-1",+ },+ ],+ responseMessages: [],+ session: createHarnessSession(),});++ const result = resolvePendingInput({+ session,+ stepInput: { context: ["channel context"] },+ });+ const deferred = consumeDeferredStepInput({ session: result.session });++ expect(result.outcome).toBe("unresolved");+ expect(deferred.input).toEqual({ context: ["channel context"] });});it("falls back to tool name when no approvalKey is provided", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -783,7 +860,7 @@ describe("resolvePendingInput", () => {// survive on session.state across the park, so approval returns// "not-applicable" and the user is never asked to approve a second time.// See research/per-tool-auth-known-issues.md, issue 3.- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -880,9 +957,221 @@ describe("resolvePendingInput", () => {});});+describe("pending input batch collection", () => {+ function approvalRequest(requestId: string, callId: string): InputRequest {+ return {+ action: { callId, input: { command: "pwd" }, kind: "tool-call", toolName: "bash" },+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId,+ };+ }++ function questionRequest(requestId: string, callId: string): InputRequest {+ return {+ action: {+ callId,+ input: { prompt: "Pick one." },+ kind: "tool-call",+ toolName: "ask_question",+ },+ display: "select",+ kind: "question",+ options: [+ { id: "red", label: "Red" },+ { id: "blue", label: "Blue" },+ ],+ prompt: "Pick one.",+ requestId,+ };+ }++ function batchOutput(callId: string, toolName: string): ModelMessage {+ return {+ content: [{ input: {}, toolCallId: callId, toolName, type: "tool-call" }],+ role: "assistant",+ };+ }++ it("reads a legacy singleton batch and rewrites it as a list", () => {+ const legacySession: HarnessSession = {+ ...createHarnessSession(),+ state: {+ "eve.runtime.pendingInputBatch": {+ requests: [approvalRequest("approval-1", "call-1")],+ responseMessages: [batchOutput("call-1", "bash")],+ },+ },+ };++ expect(getPendingInputRequestIds(legacySession.state)).toEqual(new Set(["approval-1"]));++ const appended = appendPendingInputBatch({+ requests: [questionRequest("question-1", "call-2")],+ responseMessages: [batchOutput("call-2", "ask_question")],+ session: legacySession,+ });+ expect(appended.state?.["eve.runtime.pendingInputBatch"]).toBeUndefined();+ expect(getPendingInputRequestIds(appended.state)).toEqual(+ new Set(["approval-1", "question-1"]),+ );++ const result = resolvePendingInput({+ session: legacySession,+ stepInput: { inputResponses: [{ requestId: "approval-1", optionId: "approve" }] },+ });+ expect(result.outcome).toBe("resolved");+ expect(result.session.state?.["eve.runtime.pendingInputBatch"]).toBeUndefined();+ expect(hasPendingInputBatch(result.session.state)).toBe(false);+ });++ it("keeps earlier batches open while a later batch resolves", () => {+ let session = appendPendingInputBatch({+ requests: [approvalRequest("approval-1", "call-1")],+ responseMessages: [batchOutput("call-1", "bash")],+ session: createHarnessSession(),+ });+ session = appendPendingInputBatch({+ requests: [questionRequest("question-1", "call-2")],+ responseMessages: [batchOutput("call-2", "ask_question")],+ session,+ });++ const answered = resolvePendingInput({+ session,+ stepInput: { inputResponses: [{ requestId: "question-1", optionId: "red" }] },+ });+ expect(answered.outcome).toBe("resolved");+ expect(getPendingInputRequestIds(answered.session.state)).toEqual(new Set(["approval-1"]));+ // Only the answered batch's withheld output is restored.+ expect(answered.messages).toEqual([+ { content: "previous", role: "user" },+ batchOutput("call-2", "ask_question"),+ {+ content: [+ {+ output: {+ type: "json",+ value: { optionId: "red", text: undefined, status: "answered" },+ },+ toolCallId: "call-2",+ toolName: "ask_question",+ type: "tool-result",+ },+ ],+ role: "tool",+ },+ ]);++ const approved = resolvePendingInput({+ session: answered.session,+ stepInput: { inputResponses: [{ requestId: "approval-1", optionId: "approve" }] },+ });+ expect(approved.outcome).toBe("resolved");+ expect(hasPendingInputBatch(approved.session.state)).toBe(false);+ });++ it("resolves only the first approval-bearing batch and defers later responses", () => {+ let session = appendPendingInputBatch({+ requests: [approvalRequest("approval-1", "call-1")],+ responseMessages: [batchOutput("call-1", "bash")],+ session: createHarnessSession(),+ });+ session = appendPendingInputBatch({+ requests: [approvalRequest("approval-2", "call-2")],+ responseMessages: [batchOutput("call-2", "bash")],+ session,+ });++ const first = resolvePendingInput({+ session,+ stepInput: {+ inputResponses: [+ { requestId: "approval-1", optionId: "approve" },+ { requestId: "approval-2", optionId: "approve" },+ ],+ },+ });++ expect(first.outcome).toBe("resolved");+ expect(first.messages).toEqual([+ { content: "previous", role: "user" },+ batchOutput("call-1", "bash"),+ {+ content: [+ {+ approvalId: "approval-1",+ approved: true,+ reason: undefined,+ type: "tool-approval-response",+ },+ ],+ role: "tool",+ },+ ]);+ expect(getPendingInputRequestIds(first.session.state)).toEqual(new Set(["approval-2"]));++ const deferred = consumeDeferredStepInput({ session: first.session });+ expect(deferred.input).toEqual({+ inputResponses: [{ requestId: "approval-2", optionId: "approve" }],+ });++ const second = resolvePendingInput({ session: deferred.session, stepInput: deferred.input });+ expect(second.outcome).toBe("resolved");+ expect(second.messages.at(-1)).toMatchObject({+ content: [{ approvalId: "approval-2", approved: true }],+ role: "tool",+ });+ expect(hasPendingInputBatch(second.session.state)).toBe(false);+ });++ it("leaves every batch open when a message arrives with several batches pending", () => {+ let session = appendPendingInputBatch({+ requests: [approvalRequest("approval-1", "call-1")],+ responseMessages: [batchOutput("call-1", "bash")],+ session: createHarnessSession(),+ });+ session = appendPendingInputBatch({+ requests: [questionRequest("question-1", "call-2")],+ responseMessages: [batchOutput("call-2", "ask_question")],+ session,+ });++ const result = resolvePendingInput({ session, stepInput: { message: "keep going" } });++ expect(result.outcome).toBe("continue");+ expect(result.messages).toEqual([{ content: "previous", role: "user" }]);+ expect(hasDeferredStepInput(result.session)).toBe(false);+ expect(getPendingInputRequestIds(result.session.state)).toEqual(+ new Set(["approval-1", "question-1"]),+ );+ });+});+describe("resolvePendingInput with a session-limit continuation batch", () => {+ function approvalRequest(): InputRequest {+ return {+ action: { callId: "call-1", input: { command: "pwd" }, kind: "tool-call", toolName: "bash" },+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId: "approval-1",+ };+ }+function createLimitBatchSession(): HarnessSession {- return setPendingInputBatch({+ return appendPendingInputBatch({requests: [createSessionLimitContinuationRequest({sessionId: "sess-test",@@ -894,6 +1183,24 @@ describe("resolvePendingInput with a session-limit continuation batch", () => {});}+ it("rejects a session-limit batch containing a model-anchored request", () => {+ const session = appendPendingInputBatch({+ requests: [+ createSessionLimitContinuationRequest({+ sessionId: "sess-test",+ violation: { kind: "input", limit: 12, usedTokens: 12 },+ }),+ approvalRequest(),+ ],+ responseMessages: [],+ session: createHarnessSession(),+ });++ expect(() => resolvePendingInput({ session })).toThrow(+ "Session-limit pending input batches must contain only session-limit requests.",+ );+ });+it("resolves a continue answer without appending tool messages", () => {const result = resolvePendingInput({session: createLimitBatchSession(),@@ -936,11 +1243,69 @@ describe("resolvePendingInput with a session-limit continuation batch", () => {const deferred = consumeDeferredStepInput({ session: result.session });expect(deferred.input).toEqual({ message: "also do this other thing" });});++ it("matches text against the limit batch while an approval batch is also open", () => {+ let session = appendPendingInputBatch({+ requests: [approvalRequest()],+ responseMessages: [],+ session: createHarnessSession(),+ });+ session = appendPendingInputBatch({+ requests: [+ createSessionLimitContinuationRequest({+ sessionId: "sess-test",+ violation: { kind: "input", limit: 12, usedTokens: 12 },+ }),+ ],+ responseMessages: [],+ session,+ });++ const result = resolvePendingInput({ session, stepInput: { message: "continue" } });++ expect(result.outcome).toBe("resolved");+ expect(result.limitContinuation).toEqual({ granted: true });+ expect(result.consumedMessage).toBe(true);+ expect(getPendingInputRequestIds(result.session.state)).toEqual(new Set(["approval-1"]));+ expect(hasDeferredStepInput(result.session)).toBe(false);+ });++ it("defers an approval response while the limit batch remains open", () => {+ let session = appendPendingInputBatch({+ requests: [approvalRequest()],+ responseMessages: [],+ session: createHarnessSession(),+ });+ session = appendPendingInputBatch({+ requests: [+ createSessionLimitContinuationRequest({+ sessionId: "sess-test",+ violation: { kind: "input", limit: 12, usedTokens: 12 },+ }),+ ],+ responseMessages: [],+ session,+ });++ const result = resolvePendingInput({+ session,+ stepInput: { inputResponses: [{ requestId: "approval-1", optionId: "approve" }] },+ });++ expect(result.outcome).toBe("unresolved");+ expect(getPendingInputRequestIds(result.session.state)).toEqual(+ new Set(["approval-1", "sess-test:limit:input:12"]),+ );+ const deferred = consumeDeferredStepInput({ session: result.session });+ expect(deferred.input).toEqual({+ inputResponses: [{ requestId: "approval-1", optionId: "approve" }],+ });+ });});describe("clearPendingSessionLimitPrompt", () => {it("drops a pending batch made only of session-limit continuation prompts", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [createSessionLimitContinuationRequest({sessionId: "sess-test",@@ -961,7 +1326,7 @@ describe("clearPendingSessionLimitPrompt", () => {});it("keeps model-anchored batches (tool approvals) intact", () => {- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -975,7 +1340,7 @@ describe("clearPendingSessionLimitPrompt", () => {kind: "tool-approval",options: [{ id: "approve", label: "Yes" },- { id: "deny", label: "No" },+ { id: "cancel", label: "No" },],prompt: "Approve tool call: bash",requestId: "approval-1",@@ -988,9 +1353,11 @@ describe("clearPendingSessionLimitPrompt", () => {const kept = clearPendingSessionLimitPrompt(session);const result = resolvePendingInput({ session: kept, stepInput: { message: "and then this" } });- // The approval still gates the turn: the follow-up defers behind it.- expect(result.outcome).toBe("unresolved");- expect(hasDeferredStepInput(result.session)).toBe(true);+ // The approval batch survives the limit-prompt sweep and stays+ // answerable; the follow-up message continues as an ordinary turn.+ expect(getPendingInputRequestIds(result.session.state)).toEqual(new Set(["approval-1"]));+ expect(result.outcome).toBe("continue");+ expect(hasDeferredStepInput(result.session)).toBe(false);});it("is a no-op without a pending batch", () => {diff --git a/packages/eve/src/harness/input-requests.ts b/packages/eve/src/harness/input-requests.tsindex 786b8ec44..352795b04 100644--- a/packages/eve/src/harness/input-requests.ts+++ b/packages/eve/src/harness/input-requests.ts@@ -1,680 +1,215 @@import type { ModelMessage } from "ai";-import type {- RuntimeToolCallActionRequest,- RuntimeToolResultActionResult,-} from "#runtime/actions/types.js";+import type { RuntimeToolCallActionRequest } from "#runtime/actions/types.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";import { resolveTextToResponses } from "#channel/resolve-text.js";-import { classifyInputRequest, isApprovalRequest } from "#harness/input-request-class.js";-import { coalesceTurnInputs } from "#harness/messages.js";+import {+ getApprovedTools,+ hasAnsweredApprovalBatch,+ resolveApprovalInputBatches,+} from "#harness/hitl/approval-input-requests.js";+import type { RejectedActionBatch } from "#harness/hitl/approval-input-requests.js";+import { isApprovalRequest } from "#harness/input-request-class.js";+import type { PendingInputBatch } from "#harness/pending-input-batches.js";+import { getPendingInputBatches, queueDeferredStepInput } from "#harness/pending-input-batches.js";+import { compactStepInput } from "#harness/hitl/pending-input-resolution.js";+import type {+ ResolvePendingInputResult,+ ResolvedStepInput,+} from "#harness/hitl/pending-input-resolution.js";+import { resolveQuestionOnlyInputBatches } from "#harness/hitl/question-input-requests.js";import { resolveToolCallInputObject } from "#harness/runtime-actions.js";import {- isSessionLimitContinuationRequest,- resolveSessionLimitContinuation,-} from "#harness/session-limit-continuation.js";-import type { HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";--const PENDING_INPUT_BATCH_KEY = "eve.runtime.pendingInputBatch";-const APPROVED_TOOLS_KEY = "eve.runtime.hitl.approvedTools";-const DEFERRED_STEP_INPUT_KEY = "eve.runtime.deferredStepInput";--const IGNORED_INPUT_REASON = "Ignored because the user continued without responding.";--const TOOL_EXECUTION_DENIED_CODE = "TOOL_EXECUTION_DENIED";-const TOOL_EXECUTION_DENIED_MESSAGE = "Tool execution was denied.";-const TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE = "Invalid approval response.";--type ToolResponsePart = Extract<ModelMessage, { role: "tool" }>["content"][number];--/**- * Stream-emit coordinates carried so a parked batch's resolution can attribute- * its events to the turn and step that requested the input.- */-interface PendingInputBatchEvent {- readonly sequence: number;- readonly stepIndex: number;- readonly turnId: string;-}--/**- * Serializable pending input batch stored on the session state.- */-interface PendingInputBatch {- readonly event?: PendingInputBatchEvent;- readonly requests: readonly InputRequest[];- readonly responseMessages: readonly ModelMessage[];-}--/**- * Denied tool-call approvals from one resolved batch, ready for the caller to- * emit as `rejected` `action.result` events against the originating turn.- */-export interface RejectedActionBatch {- readonly event: PendingInputBatchEvent;- readonly results: readonly RuntimeToolResultActionResult[];-}--type ApprovalTerminalStatus = "approved" | "denied" | "ignored" | "invalid";--/**- * Returns true when the step input carries user-facing turn input.- */+ clearPendingSessionLimitPrompt,+ isSessionLimitInputBatch,+ resolveSessionLimitInput,+} from "#harness/hitl/session-limit-input-requests.js";+import type { HarnessSession, StepInput } from "#harness/types.js";++export { getApprovedTools, clearPendingSessionLimitPrompt };+export type { RejectedActionBatch };+export {+ appendPendingInputBatch,+ consumeDeferredStepInput,+ getPendingInputRequestIds,+ hasDeferredStepInput,+ hasPendingInputBatch,+} from "#harness/pending-input-batches.js";++/** Returns true when the step input carries user-facing turn input. */export function hasStepInput(input?: StepInput): boolean {- if (input === undefined) {- return false;- }-+ if (input === undefined) return false;return input.message !== undefined || (input.inputResponses?.length ?? 0) > 0;}-// ----------------------------------------------------------------------------// Deferred step input-// -----------------------------------------------------------------------------/**- * Merges any queued follow-up input into the current step input and clears it- * from session state.- *- * Used when the harness has to process a pending tool-approval response first- * and defer the user's new message to the next internal model step.- */-export function consumeDeferredStepInput(input: {- readonly input?: StepInput;- readonly session: HarnessSession;-}): {- readonly input?: StepInput;- readonly session: HarnessSession;-} {- const deferredInput = getDeferredStepInput(input.session);-- if (deferredInput === undefined) {- return input;- }-- const session = clearDeferredStepInput(input.session);-- if (input.input === undefined) {- return {- input: deferredInput,- session,- };- }-- return {- input: coalesceTurnInputs(deferredInput, input.input),- session,- };-}--/**- * Returns true when the session carries queued follow-up input for the next- * internal harness step.- */-export function hasDeferredStepInput(session: HarnessSession): boolean {- return getDeferredStepInput(session) !== undefined;+/** Returns true when any pending batch still contains a tool approval. */+export function hasPendingApprovalBatch(session: HarnessSession): boolean {+ return getPendingInputBatches(session.state).some((batch) =>+ batch.requests.some((request) => isApprovalRequest(request)),+ );}-// ----------------------------------------------------------------------------// Pending input resolution-// ----------------------------------------------------------------------------/*** Resolves pending input at the start of a harness step.*- * Each pending request is either `"required"` or `"dismissable"` — see- * {@link classifyInputRequest}. While a required request is unanswered,- * follow-up input is deferred instead of dismissing and recreating the- * request; {@link consumeDeferredStepInput} replays it on the subsequent- * step. Tool approval responses additionally resolve in isolation because- * AI SDK cannot process an approval response and a new user message in the- * same request.+ * Ordered batches remain independently answerable. Session-limit prompts own+ * resolution while open; approval batches preserve AI SDK's tail-message+ * requirement; question-only batches retain dismiss-and-continue behavior.*/export function resolvePendingInput(input: {+ readonly deferMessagesWhileApprovalsPending?: boolean;readonly history?: readonly ModelMessage[];readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;readonly session: HarnessSession;readonly stepInput?: StepInput;}): ResolvePendingInputResult {- const { stepInput } = input;- let session = input.session;- const baseHistory = [...(input.history ?? session.history)];-- const pendingBatch = getPendingInputBatch(session.state);-- // No pending batch -- pass through to the model call.- if (pendingBatch === undefined) {- return { outcome: "continue", messages: baseHistory, session };+ const baseHistory = [...(input.history ?? input.session.history)];+ const batches = getPendingInputBatches(input.session.state);+ if (batches.length === 0) {+ return { outcome: "continue", messages: baseHistory, session: input.session };+ }++ const route = routePendingInput(batches);+ const deferTurnInput = hasTailApprovalResponse(baseHistory);+ const textResolutionBatch =+ route.kind === "session-limit" ? route.batch : batches.length === 1 ? batches[0] : undefined;+ const resolvedStepInput =+ textResolutionBatch === undefined+ ? input.stepInput+ : resolveTextMessageInput(textResolutionBatch, input.stepInput);+ const responses = canonicalizeInputResponses(resolvedStepInput?.inputResponses ?? []);++ if (+ route.kind === "approval" &&+ input.deferMessagesWhileApprovalsPending === true &&+ resolvedStepInput?.message !== undefined &&+ !hasAnsweredApprovalBatch(route.approvalBatches, responses)+ ) {+ return {+ deferredMessage: true,+ outcome: "unresolved",+ messages: baseHistory,+ session: queueDeferredStepInput(input.session, compactStepInput(resolvedStepInput)),+ };}- // Pending batch exists -- only resolve if we have actual responses.- const resolvedStepInput = resolveTextMessageInput(pendingBatch, stepInput);- const responses = resolvedStepInput?.inputResponses ?? [];- const resolvesApprovalBatch = pendingBatch.requests.some((request) => isApprovalRequest(request));-if (responses.length === 0 && resolvedStepInput?.message === undefined) {+ const deferredInput = compactStepInput(resolvedStepInput);+ const session =+ deferredInput.context !== undefined || deferredInput.outputSchema !== undefined+ ? queueDeferredStepInput(input.session, deferredInput)+ : input.session;return { outcome: "unresolved", messages: baseHistory, session };}- if (hasUnansweredRequiredRequest({ pendingBatch, responses })) {- session = queueDeferredStepInput(session, compactStepInput(resolvedStepInput));- return { deferredMessage: true, outcome: "unresolved", messages: baseHistory, session };+ const resolverInput = {+ baseHistory,+ batches,+ deferTurnInput,+ resolvedStepInput,+ responses,+ session: input.session,+ };+ switch (route.kind) {+ case "session-limit":+ return resolveSessionLimitInput({ ...resolverInput, pendingBatch: route.batch });+ case "approval":+ return resolveApprovalInputBatches({+ ...resolverInput,+ approvalBatches: route.approvalBatches,+ questionBatches: route.questionBatches,+ resolveApprovalKey: input.resolveApprovalKey,+ });+ case "question":+ return resolveQuestionOnlyInputBatches(resolverInput);}+}- if (responses.length === 0 && resolvedStepInput?.message !== undefined) {- // A follow-up message arrived and every pending request is dismissable- // (a required one would have deferred above): mark the unanswered- // requests ignored so the model can continue with the message.- const toolParts = buildToolResponseParts(pendingBatch, []);- const messages: ModelMessage[] = [...baseHistory, ...pendingBatch.responseMessages];- if (toolParts.length > 0) {- messages.push({ content: toolParts, role: "tool" });+type PendingInputRoute =+ | { readonly batch: PendingInputBatch; readonly kind: "session-limit" }+ | {+ readonly approvalBatches: readonly PendingInputBatch[];+ readonly kind: "approval";+ readonly questionBatches: readonly PendingInputBatch[];}+ | { readonly kind: "question" };- const rejectedActions = buildRejectedActionBatch(pendingBatch, []);- session = clearPendingInputBatch(session);+type PendingInputBatchDomain = "approval" | "question" | "session-limit";+function routePendingInput(batches: readonly PendingInputBatch[]): PendingInputRoute {+ const classified = batches.map((batch) => ({ batch, domain: classifyPendingInputBatch(batch) }));+ const limitBatch = classified.find(({ domain }) => domain === "session-limit")?.batch;+ if (limitBatch !== undefined) return { batch: limitBatch, kind: "session-limit" };++ const approvalBatches = classified+ .filter(({ domain }) => domain === "approval")+ .map(({ batch }) => batch);+ if (approvalBatches.length > 0) {+ const approvalSet = new Set(approvalBatches);return {- consumedMessage: resolvedStepInput?.messageConsumed,- outcome: "resolved",- messages,- rejectedActions,- session,+ approvalBatches,+ kind: "approval",+ questionBatches: batches.filter((batch) => !approvalSet.has(batch)),};}- const limitContinuation = resolveSessionLimitContinuation({- requests: pendingBatch.requests,- responses,- });-- // Record approved tools before clearing the batch.- session = recordApprovedTools({- pendingBatch,- resolveApprovalKey: input.resolveApprovalKey,- responses,- session,- });-- // Build tool result messages from responses.- const toolParts = buildToolResponseParts(pendingBatch, responses);-- const messages: ModelMessage[] = [...baseHistory, ...pendingBatch.responseMessages];- if (toolParts.length > 0) {- messages.push({ content: toolParts, role: "tool" });- }-- const rejectedActions = buildRejectedActionBatch(pendingBatch, responses);- session = clearPendingInputBatch(session);+ return { kind: "question" };+}- // AI SDK collects approval responses only from the tail tool message.- // Defer channel context and any follow-up message so the approval resolves- // in isolation; `consumeDeferredStepInput` replays them on the next step.- if (resolvesApprovalBatch) {- const deferredInput: {- context?: StepInput["context"];- message?: StepInput["message"];- } = {};- if ((resolvedStepInput?.context?.length ?? 0) > 0) {- deferredInput.context = resolvedStepInput?.context;- }- if (resolvedStepInput?.message !== undefined) {- deferredInput.message = resolvedStepInput.message;+function classifyPendingInputBatch(batch: PendingInputBatch): PendingInputBatchDomain {+ for (const request of batch.requests) {+ switch (request.kind) {+ case "question":+ case "session-limit":+ case "tool-approval":+ break;+ default: {+ const unhandled: never = request.kind;+ throw new TypeError(`Unhandled pending input request kind: ${String(unhandled)}`);+ }}+ }- if (deferredInput.context !== undefined || deferredInput.message !== undefined) {- session = queueDeferredStepInput(session, deferredInput);+ if (isSessionLimitInputBatch(batch)) return "session-limit";+ return batch.requests.some((request) => isApprovalRequest(request)) ? "approval" : "question";+}- return {- consumedMessage: resolvedStepInput?.messageConsumed,- deferredContext: deferredInput.context === undefined ? undefined : true,- deferredMessage: deferredInput.message === undefined ? undefined : true,- limitContinuation,- outcome: "resolved",- messages,- rejectedActions,- session,- };- }- }+function canonicalizeInputResponses(responses: readonly InputResponse[]): readonly InputResponse[] {+ const byRequestId = new Map<string, InputResponse>();+ for (const response of responses) byRequestId.set(response.requestId, response);+ return [...byRequestId.values()];+}- return {- consumedMessage: resolvedStepInput?.messageConsumed,- limitContinuation,- outcome: "resolved",- messages,- rejectedActions,- session,- };+function hasTailApprovalResponse(messages: readonly ModelMessage[]): boolean {+ const tail = messages.at(-1);+ return (+ tail?.role === "tool" && tail.content.some((part) => part.type === "tool-approval-response")+ );}function resolveTextMessageInput(pendingBatch: PendingInputBatch,stepInput: StepInput | undefined,-): (StepInput & { readonly messageConsumed?: boolean }) | undefined {- if (typeof stepInput?.message !== "string" || (stepInput.inputResponses?.length ?? 0) > 0) {+): ResolvedStepInput | undefined {+ if (typeof stepInput?.message !== "string") return stepInput;++ const batchRequestIds = new Set(pendingBatch.requests.map((request) => request.requestId));+ if (stepInput.inputResponses?.some((response) => batchRequestIds.has(response.requestId))) {return stepInput;}const responses = resolveTextToResponses(stepInput.message, pendingBatch.requests);- if (responses.length === 0) {- return stepInput;- }+ if (responses.length === 0) return stepInput;return compactStepInput({...stepInput,- inputResponses: responses,+ inputResponses: [...(stepInput.inputResponses ?? []), ...responses],messageConsumed: true,message: undefined,});}-function compactStepInput(- input: (StepInput & { readonly messageConsumed?: boolean }) | undefined,-): StepInput & { readonly messageConsumed?: boolean } {- if (input === undefined) {- return {};- }-- const result: {- context?: StepInput["context"];- inputResponses?: StepInput["inputResponses"];- message?: StepInput["message"];- messageConsumed?: boolean;- outputSchema?: StepInput["outputSchema"];- } = {};-- if ((input.context?.length ?? 0) > 0) {- result.context = input.context;- }- if ((input.inputResponses?.length ?? 0) > 0) {- result.inputResponses = input.inputResponses;- }- if (input.message !== undefined) {- result.message = input.message;- }- if (input.messageConsumed === true) {- result.messageConsumed = true;- }- if (input.outputSchema !== undefined) {- result.outputSchema = input.outputSchema;- }-- return result;-}--/**- * Drops a pending session-limit continuation prompt from a parked session.- *- * A cancelled turn settles with the step's input snapshot, which can- * resurrect a continuation prompt the user already answered — the decline- * that cancelled the turn consumed the answer inside the discarded turn- * state. Left in place, the stale prompt would queue every follow-up- * message behind an answer that will never come. Harness-authored prompts- * are deterministically re-raised by the pre-model gate, so dropping is- * always safe; model-anchored batches (tool approvals, questions) are kept- * because their tool calls still require resolution.- */-export function clearPendingSessionLimitPrompt(session: HarnessSession): HarnessSession {- const pendingBatch = getPendingInputBatch(session.state);- if (pendingBatch === undefined || pendingBatch.requests.length === 0) {- return session;- }- if (!pendingBatch.requests.every((request) => isSessionLimitContinuationRequest(request))) {- return session;- }- return clearPendingInputBatch(session);-}--function hasUnansweredRequiredRequest(input: {- readonly pendingBatch: PendingInputBatch;- readonly responses: readonly InputResponse[];-}): boolean {- const responseIds = new Set(input.responses.map((response) => response.requestId));- return input.pendingBatch.requests.some(- (request) =>- classifyInputRequest(request) === "required" && !responseIds.has(request.requestId),- );-}--type ResolvePendingInputResult = {- readonly consumedMessage?: boolean;- readonly deferredContext?: boolean;- readonly deferredMessage?: boolean;- /**- * Present when the resolved batch answered a session-limit continuation- * prompt. The tool loop grants a fresh token budget window or terminates- * the session based on `granted`.- */- readonly limitContinuation?: { readonly granted: boolean };- readonly outcome: "resolved" | "continue" | "unresolved";- readonly messages: ModelMessage[];- readonly rejectedActions?: RejectedActionBatch;- readonly session: HarnessSession;-};--// ----------------------------------------------------------------------------// Pending batch management-// -----------------------------------------------------------------------------/**- * Returns true when the session is parked on a pending HITL batch- * (tool approvals or `ask_question` prompts).- */-export function hasPendingInputBatch(state: SessionStateMap | undefined): boolean {- return getPendingInputBatch(state) !== undefined;-}--/**- * Returns the request IDs in the currently pending HITL batch.- */-export function getPendingInputRequestIds(state: SessionStateMap | undefined): ReadonlySet<string> {- return new Set(getPendingInputBatch(state)?.requests.map((request) => request.requestId));-}--function getPendingInputBatch(state: SessionStateMap | undefined): PendingInputBatch | undefined {- const value = state?.[PENDING_INPUT_BATCH_KEY];-- if (typeof value !== "object" || value === null) {- return undefined;- }-- const batch = value as PendingInputBatch;-- if (!Array.isArray(batch.requests) || !Array.isArray(batch.responseMessages)) {- return undefined;- }-- return batch;-}--/**- * Stores one pending HITL batch on the session until the user responds.- */-export function setPendingInputBatch(input: {- readonly event?: PendingInputBatchEvent;- readonly requests: readonly InputRequest[];- readonly responseMessages: readonly ModelMessage[];- readonly session: HarnessSession;-}): HarnessSession {- const state = { ...input.session.state };- state[PENDING_INPUT_BATCH_KEY] = {- event: input.event,- requests: [...input.requests],- responseMessages: [...input.responseMessages],- } satisfies PendingInputBatch;-- return { ...input.session, state };-}--function clearPendingInputBatch(session: HarnessSession): HarnessSession {- if (session.state?.[PENDING_INPUT_BATCH_KEY] === undefined) {- return session;- }-- const state = { ...session.state };- delete state[PENDING_INPUT_BATCH_KEY];-- return { ...session, state: Object.keys(state).length > 0 ? state : undefined };-}--// ----------------------------------------------------------------------------// Deferred step input state-// -----------------------------------------------------------------------------function getDeferredStepInput(session: HarnessSession): StepInput | undefined {- return session.state?.[DEFERRED_STEP_INPUT_KEY] as StepInput | undefined;-}--function queueDeferredStepInput(session: HarnessSession, input: StepInput): HarnessSession {- const existing = getDeferredStepInput(session);- const deferredInput = existing === undefined ? input : coalesceTurnInputs(existing, input);- const state = { ...session.state };- state[DEFERRED_STEP_INPUT_KEY] = deferredInput;-- return {- ...session,- state,- };-}--function clearDeferredStepInput(session: HarnessSession): HarnessSession {- if (session.state?.[DEFERRED_STEP_INPUT_KEY] === undefined) {- return session;- }-- const state = { ...session.state };- delete state[DEFERRED_STEP_INPUT_KEY];-- return {- ...session,- state: Object.keys(state).length > 0 ? state : undefined,- };-}--// ----------------------------------------------------------------------------// Approval tracking-// -----------------------------------------------------------------------------/**- * Returns the set of tool names that have been approved at least once- * during this session.- */-export function getApprovedTools(session: HarnessSession): ReadonlySet<string> {- const value = session.state?.[APPROVED_TOOLS_KEY];-- if (!Array.isArray(value)) {- return new Set();- }-- return new Set(value as string[]);-}--/**- * Resolves the approval key for a request. When a `resolveApprovalKey`- * function is provided and returns a string, that compound key is recorded- * instead of the bare tool name.- */-function recordApprovedTools(input: {- readonly pendingBatch: PendingInputBatch;- readonly resolveApprovalKey?: (request: InputRequest) => string | undefined;- readonly responses: readonly InputResponse[];- readonly session: HarnessSession;-}): HarnessSession {- const approvedIds = new Set(- input.responses.filter((r) => r.optionId === "approve").map((r) => r.requestId),- );-- const newKeys = input.pendingBatch.requests- .filter((r) => approvedIds.has(r.requestId))- .map((r) => input.resolveApprovalKey?.(r) ?? r.action.toolName);-- if (newKeys.length === 0) {- return input.session;- }-- const existing = getApprovedTools(input.session);- const combined = [...new Set([...existing, ...newKeys])];- const state = { ...input.session.state };- state[APPROVED_TOOLS_KEY] = combined;-- return { ...input.session, state };-}--// ----------------------------------------------------------------------------// Tool response building-// -----------------------------------------------------------------------------/**- * Resolves whether an approval request was granted and, when auto-denied- * because the user continued without responding, the reason to record.- */-function resolveApprovalOutcome(response: InputResponse | undefined): {- readonly approved: boolean;- readonly reason: string | undefined;- readonly status: ApprovalTerminalStatus;-} {- if (response === undefined) {- return {- approved: false,- reason: IGNORED_INPUT_REASON,- status: "ignored",- };- }-- if (response.optionId === "approve") {- return {- approved: true,- reason: undefined,- status: "approved",- };- }-- if (response.optionId === "cancel") {- return {- approved: false,- reason: TOOL_EXECUTION_DENIED_MESSAGE,- status: "denied",- };- }-- return {- approved: false,- reason: TOOL_EXECUTION_INVALID_APPROVAL_MESSAGE,- status: "invalid",- };-}--/**- * Builds one rejected `action.result` payload per denied tool-call approval so- * the stream records denials that otherwise live only in model history.- */-function buildRejectedActionBatch(- batch: PendingInputBatch,- responses: readonly InputResponse[],-): RejectedActionBatch | undefined {- if (batch.event === undefined) {- return undefined;- }-- const responseMap = new Map(responses.map((r) => [r.requestId, r]));- const results: RuntimeToolResultActionResult[] = [];- for (const request of batch.requests) {- if (!isApprovalRequest(request)) {- continue;- }-- const { approved, reason, status } = resolveApprovalOutcome(responseMap.get(request.requestId));- if (approved) {- continue;- }-- results.push({- callId: request.action.callId,- isError: true,- kind: "tool-result",- output: {- approval: {- requestId: request.requestId,- status,- },- code: TOOL_EXECUTION_DENIED_CODE,- message: reason ?? TOOL_EXECUTION_DENIED_MESSAGE,- tool: {- result: "not_run",- },- },- toolName: request.action.toolName,- });- }-- return results.length > 0 ? { event: batch.event, results } : undefined;-}--function buildToolResponseParts(- batch: PendingInputBatch,- responses: readonly InputResponse[],-): ToolResponsePart[] {- const responseMap = new Map(responses.map((r) => [r.requestId, r]));-- const parts: ToolResponsePart[] = [];- for (const request of batch.requests) {- parts.push(...buildToolResponsePartsForRequest(request, responseMap.get(request.requestId)));- }- return parts;-}--function buildToolResponsePartsForRequest(- request: InputRequest,- response: InputResponse | undefined,-): ToolResponsePart[] {- // A session-limit continuation prompt is harness-authored: no matching- // tool call exists in model history, so resolving it must not append a- // tool message the provider would reject as unmatched. This is currently- // the only harness-authored request type; if another appears, replace this- // toolName predicate with a generic synthetic-request marker instead of- // stacking a second special case here.- if (isSessionLimitContinuationRequest(request)) {- return [];- }-- if (isApprovalRequest(request)) {- const { approved, reason } = resolveApprovalOutcome(response);- const parts: ToolResponsePart[] = [- {- approvalId: request.requestId,- approved,- reason,- type: "tool-approval-response",- },- ];- /*- * On denial (explicit "cancel" or auto-deny when the user continues- * without responding), splice in the matching `execution-denied`- * tool-result. AI SDK's `streamText` synthesizes this for the- * current turn's `initialResponseMessages`, but that synthesis is- * gated on the input messages' last entry being a tool message —- * on subsequent turns (when a new user message is the tail of- * history) the synthesis is skipped, and the persisted- * `tool-approval-response` is stripped during provider prompt- * conversion. Without an own `tool-result` in history, the prior- * `tool_use` block replays unmatched and some providers reject- * the request with 400.- */- if (!approved) {- parts.push({- output: { type: "execution-denied", reason },- toolCallId: request.action.callId,- toolName: request.action.toolName,- type: "tool-result",- });- }- return parts;- }-- return [- {- output: {- type: "json",- value:- response !== undefined- ? { optionId: response.optionId, text: response.text, status: "answered" }- : { status: "ignored" },- },- toolCallId: request.action.callId,- toolName: request.action.toolName,- type: "tool-result",- },- ];-}--// ----------------------------------------------------------------------------// Tool call helpers-// -----------------------------------------------------------------------------/**- * Creates a runtime tool-call action shape from an AI SDK tool call.- */+/** Creates a runtime tool-call action shape from an AI SDK tool call. */export function createRuntimeToolCallActionFromToolCall(input: {readonly toolCall: {readonly input: unknown;diff --git a/packages/eve/src/harness/pending-input-batches.test.ts b/packages/eve/src/harness/pending-input-batches.test.tsnew file mode 100644index 000000000..baf761cc6--- /dev/null+++ b/packages/eve/src/harness/pending-input-batches.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";++import type { InputRequest } from "#runtime/input/types.js";+import { resolvePendingInput } from "#harness/input-requests.js";+import { appendPendingInputBatch, getPendingInputBatches } from "#harness/pending-input-batches.js";+import type { HarnessSession } from "#harness/types.js";++const DUPLICATE_ID_ERROR =+ 'Internal pending input invariant violated: requestId must be unique across all pending batches: "duplicate".';++function session(state?: HarnessSession["state"]): HarnessSession {+ return {+ agent: { modelReference: {} as never, system: "", tools: [] },+ compaction: { recentWindowSize: 10, threshold: 0.8 },+ continuationToken: "test",+ history: [],+ sessionId: "session-1",+ state,+ };+}++function approval(requestId: string, callId: string): InputRequest {+ return {+ action: { callId, input: {}, kind: "tool-call", toolName: "bash" },+ kind: "tool-approval",+ prompt: "Approve bash",+ requestId,+ };+}++function question(requestId: string, callId: string): InputRequest {+ return {+ action: { callId, input: {}, kind: "tool-call", toolName: "ask_question" },+ display: "text",+ kind: "question",+ prompt: "Which option?",+ requestId,+ };+}++describe("pending input request ID uniqueness", () => {+ it("rejects duplicate IDs within a newly appended batch", () => {+ expect(() =>+ appendPendingInputBatch({+ requests: [approval("duplicate", "call-1"), question("duplicate", "call-2")],+ responseMessages: [],+ session: session(),+ }),+ ).toThrow(DUPLICATE_ID_ERROR);+ });++ it("rejects an approval/question ID collision across newly appended batches", () => {+ const first = appendPendingInputBatch({+ requests: [approval("duplicate", "call-1")],+ responseMessages: [],+ session: session(),+ });++ expect(() =>+ appendPendingInputBatch({+ requests: [question("duplicate", "call-2")],+ responseMessages: [],+ session: first,+ }),+ ).toThrow(DUPLICATE_ID_ERROR);+ });++ it("rejects duplicate IDs in a persisted batch collection", () => {+ const persisted = session({+ "eve.runtime.pendingInputBatches": [+ { requests: [approval("duplicate", "call-1")], responseMessages: [] },+ { requests: [question("duplicate", "call-2")], responseMessages: [] },+ ],+ });++ expect(() =>+ resolvePendingInput({+ session: persisted,+ stepInput: { inputResponses: [{ optionId: "approve", requestId: "duplicate" }] },+ }),+ ).toThrow(DUPLICATE_ID_ERROR);+ });++ it("rejects duplicate IDs in a persisted legacy singleton", () => {+ const persisted = session({+ "eve.runtime.pendingInputBatch": {+ requests: [question("duplicate", "call-1"), question("duplicate", "call-2")],+ responseMessages: [],+ },+ });++ expect(() => getPendingInputBatches(persisted.state)).toThrow(DUPLICATE_ID_ERROR);+ });+});++describe("persisted pending input validation", () => {+ it("rejects an unknown request kind instead of routing it as a question", () => {+ const persisted = session({+ "eve.runtime.pendingInputBatches": [+ {+ requests: [+ {+ ...question("unknown-kind", "call-unknown"),+ kind: "future-input-kind",+ },+ ],+ responseMessages: [],+ },+ ],+ });++ expect(() => resolvePendingInput({ session: persisted })).toThrow(+ "Unhandled pending input request kind: future-input-kind",+ );+ });+});diff --git a/packages/eve/src/harness/pending-input-batches.ts b/packages/eve/src/harness/pending-input-batches.tsnew file mode 100644index 000000000..b0c74fffc--- /dev/null+++ b/packages/eve/src/harness/pending-input-batches.ts@@ -0,0 +1,246 @@+import type { ModelMessage } from "ai";++import type { InputRequest } from "#runtime/input/types.js";+import type { HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";+import { coalesceTurnInputs } from "#harness/messages.js";++const PENDING_INPUT_BATCHES_KEY = "eve.runtime.pendingInputBatches";+/** Pre-collection singleton key; read once for sessions parked before the upgrade. */+const LEGACY_PENDING_INPUT_BATCH_KEY = "eve.runtime.pendingInputBatch";+const DEFERRED_STEP_INPUT_KEY = "eve.runtime.deferredStepInput";+const DUPLICATE_REQUEST_ID_MESSAGE =+ "Internal pending input invariant violated: requestId must be unique across all pending batches";++/**+ * Stream-emit coordinates carried so a parked batch's resolution can attribute+ * its events to the turn and step that requested the input.+ */+export interface PendingInputBatchEvent {+ readonly sequence: number;+ readonly stepIndex: number;+ readonly turnId: string;+}++/**+ * Serializable pending input batch stored on the session state: one parked+ * assistant turn's requests plus its withheld model output.+ */+export interface PendingInputBatch {+ readonly event?: PendingInputBatchEvent;+ readonly requests: readonly InputRequest[];+ readonly responseMessages: readonly ModelMessage[];+}++/**+ * Returns true when the session holds at least one pending HITL batch+ * (tool approvals or `ask_question` prompts).+ */+export function hasPendingInputBatch(state: SessionStateMap | undefined): boolean {+ return getPendingInputBatches(state).length > 0;+}++/**+ * Returns the request IDs across every pending HITL batch.+ */+export function getPendingInputRequestIds(state: SessionStateMap | undefined): ReadonlySet<string> {+ return new Set(+ getPendingInputBatches(state).flatMap((batch) =>+ batch.requests.map((request) => request.requestId),+ ),+ );+}++function coercePendingInputBatch(value: unknown): PendingInputBatch | undefined {+ if (typeof value !== "object" || value === null) {+ return undefined;+ }++ const batch = value as PendingInputBatch;++ if (!Array.isArray(batch.requests) || !Array.isArray(batch.responseMessages)) {+ return undefined;+ }++ return batch;+}++/**+ * Reads the ordered pending batches. Sessions parked before the collection+ * shape carry the legacy singleton key; it reads as a one-element list and+ * is rewritten to the list shape on the next batch write.+ */+export function getPendingInputBatches(+ state: SessionStateMap | undefined,+): readonly PendingInputBatch[] {+ const value = state?.[PENDING_INPUT_BATCHES_KEY];+ if (Array.isArray(value)) {+ const batches = value+ .map((entry) => coercePendingInputBatch(entry))+ .filter((batch): batch is PendingInputBatch => batch !== undefined);+ assertUniqueRequestIds(batches);+ return batches;+ }++ const legacy = coercePendingInputBatch(state?.[LEGACY_PENDING_INPUT_BATCH_KEY]);+ const batches = legacy === undefined ? [] : [legacy];+ assertUniqueRequestIds(batches);+ return batches;+}++function assertUniqueRequestIds(batches: readonly PendingInputBatch[]): void {+ const requestIds = new Set<string>();+ for (const batch of batches) {+ for (const request of batch.requests) {+ if (requestIds.has(request.requestId)) {+ throw new TypeError(+ `${DUPLICATE_REQUEST_ID_MESSAGE}: ${JSON.stringify(request.requestId)}.`,+ );+ }+ requestIds.add(request.requestId);+ }+ }+}++/**+ * Removes the given batches (matched by identity from a prior+ * {@link getPendingInputBatches} read) and keeps every other batch open.+ *+ * Removal is the only exported way to shrink the collection: a wholesale+ * setter would reintroduce the overwrite hazard the collection exists to+ * prevent — a writer clobbering batches it never resolved.+ */+export function removePendingInputBatches(+ session: HarnessSession,+ batches: readonly PendingInputBatch[],+): HarnessSession {+ const removed = new Set(batches);+ return setPendingInputBatches(+ session,+ getPendingInputBatches(session.state).filter((batch) => !removed.has(batch)),+ );+}++function setPendingInputBatches(+ session: HarnessSession,+ batches: readonly PendingInputBatch[],+): HarnessSession {+ assertUniqueRequestIds(batches);+ const state = { ...session.state };+ delete state[LEGACY_PENDING_INPUT_BATCH_KEY];+ if (batches.length === 0) {+ delete state[PENDING_INPUT_BATCHES_KEY];+ } else {+ state[PENDING_INPUT_BATCHES_KEY] = batches.map((batch) => ({+ event: batch.event,+ requests: [...batch.requests],+ responseMessages: [...batch.responseMessages],+ }));+ }++ return { ...session, state: Object.keys(state).length > 0 ? state : undefined };+}++/**+ * Appends one pending HITL batch for a parked assistant turn. Earlier+ * batches stay open and independently answerable.+ */+export function appendPendingInputBatch(input: {+ readonly event?: PendingInputBatchEvent;+ readonly requests: readonly InputRequest[];+ readonly responseMessages: readonly ModelMessage[];+ readonly session: HarnessSession;+}): HarnessSession {+ return setPendingInputBatches(input.session, [+ ...getPendingInputBatches(input.session.state),+ {+ event: input.event,+ requests: input.requests,+ responseMessages: input.responseMessages,+ },+ ]);+}++// ---------------------------------------------------------------------------+// Deferred step input+// ---------------------------------------------------------------------------++/**+ * Merges any queued follow-up input into the current step input and clears it+ * from session state. When `preferCurrentInput` is set, fresh input is returned+ * alone and the queued input remains deferred.+ *+ * Used when the harness has to process a pending tool-approval response first+ * and defer the user's new message to the next internal model step.+ */+export function consumeDeferredStepInput(input: {+ readonly input?: StepInput;+ readonly preferCurrentInput?: boolean;+ readonly session: HarnessSession;+}): {+ readonly input?: StepInput;+ readonly session: HarnessSession;+} {+ const deferredInput = getDeferredStepInput(input.session);++ if (deferredInput === undefined) {+ return input;+ }++ // A fresh task delivery may answer the request that caused the deferral.+ // Resolve it alone, leaving the older turn input queued for the next step.+ if (input.preferCurrentInput === true && input.input !== undefined) {+ return { input: input.input, session: input.session };+ }++ const session = clearDeferredStepInput(input.session);++ if (input.input === undefined) {+ return {+ input: deferredInput,+ session,+ };+ }++ return {+ input: coalesceTurnInputs(deferredInput, input.input),+ session,+ };+}++/**+ * Returns true when the session carries queued follow-up input for the next+ * internal harness step.+ */+export function hasDeferredStepInput(session: HarnessSession): boolean {+ return getDeferredStepInput(session) !== undefined;+}++function getDeferredStepInput(session: HarnessSession): StepInput | undefined {+ return session.state?.[DEFERRED_STEP_INPUT_KEY] as StepInput | undefined;+}++export function queueDeferredStepInput(session: HarnessSession, input: StepInput): HarnessSession {+ const existing = getDeferredStepInput(session);+ const deferredInput = existing === undefined ? input : coalesceTurnInputs(existing, input);+ const state = { ...session.state };+ state[DEFERRED_STEP_INPUT_KEY] = deferredInput;++ return {+ ...session,+ state,+ };+}++function clearDeferredStepInput(session: HarnessSession): HarnessSession {+ if (session.state?.[DEFERRED_STEP_INPUT_KEY] === undefined) {+ return session;+ }++ const state = { ...session.state };+ delete state[DEFERRED_STEP_INPUT_KEY];++ return {+ ...session,+ state: Object.keys(state).length > 0 ? state : undefined,+ };+}diff --git a/packages/eve/src/harness/proxy-input-requests.test.ts b/packages/eve/src/harness/proxy-input-requests.test.tsindex 9c6197bd3..2732a0d68 100644--- a/packages/eve/src/harness/proxy-input-requests.test.ts+++ b/packages/eve/src/harness/proxy-input-requests.test.ts@@ -4,8 +4,12 @@ import {clearProxyInputRequestsForChild,getProxyInputRequests,hasProxyInputRequests,+ retireProxyInputRequests,+ toProxyInputRequestEntries,upsertProxyInputRequests,} from "#harness/proxy-input-requests.js";+import type { SubagentInputRequestHookPayload } from "#channel/types.js";+import type { InputRequest, InputRequestKind } from "#runtime/input/types.js";import type { HarnessSession } from "#harness/types.js";function createSession(state?: Record<string, unknown>): HarnessSession {@@ -23,6 +27,15 @@ function createSession(state?: Record<string, unknown>): HarnessSession {};}+function createRequest(requestId: string, kind: InputRequestKind): InputRequest {+ return {+ action: { callId: requestId, input: {}, kind: "tool-call", toolName: "test" },+ kind,+ prompt: "Respond",+ requestId,+ };+}+describe("upsertProxyInputRequests", () => {it("records a fresh batch of proxy entries", () => {const session = createSession();@@ -39,7 +52,7 @@ describe("upsertProxyInputRequests", () => {});});- it("replaces prior entries for the same child continuation token", () => {+ it("keeps two batches from the same child independently addressable", () => {let session = upsertProxyInputRequests({entries: [["req-1", { childContinuationToken: "child-a", kind: "question" }]],forChildContinuationToken: "child-a",@@ -53,12 +66,37 @@ describe("upsertProxyInputRequests", () => {});const entries = getProxyInputRequests(session.state);- expect(entries.size).toBe(1);+ expect(entries.size).toBe(2);+ expect(entries.get("req-1")).toEqual({+ childContinuationToken: "child-a",+ kind: "question",+ });expect(entries.get("req-2")).toEqual({childContinuationToken: "child-a",kind: "question",});- expect(entries.has("req-1")).toBe(false);+ });++ it("replaces only a reused request ID", () => {+ let session = upsertProxyInputRequests({+ entries: [+ ["req-1", { childContinuationToken: "child-a", kind: "question" }],+ ["req-2", { childContinuationToken: "child-a", kind: "question" }],+ ],+ forChildContinuationToken: "child-a",+ session: createSession(),+ });++ session = upsertProxyInputRequests({+ entries: [["req-1", { childContinuationToken: "child-b", kind: "tool-approval" }]],+ forChildContinuationToken: "child-b",+ session,+ });++ expect([...getProxyInputRequests(session.state)]).toEqual([+ ["req-1", { childContinuationToken: "child-b", kind: "tool-approval" }],+ ["req-2", { childContinuationToken: "child-a", kind: "question" }],+ ]);});it("keeps entries from other children when upserting", () => {@@ -87,6 +125,48 @@ describe("upsertProxyInputRequests", () => {});});+describe("toProxyInputRequestEntries", () => {+ it("records shared batch and approval metadata on every route", () => {+ const requests = [+ createRequest("question-1", "question"),+ createRequest("approval-1", "tool-approval"),+ ];+ const payload = {+ callId: "call-1",+ childContinuationToken: "child-a",+ childSessionId: "child-session",+ event: { requests, sequence: 3, stepIndex: 2, turnId: "turn-1" },+ kind: "subagent-input-request",+ subagentName: "delegate",+ } satisfies SubagentInputRequestHookPayload;++ expect(toProxyInputRequestEntries(payload)).toEqual([+ [+ "question-1",+ {+ batch: {+ approvalRequestIds: ["approval-1"],+ requestIds: ["question-1", "approval-1"],+ },+ childContinuationToken: "child-a",+ kind: "question",+ },+ ],+ [+ "approval-1",+ {+ batch: {+ approvalRequestIds: ["approval-1"],+ requestIds: ["question-1", "approval-1"],+ },+ childContinuationToken: "child-a",+ kind: "tool-approval",+ },+ ],+ ]);+ });+});+describe("clearProxyInputRequestsForChild", () => {it("removes only the target child's entries", () => {let session = upsertProxyInputRequests({@@ -118,6 +198,30 @@ describe("clearProxyInputRequestsForChild", () => {});});+describe("retireProxyInputRequests", () => {+ it("removes only answered request IDs, including partial same-child batches", () => {+ const session = upsertProxyInputRequests({+ entries: [+ ["req-1", { childContinuationToken: "child-a", kind: "question" }],+ ["req-2", { childContinuationToken: "child-a", kind: "question" }],+ ],+ forChildContinuationToken: "child-a",+ session: createSession(),+ });++ const next = retireProxyInputRequests(session, ["req-1"]);++ expect([...getProxyInputRequests(next.state)]).toEqual([+ ["req-2", { childContinuationToken: "child-a", kind: "question" }],+ ]);+ });++ it("is idempotent for an already-retired request ID", () => {+ const session = createSession();+ expect(retireProxyInputRequests(session, ["req-1"])).toBe(session);+ });+});+describe("getProxyInputRequests type safety", () => {it("returns an empty map when the session carries no proxy state", () => {const entries = getProxyInputRequests(createSession().state);@@ -147,4 +251,22 @@ describe("getProxyInputRequests type safety", () => {});expect(getProxyInputRequests(session.state).size).toBe(0);});++ it("keeps legacy routes and ignores malformed optional batch metadata", () => {+ const session = createSession({+ "eve.runtime.proxyInputRequests": {+ legacy: { childContinuationToken: "child-a", kind: "question" },+ malformed: {+ batch: { approvalRequestIds: ["other"], requestIds: ["malformed"] },+ childContinuationToken: "child-a",+ kind: "tool-approval",+ },+ },+ });++ expect([...getProxyInputRequests(session.state)]).toEqual([+ ["legacy", { childContinuationToken: "child-a", kind: "question" }],+ ["malformed", { childContinuationToken: "child-a", kind: "tool-approval" }],+ ]);+ });});diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.tsindex 3ae2c1f2d..f19dd9dac 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/proxy-input-requests.ts@@ -12,10 +12,17 @@ const PROXY_INPUT_REQUEST_KINDS = {/** Routing and control metadata for one descendant-owned input request. */export interface ProxyInputRequest {+ /** Batch semantics are optional so sessions written before this field remain routable. */+ readonly batch?: ProxyInputRequestBatch;readonly childContinuationToken: string;readonly kind: InputRequestKind;}+export interface ProxyInputRequestBatch {+ readonly approvalRequestIds: readonly string[];+ readonly requestIds: readonly string[];+}+/** `requestId → route` map stored on the parent session. */type ProxyInputRequestMap = Readonly<Record<string, ProxyInputRequest>>;@@ -41,22 +48,16 @@ export function hasProxyInputRequests(state: SessionStateMap | undefined): boole}/**- * Replaces prior entries for `forChildContinuationToken` with the- * provided ones. A child raising a fresh batch overwrites its prior- * batch — the parent never keeps stale request metadata.+ * Merges the provided routes into the parent session by request ID. Existing+ * routes with different IDs stay independently answerable; re-recording the+ * same request ID replaces only that route, making durable retries idempotent.*/export function upsertProxyInputRequests(input: {readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];readonly forChildContinuationToken: string;readonly session: HarnessSession;}): HarnessSession {- const next: Record<string, ProxyInputRequest> = {};-- for (const [requestId, route] of Object.entries(readMap(input.session.state))) {- if (route.childContinuationToken !== input.forChildContinuationToken) {- next[requestId] = route;- }- }+ const next = { ...readMap(input.session.state) };for (const [requestId, route] of input.entries) {next[requestId] = route;@@ -92,6 +93,25 @@ export function clearProxyInputRequestsForChild(return writeMap(session, next);}+/** Removes only the request IDs whose responses were successfully forwarded. */+export function retireProxyInputRequests<T extends { readonly state?: SessionStateMap }>(+ session: T,+ requestIds: readonly string[],+): T {+ const current = readMap(session.state);+ const next = { ...current };+ let changed = false;++ for (const requestId of requestIds) {+ if (Object.hasOwn(next, requestId)) {+ delete next[requestId];+ changed = true;+ }+ }++ return changed ? writeMap(session, next) : session;+}+/*** Removes every proxy entry. Called when a cancelled turn orphans its* descendants so stale HITL responses no longer route to them.@@ -110,11 +130,19 @@ export function clearAllProxyInputRequests(session: HarnessSession): HarnessSessexport function toProxyInputRequestEntries(payload: SubagentInputRequestHookPayload,): readonly (readonly [requestId: string, route: ProxyInputRequest])[] {+ const batch: ProxyInputRequestBatch = {+ approvalRequestIds: payload.event.requests.flatMap((request) =>+ request.kind === "tool-approval" ? [request.requestId] : [],+ ),+ requestIds: payload.event.requests.map((request) => request.requestId),+ };+return payload.event.requests.map((request) =>[request.requestId,{+ batch,childContinuationToken: payload.childContinuationToken,kind: request.kind,},@@ -131,7 +159,7 @@ function readMap(state: SessionStateMap | undefined): ProxyInputRequestMap {const result: Record<string, ProxyInputRequest> = {};for (const [key, value] of Object.entries(raw)) {- const request = parseProxyInputRequest(value);+ const request = parseProxyInputRequest(value, key);if (request !== undefined) {result[key] = request;}@@ -139,10 +167,10 @@ function readMap(state: SessionStateMap | undefined): ProxyInputRequestMap {return result;}-function writeMap(- session: HarnessSession,+function writeMap<T extends { readonly state?: SessionStateMap }>(+ session: T,entries: Record<string, ProxyInputRequest>,-): HarnessSession {+): T {const state = { ...session.state };if (Object.keys(entries).length === 0) {@@ -157,7 +185,7 @@ function writeMap(return { ...session, state };}-function parseProxyInputRequest(value: unknown): ProxyInputRequest | undefined {+function parseProxyInputRequest(value: unknown, requestId: string): ProxyInputRequest | undefined {if (value === null || typeof value !== "object" || Array.isArray(value)) {return undefined;}@@ -167,10 +195,41 @@ function parseProxyInputRequest(value: unknown): ProxyInputRequest | undefined {if (typeof value.childContinuationToken !== "string" || !isInputRequestKind(value.kind)) {return undefined;}- return {+ const request = {childContinuationToken: value.childContinuationToken,kind: value.kind,};+ const batch = "batch" in value ? parseProxyInputRequestBatch(value.batch) : undefined;+ return batch === undefined || !batch.requestIds.includes(requestId)+ ? request+ : { ...request, batch };+}++function parseProxyInputRequestBatch(value: unknown): ProxyInputRequestBatch | undefined {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return undefined;+ }+ if (!("approvalRequestIds" in value) || !("requestIds" in value)) {+ return undefined;+ }+ if (!isStringArray(value.approvalRequestIds) || !isStringArray(value.requestIds)) {+ return undefined;+ }+ const requestIds = new Set(value.requestIds);+ if (+ requestIds.size !== value.requestIds.length ||+ value.approvalRequestIds.some((requestId) => !requestIds.has(requestId))+ ) {+ return undefined;+ }+ return {+ approvalRequestIds: value.approvalRequestIds,+ requestIds: value.requestIds,+ };+}++function isStringArray(value: unknown): value is string[] {+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");}function isInputRequestKind(value: unknown): value is InputRequestKind {diff --git a/packages/eve/src/harness/session-limit-enforcement.ts b/packages/eve/src/harness/session-limit-enforcement.tsindex b5fa8afa9..7a30b5827 100644--- a/packages/eve/src/harness/session-limit-enforcement.ts+++ b/packages/eve/src/harness/session-limit-enforcement.ts@@ -20,7 +20,7 @@ import {setHarnessEmissionState,type HarnessEmissionState,} from "#harness/emission.js";-import { setPendingInputBatch } from "#harness/input-requests.js";+import { appendPendingInputBatch } from "#harness/input-requests.js";import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";import { SessionLimitDeclinedError } from "#harness/turn-cancellation.js";import {@@ -143,7 +143,7 @@ async function parkOnSessionTokenLimit(input: {});let emissionState = input.emissionState;- const parkedSession = setPendingInputBatch({+ const parkedSession = appendPendingInputBatch({event: {sequence: emissionState.sequence,stepIndex: emissionState.stepIndex,diff --git a/packages/eve/src/harness/tool-loop-compaction-accounting.test.ts b/packages/eve/src/harness/tool-loop-compaction-accounting.test.tsindex a77054094..08a73dd1b 100644--- a/packages/eve/src/harness/tool-loop-compaction-accounting.test.ts+++ b/packages/eve/src/harness/tool-loop-compaction-accounting.test.ts@@ -1,7 +1,7 @@import { generateText, jsonSchema, type LanguageModel, ToolLoopAgent } from "ai";import { afterEach, describe, expect, it, vi } from "vitest";-import { setPendingInputBatch } from "#harness/input-requests.js";+import { appendPendingInputBatch } from "#harness/input-requests.js";import { createToolLoopHarness } from "#harness/tool-loop.js";import type { HarnessSession, StepFn, StepNext, ToolLoopHarnessConfig } from "#harness/types.js";@@ -249,7 +249,7 @@ describe("tool-loop structured compaction accounting", () => {]);const runStep = createToolLoopHarness(createTestConfig());- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {diff --git a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.tsindex 325a9ae52..8a2747b18 100644--- a/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts+++ b/packages/eve/src/harness/tool-loop-generate-approval-resume.integration.test.ts@@ -1,9 +1,10 @@-import { jsonSchema, type LanguageModel, type ModelMessage } from "ai";+import { jsonSchema, type LanguageModel, type ModelMessage, simulateReadableStream } from "ai";import { MockLanguageModelV4 } from "ai/test";import { describe, expect, it, vi } from "vitest";-import { setPendingInputBatch } from "#harness/input-requests.js";+import { appendPendingInputBatch } from "#harness/input-requests.js";import { createToolLoopHarness } from "#harness/tool-loop.js";+import { setTurnUsageState } from "#harness/turn-tag-state.js";import type { HarnessSession, ToolLoopHarnessConfig } from "#harness/types.js";const usage = {@@ -20,6 +21,27 @@ const usage = {},};+type StreamResult = Awaited<ReturnType<MockLanguageModelV4["doStream"]>>;+type StreamPart = StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;++function textStreamResult(text: string): StreamResult {+ return {+ stream: simulateReadableStream({+ chunks: [+ { type: "stream-start", warnings: [] },+ { id: "answer", type: "text-start" },+ { delta: text, id: "answer", type: "text-delta" },+ { id: "answer", type: "text-end" },+ {+ finishReason: { raw: undefined, unified: "stop" },+ type: "finish",+ usage,+ },+ ] satisfies StreamPart[],+ }),+ };+}+const toolCall = {input: { command: "pwd" },toolCallId: "call-1",@@ -33,7 +55,20 @@ const approvalRequest = {type: "tool-approval-request" as const,};-function createPendingApprovalSession(): HarnessSession {+const secondToolCall = {+ input: { command: "whoami" },+ toolCallId: "call-2",+ toolName: "bash",+ type: "tool-call" as const,+};++const secondApprovalRequest = {+ approvalId: "approval-2",+ toolCallId: secondToolCall.toolCallId,+ type: "tool-approval-request" as const,+};++function createPendingApprovalSession(history?: readonly ModelMessage[]): HarnessSession {const session: HarnessSession = {agent: {modelReference: { id: "generate-approval-resume-model" },@@ -48,11 +83,11 @@ function createPendingApprovalSession(): HarnessSession {},compaction: { recentWindowSize: 10, threshold: 100_000 },continuationToken: "http:generate-approval-resume-session",- history: [{ content: "Run pwd.", role: "user" }],+ history: [...(history ?? [{ content: "Run pwd.", role: "user" }])],sessionId: "generate-approval-resume-session",};- return setPendingInputBatch({+ return appendPendingInputBatch({requests: [{action: {@@ -82,6 +117,78 @@ function createPendingApprovalSession(): HarnessSession {});}+function createTwoPendingApprovalSession(): HarnessSession {+ return appendPendingInputBatch({+ requests: [+ {+ action: {+ callId: secondToolCall.toolCallId,+ input: secondToolCall.input,+ kind: "tool-call",+ toolName: secondToolCall.toolName,+ },+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId: secondApprovalRequest.approvalId,+ },+ ],+ responseMessages: [+ {+ content: [secondToolCall, secondApprovalRequest],+ role: "assistant",+ },+ ],+ session: createPendingApprovalSession(),+ });+}++function createModel(): MockLanguageModelV4 {+ return new MockLanguageModelV4({+ doGenerate: {+ content: [{ text: "The command returned /workspace.", type: "text" }],+ finishReason: { raw: undefined, unified: "stop" },+ usage,+ warnings: [],+ },+ modelId: "generate-approval-resume-model",+ provider: "eve-integration-mock",+ });+}++function createConfig(+ model: MockLanguageModelV4,+ execute: (input: unknown, options: unknown) => Promise<string>,+): ToolLoopHarnessConfig {+ const tools: ToolLoopHarnessConfig["tools"] = new Map([+ [+ toolCall.toolName,+ {+ description: "Run a shell command.",+ execute,+ inputSchema: jsonSchema({ type: "object" }),+ name: toolCall.toolName,+ toModelOutput: (output) => {+ if (typeof output !== "string") {+ throw new TypeError("Expected the bash test tool to return a string.");+ }+ return { type: "text", value: `canonical:${output}` };+ },+ },+ ],+ ]);+ return {+ mode: "conversation",+ resolveModel: async (): Promise<LanguageModel> => model,+ tools,+ };+}+function findPart(messages: readonly ModelMessage[],type: "tool-approval-response" | "tool-call" | "tool-result",@@ -100,44 +207,118 @@ function findPart(}describe("tool loop generate approval resume (real AI SDK)", () => {- it("persists the approved pre-model tool result without an event handler", async () => {+ it("executes two approvals delivered together exactly once each", async () => {+ const execute = vi.fn(async (input: unknown) =>+ (input as { command: string }).command === "pwd" ? "/workspace" : "eve",+ );+ const model = createModel();++ const first = await createToolLoopHarness(createConfig(model, execute))(+ createTwoPendingApprovalSession(),+ {+ inputResponses: [+ { optionId: "approve", requestId: approvalRequest.approvalId },+ { optionId: "approve", requestId: secondApprovalRequest.approvalId },+ ],+ },+ );+ if (typeof first.next !== "function") {+ throw new TypeError("Expected the deferred approval to schedule another harness step.");+ }+ const result = await first.next(first.session);++ expect(model.doGenerateCalls).toHaveLength(2);+ expect(execute).toHaveBeenCalledTimes(2);+ expect(execute).toHaveBeenNthCalledWith(+ 1,+ toolCall.input,+ expect.objectContaining({ toolCallId: toolCall.toolCallId }),+ );+ expect(execute).toHaveBeenNthCalledWith(+ 2,+ secondToolCall.input,+ expect.objectContaining({ toolCallId: secondToolCall.toolCallId }),+ );++ const toolResultCallIds = result.session.history.flatMap((message) =>+ message.role === "tool" && Array.isArray(message.content)+ ? message.content.flatMap((part) => (part.type === "tool-result" ? [part.toolCallId] : []))+ : [],+ );+ expect(toolResultCallIds).toEqual([toolCall.toolCallId, secondToolCall.toolCallId]);+ });++ it("executes an approval before replaying its message after a limit continuation", async () => {const execute = vi.fn(async () => "/workspace");const model = new MockLanguageModelV4({- doGenerate: {- content: [{ text: "The command returned /workspace.", type: "text" }],- finishReason: { raw: undefined, unified: "stop" },- usage,- warnings: [],- },+ doStream: [textStreamResult("The command completed."), textStreamResult("Summary complete.")],modelId: "generate-approval-resume-model",provider: "eve-integration-mock",});- const tools: ToolLoopHarnessConfig["tools"] = new Map([- [- toolCall.toolName,+ const config = {+ ...createConfig(model, execute),+ handleEvent: async () => {},+ } satisfies ToolLoopHarnessConfig;+ const usageState = {+ cacheReadTokens: 0,+ cacheWriteTokens: 0,+ costUsd: 0,+ inputTokens: 12,+ outputTokens: 3,+ sawCost: false,+ };+ const session = setTurnUsageState(+ {+ ...createPendingApprovalSession(),+ limits: { maxInputTokensPerSession: 12 },+ },+ { ...usageState, session: usageState, turnId: "turn_previous" },+ );+ const runStep = createToolLoopHarness(config);++ const limited = await runStep(session, {+ inputResponses: [{ optionId: "approve", requestId: approvalRequest.approvalId }],+ message: "Then summarize it.",+ });++ expect(execute).not.toHaveBeenCalled();+ const resumed = await runStep(limited.session, {+ inputResponses: [{- description: "Run a shell command.",- execute,- inputSchema: jsonSchema({ type: "object" }),- name: toolCall.toolName,- toModelOutput: (output) => {- if (typeof output !== "string") {- throw new TypeError("Expected the bash test tool to return a string.");- }- return { type: "text", value: `canonical:${output}` };- },+ optionId: "continue",+ requestId: `${session.sessionId}:limit:input:12`,},],- ]);- const config: ToolLoopHarnessConfig = {- mode: "conversation",- resolveModel: async (): Promise<LanguageModel> => model,- tools,- };+ });- const result = await createToolLoopHarness(config)(createPendingApprovalSession(), {- inputResponses: [{ optionId: "approve", requestId: approvalRequest.approvalId }],+ expect(execute).toHaveBeenCalledExactlyOnceWith(+ toolCall.input,+ expect.objectContaining({ toolCallId: toolCall.toolCallId }),+ );+ expect(typeof resumed.next).toBe("function");+ if (typeof resumed.next !== "function") {+ throw new TypeError("Expected the deferred message to run after approval execution.");+ }+ await resumed.next(resumed.session);++ expect(model.doStreamCalls).toHaveLength(2);+ expect(model.doStreamCalls[0]?.prompt.at(-1)?.role).toBe("tool");+ expect(model.doStreamCalls[1]?.prompt.at(-1)).toMatchObject({+ content: [{ text: "Then summarize it.", type: "text" }],+ role: "user",});+ });++ it("persists the approved pre-model tool result without an event handler", async () => {+ const execute = vi.fn(async () => "/workspace");+ const model = createModel();++ const result = await createToolLoopHarness(createConfig(model, execute))(+ createPendingApprovalSession(),+ {+ inputResponses: [{ optionId: "approve", requestId: approvalRequest.approvalId }],+ },+ );expect(model.doGenerateCalls).toHaveLength(1);expect(model.doStreamCalls).toHaveLength(0);@@ -175,4 +356,74 @@ describe("tool loop generate approval resume (real AI SDK)", () => {role: "assistant",});});++ // Acceptance gate for the HITL non-blocking plan (research/hitl-request-lifecycle.md):+ // once messages run as normal turns while an approval is open, the approval batch is+ // restored *after* that intervening exchange. This proves the AI SDK accepts the+ // late-spliced transcript shape before any behavior change lands.+ it("splices the approved batch after an intervening conversation turn", async () => {+ const interveningHistory: readonly ModelMessage[] = [+ { content: "Run pwd.", role: "user" },+ { content: "Any update on that command?", role: "user" },+ {+ content: [{ text: "Still waiting for approval to run pwd.", type: "text" }],+ role: "assistant",+ },+ ];+ const execute = vi.fn(async () => "/workspace");+ const model = createModel();++ const result = await createToolLoopHarness(createConfig(model, execute))(+ createPendingApprovalSession(interveningHistory),+ {+ inputResponses: [{ optionId: "approve", requestId: approvalRequest.approvalId }],+ },+ );++ expect(model.doGenerateCalls).toHaveLength(1);+ expect(execute).toHaveBeenCalledExactlyOnceWith(+ toolCall.input,+ expect.objectContaining({ toolCallId: toolCall.toolCallId }),+ );++ // The provider prompt keeps the intervening turn before the restored batch.+ const providerPrompt = model.doGenerateCalls[0]?.prompt ?? [];+ const interveningIndex = providerPrompt.findIndex(+ (message) =>+ message.role === "user" && JSON.stringify(message.content).includes("Any update"),+ );+ const toolCallIndex = providerPrompt.findIndex(+ (message) =>+ message.role === "assistant" &&+ Array.isArray(message.content) &&+ message.content.some((part) => part.type === "tool-call"),+ );+ expect(interveningIndex).toBeGreaterThanOrEqual(0);+ expect(toolCallIndex).toBeGreaterThan(interveningIndex);+ expect(findPart(providerPrompt, "tool-result")).toMatchObject({+ output: { type: "text", value: "canonical:/workspace" },+ toolCallId: toolCall.toolCallId,+ toolName: toolCall.toolName,+ });++ // Committed history: intervening exchange first, then the restored batch, exactly once.+ expect(result.session.history.map((message) => message.role)).toEqual([+ "user",+ "user",+ "assistant",+ "assistant",+ "tool",+ "tool",+ "assistant",+ ]);+ expect(findPart(result.session.history, "tool-call")).toEqual(toolCall);+ expect(findPart(result.session.history, "tool-approval-response")).toMatchObject({+ approvalId: approvalRequest.approvalId,+ approved: true,+ });+ expect(result.session.history.at(-1)).toMatchObject({+ content: [{ text: "The command returned /workspace.", type: "text" }],+ role: "assistant",+ });+ });});diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex d9b7b8441..46c7ab923 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -39,9 +39,10 @@ import {requestAuthorization,} from "#harness/authorization.js";import {+ getPendingInputRequestIds,hasDeferredStepInput,hasPendingInputBatch,- setPendingInputBatch,+ appendPendingInputBatch,} from "#harness/input-requests.js";import { getPendingRuntimeActionBatch } from "#harness/runtime-actions.js";import { AGENT_HANDLES_STATE_KEY } from "#harness/handles/store.js";@@ -419,6 +420,34 @@ function setupMockAgent(result: Record<string, unknown>): void {} as unknown as MockAgentConstructor);}+function setupMockAgentSequence(results: readonly Record<string, unknown>[]): void {+ let index = 0;+ vi.mocked(ToolLoopAgent).mockImplementation(function (+ this: MockAgentInstance,+ settings: MockAgentSettings,+ ) {+ const result = results[index++];+ if (result === undefined) {+ throw new Error("ToolLoopAgent mock exhausted its scripted results.");+ }+ const { onStepFinish, prepareStep } = settings;+ this.generate = vi.fn().mockImplementation(async (options: { messages: unknown[] }) => {+ if (prepareStep) {+ await prepareStep({+ messages: options.messages,+ steps: [],+ stepNumber: 0,+ model: {},+ context: undefined,+ });+ }+ if (onStepFinish) await onStepFinish(result);+ return createMockGenerateResult(result);+ });+ return this;+ } as MockAgentConstructor);+}+/*** Builds a terminal step result whose assistant turn calls the framework* `final_output` tool with `structured` as its (provider-constrained) input.@@ -434,7 +463,7 @@ function finalOutputResult(text: string, structured: unknown): Record<string, un}function createPendingBashApprovalSession(): HarnessSession {- return setPendingInputBatch({+ return appendPendingInputBatch({requests: [{action: {@@ -485,7 +514,7 @@ function createPendingBashApprovalSession(): HarnessSession {}function createPendingProtectedActionApprovalSession(): HarnessSession {- return setPendingInputBatch({+ return appendPendingInputBatch({requests: [{action: {@@ -6190,10 +6219,10 @@ describe("createToolLoopHarness", () => {);const pendingResponseMessages = (- result.session.state?.["eve.runtime.pendingInputBatch"] as- | { responseMessages?: readonly ModelMessage[] }+ result.session.state?.["eve.runtime.pendingInputBatches"] as+ | readonly { responseMessages?: readonly ModelMessage[] }[]| undefined- )?.responseMessages;+ )?.[0]?.responseMessages;expect(result.next).toBeNull();expect(pendingResponseMessages).toEqual([@@ -7159,22 +7188,22 @@ describe("createToolLoopHarness", () => {expect(events.filter((event) => event.type === "action.result")).toHaveLength(1);});- it("queues a follow-up user message until the pending tool approval resolves", async () => {+ it("runs a follow-up user message while the pending tool approval stays open", async () => {const generateCalls: unknown[] = [];const agentResults = [{finishReason: "stop",- response: {- messages: [{ content: "Okay, I will not run that command.", role: "assistant" }],- },- text: "Okay, I will not run that command.",+ response: { messages: [{ content: "Hello!", role: "assistant" }] },+ text: "Hello!",toolCalls: [],toolResults: [],},{finishReason: "stop",- response: { messages: [{ content: "Hello!", role: "assistant" }] },- text: "Hello!",+ response: {+ messages: [{ content: "Okay, I will not run that command.", role: "assistant" }],+ },+ text: "Okay, I will not run that command.",toolCalls: [],toolResults: [],},@@ -7208,7 +7237,7 @@ describe("createToolLoopHarness", () => {return this;} as MockAgentConstructor);- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -7270,20 +7299,32 @@ describe("createToolLoopHarness", () => {]),});+ // The follow-up message runs as an ordinary turn: the model is called+ // without the withheld approval batch, and the approval stays open.const firstResult = await createToolLoopHarness(config)(session, {message: "Hi instead.",});expect(firstResult.next).toBeNull();- expect(generateCalls).toEqual([]);- expect(hasDeferredStepInput(firstResult.session)).toBe(true);+ expect(generateCalls).toHaveLength(1);+ expect((generateCalls[0] as { role: string; content: unknown }[]).at(-1)).toEqual({+ content: "Hi instead.",+ role: "user",+ });+ expect(+ (generateCalls[0] as { role: string }[]).every((message) => message.role !== "tool"),+ ).toBe(true);+ expect(hasDeferredStepInput(firstResult.session)).toBe(false);+ expect(hasPendingInputBatch(firstResult.session.state)).toBe(true);+ // The late denial still restores the withheld batch behind the+ // intervening exchange and resolves it.const deniedResult = await createToolLoopHarness(config)(firstResult.session, {inputResponses: [{ requestId: "approval-1", optionId: "cancel" }],});- expect(typeof deniedResult.next).toBe("function");- expect(generateCalls[0]).toEqual([+ expect(generateCalls).toHaveLength(2);+ expect((generateCalls[1] as { role: string; content: unknown }[]).slice(-2)).toEqual([{content: [{@@ -7321,24 +7362,310 @@ describe("createToolLoopHarness", () => {role: "tool",},]);-- const secondResult = await createToolLoopHarness(config)(deniedResult.session);-- expect(secondResult.next).toBeNull();- expect((generateCalls[1] as { role: string; content: unknown }[]).at(-1)).toEqual({+ expect((generateCalls[1] as { role: string; content: unknown }[])[0]).toEqual({content: "Hi instead.",role: "user",});- expect(secondResult.session.history.at(-2)).toEqual({- content: "Hi instead.",- role: "user",+ expect(hasPendingInputBatch(deniedResult.session.state)).toBe(false);+ expect(deniedResult.session.history.at(-1)).toEqual({+ content: "Okay, I will not run that command.",+ role: "assistant",+ });+ });++ it("parks a second input batch while an earlier approval stays open", async () => {+ const generateCalls: Array<Array<{ role: string; content: unknown }>> = [];+ const agentResults = [+ {+ finishReason: "tool-calls",+ response: {+ messages: [+ {+ content: [+ { text: "Which color?", type: "text" },+ {+ input: {+ options: [+ { id: "red", label: "Red" },+ { id: "blue", label: "Blue" },+ ],+ prompt: "Pick a color.",+ },+ toolCallId: "question-call",+ toolName: "ask_question",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ],+ },+ text: "",+ toolCalls: [+ {+ input: {+ options: [+ { id: "red", label: "Red" },+ { id: "blue", label: "Blue" },+ ],+ prompt: "Pick a color.",+ },+ toolCallId: "question-call",+ toolName: "ask_question",+ type: "tool-call",+ },+ ],+ toolResults: [],+ },+ {+ finishReason: "stop",+ response: { messages: [{ content: "Red it is.", role: "assistant" }] },+ text: "Red it is.",+ toolCalls: [],+ toolResults: [],+ },+ {+ finishReason: "stop",+ response: {+ messages: [{ content: "Understood, not running it.", role: "assistant" }],+ },+ text: "Understood, not running it.",+ toolCalls: [],+ toolResults: [],+ },+ ] satisfies Record<string, unknown>[];+ let instanceIndex = 0;++ vi.mocked(ToolLoopAgent).mockImplementation(function (+ this: MockAgentInstance,+ settings: MockAgentSettings,+ ) {+ const result = agentResults[instanceIndex];+ instanceIndex += 1;+ if (result === undefined) {+ throw new Error("ToolLoopAgent mock exhausted its scripted results.");+ }+ const { onStepFinish, prepareStep } = settings;+ this.generate = vi.fn().mockImplementation(async (input: { messages: unknown[] }) => {+ if (prepareStep) {+ await prepareStep({+ messages: input.messages,+ steps: [],+ stepNumber: 0,+ model: {},+ context: undefined,+ });+ }+ generateCalls.push(input.messages as Array<{ role: string; content: unknown }>);+ if (onStepFinish) await onStepFinish(result);+ return createMockGenerateResult(result);+ });+ return this;+ } as MockAgentConstructor);++ const session = appendPendingInputBatch({+ requests: [+ {+ action: {+ callId: "call-1",+ input: { command: "rm -rf /tmp/demo" },+ kind: "tool-call",+ toolName: "bash",+ },+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId: "approval-1",+ },+ ],+ responseMessages: [+ {+ content: [+ {+ input: { command: "rm -rf /tmp/demo" },+ toolCallId: "call-1",+ toolName: "bash",+ type: "tool-call",+ },+ {+ approvalId: "approval-1",+ toolCallId: "call-1",+ type: "tool-approval-request",+ },+ ],+ role: "assistant",+ },+ ],+ session: createTestSession({+ agent: {+ modelReference: { id: "test-model" },+ system: "You are a test assistant.",+ tools: [+ { description: "Run shell commands", name: "bash", inputSchema: { type: "object" } },+ {+ description: "Ask the user a question.",+ name: "ask_question",+ inputSchema: { type: "object" },+ },+ ],+ },+ }),+ });+ const config = createTestConfig("conversation", undefined, {+ tools: new Map([+ [+ "bash",+ {+ description: "Run shell commands",+ execute: vi.fn().mockResolvedValue("ok"),+ inputSchema: jsonSchema({ type: "object" }),+ name: "bash",+ },+ ],+ ]),+ });++ // The intervening turn raises its own question batch; the approval batch+ // must survive it instead of being overwritten.+ const questionTurn = await createToolLoopHarness(config)(session, {+ message: "Ask me which color to use.",});- expect(secondResult.session.history.at(-1)).toEqual({- content: "Hello!",+ expect(questionTurn.next).toBeNull();+ expect(getPendingInputRequestIds(questionTurn.session.state)).toEqual(+ new Set(["approval-1", "question-call"]),+ );++ // Answering the question closes only its own batch.+ const answered = await createToolLoopHarness(config)(questionTurn.session, {+ inputResponses: [{ requestId: "question-call", optionId: "red" }],+ });+ expect(getPendingInputRequestIds(answered.session.state)).toEqual(new Set(["approval-1"]));+ const answeredPrompt = generateCalls[1] ?? [];+ expect(+ answeredPrompt.some((message) => JSON.stringify(message.content).includes("question-call")),+ ).toBe(true);+ expect(+ answeredPrompt.some((message) => JSON.stringify(message.content).includes("call-1")),+ ).toBe(false);++ // The original approval still resolves afterwards.+ const denied = await createToolLoopHarness(config)(answered.session, {+ inputResponses: [{ requestId: "approval-1", optionId: "cancel" }],+ });+ expect(hasPendingInputBatch(denied.session.state)).toBe(false);+ expect(denied.session.history.at(-1)).toEqual({+ content: "Understood, not running it.",role: "assistant",});});+ it("releases a message wedged behind an approval by an earlier version", async () => {+ const generateCalls: Array<Array<{ role: string; content: unknown }>> = [];+ const stillHere = {+ finishReason: "stop",+ response: { messages: [{ content: "Still here!", role: "assistant" }] },+ text: "Still here!",+ toolCalls: [],+ toolResults: [],+ };+ vi.mocked(ToolLoopAgent).mockImplementation(function (+ this: MockAgentInstance,+ settings: MockAgentSettings,+ ) {+ const { onStepFinish, prepareStep } = settings;+ this.generate = vi.fn().mockImplementation(async (input: { messages: unknown[] }) => {+ if (prepareStep) {+ await prepareStep({+ messages: input.messages,+ steps: [],+ stepNumber: 0,+ model: {},+ context: undefined,+ });+ }+ generateCalls.push(input.messages as Array<{ role: string; content: unknown }>);+ if (onStepFinish) await onStepFinish(stillHere);+ return createMockGenerateResult(stillHere);+ });+ return this;+ } as MockAgentConstructor);++ // A session wedged by the pre-collection deferral: the singleton batch+ // key plus a message swallowed into the deferred step input.+ const session = createTestSession({+ agent: {+ modelReference: { id: "test-model" },+ system: "You are a test assistant.",+ tools: [+ { description: "Run shell commands", name: "bash", inputSchema: { type: "object" } },+ ],+ },+ });+ const wedged = {+ ...session,+ state: {+ "eve.runtime.deferredStepInput": { message: "Wedged hello." },+ "eve.runtime.pendingInputBatch": {+ requests: [+ {+ action: {+ callId: "call-1",+ input: { command: "rm -rf /tmp/demo" },+ kind: "tool-call",+ toolName: "bash",+ },+ allowFreeform: false,+ display: "confirmation",+ kind: "tool-approval",+ options: [+ { id: "approve", label: "Yes" },+ { id: "cancel", label: "No" },+ ],+ prompt: "Approve tool call: bash",+ requestId: "approval-1",+ },+ ],+ responseMessages: [+ {+ content: [+ {+ input: { command: "rm -rf /tmp/demo" },+ toolCallId: "call-1",+ toolName: "bash",+ type: "tool-call",+ },+ {+ approvalId: "approval-1",+ toolCallId: "call-1",+ type: "tool-approval-request",+ },+ ],+ role: "assistant",+ },+ ],+ },+ },+ };++ const result = await createToolLoopHarness(createTestConfig("conversation"))(wedged, {+ message: "Are you there?",+ });++ // The wedged message finally runs as an ordinary turn; the approval+ // stays open and answerable.+ expect(generateCalls).toHaveLength(1);+ const lastMessages = (generateCalls[0] ?? []).filter((message) => message.role === "user");+ expect(JSON.stringify(lastMessages)).toContain("Wedged hello.");+ expect(JSON.stringify(lastMessages)).toContain("Are you there?");+ expect(hasDeferredStepInput(result.session)).toBe(false);+ expect(getPendingInputRequestIds(result.session.state)).toEqual(new Set(["approval-1"]));+ });+it("consumes text approval shortcuts without appending them as user messages", async () => {const generateCalls: unknown[] = [];@@ -7373,7 +7700,7 @@ describe("createToolLoopHarness", () => {? (settings: S) => ToolLoopAgent: never);- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -7566,26 +7893,26 @@ describe("createToolLoopHarness", () => {});});- it("deferred message lands as last non-system message after explicit approval denial", async () => {- // Step 1: pending approval + user sends a follow-up message. The approval- // remains pending and the message is deferred. Step 2: the user denies the- // approval. Step 3: the deferred message is consumed and appears as the- // last message the model sees.+ it("follow-up message precedes a late approval denial in committed history", async () => {+ // Step 1: pending approval + user sends a follow-up message. The message+ // runs as an ordinary turn while the approval stays open. Step 2: the+ // user denies the approval; the withheld batch is restored behind the+ // intervening exchange and resolves as denied.const generateCalls: Array<Array<{ role: string; content: unknown }>> = [];const agentResults = [{finishReason: "stop",- response: {- messages: [{ content: "I will not run that command.", role: "assistant" }],- },- text: "I will not run that command.",+ response: { messages: [{ content: "Sure, here you go.", role: "assistant" }] },+ text: "Sure, here you go.",toolCalls: [],toolResults: [],},{finishReason: "stop",- response: { messages: [{ content: "Sure, here you go.", role: "assistant" }] },- text: "Sure, here you go.",+ response: {+ messages: [{ content: "I will not run that command.", role: "assistant" }],+ },+ text: "I will not run that command.",toolCalls: [],toolResults: [],},@@ -7621,7 +7948,7 @@ describe("createToolLoopHarness", () => {? (settings: S) => ToolLoopAgent: never);- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -7684,35 +8011,261 @@ describe("createToolLoopHarness", () => {]),});- // Step 1: user sends "Do something else" while approval is pending.- // Approval remains pending; message is deferred.+ // Step 1: the follow-up message runs immediately; the approval stays open.const firstResult = await createToolLoopHarness(config)(session, {message: "Do something else",});expect(firstResult.next).toBeNull();- expect(generateCalls).toEqual([]);+ expect(generateCalls).toHaveLength(1);+ expect(generateCalls[0]?.at(-1)).toEqual({ content: "Do something else", role: "user" });+ expect(hasPendingInputBatch(firstResult.session.state)).toBe(true);- // Step 2: user denies the approval; the deferred message is NOT in this call.+ // Step 2: the late denial restores the withheld batch behind the+ // intervening exchange; the model sees the denial as the tail.const deniedResult = await createToolLoopHarness(config)(firstResult.session, {inputResponses: [{ requestId: "approval-1", optionId: "cancel" }],});- expect(typeof deniedResult.next).toBe("function");- const step2Last = generateCalls[0]?.at(-1);- expect(step2Last?.role).toBe("tool");+ expect(generateCalls).toHaveLength(2);+ expect(generateCalls[1]?.at(-1)?.role).toBe("tool");- // Step 3: harness consumes the deferred message.- const secondResult = await createToolLoopHarness(config)(deniedResult.session);- expect(secondResult.next).toBeNull();+ // Committed history keeps the intervening exchange before the batch.+ const history = deniedResult.session.history;+ expect(history[0]).toEqual({ content: "Do something else", role: "user" });+ expect(history[1]).toEqual({ content: "Sure, here you go.", role: "assistant" });+ expect(history.at(-1)).toEqual({+ content: "I will not run that command.",+ role: "assistant",+ });+ expect(hasPendingInputBatch(deniedResult.session.state)).toBe(false);+ });- // The deferred user message is the last message the model sees.- const step3Last = generateCalls[1]?.at(-1);- expect(step3Last).toEqual({ content: "Do something else", role: "user" });+ it.each([+ { delegated: false, label: "task" },+ { delegated: true, label: "delegated task" },+ ])(+ "defers an unrelated message behind an open approval in $label mode",+ async ({ delegated }) => {+ const { emit, events } = createEventCollector();+ const config = createTestConfig("task", emit, {+ capabilities: { requestInput: true },+ tools: new Map([+ [+ "bash",+ {+ description: "Run shell commands",+ execute: vi.fn().mockResolvedValue("ok"),+ inputSchema: jsonSchema({ type: "object" }),+ name: "bash",+ },+ ],+ ]),+ });+ const run = () =>+ createToolLoopHarness(config)(createPendingBashApprovalSession(), {+ message: "Do something unrelated.",+ });- // History reflects the full conversation.- expect(secondResult.session.history.at(-1)).toEqual({- content: "Sure, here you go.",- role: "assistant",+ let result: Awaited<ReturnType<typeof run>>;+ if (delegated) {+ const ctx = new ContextContainer();+ setDelegatedParent(ctx);+ result = await contextStorage.run(ctx, run);+ } else {+ result = await run();+ }++ expect(vi.mocked(ToolLoopAgent)).not.toHaveBeenCalled();+ expect(result.next).toBeNull();+ expect(getPendingInputRequestIds(result.session.state)).toEqual(new Set(["approval-1"]));+ expect(hasDeferredStepInput(result.session)).toBe(true);+ expect(events.some((event) => event.type === "session.completed")).toBe(false);+ },+ );++ it.each([+ { approved: true, reply: "approve" },+ { approved: false, reply: "cancel" },+ ])(+ "resolves text $reply before replaying a deferred task message",+ async ({ approved, reply }) => {+ const generateCalls: Array<Array<{ content: unknown; role: string }>> = [];+ const agentResults = [+ {+ finishReason: "stop",+ response: { messages: [{ content: "Approval resolved.", role: "assistant" }] },+ text: "Approval resolved.",+ toolCalls: [],+ toolResults: [],+ },+ {+ finishReason: "stop",+ response: { messages: [{ content: "Task complete.", role: "assistant" }] },+ text: "Task complete.",+ toolCalls: [],+ toolResults: [],+ },+ ] satisfies Record<string, unknown>[];+ let resultIndex = 0;+ vi.mocked(ToolLoopAgent).mockImplementation(function (+ this: MockAgentInstance,+ settings: MockAgentSettings,+ ) {+ const result = agentResults[resultIndex++];+ if (result === undefined) throw new Error("ToolLoopAgent mock exhausted its results.");+ const { onStepFinish, prepareStep } = settings;+ this.generate = vi.fn().mockImplementation(async (input: { messages: unknown[] }) => {+ if (prepareStep) {+ await prepareStep({+ context: undefined,+ messages: input.messages,+ model: {},+ stepNumber: 0,+ steps: [],+ });+ }+ generateCalls.push(input.messages as Array<{ content: unknown; role: string }>);+ if (onStepFinish) await onStepFinish(result);+ return createMockGenerateResult(result);+ });+ return this;+ } as MockAgentConstructor);++ const config = createTestConfig("task", undefined, {+ capabilities: { requestInput: true },+ tools: new Map([+ [+ "bash",+ {+ description: "Run shell commands",+ execute: vi.fn().mockResolvedValue("ok"),+ inputSchema: jsonSchema({ type: "object" }),+ name: "bash",+ },+ ],+ ]),+ });+ const harness = createToolLoopHarness(config);+ const deferred = await harness(createPendingBashApprovalSession(), {+ message: "Do something unrelated.",+ });++ const resolved = await harness(deferred.session, { message: reply });++ expect(generateCalls).toHaveLength(1);+ const approvalMessage = generateCalls[0]?.at(-1);+ expect(approvalMessage?.role).toBe("tool");+ expect(approvalMessage?.content).toEqual(+ expect.arrayContaining([expect.objectContaining({ approvalId: "approval-1", approved })]),+ );+ expect(hasPendingInputBatch(resolved.session.state)).toBe(false);+ expect(hasDeferredStepInput(resolved.session)).toBe(true);+ expect(typeof resolved.next).toBe("function");+ if (typeof resolved.next !== "function") throw new Error("Expected deferred replay step.");++ const completed = await resolved.next(resolved.session);++ expect(generateCalls).toHaveLength(2);+ expect(generateCalls[1]?.at(-1)).toEqual({+ content: "Do something unrelated.",+ role: "user",+ });+ expect(completed.next).toEqual({ done: true, output: "Task complete." });+ },+ );++ it("continues deferred input when approval resolution raises another request", async () => {+ setupMockAgentSequence([+ {+ finishReason: "tool-calls",+ response: {+ messages: [+ {+ content: [+ {+ input: { prompt: "Which color?" },+ toolCallId: "question-1",+ toolName: "ask_question",+ type: "tool-call",+ },+ ],+ role: "assistant",+ },+ ],+ },+ text: "",+ toolCalls: [+ {+ input: { prompt: "Which color?" },+ toolCallId: "question-1",+ toolName: "ask_question",+ type: "tool-call",+ },+ ],+ toolResults: [],+ },+ {+ finishReason: "stop",+ response: { messages: [{ content: "Handled the deferred message.", role: "assistant" }] },+ text: "Handled the deferred message.",+ toolCalls: [],+ toolResults: [],+ },+ ]);++ const base = createPendingBashApprovalSession();+ const session = {+ ...base,+ agent: {+ ...base.agent,+ tools: [+ ...base.agent.tools,+ {+ description: "Ask the user a question.",+ inputSchema: { type: "object" },+ name: "ask_question",+ },+ ],+ },+ };+ const config = createTestConfig("conversation", undefined, {+ tools: new Map([+ [+ "bash",+ {+ description: "Run shell commands",+ execute: vi.fn().mockResolvedValue("ok"),+ inputSchema: jsonSchema({ type: "object" }),+ name: "bash",+ },+ ],+ [+ "ask_question",+ {+ description: "Ask the user a question.",+ inputSchema: jsonSchema({ type: "object" }),+ name: "ask_question",+ },+ ],+ ]),+ });+ const runStep = createToolLoopHarness(config);++ const first = await runStep(session, {+ inputResponses: [{ optionId: "cancel", requestId: "approval-1" }],+ message: "Use this instead.",});++ expect(typeof first.next).toBe("function");+ expect(getPendingInputRequestIds(first.session.state)).toEqual(new Set(["question-1"]));+ if (typeof first.next !== "function") {+ throw new TypeError("Expected deferred input to continue after the new question.");+ }+ const result = await first.next(first.session);++ expect(result.next).toBeNull();+ expect(hasDeferredStepInput(result.session)).toBe(false);+ expect(hasPendingInputBatch(result.session.state)).toBe(false);+ expect(JSON.stringify(result.session.history)).toContain("Use this instead.");});it("emits input.requested for ask_question and does not emit actions.requested", async () => {@@ -7867,7 +8420,7 @@ describe("createToolLoopHarness", () => {],prompt: "Which context should I use?",};- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {@@ -7954,7 +8507,7 @@ describe("createToolLoopHarness", () => {],prompt: "Which context should I use?",};- const session = setPendingInputBatch({+ const session = appendPendingInputBatch({requests: [{action: {diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 248dc9bab..5f1f3c603 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -127,9 +127,10 @@ import {getApprovedTools,getPendingInputRequestIds,hasDeferredStepInput,+ hasPendingApprovalBatch,hasStepInput,resolvePendingInput,- setPendingInputBatch,+ appendPendingInputBatch,} from "#harness/input-requests.js";import {convertStaleResponsesToUserMessage,@@ -699,7 +700,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// Resolve deferred input, runtime actions, then HITL input; each stage// may park when its resume payload has not arrived.- const stepInput = consumeDeferredStepInput({ input, session });+ const stepInput = consumeDeferredStepInput({+ input,+ preferCurrentInput:+ config.mode !== "conversation" && input !== undefined && hasPendingApprovalBatch(session),+ session,+ });session = stepInput.session;const resolvedRuntimeActions = await resolvePendingRuntimeActions({@@ -731,13 +737,19 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {: effectiveStepInput;const pending = resolvePendingInput({+ deferMessagesWhileApprovalsPending: config.mode !== "conversation",history: resolvedRuntimeActions.messages,resolveApprovalKey: resolveApprovalKeyFromTools(config.tools),session,stepInput: effectiveStepInput,});if (pending.outcome === "unresolved") {- if (emit && pending.deferredMessage === true && hasStepInput(input)) {+ if (+ emit &&+ config.mode === "conversation" &&+ pending.deferredMessage === true &&+ hasStepInput(input)+ ) {try {emissionState = await emitTurnPreamble(emit,@@ -769,16 +781,18 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {// observability) never see the tool call resolve. Attributed to the turn// that requested approval via the parked batch's emit coordinates.if (emit && pending.rejectedActions) {- for (const result of pending.rejectedActions.results) {- await emit(- createActionResultEvent({- rejected: true,- result,- sequence: pending.rejectedActions.event.sequence,- stepIndex: pending.rejectedActions.event.stepIndex,- turnId: pending.rejectedActions.event.turnId,- }),- );+ for (const rejectedBatch of pending.rejectedActions) {+ for (const result of rejectedBatch.results) {+ await emit(+ createActionResultEvent({+ rejected: true,+ result,+ sequence: rejectedBatch.event.sequence,+ stepIndex: rejectedBatch.event.stepIndex,+ turnId: rejectedBatch.event.turnId,+ }),+ );+ }}}@@ -2215,7 +2229,7 @@ async function handleStepResult(input: {// --- Park on input requests -----------------------------------------------if (inputRequests.length > 0) {- let parkedSession = setPendingInputBatch({+ let parkedSession = appendPendingInputBatch({event: {sequence: emissionState.sequence,stepIndex: emissionState.stepIndex,@@ -2242,7 +2256,10 @@ async function handleStepResult(input: {}}- return { next: null, session: parkedSession };+ return {+ next: hasDeferredStepInput(parkedSession) ? runStep : null,+ session: parkedSession,+ };}// --- Park on authorization request ------------------------------------------