The Open Framework for Building Agents
[2/2] fix(eve): keep a subagent's approval open until the subagent settles it (#4428)
Ben Pankow6ab30a50b446
diff --git a/.changeset/subagent-approval-settlement.md b/.changeset/subagent-approval-settlement.mdnew file mode 100644index 000000000..31ebd1900--- /dev/null+++ b/.changeset/subagent-approval-settlement.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A subagent's tool approval now stays open on the parent until the subagent settles it. If the subagent's response policy refuses the person who answered, someone else can still answer it, by text or button, instead of the prompt disappearing while the subagent waits. The parent closes the prompt when it relays the subagent's own `input.resolved`, so channels such as Telegram and Discord clear its buttons.diff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex d5803200b..3abce8dcf 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. 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"`.+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. A subagent's tool approval instead stays open until the subagent resolves it, and the session relays that subagent's `input.resolved`. 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/docs/subagents/index.mdx b/docs/subagents/index.mdxindex 02fe91ca5..4b5bdba65 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -229,7 +229,7 @@ By default, a subagent named `researcher` collides with an authored tool named `Do not rely on subagent delegation by itself as an approval boundary. Put sensitive tools behind `approval`, connection approval, route/session authorization, or other controls wherever those tools can be called.-Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. On text-only channels, a typed reply that matches an option of the first open prompt, such as `approve` for a tool approval or `continue` for a session limit, answers it as the person who typed it, so a person answers several proxied prompts one message at a time. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails, along with the same tool `name` and `kind: "agent"` as the call's `task.started`. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.+Each delegated subagent spins up its own child session and stream. The parent stream carries the call's `task.started` and `task.settled` events, `agent.started` when the child session opens, plus interactive `input.requested`, `authorization.required`, and `authorization.completed` events proxied from descendants so the root channel can prompt the user. The parent emits `input.resolved` when it routes an answer back down to the descendant that asked. A tool approval is the exception: the descendant decides it, since its response policy can refuse the person who answered, so the approval stays open on the parent until the descendant settles or resolves it. The parent relays the descendant's `approval.settled` and `input.resolved` for it. On text-only channels, a typed reply that matches an option of the first open prompt, such as `approve` for a tool approval or `continue` for a session limit, answers it as the person who typed it, so a person answers several proxied prompts one message at a time. `task.settled` carries the child's reply as `output` when the call completes, or `error.message` when it fails, along with the same tool `name` and `kind: "agent"` as the call's `task.started`. To follow the child's other progress, pass the `agent.started` event to [`session.agent()`](./guides/client/streaming#follow-a-subagent) on a client session attached to the parent and follow the child with `stream()`. It reads `agent.started.data.streamPath`: the child's own session stream for a local child, or a parent-origin proxy for a remote child, which the parent authenticates to the remote deployment.`agent.started` carries the `callId` and `turnId` of the call that opened the session, the call's `taskId`, the agent `name`, and the child's `sessionId`. Later calls with the same `taskId` reach the same session and do not announce it again, so match a child to its calls by `taskId`. A session an authored workflow tool opens with `ctx.agent` is announced the same way, with its `taskId` only when the workflow tool call runs as a task.diff --git a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/agent.tsindex 653b2e9a8..e7b520f24 100644--- a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts+++ b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts@@ -25,6 +25,16 @@ function respond(request: MockModelRequest): MockModelResponse | string {],};}+ if (message.includes("Call the release-pair subagent exactly once")) {+ const result = taskResultOf(request, "release-pair");+ if (result !== undefined) return `The release-pair subagent returned: ${result}`;+ if (hasReceipt(request, "release-pair")) return waitForTasks();+ return {+ toolCalls: [+ { input: { message: "Deploy the release and publish its notes." }, name: "release-pair" },+ ],+ };+ }if (message.includes("Call the stock-price subagent exactly once")) {const quote = taskResultOf(request, "stock-price");if (quote !== undefined) return `The stock-price subagent returned: ${quote}`;diff --git a/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/agent.tsnew file mode 100644index 000000000..fa9befd2f--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/agent.ts@@ -0,0 +1,22 @@+import { defineAgent } from "eve";+import { mockModel } from "eve/evals";++export const RELEASE_PAIR_MARKER = "RELEASE-PAIR-DONE-4T8Q";++export default defineAgent({+ description: "Deploy a release and publish its notes, asking for approval of each.",+ // Both gated calls in one step, so the parent relays two approvals at once.+ model: mockModel(({ toolResults }) => {+ if (toolResults.length === 0) {+ return {+ toolCalls: [+ { input: {}, name: "deploy_release" },+ { input: {}, name: "publish_notes" },+ ],+ };+ }+ const outputs = toolResults.map((result) => `${result.name}=${JSON.stringify(result.output)}`);+ return `${RELEASE_PAIR_MARKER} ${outputs.join(" ")}`;+ }),+ modelContextWindowTokens: 1_000_000,+});diff --git a/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/tools/deploy_release.ts b/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/tools/deploy_release.tsnew file mode 100644index 000000000..024448ee3--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/tools/deploy_release.ts@@ -0,0 +1,12 @@+import { defineTool } from "eve/tools";+import { always } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ approval: always(),+ description: "Deploy the release.",+ inputSchema: z.object({}),+ async execute() {+ return { deployed: true };+ },+});diff --git a/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/tools/publish_notes.ts b/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/tools/publish_notes.tsnew file mode 100644index 000000000..57673d5cd--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/agent/subagents/release-pair/tools/publish_notes.ts@@ -0,0 +1,12 @@+import { defineTool } from "eve/tools";+import { always } from "eve/tools/approval";+import { z } from "zod";++export default defineTool({+ approval: always(),+ description: "Publish the release notes.",+ inputSchema: z.object({}),+ async execute() {+ return { published: true };+ },+});diff --git a/e2e/fixtures/agent-subagents-hitl/evals/proxied-approvals-one-at-a-time.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/proxied-approvals-one-at-a-time.eval.tsnew file mode 100644index 000000000..e4e2c3945--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/evals/proxied-approvals-one-at-a-time.eval.ts@@ -0,0 +1,98 @@+import { defineEval } from "eve/evals";+import type { EveEvalContext, EveEvalSession, EveEvalTurn } from "eve/evals";++const MARKER = "RELEASE-PAIR-DONE-4T8Q";++/**+ * Alice asks the agent to ship a release through a subagent that needs two+ * approvals at once. On a text-only channel she answers them one message at a+ * time: each typed reply answers the first open approval only.+ */+export default defineEval({+ tags: ["session-inbox"],+ description: "Typed replies at the parent answer a subagent's two approvals one at a time.",+ timeoutMs: 90_000,++ async test(t) {+ const started = await t.send(+ "Call the release-pair subagent exactly once and relay its final result when it completes.",+ );+ const blocked = await waitForInputs(t, started.session, ["deploy_release", "publish_notes"]);++ const deployRequestId = blocked.pendingInputRequests[0]?.requestId;+ // The reply answers only the first approval. The subagent decides it, and the parent relays+ // its settlement before showing the next prompt; Alice replies once she sees that one.+ const approved = await blocked.send("approve");+ approved.noFailedActions();+ const settledInTurn = approved.events.some(+ (event) => event.type === "approval.settled" && event.data.requestId === deployRequestId,+ );+ if (!settledInTurn) {+ await watchNextTurn(t, approved.session, "deploy approval settlement").waitForEvent(+ "approval.settled",+ { data: { outcome: "approved", requestId: deployRequestId } },+ );+ }+ const resolved = approved.events.flatMap((event) =>+ event.type === "input.resolved" ? event.data.resolutions : [],+ );+ if (resolved.some((resolution) => resolution.requestId !== deployRequestId)) {+ throw new Error(`The first reply resolved ${JSON.stringify(resolved)}.`);+ }++ const cancelled = await approved.session.send("cancel");+ cancelled.noFailedActions();+ const completed = cancelled.message?.includes(MARKER)+ ? cancelled+ : await waitForMessage(t, approved.session, MARKER);+ completed.messageIncludes('deploy_release={"deployed":true}');+ if (completed.message?.includes('"published":true') === true) {+ throw new Error("The typed cancel ran publish_notes instead of denying it.");+ }++ t.calledSubagent("release-pair", { status: "completed", count: 1 });+ },+});++/** Waits until exactly `toolNames` have open approvals on the parent, in that order. */+async function waitForInputs(+ t: EveEvalContext,+ initialSession: EveEvalSession,+ toolNames: readonly string[],+): Promise<EveEvalSession> {+ let session = initialSession;+ const pending = () => session.pendingInputRequests.map((request) => request.action.toolName);+ for (let attempt = 0; attempt < 5; attempt += 1) {+ if (JSON.stringify(pending()) === JSON.stringify(toolNames)) return session;+ const live = watchNextTurn(t, session, "subagent input wait");+ const turn = await live.result();+ turn.noFailedActions();+ session = live.session;+ }+ throw new Error(+ `Expected open approvals ${JSON.stringify(toolNames)}, saw ${JSON.stringify(pending())}.`,+ );+}++async function waitForMessage(+ t: EveEvalContext,+ initialSession: EveEvalSession,+ marker: string,+): Promise<EveEvalTurn> {+ let session = initialSession;+ for (let attempt = 0; attempt < 5; attempt += 1) {+ const live = watchNextTurn(t, session, "subagent completion wait");+ const turn = await live.result();+ turn.noFailedActions();+ if (turn.message?.includes(marker) === true) return turn;+ session = live.session;+ }+ throw new Error("Subagent result did not reach the parent after five turns.");+}++function watchNextTurn(t: EveEvalContext, session: EveEvalSession, operation: string) {+ if (session.sessionId === undefined || session.state === undefined) {+ throw new Error(`${operation} has no parent session cursor.`);+ }+ return t.target.watchTurn(session.sessionId, { startIndex: session.state.streamIndex });+}diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex b9384d49b..7d85f3029 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -335,7 +335,10 @@ export interface SubagentInputRequestHookPayload {readonly subagentName: string;}-/** Responder-specific lifecycle event forwarded from a delegated child. */+/**+ * Lifecycle event forwarded from a delegated child: responder and sign-in progress, and the+ * resolution of its requests. The parent relays it unchanged.+ */export type SubagentAuthorizationEvent = Extract<UnstampedMessageStreamEvent,{@@ -343,7 +346,8 @@ export type SubagentAuthorizationEvent = Extract<| "approval.candidate"| "approval.settled"| "authorization.required"- | "authorization.completed";+ | "authorization.completed"+ | "input.resolved";}>;diff --git a/packages/eve/src/execution/forward-session-input.ts b/packages/eve/src/execution/forward-session-input.tsindex f7c8d2ac2..78a27e436 100644--- a/packages/eve/src/execution/forward-session-input.ts+++ b/packages/eve/src/execution/forward-session-input.ts@@ -7,6 +7,7 @@ import {SessionInboxKey,} from "#context/keys.js";import { forwardLegacySessionInput } from "#execution/legacy-remote-agent/protocol.js";+import { resolvedForParent } from "#harness/proxy-input-requests.js";import { postSessionCallbackRequest } from "#execution/session-callback-request.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -21,12 +22,18 @@ export async function forwardSessionInput(if (callback === undefined) return false;const legacyCaller = ctx.get(LegacyRemoteAgentCallerKey);if (legacyCaller !== undefined) return await forwardLegacySessionInput(ctx, legacyCaller, event);+ if (event.type === "input.resolved") {+ const relayed = resolvedForParent(event.data);+ if (relayed === undefined) return false;+ event = { data: relayed, type: "input.resolved" };+ }if (event.type !== "input.requested" &&event.type !== "authorization.required" &&event.type !== "authorization.completed" &&event.type !== "approval.candidate" &&- event.type !== "approval.settled"+ event.type !== "approval.settled" &&+ event.type !== "input.resolved")return false;diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.tsindex 23798f9e9..6a246d599 100644--- a/packages/eve/src/execution/proxied-deliver-step.ts+++ b/packages/eve/src/execution/proxied-deliver-step.ts@@ -116,7 +116,8 @@ async function routeProxiedDeliver(for (const [childIndex, forChild] of routed.forChildren.entries()) {if (forChild.workflowAsk !== undefined || forChild.message !== undefined) {- for (const { requestId } of forChild.resolved.resolutions) resolvedRequests.add(requestId);+ for (const { requestId } of forChild.payload.inputResponses)+ resolvedRequests.add(requestId);}if (forChild.message !== undefined) {const { sequence, turnId } = forChild.resolved.event;@@ -210,13 +211,19 @@ async function routeProxiedDeliver(}const view = sessionView(storedProjection(durableSession.state), durableSession.state);const resolvedEvents = [...routeAnswer(view, { children: answered }).events];- // 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.+ // Answers that leave other requests pending, and nothing for the turn itself, keep the+ // open turn held, so it parks again as after a partial approval answer. A forwarded approval+ // stays open until its child settles it, but it no longer waits on the person.+ const forwarded = new Set(+ [...children.values()].flatMap((child) =>+ child.payloads.flatMap((payload) => (payload.inputResponses ?? []).map((r) => r.requestId)),+ ),+ );if (- resolvedEvents.length > 0 &&+ children.size > 0 &&parentPayloads.size === 0 &&parentAction === undefined &&- getProxyInputRequests(durableSession.state).size > 0+ [...getProxyInputRequests(durableSession.state).keys()].some((id) => !forwarded.has(id))) {resolvedEvents.push(...hold(view, { on: "input" }).events);}diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex ae16b8eb9..692bf8962 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -40,6 +40,7 @@ import {positionState,withOpenTurn,withParkedStep,+ withPublished,withQueuedInput,} from "#internal/testing/session-machine.js";import type { HarnessSession, StepFn, StepResult } from "#harness/types.js";@@ -59,6 +60,7 @@ import {createDurableSessionValues,type DurableSessionState,readDurableSession,+ replaceDurableSessionSnapshot,} from "#execution/durable-session-store.js";import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";import { defineTool } from "#tools/definition.js";@@ -503,6 +505,83 @@ describe("routeProxiedDeliverStep", () => {});});+ describe("a forwarded subagent approval", () => {+ const auth = {+ attributes: {},+ authenticator: "test",+ principalId: "bob",+ principalType: "user",+ };+ const approvalRoute = {+ childContinuationToken: "child-token",+ event: REQUEST_EVENT,+ kind: "tool-approval" as const,+ reply: { options: [{ id: "approve", label: "Approve" }] },+ };+ function parkedOn(requestIds: readonly string[]) {+ const relayed = createInputRequestedEvent({+ ...REQUEST_EVENT,+ callId: "child-call",+ requests: requestIds.map((requestId) => ({+ action: { callId: requestId, input: {}, kind: "tool-call", toolName: "deploy" },+ kind: "tool-approval",+ options: approvalRoute.reply.options,+ prompt: "Approve deploy?",+ requestId,+ })),+ });+ const session = upsertProxyInputRequests({+ entries: requestIds.map((requestId) => [requestId, approvalRoute] as const),+ forChildContinuationToken: "child-token",+ session: withPublished(withOpenTurn(createStubSession(), REQUEST_EVENT), [relayed]),+ });+ // Read back what each step persists, so a later step sees the routes it left.+ vi.mocked(readDurableSession).mockImplementation((state) => state.snapshot!.session);+ return replaceDurableSessionSnapshot({ session, state: createStubSessionState() });+ }+ async function approveFirst(sessionState: DurableSessionState) {+ workflowWritesByNamespace.clear();+ const result = await runSessionStateStep(+ {+ serializedContext: createSerializedContext(),+ delivery: { auth, kind: "deliver" as const, payloads: [{ message: "approve" }] },+ sessionWritable: createTestWritable(),+ sessionState,+ },+ routeProxiedDeliverStep,+ );+ const writes = workflowWritesByNamespace.get(DEFAULT_WORKFLOW_STREAM_NAMESPACE) ?? [];+ const types = writes.map(+ (chunk) => JSON.parse(new TextDecoder().decode(chunk as Uint8Array)).type,+ );+ return { result, types };+ }++ it("stays answerable until the subagent closes it", async () => {+ // The child's response policy may refuse Bob, so a second reply still reaches it.+ const first = await approveFirst(parkedOn(["approval-1"]));+ await approveFirst(first.result.sessionState);++ expect(resumeHookMock).toHaveBeenCalledTimes(2);+ for (const [, delivery] of resumeHookMock.mock.calls) {+ expect(delivery).toMatchObject({+ payloads: [{ inputResponses: [{ optionId: "approve", requestId: "approval-1" }] }],+ });+ }+ expect(first.types).not.toContain("input.resolved");+ });++ it("holds the open turn while another approval still waits on a person", async () => {+ const { types } = await approveFirst(parkedOn(["approval-1", "approval-2"]));+ expect(types).toContain("turn.waiting");+ });++ it("does not hold the open turn on the approval it just forwarded", async () => {+ const { types } = await approveFirst(parkedOn(["approval-1"]));+ expect(types).not.toContain("turn.waiting");+ });+ });+it.each([["local", { "eve.channel": { kind: "subagent" } }],[diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.tsindex c18dbaf49..8ac0e077d 100644--- a/packages/eve/src/harness/proxy-input-requests.ts+++ b/packages/eve/src/harness/proxy-input-requests.ts@@ -1,4 +1,5 @@import type { SubagentInputRequestHookPayload } from "#channel/types.js";+import type { InputResolvedStreamEvent } from "#protocol/message.js";import type { StepCoordinates as PendingInputBatchEvent } from "#harness/session-machine/view.js";import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";import { inputOptionSchema, type InputOption, type InputRequestKind } from "#shared/input.js";@@ -61,6 +62,27 @@ export interface ProxyInputRequestBatch {readonly requestIds: readonly string[];}+/**+ * Whether the child, not this session, closes a relayed request. A child's tool approval can+ * refuse the person who answered, so it stays open here until the child's own `input.resolved`+ * or `approval.settled` arrives. This session closes every other relayed request once it+ * forwards the answer.+ */+export function resolvedByChild(kind: InputRequestKind): boolean {+ return kind === "tool-approval";+}++/**+ * The part of a child's `input.resolved` its parent relays: the requests the parent leaves for+ * the child to close. `undefined` when the parent already closed all of them.+ */+export function resolvedForParent(+ data: InputResolvedStreamEvent["data"],+): InputResolvedStreamEvent["data"] | undefined {+ const resolutions = data.resolutions.filter(({ kind }) => resolvedByChild(kind));+ return resolutions.length === 0 ? undefined : { ...data, resolutions };+}+/** `requestId → route` map stored on the parent session. */type ProxyInputRequestMap = Readonly<Record<string, ProxyInputRequest>>;diff --git a/packages/eve/src/subagents/adapter.test.ts b/packages/eve/src/subagents/adapter.test.tsindex 37a4d762c..b0bdd2ea8 100644--- a/packages/eve/src/subagents/adapter.test.ts+++ b/packages/eve/src/subagents/adapter.test.ts@@ -121,6 +121,38 @@ describe("SUBAGENT_ADAPTER authorization handlers", () => {});});+ it("forwards only the resolutions of requests its parent leaves to it", async () => {+ resumeHookMock.mockClear();+ const at = { sequence: 2, stepIndex: 1, turnId: "turn-hitl" };+ const approval = {+ kind: "tool-approval" as const,+ outcome: "approved" as const,+ requestId: "a",+ };+ const question = { kind: "question" as const, outcome: "answered" as const, requestId: "q" };++ await callAdapterEventHandler(+ SUBAGENT_ADAPTER,+ { data: { ...at, resolutions: [question] }, type: "input.resolved" },+ makeContext(),+ );+ expect(resumeHookMock).not.toHaveBeenCalled();++ await callAdapterEventHandler(+ SUBAGENT_ADAPTER,+ { data: { ...at, resolutions: [question, approval] }, type: "input.resolved" },+ makeContext(),+ );+ expect(resumeHookMock).toHaveBeenCalledOnce();+ expect(resumeHookMock).toHaveBeenCalledWith("parent-token", {+ callId: "call-123",+ childSessionId: "child-session",+ event: { data: { ...at, resolutions: [approval] }, type: "input.resolved" },+ kind: "subagent-authorization-event",+ subagentName: "linear",+ });+ });+it("skips forwarding when the adapter state is invalid", async () => {resumeHookMock.mockClear();const base = makeContext();diff --git a/packages/eve/src/subagents/adapter.ts b/packages/eve/src/subagents/adapter.tsindex 404ef04ba..5387a8dc5 100644--- a/packages/eve/src/subagents/adapter.ts+++ b/packages/eve/src/subagents/adapter.ts@@ -5,6 +5,7 @@ import type {SubagentInputRequestHookPayload,} from "#channel/types.js";import { ContinuationTokenKey, SessionIdKey, SessionInboxKey } from "#context/keys.js";+import { resolvedForParent } from "#harness/proxy-input-requests.js";import { SUBAGENT_ADAPTER_KIND, isSubagentAdapterState } from "#subagents/adapter-state.js";import { createErrorId, createLogger } from "#internal/logging.js";@@ -14,8 +15,9 @@ const log = createLogger("execution.subagent-adapter");* Framework adapter that bridges a child subagent session to its* parent.*- * It proxies child `input.requested` events upward so the parent channel- * can render HITL prompts and route responses back down to the child.+ * It proxies child `input.requested` events upward so the parent channel can+ * render HITL prompts and route responses back down to the child, and the+ * `input.resolved` of requests only the child can close.*/export const SUBAGENT_ADAPTER: ChannelAdapter = {kind: SUBAGENT_ADAPTER_KIND,@@ -31,6 +33,11 @@ export const SUBAGENT_ADAPTER: ChannelAdapter = {async "authorization.completed"(data, ctx) {await forwardSubagentAuthorizationEvent({ data, type: "authorization.completed" }, ctx);},+ async "input.resolved"(data, ctx) {+ const relayed = resolvedForParent(data);+ if (relayed === undefined) return;+ await forwardSubagentAuthorizationEvent({ data: relayed, type: "input.resolved" }, ctx);+ },async "input.requested"(data, ctx) {const state = ctx.state;diff --git a/packages/eve/src/subagents/callback-route.test.ts b/packages/eve/src/subagents/callback-route.test.tsindex 3db0f2092..0bcdca733 100644--- a/packages/eve/src/subagents/callback-route.test.ts+++ b/packages/eve/src/subagents/callback-route.test.ts@@ -133,7 +133,7 @@ describe("session callback route", () => {]);});- it.each(["approval.candidate", "approval.settled"])(+ it.each(["approval.candidate", "approval.settled", "input.resolved"])("rejects a malformed %s callback before it reaches the parent channel",async (type) => {const response = await handleSessionCallbackRequest(@@ -154,19 +154,21 @@ describe("session callback route", () => {},);- it("relays a well-formed approval settlement", async () => {- resumeHookMock.mockResolvedValue(undefined);- const event = {+ const at = { sequence: 0, stepIndex: 1, turnId: "child-turn" };+ it.each([+ {type: "approval.settled",+ data: { ...at, outcome: "approved", requestId: "approval-1", responderPrincipalId: "alice" },+ },+ {+ type: "input.resolved",data: {- outcome: "approved",- requestId: "approval-1",- responderPrincipalId: "alice",- sequence: 0,- stepIndex: 1,- turnId: "child-turn",+ ...at,+ resolutions: [{ kind: "tool-approval", outcome: "approved", requestId: "approval-1" }],},- };+ },+ ])("relays a well-formed $type", async (event) => {+ resumeHookMock.mockResolvedValue(undefined);const payload = {callId: "call-2",childSessionId: "remote-session",diff --git a/packages/eve/src/subagents/callback-route.ts b/packages/eve/src/subagents/callback-route.tsindex 1c2c6a81f..775c744d9 100644--- a/packages/eve/src/subagents/callback-route.ts+++ b/packages/eve/src/subagents/callback-route.ts@@ -3,7 +3,7 @@ import { resumeHook } from "#internal/workflow/runtime.js";import { z } from "#compiled/zod/index.js";import type { RouteContext } from "#public/definitions/channel.js";import type { RuntimeSubagentChildResult } from "#shared/action-types.js";-import { inputRequestSchema } from "#shared/input.js";+import { inputRequestSchema, inputResponseSchema } from "#shared/input.js";import { agentTurnOutcomeWithCostSchema } from "#shared/agent-turn-outcome.js";import { jsonValueSchema } from "#shared/json-schemas.js";@@ -73,6 +73,33 @@ const sessionAuthorizationCallbackSchema = z.object({}).passthrough(),}),+ z.object({+ type: z.literal("input.resolved"),+ data: z+ .object({+ resolutions: z.array(+ z+ .object({+ kind: z.enum(["question", "session-limit", "tool-approval"]),+ outcome: z.enum([+ "answered",+ "approved",+ "cancelled",+ "denied",+ "ignored",+ "invalid",+ ]),+ requestId: z.string(),+ response: inputResponseSchema.optional(),+ })+ .passthrough(),+ ),+ sequence: z.number(),+ stepIndex: z.number(),+ turnId: z.string(),+ })+ .passthrough(),+ }),z.object({type: z.literal("authorization.required"),data: zdiff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex 2d1e7ef98..f4560cb1e 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -181,6 +181,70 @@ describe("proxied stream hooks", () => {]);});+ const at = { sequence: 7, stepIndex: 2, turnId: "child-turn" };+ it.each([+ [+ "settles it as a responder",+ {+ data: {+ ...at,+ outcome: "approved",+ requestId: "approval-1",+ responderPrincipalId: "alice",+ },+ type: "approval.settled",+ },+ ],+ [+ "resolves it",+ {+ data: {+ ...at,+ resolutions: [{ kind: "tool-approval", outcome: "approved", requestId: "approval-1" }],+ },+ type: "input.resolved",+ },+ ],+ ] as const)("closes a relayed approval when the child %s", async (_, event) => {+ const f = fixture();+ const approval = {+ action: { callId: "deploy-1", input: {}, kind: "tool-call" as const, toolName: "deploy" },+ kind: "tool-approval" as const,+ options: [+ { id: "approve", label: "Approve" },+ { id: "cancel", label: "Cancel" },+ ],+ prompt: "Approve deploy?",+ requestId: "approval-1",+ };+ const relayed = await emitProxiedSubagentEvent({+ ...f,+ hookPayload: { ...f.hookPayload, event: { ...f.hookPayload.event, requests: [approval] } },+ });+ const parked = relayed.sessionState.snapshot.session;+ const answer = { payload: { message: "approve" }, resolveMessage: true };+ expect(routeDeliverPayload({ ...answer, state: parked.state }).forChildren).toHaveLength(1);++ const closed = await emitProxiedSubagentEvent({+ ...f,+ durableSession: parked,+ hookPayload: {+ callId: "child-call",+ childSessionId: "child-session",+ event,+ kind: "subagent-authorization-event",+ subagentName: "child",+ },+ });+ expect(f.events.at(-1)).toMatchObject({ data: event.data, type: event.type });+ const after = closed.sessionState.snapshot.session.state;+ expect(getProxyInputRequests(after).has("approval-1")).toBe(false);+ expect(routeDeliverPayload({ ...answer, state: after })).toMatchObject({+ forChildren: [],+ forSelf: { message: "approve" },+ });+ });+it("forwards a remote session's own input without asking on its channel", async () => {const f = fixture();f.ctx.set(SessionCallbackKey, {diff --git a/packages/eve/src/subagents/hitl-proxy.integration.test.ts b/packages/eve/src/subagents/hitl-proxy.integration.test.tsindex 09836e21f..0578fe18f 100644--- a/packages/eve/src/subagents/hitl-proxy.integration.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.integration.test.ts@@ -345,17 +345,8 @@ describe("subagent HITL proxy → Slack-style text-approve regression (Finding #payload: {inputResponses: [{ optionId: "approve", requestId: "req-approve-1" }],},- resolved: {- event: { sequence: 0, stepIndex: 0, turnId: "turn_0" },- resolutions: [- {- kind: "tool-approval",- outcome: "approved",- requestId: "req-approve-1",- response: { optionId: "approve", requestId: "req-approve-1" },- },- ],- },+ // The child decides the approval, so it stays open here until the child settles it.+ resolved: { event: { sequence: 0, stepIndex: 0, turnId: "turn_0" }, resolutions: [] },},]);});diff --git a/packages/eve/src/subagents/hitl-proxy.test.ts b/packages/eve/src/subagents/hitl-proxy.test.tsindex 424f7a831..65c44d35c 100644--- a/packages/eve/src/subagents/hitl-proxy.test.ts+++ b/packages/eve/src/subagents/hitl-proxy.test.ts@@ -485,10 +485,12 @@ describe("routeDeliverPayload message resolution", () => {childContinuationToken: "child-token",message: "approve",payload: { inputResponses: [{ optionId: "approve", requestId: "approve-1" }] },- resolved: { resolutions: [{ outcome: "approved", requestId: "approve-1" }] },+ // The child decides the approval; the parent closes it on the child's settlement.+ resolved: { resolutions: [] },},]);+ // The child settled approve-1, which retires its route.const second = routeDeliverPayload({payload: { message: "cancel" },resolveMessage: true,@@ -497,7 +499,7 @@ describe("routeDeliverPayload message resolution", () => {expect(second.forChildren).toMatchObject([{payload: { inputResponses: [{ optionId: "cancel", requestId: "approve-2" }] },- resolved: { resolutions: [{ outcome: "denied", requestId: "approve-2" }] },+ resolved: { resolutions: [] },},]);});diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.tsindex 0ca9a4a33..ce0faf6cd 100644--- a/packages/eve/src/subagents/hitl-proxy.ts+++ b/packages/eve/src/subagents/hitl-proxy.ts@@ -4,7 +4,7 @@ import { resolveInputOutcome } from "#harness/input-request-resolution.js";import { firstOpenInput } from "#harness/open-input-request.js";import { storedProjection } from "#harness/session-machine/view.js";import type { StepCoordinates as PendingInputBatchEvent } from "#harness/session-machine/view.js";-import { getProxyInputRequests } from "#harness/proxy-input-requests.js";+import { getProxyInputRequests, resolvedByChild } from "#harness/proxy-input-requests.js";import type { WorkflowAskRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";import type { SessionStateMap } from "#harness/types.js";import type { InputResolution } from "#protocol/message.js";@@ -164,7 +164,11 @@ export function routeDeliverPayload(input: {routes,}): RoutedChildDelivery => {const responseIds = new Set(parentRequestIds);- const retireRequestIds = new Set(responseIds);+ const decided = (requestId: string) => {+ const kind = entries.get(requestId)?.kind;+ return kind === undefined || !resolvedByChild(kind);+ };+ const retireRequestIds = new Set([...responseIds].filter(decided));// A fully-answered approval batch retires its sibling requests// too, so a late free-form answer cannot route through a stale@@ -174,7 +178,9 @@ export function routeDeliverPayload(input: {route.batch !== undefined &&batchResolves({ batch: route.batch, childContinuationToken, entries, responseIds })) {- for (const requestId of route.batch.requestIds) retireRequestIds.add(requestId);+ for (const requestId of route.batch.requestIds) {+ if (decided(requestId)) retireRequestIds.add(requestId);+ }}}