The Open Framework for Building Agents
fix(eve): park the turn again after a partial answer to relayed questions (#4280)
e0-gh-vercel-connect[bot]983c37504a24
diff --git a/.changeset/partial-ask-turn-waiting.md b/.changeset/partial-ask-turn-waiting.mdnew file mode 100644index 000000000..c9f710b4d--- /dev/null+++ b/.changeset/partial-ask-turn-waiting.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Answering some of several pending `ctx.ask()` or subagent questions now parks the open turn again with `turn.waiting`, as a partial answer to tool approvals already does, so clients waiting for the next rest point stop reading instead of hanging until the last answer.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 11e52ca50..cbcd11718 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -123,7 +123,7 @@ Note: consider the privacy, confidentiality, and user-experience implications foA delegated subagent publishes progress on its own child-session stream. When a subagent tool call or a workflow tool's `ctx.agent` opens a session, the parent emits `agent.started` with the call's `callId` and `turnId`, its `taskId` when the call runs as a task, the child's `sessionId`, and a `streamPath` that a client follows with `session.agent(started).stream()`. A subagent tool call is a [task](#task-events) whose `task.started` has `kind: "agent"`: its `task.started` and `task.settled` carry the call, and `task.settled.data.output` is the child's reply. A call that fails before the child session opens has no `agent.started`. A settled call does not end the child session; later calls with the same `taskId` reach it.-A question or sign-in from inside a running call does not end the turn. This covers a workflow tool's `ctx.ask()`, including the built-in `ask_question` tool, and a delegated subagent's question or sign-in. The stream emits `input.requested` or `authorization.required`, then `turn.waiting` with `on: "input"` and the open turn's `turnId`. After the answer or sign-in, the turn resumes with the next `step.started` for the same `turnId`, and only `turn.completed`, `turn.failed`, or `turn.cancelled` ends it. When you answer a question that belongs to a workflow tool or a subagent, the session you answer on emits `input.resolved` for it as it routes the answer down. If the workflow tool run that relayed a question or approval ends before anyone answers, that session emits `input.resolved` with `outcome: "cancelled"` for it. This covers the run's own `ctx.ask()` questions and requests from sessions it opened with `ctx.agent`. A cancelled turn does the same for every question or approval the session relays. A sign-in or tool approval the turn raises itself holds it the same way, also with `on: "input"`. A message from the same person steers the turn and cancels the request: a sign-in reports `authorization.completed` with `outcome: "declined"`, and an approval reports `input.resolved` with `outcome: "ignored"`. Messages from other people wait until the turn ends. Cancelling the turn ends both: a held sign-in reports `authorization.completed` with `outcome: "declined"`, and a held approval reports `input.resolved` with `outcome: "cancelled"`.+A question or sign-in from inside a running call does not end the turn. This covers a workflow tool's `ctx.ask()`, including the built-in `ask_question` tool, and a delegated subagent's question or sign-in. The stream emits `input.requested` or `authorization.required`, then `turn.waiting` with `on: "input"` and the open turn's `turnId`. After the answer or sign-in, the turn resumes with the next `step.started` for the same `turnId`, and only `turn.completed`, `turn.failed`, or `turn.cancelled` ends it. When you answer a question that belongs to a workflow tool or a subagent, the session you answer on emits `input.resolved` for it as it routes the answer down. While other relayed questions are still pending, it then emits `turn.waiting` with `on: "input"` again. If the workflow tool run that relayed a question or approval ends before anyone answers, that session emits `input.resolved` with `outcome: "cancelled"` for it. This covers the run's own `ctx.ask()` questions and requests from sessions it opened with `ctx.agent`. A cancelled turn does the same for every question or approval the session relays. A sign-in or tool approval the turn raises itself holds it the same way, also with `on: "input"`. A message from the same person steers the turn and cancels the request: a sign-in reports `authorization.completed` with `outcome: "declined"`, and an approval reports `input.resolved` with `outcome: "ignored"`. Messages from other people wait until the turn ends. Cancelling the turn ends both: a held sign-in reports `authorization.completed` with `outcome: "declined"`, and a held approval reports `input.resolved` with `outcome: "cancelled"`.### Task eventsdiff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.tsindex 6ec9bc2d0..d1029d0dd 100644--- a/packages/eve/src/execution/proxied-deliver-step.ts+++ b/packages/eve/src/execution/proxied-deliver-step.ts@@ -21,7 +21,7 @@ import {resolveRemoteAgentStreamHeaders,respondToRemoteAgentSession,} from "#execution/agent-sessions/remote.js";-import { routeDeliverPayload } from "#subagents/hitl-proxy.js";+import { createTurnWaitingOnInputEvent, routeDeliverPayload } from "#subagents/hitl-proxy.js";import { resumeSessionInbox } from "#execution/session-inbox/resume.js";import {sendWorkflowAskAnswers,@@ -195,6 +195,16 @@ async function routeProxiedDeliver(durableSession = retireProxyInputRequests(durableSession, [...child.resolutions.keys()]);retired = true;}+ // Answers that leave requests pending, and nothing for the turn itself, keep+ // the open turn held, so it parks again as after a partial approval answer.+ if (+ resolvedEvents.length > 0 &&+ parentPayloads.size === 0 &&+ parentAction === undefined &&+ getProxyInputRequests(durableSession.state).size > 0+ ) {+ resolvedEvents.push(createTurnWaitingOnInputEvent(durableSession));+ }const context = await relaySessionEvents({diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.tsindex b738f9f49..79d3a477a 100644--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts@@ -16,6 +16,7 @@ import {askThenRaceWorkflow,answerWithResponderWorkflow,confirmDeployWorkflow,+ confirmTwoStepsWorkflow,deployServiceWorkflow,failingDeployWorkflow,reportingDeployWorkflow,@@ -320,6 +321,72 @@ describe("workflow tools", () => {});}, 60_000);+ it("parks the open turn again when one of two pending ctx.ask questions is answered", async () => {+ const runtime = await createWorkflowToolRuntime({+ agentName: "workflow-tool-two-asks",+ execute: confirmTwoStepsWorkflow,+ toolName: "confirm_deploy",+ });++ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: 'Run confirm_deploy with service "api"' },+ serializedContext: buildWorkflowToolSerializedContext({+ continuationToken: "http:workflow-tool-two-asks",+ requestInput: true,+ }),+ },+ ]);+ const stream = captureTurnEvents(run);+ const answer = async (requestId: string) =>+ await resumeSessionInbox(sessionCommandHookToken(run.runId), {+ kind: "send",+ payload: { inputResponses: [{ optionId: "approve", requestId }] },+ });+ const requestIds = (events: readonly MessageStreamEvent[]) =>+ filterEventsByType(events, "input.requested").flatMap((event) =>+ event.data.requests.map((request) => request.requestId),+ );+ try {+ const asked: MessageStreamEvent[] = [];+ await stream.nextUntil((event) => {+ asked.push(event);+ return event.type === "turn.waiting" && requestIds(asked).length === 2;+ });+ const [first, second] = requestIds(asked);+ const parked = filterEventsByType(asked, "turn.waiting").at(-1)!;++ await answer(first!);+ const answeredFirst = await stream.nextUntil((event) => event.type === "input.resolved");+ await answer(second!);+ const answeredSecond = await stream.nextUntil((event) => event.type === "turn.completed");++ // The second question still holds the turn, so the first answer ends+ // at a new rest point, as a partial answer to two approvals does.+ const events = [...answeredFirst, ...answeredSecond];+ const resolvedSecond = events.findIndex(+ (event) =>+ event.type === "input.resolved" &&+ event.data.resolutions.some((resolution) => resolution.requestId === second),+ );+ expect(events.slice(0, resolvedSecond).map((event) => event.type)).toEqual([+ "input.resolved",+ "turn.waiting",+ ]);+ expect(filterEventsByType(events, "turn.waiting")[0]?.data).toMatchObject({+ on: "input",+ turnId: parked.data.turnId,+ });+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ }, 60_000);+it("lets a deadline win a race against an unanswered ask and withdraws the ask", async () => {const runtime = await createWorkflowToolRuntime({agentName: "workflow-tool-ask-deadline",diff --git a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts b/packages/eve/src/internal/testing/workflow-tool-fixtures.tsindex b236cae65..cc1f2834c 100644--- a/packages/eve/src/internal/testing/workflow-tool-fixtures.ts+++ b/packages/eve/src/internal/testing/workflow-tool-fixtures.ts@@ -157,6 +157,21 @@ export async function answerWithResponderWorkflow(return JSON.stringify({ answer, runStartPrincipal: ctx.session.auth.current?.principalId });}+/** Asks two questions at once, so answering one leaves the other pending. */+export async function confirmTwoStepsWorkflow(+ input: DeployInput,+ ctx: WorkflowToolContext,+): Promise<{ readonly migrate: string; readonly rollout: string }> {+ "use workflow";++ const options = [{ id: "approve", label: "Approve" }];+ const [migrate, rollout] = await Promise.all([+ ctx.ask({ display: "confirmation", options, prompt: `Migrate ${input.service}?` }),+ ctx.ask({ display: "confirmation", options, prompt: `Roll out ${input.service}?` }),+ ]);+ return { migrate: migrate.status, rollout: rollout.status };+}+export async function failingDeployWorkflow(input: DeployInput): Promise<never> {"use workflow";diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex ab3a1849c..45409ca41 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -48,7 +48,7 @@ export async function emitProxiedInputRequest(input: {turnId: input.hookPayload.event.turnId,}),);- await emitTurnWaiting(input.emit, input.session);+ await input.emit(createTurnWaitingOnInputEvent(input.session));return toProxyInputRequestEntries(input.hookPayload);}@@ -65,20 +65,19 @@ export async function emitProxiedAuthorizationEvent(input: {}): Promise<void> {await input.emit(input.hookPayload.event);if (input.hookPayload.event.type === "authorization.required") {- await emitTurnWaiting(input.emit, input.session);+ await input.emit(createTurnWaitingOnInputEvent(input.session));}}-async function emitTurnWaiting(emit: HarnessEmitFn, session: HarnessSessionBase): Promise<void> {+/** The `turn.waiting` that parks the session's open turn while a person must act. */+export function createTurnWaitingOnInputEvent(session: Pick<HarnessSessionBase, "state">) {const turn = getHarnessEmissionState(session.state);- await emit(- createTurnWaitingEvent({- on: "input",- sequence: turn.sequence,- turnId: turn.turnId,- usage: getSessionUsage(session),- }),- );+ return createTurnWaitingEvent({+ on: "input",+ sequence: turn.sequence,+ turnId: turn.turnId,+ usage: getSessionUsage(session),+ });}// ---------------------------------------------------------------------------