The Open Framework for Building Agents
fix(eve): subagents - dispatch parent hooks for proxied events (#3789)
Andrew Barbaa58fa96889bb
diff --git a/.changeset/fix-proxied-input-hooks.md b/.changeset/fix-proxied-input-hooks.mdnew file mode 100644index 000000000..7679fa7f7--- /dev/null+++ b/.changeset/fix-proxied-input-hooks.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Run parent stream-event hooks after publishing proxied input requests, authorization events, and their completion/waiting events. Hooks receive the parent context and the published event ID.diff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex 7c4c98695..06d3c032f 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -183,12 +183,14 @@ Hooks always run after the event is durably recorded, so if a hook throws, the sA thrown handler during a model turn propagates through turn execution and surfaces as `turn.failed`. In a conversation session, this includes handlers for `turn.started` and the first `step.started` of a model call: the failed turn ends with `session.waiting`, and the next message can start another turn. Task-mode boundary failures remain terminal. If a hook subscribed to a failure-cascade event also throws, it escalates to `session.failed`. For belt-and-suspenders semantics inside a hook, wrap the body in `try`/`catch`. eve treats a thrown hook as a real failure.-For `subagent.called` and `subagent.completed`, a thrown handler fails the notification step and follows the workflow runtime's step retry policy. A retry can publish the event again before rerunning its hooks. Parent execution waits for the notification step to finish or exhaust its retries.+For `subagent.called`, `subagent.completed`, and events proxied from a child, a thrown handler fails the publishing step and follows the workflow runtime's step retry policy. A retry can publish the event again before rerunning its hooks. Parent execution waits for the publishing step to finish or exhaust its retries. Exhausting retries fails the session.## Subagent isolationSubagents may carry their own `agent/hooks/` directory. Subagent hooks fire only inside the subagent scope. Parent-agent hooks do not fire for subagent turns, and subagent hooks see only the subagent's own context.+Interactive events such as `input.requested` and `authorization.required` are also published on the parent stream. Parent hooks observe these events after the parent channel handler and stream write, with the parent's session, agent, and channel context. The event retains the child's turn coordinates, so `event.data.turnId` can differ from `ctx.session.turn.id`. The accompanying parent `turn.completed` and `session.waiting` events also invoke parent hooks; they do not resolve pending input requests.+## Hook vs tool vs provider| Need | Use |diff --git a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts b/e2e/fixtures/agent-subagents-hitl/agent/agent.tsindex 36bd0de92..b73e6c6e1 100644--- a/e2e/fixtures/agent-subagents-hitl/agent/agent.ts+++ b/e2e/fixtures/agent-subagents-hitl/agent/agent.ts@@ -7,6 +7,12 @@ const STOCK_PRICE = "178.92";function respond(request: MockModelRequest): MockModelResponse | string {const message = request.lastUserMessage ?? "";+ if (message.includes("Read the parent input-hook audit")) {+ const audit = request.toolResults.find((result) => result.name === "read_input_hooks");+ return audit === undefined+ ? { toolCalls: [{ name: "read_input_hooks", input: {} }] }+ : JSON.stringify(audit.output);+ }const prompt = request.messages.map((entry) => entry.text).join("\n");if (message.includes("Call the stock-price subagent exactly once")) {return request.toolResults.some((result) => result.name === "stock-price")diff --git a/e2e/fixtures/agent-subagents-hitl/agent/hooks/input-audit.ts b/e2e/fixtures/agent-subagents-hitl/agent/hooks/input-audit.tsnew file mode 100644index 000000000..54aae0620--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/agent/hooks/input-audit.ts@@ -0,0 +1,9 @@+import { defineHook } from "eve/hooks";+import { recordInputHook } from "../../input-hook-audit";++export default defineHook({+ events: {+ "input.requested": (event, ctx) => recordInputHook("typed", event, ctx),+ "*": (event, ctx) => recordInputHook("wildcard", event, ctx),+ },+});diff --git a/e2e/fixtures/agent-subagents-hitl/agent/tools/read_input_hooks.ts b/e2e/fixtures/agent-subagents-hitl/agent/tools/read_input_hooks.tsnew file mode 100644index 000000000..8971b5281--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/agent/tools/read_input_hooks.ts@@ -0,0 +1,11 @@+import { defineTool } from "eve/tools";+import { z } from "zod";+import { inputHookAudit } from "../../input-hook-audit";++export default defineTool({+ description: "Read the parent session's recorded input-request hook observations.",+ inputSchema: z.strictObject({}),+ execute() {+ return inputHookAudit.get();+ },+});diff --git a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.tsindex 2f880455c..806fddb9f 100644--- a/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts+++ b/e2e/fixtures/agent-subagents-hitl/evals/hitl.eval.ts@@ -1,6 +1,7 @@import { defineEval } from "eve/evals";import type { EveEvalContext, EveEvalSession, EveEvalTurn } from "eve/evals";import { equals } from "eve/evals/expect";+import type { InputHookObservation } from "../input-hook-audit";const GOOG_PRICE = "178.92";@@ -42,6 +43,38 @@ export default defineEval({: await waitForMessage(t, blocked, GOOG_PRICE);completed.messageIncludes(GOOG_PRICE);+ const audit = await completed.session.send(+ "Alice reviews Bob's stock-price approval. Read the parent input-hook audit.",+ );+ audit.expectOk();+ audit.calledTool("read_input_hooks", { count: 1, status: "completed" });+ const observations = audit.toolCalls.find((call) => call.name === "read_input_hooks")?.output;+ t.eventsSatisfy(+ "parent input hooks record the published approval once per subscriber",+ (events) => {+ if (!Array.isArray(observations) || observations.length !== 2) return false;+ const approvals = events.filter((event) => event.type === "input.requested");+ const approval = approvals[0];+ if (approvals.length !== 1 || approval?.type !== "input.requested") return false;+ const records = observations as InputHookObservation[];+ return (+ records.every(+ (record) =>+ record.sessionId === started.sessionId &&+ record.eventId === approval.meta.id &&+ record.requestIds.length === approval.data.requests.length &&+ record.requestIds.every(+ (id, index) => id === approval.data.requests[index]?.requestId,+ ),+ ) &&+ (["typed", "wildcard"] as const).every(+ (subscriber) =>+ records.filter((record) => record.subscriber === subscriber).length === 1,+ )+ );+ },+ );+t.succeeded();t.calledSubagent("stock-price", { status: "completed", count: 1 });t.noFailedActions();diff --git a/e2e/fixtures/agent-subagents-hitl/input-hook-audit.ts b/e2e/fixtures/agent-subagents-hitl/input-hook-audit.tsnew file mode 100644index 000000000..6234bcc18--- /dev/null+++ b/e2e/fixtures/agent-subagents-hitl/input-hook-audit.ts@@ -0,0 +1,31 @@+import { defineState } from "eve/context";+import type { HookContext, HookEvent } from "eve/hooks";++export interface InputHookObservation {+ readonly subscriber: "typed" | "wildcard";+ readonly eventId: string;+ readonly sessionId: string;+ readonly requestIds: readonly string[];+}++export const inputHookAudit = defineState<InputHookObservation[]>(+ "hitl-fixture.input-hook-audit",+ () => [],+);++export function recordInputHook(+ subscriber: InputHookObservation["subscriber"],+ event: HookEvent,+ ctx: HookContext,+): void {+ if (event.type !== "input.requested") return;+ inputHookAudit.update((observations) => [+ ...observations,+ {+ subscriber,+ eventId: event.meta.id,+ sessionId: ctx.session.id,+ requestIds: event.data.requests.map((request) => request.requestId),+ },+ ]);+}diff --git a/packages/eve/src/execution/publish-channel-event.ts b/packages/eve/src/execution/publish-channel-event.tsnew file mode 100644index 000000000..f83fb0c67--- /dev/null+++ b/packages/eve/src/execution/publish-channel-event.ts@@ -0,0 +1,29 @@+import {+ callAdapterEventHandler,+ type ChannelAdapter,+ type ChannelAdapterContext,+} from "#channel/adapter.js";+import type { ContextContainer } from "#context/container.js";+import { setChannelContext } from "#execution/channel-context.js";+import {+ encodeMessageStreamEvent,+ stampMessageStreamEvent,+ type MessageStreamEvent,+ type UnstampedMessageStreamEvent,+} from "#protocol/message.js";++/** Publishes an already-routed event and returns its durable stream identity. */+export async function publishChannelEvent(input: {+ readonly adapter: ChannelAdapter;+ readonly adapterCtx: ChannelAdapterContext;+ readonly ctx: ContextContainer;+ readonly deliveryIds?: readonly string[];+ readonly event: UnstampedMessageStreamEvent;+ readonly writer: WritableStreamDefaultWriter<Uint8Array>;+}): Promise<MessageStreamEvent> {+ const event = await callAdapterEventHandler(input.adapter, input.event, input.adapterCtx);+ setChannelContext(input.ctx, { ...input.adapter, state: { ...input.adapterCtx.state } });+ const stamped = stampMessageStreamEvent(event, input.deliveryIds);+ await input.writer.write(encodeMessageStreamEvent(stamped));+ return stamped;+}diff --git a/packages/eve/src/execution/session/event-sink.ts b/packages/eve/src/execution/session/event-sink.tsindex 41d0f6cba..ebafe7a8f 100644--- a/packages/eve/src/execution/session/event-sink.ts+++ b/packages/eve/src/execution/session/event-sink.ts@@ -1,14 +1,13 @@import { buildAdapterContext } from "#channel/adapter-context.js";-import { callAdapterEventHandler, type ChannelAdapter } from "#channel/adapter.js";+import type { ChannelAdapter } from "#channel/adapter.js";import type { ContextContainer } from "#context/container.js";import { ScheduleIdKey, TurnDeliveryIdsKey, TurnTaskDeliveryKey } from "#context/keys.js";import * as activityCohort from "#execution/activity-cohort.js";-import { setChannelContext } from "#execution/channel-context.js";+import { publishChannelEvent } from "#execution/publish-channel-event.js";import { observeSessionActivity } from "#execution/session-activity-projection.js";import { scheduledLaunchDeliveryEvent } from "#execution/scheduled-launch-delivery.js";import { forwardTaskEventToSessionCallback } from "#execution/task-event-callback.js";import {- encodeMessageStreamEvent,type MessageStreamEvent,stampMessageStreamEvent,type UnstampedMessageStreamEvent,@@ -61,10 +60,14 @@ export function createSessionEventSink(input: SessionEventSinkInput): SessionEvesuppressed: true,};}- const toEmit = await callAdapterEventHandler(adapter, deliverableEvent, adapterCtx);- setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });- const stamped = stampMessageStreamEvent(toEmit, ctx.get(TurnDeliveryIdsKey));- await writer.write(encodeMessageStreamEvent(stamped));+ const stamped = await publishChannelEvent({+ adapter,+ adapterCtx,+ ctx,+ writer,+ event: deliverableEvent,+ deliveryIds: ctx.get(TurnDeliveryIdsKey),+ });return { event: stamped, suppressed: false };};diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex 69e7578e8..090949953 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -3641,7 +3641,10 @@ describe("runProxySubagentEventStep", () => {*/function buildSerializedContextForAdapter(adapter: ChannelAdapter,- options: { readonly acceptedForwardedTracePolicy?: boolean } = {},+ options: {+ readonly acceptedForwardedTracePolicy?: boolean;+ readonly hookRegistry?: ReturnType<typeof createRuntimeHookRegistry>;+ } = {},): Record<string, unknown> {const bundle = {adapterRegistry: {@@ -3655,7 +3658,7 @@ describe("runProxySubagentEventStep", () => {turnAgent: TestTurnAgent,},},- hookRegistry: createEmptyHookRegistry(),+ hookRegistry: options.hookRegistry ?? createEmptyHookRegistry(),resolvedAgent: { config: {} },subagentRegistry: {},toolRegistry: {},@@ -3722,6 +3725,62 @@ describe("runProxySubagentEventStep", () => {};}+ it.each(["direct", "proxied"] as const)(+ "dispatches the parent input hook once after %s channel delivery",+ async (delivery) => {+ const order: string[] = [];+ const hook = vi.fn(() => {+ order.push("hook");+ });+ const adapter: ChannelAdapter = {+ kind: "input-hook-parity",+ "input.requested"() {+ order.push("channel");+ },+ };+ const hookRegistry = createRuntimeHookRegistry([+ {+ events: { "input.requested": hook },+ logicalPath: "hooks/audit.ts",+ slug: "audit",+ sourceId: "hooks/audit.ts",+ sourceKind: "module",+ },+ ]);+ const serializedContext = buildSerializedContextForAdapter(adapter, { hookRegistry });+ const session = createStubSession({+ sessionId: "parent-session",+ continuationToken: "http:proxy-test",+ });+ installSessionStoreMocks([session]);+ const sessionState = createStubSessionState({+ sessionId: "parent-session",+ continuationToken: "http:proxy-test",+ });+ const hookPayload = buildHookPayload();+ const sessionWritable = createTestWritable();+ if (delivery === "proxied") {+ await runProxySubagentEventStep({+ hookPayload,+ sessionWritable,+ serializedContext,+ sessionState,+ });+ } else {+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => async (session) => {+ await input.handleEvent?.(createInputRequestedEvent(hookPayload.event));+ return { next: null, session };+ });+ await turnStep({ sessionWritable, serializedContext, sessionState });+ }+ expect(order).toEqual(["channel", "hook"]);+ expect(hook).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ type: "input.requested", data: hookPayload.event }),+ expect.objectContaining({ session: expect.objectContaining({ id: "parent-session" }) }),+ );+ },+ );+it("persists adapter-state mutations from the input.requested handler onto the returned serializedContext", async () => {// The stub adapter mirrors Slack's contract: its `input.requested`// handler writes a `pendingRequests` entry onto `adapterCtx.state`diff --git a/packages/eve/src/subagents/auth-proxy.integration.test.ts b/packages/eve/src/subagents/auth-proxy.integration.test.tsindex 6eee52777..005e1adce 100644--- a/packages/eve/src/subagents/auth-proxy.integration.test.ts+++ b/packages/eve/src/subagents/auth-proxy.integration.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi, type Mock } from "vitest";import type { ChannelAdapter, ChannelAdapterContext } from "#channel/adapter.js";import type {@@ -11,8 +11,9 @@ import { emitProxiedSubagentEvent } from "#subagents/event-proxy-step.js";import { projectToDurableSession } from "#execution/session.js";import type { HarnessSession } from "#harness/types.js";import type { MessageStreamEvent } from "#protocol/message.js";+import type { StreamEventHook } from "#public/definitions/hook.js";import { deserializeRuntimeAdapter } from "#runtime/channels/registry.js";-import { createEmptyHookRegistry } from "#runtime/hooks/registry.js";+import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";import {BundleKey,ChannelKey,@@ -47,7 +48,10 @@ const turnAgent = {workspaceSpec: {} as never,};-function buildBundle(adapter: ChannelAdapter): CompiledBundle {+function buildBundle(+ adapter: ChannelAdapter,+ hook: StreamEventHook<MessageStreamEvent>,+): CompiledBundle {return {adapterRegistry: {adaptersByKind: new Map([[adapter.kind, adapter]]),@@ -60,7 +64,22 @@ function buildBundle(adapter: ChannelAdapter): CompiledBundle {turnAgent,},},- hookRegistry: createEmptyHookRegistry(),+ hookRegistry: createRuntimeHookRegistry([+ {+ events: {+ "authorization.required": hook,+ "authorization.completed": hook,+ "approval.candidate": hook,+ "approval.settled": hook,+ "turn.completed": hook,+ "session.waiting": hook,+ },+ logicalPath: "hooks/audit.ts",+ slug: "audit",+ sourceId: "hooks/audit.ts",+ sourceKind: "module",+ },+ ]),resolvedAgent: { config: {} },subagentRegistry: {},toolRegistry: {},@@ -71,8 +90,10 @@ function buildBundle(adapter: ChannelAdapter): CompiledBundle {function buildContext(input: { readonly adapter: ChannelAdapter; readonly sessionId: string }): {readonly bundle: ReturnType<typeof buildBundle>;readonly ctx: ContextContainer;+ readonly hook: Mock<StreamEventHook<MessageStreamEvent>>;} {- const bundle = buildBundle(input.adapter);+ const hook = vi.fn<StreamEventHook<MessageStreamEvent>>();+ const bundle = buildBundle(input.adapter, hook);const ctx = new ContextContainer();ctx.set(AuthKey, null);ctx.set(BundleKey, bundle);@@ -80,7 +101,7 @@ function buildContext(input: { readonly adapter: ChannelAdapter; readonly sessioctx.set(ContinuationTokenKey, "http:parent");ctx.set(ModeKey, "conversation");ctx.set(SessionIdKey, input.sessionId);- return { bundle, ctx };+ return { bundle, ctx, hook };}function rehydrateContext(input: {@@ -141,7 +162,10 @@ describe("subagent authorization proxy", () => {it("preserves approval candidate and settlement events", async () => {const parentSessionId = "parent-approval-session";const session = createSession(parentSessionId);- const { ctx } = buildContext({ adapter: authorizationAdapter, sessionId: parentSessionId });+ const { ctx, hook } = buildContext({+ adapter: authorizationAdapter,+ sessionId: parentSessionId,+ });const chunks: Uint8Array[] = [];const sessionWritable = createCapturingWritable(chunks);const candidateEvent: SubagentAuthorizationEvent = {@@ -183,11 +207,13 @@ describe("subagent authorization proxy", () => {expect(decodeEvent(chunks[0]!)).toMatchObject(candidateEvent);expect(decodeEvent(chunks[1]!)).toMatchObject(settledEvent);+ expect(hook.mock.calls.map(([event]) => event)).toEqual(chunks.map(decodeEvent));+ expect(hook.mock.calls.every(([, ctx]) => ctx.session.id === parentSessionId)).toBe(true);});it("preserves required/completed events as standalone parent turns", async () => {const parentSessionId = "parent-session";const session = createSession(parentSessionId);- const { bundle, ctx } = buildContext({+ const { bundle, ctx, hook } = buildContext({adapter: authorizationAdapter,sessionId: parentSessionId,});@@ -253,5 +279,7 @@ describe("subagent authorization proxy", () => {expect(decodeEvent(chunks[3]!)).toMatchObject(completedEvent);expect(decodeEvent(chunks[4]!).type).toBe("turn.completed");expect(decodeEvent(chunks[5]!).type).toBe("session.waiting");+ expect(hook.mock.calls.map(([event]) => event)).toEqual(chunks.map(decodeEvent));+ expect(hook.mock.calls.every(([, ctx]) => ctx.session.id === parentSessionId)).toBe(true);});});diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsnew file mode 100644index 000000000..b4e2d0524--- /dev/null+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -0,0 +1,227 @@+import { describe, expect, it, vi } from "vitest";++import type { ChannelAdapter } from "#channel/adapter.js";+import type { SubagentInputRequestHookPayload } from "#channel/types.js";+import { ContextContainer } from "#context/container.js";+import { AuthKey, ContinuationTokenKey, ModeKey, SessionIdKey } from "#context/keys.js";+import type { DurableSession } from "#execution/durable-session-store.js";+import { getProxyInputRequests } from "#harness/proxy-input-requests.js";+import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";+import type { MessageStreamEvent } from "#protocol/message.js";+import type { HookContext } from "#public/definitions/hook.js";+import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";+import {+ BundleKey,+ ChannelKey,+ type CompiledBundle,+} from "#runtime/sessions/runtime-context-keys.js";+import type { RunMode } from "#shared/run-mode.js";+import { emitProxiedSubagentEvent } from "#subagents/event-proxy-step.js";+import { routeDeliverPayload } from "#subagents/hitl-proxy.js";++function fixture(mode: RunMode = "conversation", turnId = "parent-turn") {+ const order: string[] = [];+ const events: MessageStreamEvent[] = [];+ const typed = vi.fn(async (event: MessageStreamEvent, _ctx: HookContext) => {+ order.push(`typed:${event.type}`);+ });+ const wildcard = vi.fn((event: MessageStreamEvent, _ctx: HookContext) => {+ order.push(`wildcard:${event.type}`);+ });+ const adapter: ChannelAdapter = {+ kind: "proxy-hook-test",+ "input.requested"(data, ctx) {+ order.push("channel:input.requested");+ ctx.state.pendingRequests = data.requests;+ ctx.session.continuation?.alias("parent-thread");+ },+ "turn.completed"() {+ order.push("channel:turn.completed");+ },+ "session.waiting"() {+ order.push("channel:session.waiting");+ },+ };+ const turnAgent = { id: "parent", model: { id: "unused" }, tools: [] };+ const bundle: CompiledBundle = {+ adapterRegistry: { adaptersByKind: new Map([[adapter.kind, adapter]]) },+ compiledArtifactsSource: {},+ graph: { root: { sandboxRegistry: { sandbox: null }, turnAgent } },+ hookRegistry: createRuntimeHookRegistry([+ {+ events: {+ "input.requested": typed,+ "turn.completed": typed,+ "session.waiting": typed,+ "*": wildcard,+ },+ logicalPath: "hooks/audit.ts",+ slug: "audit",+ sourceId: "hooks/audit.ts",+ sourceKind: "module",+ },+ ]),+ nodeId: "parent",+ resolvedAgent: { config: {} },+ subagentRegistry: {},+ turnAgent,+ } as never;+ const ctx = new ContextContainer();+ ctx.set(AuthKey, null);+ ctx.set(BundleKey, bundle);+ ctx.set(ChannelKey, adapter);+ ctx.set(ContinuationTokenKey, "http:parent");+ ctx.set(ModeKey, mode);+ ctx.set(SessionIdKey, "parent-session");+ const durableSession: DurableSession = {+ agent: { system: "" },+ continuationToken: "http:parent",+ history: [],+ sessionId: "parent-session",+ state: {+ "eve.harness.emission": { turnId, sequence: 1, stepIndex: 0, sessionStarted: true },+ },+ };+ const request = createSessionLimitContinuationRequest({+ sessionId: "child-session",+ violation: { kind: "input", limit: 100, usedTokens: 101 },+ });+ const hookPayload: SubagentInputRequestHookPayload = {+ kind: "subagent-input-request",+ callId: "child-call",+ childContinuationToken: "child-token",+ childSessionId: "child-session",+ subagentName: "child",+ event: { requests: [request], turnId: "child-turn", sequence: 7, stepIndex: 2 },+ };+ const sessionWritable = new WritableStream<Uint8Array>({+ write(chunk) {+ const event = JSON.parse(new TextDecoder().decode(chunk)) as MessageStreamEvent;+ events.push(event);+ order.push(`stream:${event.type}`);+ },+ });+ return {+ ctx,+ durableSession,+ hookPayload,+ sessionWritable,+ events,+ order,+ request,+ typed,+ wildcard,+ };+}++describe("proxied stream hooks", () => {+ it.each([+ { mode: "conversation", turnId: "parent-turn" },+ { mode: "conversation", turnId: "" },+ { mode: "task", turnId: "parent-turn" },+ ] as const)(+ "publishes hooks in parent context ($mode, turn=$turnId)",+ async ({ mode, turnId }) => {+ const f = fixture(mode, turnId);+ const result = await emitProxiedSubagentEvent(f);+ const types =+ mode === "conversation"+ ? ["input.requested", "turn.completed", "session.waiting"]+ : ["input.requested"];+ expect(f.events.map((event) => event.type)).toEqual(types);+ expect(f.order).toEqual(+ types.flatMap((type) => [+ `channel:${type}`,+ `stream:${type}`,+ `typed:${type}`,+ `wildcard:${type}`,+ ]),+ );+ expect(f.typed.mock.calls.map(([event]) => event)).toEqual(f.events);+ expect(f.wildcard.mock.calls.map(([event]) => event)).toEqual(f.events);+ for (const [, ctx] of [...f.typed.mock.calls, ...f.wildcard.mock.calls]) {+ expect(ctx).toMatchObject({+ session: { id: "parent-session", turn: { id: turnId || "turn_1" } },+ agent: { name: "parent", nodeId: "parent" },+ channel: { kind: "proxy-hook-test", continuationToken: "http:parent-thread" },+ });+ }+ expect(f.events[0]).toMatchObject({ data: f.hookPayload.event });+ expect(result.serializedContext[ChannelKey.name]).toMatchObject({+ state: { pendingRequests: [f.request] },+ });+ expect(result.sessionState.continuationToken).toBe("http:parent-thread");+ expect(result.sessionState.hasProxyInputRequests).toBe(true);+ const routed = routeDeliverPayload({+ payload: { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] },+ state: result.sessionState.snapshot.session.state,+ });+ expect(routed.forSelf).toBeUndefined();+ expect(routed.forChildren).toEqual([+ {+ childContinuationToken: "child-token",+ payload: { inputResponses: [{ requestId: f.request.requestId, optionId: "continue" }] },+ retireRequestIds: [f.request.requestId],+ },+ ]);+ },+ );++ it("retains pre-recorded task response destinations and child request IDs", async () => {+ const f = fixture();+ const childRequestId = f.request.requestId;+ const requestId = `task-1:${childRequestId}`;+ const route = {+ childContinuationToken: "child-token",+ childRequestId,+ childResponseUrl: "https://child.example/eve/input",+ kind: "session-limit",+ taskId: "task-1",+ } as const;+ const result = await emitProxiedSubagentEvent({+ ...f,+ recordProxyInputRequests: false,+ durableSession: {+ ...f.durableSession,+ state: {+ ...f.durableSession.state,+ "eve.runtime.proxyInputRequests": { [requestId]: route },+ },+ },+ hookPayload: {+ ...f.hookPayload,+ event: { ...f.hookPayload.event, requests: [{ ...f.request, requestId }] },+ },+ });+ expect(f.typed.mock.calls.filter(([event]) => event.type === "input.requested")).toHaveLength(+ 1,+ );+ const state = result.sessionState.snapshot.session.state;+ expect(getProxyInputRequests(state).get(requestId)).toEqual(route);+ expect(+ routeDeliverPayload({+ payload: { inputResponses: [{ requestId, optionId: "continue" }] },+ state,+ }).forChildren,+ ).toEqual([+ {+ childContinuationToken: route.childContinuationToken,+ childResponseUrl: route.childResponseUrl,+ taskId: route.taskId,+ payload: { inputResponses: [{ requestId: childRequestId, optionId: "continue" }] },+ retireRequestIds: [requestId],+ },+ ]);+ });++ it("propagates hook failures after publication and releases the writer", async () => {+ const f = fixture();+ const error = new Error("audit unavailable");+ f.typed.mockRejectedValueOnce(error);+ await expect(emitProxiedSubagentEvent(f)).rejects.toBe(error);+ expect(f.events.map((event) => event.type)).toEqual(["input.requested"]);+ expect(f.typed).toHaveBeenCalledOnce();+ expect(f.wildcard).not.toHaveBeenCalled();+ expect(f.sessionWritable.locked).toBe(false);+ });+});diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.tsindex 09cacf020..fc1e6dd5b 100644--- a/packages/eve/src/subagents/event-proxy-step.ts+++ b/packages/eve/src/subagents/event-proxy-step.ts@@ -1,14 +1,14 @@import { buildAdapterContext } from "#channel/adapter-context.js";-import { callAdapterEventHandler } from "#channel/adapter.js";import type {SubagentAuthorizationEventHookPayload,SubagentInputRequestHookPayload,} from "#channel/types.js";import type { ContextContainer } from "#context/container.js";+import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";import { ModeKey } from "#context/keys.js";import { withContextScope } from "#context/run-step.js";import { deserializeContext, serializeContext } from "#context/serialize.js";-import { setChannelContext } from "#execution/channel-context.js";+import { publishChannelEvent } from "#execution/publish-channel-event.js";import {createDurableSessionState,type DurableSession,@@ -27,7 +27,6 @@ import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";import type { AnswerHookRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";import type { HarnessSession } from "#harness/types.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";-import { encodeMessageStreamEvent, stampMessageStreamEvent } from "#protocol/message.js";import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import type { RunMode } from "#shared/run-mode.js";@@ -127,8 +126,10 @@ export async function emitProxiedSubagentEvent(input: {// A re-emitted child event is a distinct event on the parent stream, so it// gets its own id rather than the child's.const emit = async (event: UnstampedMessageStreamEvent): Promise<void> => {- const transformed = await callAdapterEventHandler(adapter, event, adapterCtx);- await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(transformed)));+ // The child event is already routed; do not forward it again or apply+ // the parent's scheduled-turn suppression from createSessionEventSink.+ const stamped = await publishChannelEvent({ adapter, adapterCtx, ctx, event, writer });+ await dispatchStreamEventHooks({ ctx, registry: bundle.hookRegistry, event: stamped });};const scopeResult = await withContextScope(ctx, session, async (enrichedSession) => {@@ -159,8 +160,6 @@ export async function emitProxiedSubagentEvent(input: {writer.releaseLock();}- setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });-if (input.recordProxyInputRequests !== false &&proxyEntries !== undefined &&