The Open Framework for Building Agents
feat(eve): let hooks cancel the running turn with ctx.cancel() (#3718)
Rui2cfcecc39651
diff --git a/.changeset/hook-context-cancel.md b/.changeset/hook-context-cancel.mdnew file mode 100644index 000000000..96e2a2d36--- /dev/null+++ b/.changeset/hook-context-cancel.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Hooks can call `ctx.cancel()` to cancel the running turn after the remaining subscribers for the event run. The turn then settles like `session.cancel()`, with `turn.cancelled` followed by `session.waiting`.diff --git a/.changeset/isolate-hook-failures.md b/.changeset/isolate-hook-failures.mdnew file mode 100644index 000000000..54c50346e--- /dev/null+++ b/.changeset/isolate-hook-failures.md@@ -0,0 +1,5 @@+---+"eve": minor+---++A stream-event hook that throws no longer fails the turn or session. eve logs the failure with the hook and event identifiers, runs the remaining subscribers, and continues execution, including for `turn.started` and `step.started` hooks, which previously ended the turn with `EVENT_HANDLER_FAILED`.diff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex 6940da5c9..2810bf90b 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -61,6 +61,7 @@ helpers documented in [Session context](./session-context):interface HookContext extends SessionContext {readonly agent: { readonly name: string; readonly nodeId?: string };readonly channel: { readonly kind?: string; readonly continuationToken?: string };+ cancel(): void;}```@@ -181,9 +182,40 @@ Hooks always run after the event is durably recorded, so if a hook throws, the s## What happens when a hook throws-A thrown handler during a model turn propagates through turn execution and surfaces as `turn.failed`. 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. 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.+eve logs a thrown or rejected handler with the hook slug, subscription, event type, event ID, and session ID, then runs the remaining subscribers in order. The current turn, subagent notification, and session continue. This applies to every stream-event hook, including `turn.started`, `step.started`, and failure events. Throwing from a hook does not reject work or veto a turn. To stop the running turn, call [`ctx.cancel()`](#cancel-the-running-turn-from-a-hook).-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.+A hook failure does not trigger a retry. State changes and external side effects made before the exception are not rolled back. If a side effect needs retries or compensation, handle that inside the hook. Runtime failures outside the authored handler, such as failures setting up context or persisting state, still propagate. If persisting state after a subagent notification fails, the workflow runtime retries the notification step, which can publish the event again.++## Cancel the running turn from a hook++Call `ctx.cancel()` when a hook finds that the turn cannot proceed. For example, a `turn.started` hook that cannot load the caller's credentials can stop the turn before the model runs, instead of letting every tool call fail:++```ts title="agent/hooks/require-credentials.ts"+import { defineHook } from "eve/hooks";+import { loadWorkspaceCredentials } from "../lib/credentials";++export default defineHook({+ events: {+ async "turn.started"(_event, ctx) {+ try {+ await loadWorkspaceCredentials(ctx.session.auth.current);+ } catch (error) {+ console.warn("cancelling turn: workspace credentials unavailable", {+ error,+ sessionId: ctx.session.id,+ });+ ctx.cancel();+ }+ },+ },+});+```++The remaining subscribers for the event still run. Then eve cancels the turn the same way [`session.cancel()`](./client/streaming) does: in-flight model and tool work is aborted, delegated child turns are cancelled, and the turn ends with `turn.cancelled` followed by `session.waiting`. No failure event is emitted. A cancel from `turn.started` or `step.started` takes effect before that model call. In a conversation, the next message starts a new turn. A delegated task reports the cancellation to its caller.++`ctx.cancel()` returns `void` rather than a promise. The turn stops after the hook returns, so there is nothing to await. Call it before the handler's promise settles: eve ignores a call from work the handler does not await and logs a warning.++`ctx.cancel()` only stops a running turn. eve logs a warning and ignores the call on `step.failed`, `turn.completed`, `turn.failed`, `turn.cancelled`, `session.waiting`, `session.completed`, `session.failed`, `context.cleared`, and `subagent.*` events, and during clear or compact requests.## Subagent isolationdiff --git a/e2e/fixtures/agent-basic-runtime/agent/agent.ts b/e2e/fixtures/agent-basic-runtime/agent/agent.tsindex d097e7868..ebe1b3cf2 100644--- a/e2e/fixtures/agent-basic-runtime/agent/agent.ts+++ b/e2e/fixtures/agent-basic-runtime/agent/agent.ts@@ -34,6 +34,12 @@ const config = e2eAgentConfig({? { toolCalls: [{ name: "call_child", input: {} }] }: JSON.stringify(result.output);}+ if (lastUserMessage?.includes("read_audit_outbox")) {+ const result = toolResults.find((entry) => entry.name === "read_audit_outbox");+ return result === undefined+ ? { toolCalls: [{ name: "read_audit_outbox", input: {} }] }+ : JSON.stringify(result.output);+ }if (lastUserMessage === CHILD_REQUEST) {return {toolCalls: [{ name: "final_output", input: { answer: "client-recursion-ok" } }],diff --git a/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts b/e2e/fixtures/agent-basic-runtime/agent/channels/eve.tsindex b8d49b762..485c0ceac 100644--- a/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts+++ b/e2e/fixtures/agent-basic-runtime/agent/channels/eve.ts@@ -1,6 +1,7 @@import type { AuthFn } from "eve/channels/auth";import { eveChannel } from "eve/channels/eve";import type { SessionAuthContext } from "eve/context";+import { authenticateWorkspaceMember } from "../lib/workspace";const PRINCIPAL_A = "Bearer e2e-create-once-a";const PRINCIPAL_B = "Bearer e2e-create-once-b";@@ -20,9 +21,10 @@ const authenticateA: AuthFn<Request> = (request) =>request.headers.get("authorization") === PRINCIPAL_A ? principal("issuer-a") : null;const authenticateB: AuthFn<Request> = (request) =>request.headers.get("authorization") === PRINCIPAL_B ? principal("issuer-b") : null;-const authenticateEvalDriver: AuthFn<Request> = (request) => ({- ...principal("eval-driver"),- attributes: { denyBoundary: request.headers.get("x-e2e-deny-boundary") ?? "" },-});+const authenticateMember: AuthFn<Request> = (request) =>+ authenticateWorkspaceMember(request.headers.get("authorization"));+const authenticateEvalDriver: AuthFn<Request> = () => principal("eval-driver");-export default eveChannel({ auth: [authenticateA, authenticateB, authenticateEvalDriver] });+export default eveChannel({+ auth: [authenticateA, authenticateB, authenticateMember, authenticateEvalDriver],+});diff --git a/e2e/fixtures/agent-basic-runtime/agent/hooks/admission.ts b/e2e/fixtures/agent-basic-runtime/agent/hooks/admission.tsdeleted file mode 100644index afe3abe96..000000000--- a/e2e/fixtures/agent-basic-runtime/agent/hooks/admission.ts+++ /dev/null@@ -1,14 +0,0 @@-import { defineHook } from "eve/hooks";--export default defineHook({- events: {- "*"(event, ctx) {- if (- (event.type === "turn.started" || event.type === "step.started") &&- ctx.session.auth.current?.attributes.denyBoundary === event.type- ) {- throw new Error("Fixture admission denied.");- }- },- },-});diff --git a/e2e/fixtures/agent-basic-runtime/agent/hooks/audit-export.ts b/e2e/fixtures/agent-basic-runtime/agent/hooks/audit-export.tsnew file mode 100644index 000000000..54a8e8500--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/agent/hooks/audit-export.ts@@ -0,0 +1,19 @@+import { defineHook, type HookContext, type HookEvent } from "eve/hooks";+import { auditOutbox, exportAuditEvent } from "../lib/workspace";++async function exportOrQueue(event: HookEvent, ctx: HookContext): Promise<void> {+ try {+ await exportAuditEvent(ctx.session.auth.current, event);+ } catch (error) {+ auditOutbox.update((queued) => [...queued, { eventId: event.meta.id, type: event.type }]);+ // Rethrow so eve logs the failed export. The turn keeps running.+ throw error;+ }+}++export default defineHook({+ events: {+ "turn.started": exportOrQueue,+ "step.started": exportOrQueue,+ },+});diff --git a/e2e/fixtures/agent-basic-runtime/agent/hooks/require-credentials.ts b/e2e/fixtures/agent-basic-runtime/agent/hooks/require-credentials.tsnew file mode 100644index 000000000..130625469--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/agent/hooks/require-credentials.ts@@ -0,0 +1,19 @@+import { defineHook } from "eve/hooks";+import { loadWorkspaceCredentials } from "../lib/workspace";++export default defineHook({+ events: {+ async "turn.started"(_event, ctx) {+ try {+ await loadWorkspaceCredentials(ctx.session.auth.current);+ } catch (error) {+ // Without credentials every workspace tool call would fail; stop before the model runs.+ console.warn("cancelling turn: workspace credentials unavailable", {+ error: error instanceof Error ? error.message : String(error),+ sessionId: ctx.session.id,+ });+ ctx.cancel();+ }+ },+ },+});diff --git a/e2e/fixtures/agent-basic-runtime/agent/lib/workspace.ts b/e2e/fixtures/agent-basic-runtime/agent/lib/workspace.tsnew file mode 100644index 000000000..de1a7808d--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/agent/lib/workspace.ts@@ -0,0 +1,87 @@+import { defineState, type SessionAuthContext } from "eve/context";++/**+ * Workspace member directory. A deployed agent would read members from its+ * identity provider and their credentials from a secret store.+ */+interface WorkspaceMember {+ /** Absent when the member's credential grant was revoked. */+ readonly credentials?: WorkspaceCredentials;+ readonly auditSink: "reachable" | "unreachable";+}++export interface WorkspaceCredentials {+ readonly token: string;+}++const MEMBERS: Readonly<Record<string, WorkspaceMember>> = {+ alice: { auditSink: "reachable", credentials: { token: "alice-workspace-token" } },+ bob: { auditSink: "reachable" },+ carol: { auditSink: "unreachable", credentials: { token: "carol-workspace-token" } },+};++const AUTHENTICATOR = "workspace";+const TOKEN_PREFIX = "Bearer workspace-";++/** Resolves a workspace member from their bearer token. */+export function authenticateWorkspaceMember(+ authorization: string | null,+): SessionAuthContext | null {+ const name = authorization?.startsWith(TOKEN_PREFIX)+ ? authorization.slice(TOKEN_PREFIX.length)+ : undefined;+ if (name === undefined || MEMBERS[name] === undefined) return null;+ return {+ attributes: {},+ authenticator: AUTHENTICATOR,+ issuer: "workspace",+ principalId: name,+ principalType: "user",+ subject: name,+ };+}++function findMember(principal: SessionAuthContext | null): [string, WorkspaceMember] | undefined {+ const name = principal?.authenticator === AUTHENTICATOR ? principal.subject : undefined;+ const member = name === undefined ? undefined : MEMBERS[name];+ return name === undefined || member === undefined ? undefined : [name, member];+}++/** True for callers who signed in as workspace members. */+export function isWorkspaceMember(principal: SessionAuthContext | null): boolean {+ return findMember(principal) !== undefined;+}++/** Loads the caller's workspace credentials; callers outside the workspace need none. */+export async function loadWorkspaceCredentials(+ principal: SessionAuthContext | null,+): Promise<WorkspaceCredentials | undefined> {+ const found = findMember(principal);+ if (found === undefined) return undefined;+ const [name, member] = found;+ if (member.credentials === undefined) {+ throw new Error(`The workspace credential grant for ${name} was revoked.`);+ }+ return member.credentials;+}++/** Sends one event to the caller's workspace audit sink. */+export async function exportAuditEvent(+ principal: SessionAuthContext | null,+ event: { readonly type: string },+): Promise<void> {+ const found = findMember(principal);+ if (found === undefined) return;+ const [name, member] = found;+ if (member.auditSink === "unreachable") {+ throw new Error(`The audit sink for ${name}'s workspace is unreachable (${event.type}).`);+ }+}++export interface QueuedAuditEvent {+ readonly eventId: string;+ readonly type: string;+}++/** Audit events kept for retry while the workspace audit sink is unreachable. */+export const auditOutbox = defineState<QueuedAuditEvent[]>("basic-runtime.audit-outbox", () => []);diff --git a/e2e/fixtures/agent-basic-runtime/agent/tools/read_audit_outbox.ts b/e2e/fixtures/agent-basic-runtime/agent/tools/read_audit_outbox.tsnew file mode 100644index 000000000..8de3ec7c1--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/agent/tools/read_audit_outbox.ts@@ -0,0 +1,19 @@+import { defineDynamic, defineTool } from "eve/tools";+import { z } from "zod";+import { auditOutbox, isWorkspaceMember } from "../lib/workspace";++// Only workspace members have an audit outbox, so other callers never see this tool.+export default defineDynamic({+ events: {+ "step.started": (_event, ctx) =>+ isWorkspaceMember(ctx.session.auth.current)+ ? defineTool({+ description: "List audit events waiting for the workspace audit sink.",+ inputSchema: z.strictObject({}),+ async execute() {+ return auditOutbox.get();+ },+ })+ : null,+ },+});diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/audit-export-failure.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/audit-export-failure.eval.tsnew file mode 100644index 000000000..1a8708019--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/audit-export-failure.eval.ts@@ -0,0 +1,50 @@+import { defineEval } from "eve/evals";+import { satisfies } from "eve/evals/expect";+import type { QueuedAuditEvent } from "../../agent/lib/workspace";++export default defineEval({+ description:+ "An audit hook that queues its event and throws on turn.started and step.started leaves the turn and the conversation running.",+ async test(t) {+ const session = await t.session();+ const auth = { authorization: "Bearer workspace-carol" };++ const first = await session.send(+ "Carol asks for a one-sentence status update. Reply without calling tools.",+ { headers: auth },+ );+ first.expectOk();+ first.event("turn.completed", { count: 1 });+ first.event("session.waiting", { count: 1 });+ first.notEvent("turn.cancelled");+ first.notEvent("turn.failed");+ first.notEvent("session.failed");+ const turnStarted = first.events.find((event) => event.type === "turn.started");+ const stepStarted = first.events.find((event) => event.type === "step.started");++ const next = await session.send(+ "Carol asks which audit events are still waiting to be exported. Call read_audit_outbox once and report what it returns.",+ { headers: auth },+ );+ next.expectOk();+ next.event("turn.started", { count: 1, data: { sequence: 1 } });+ next.notEvent("session.started");+ next.calledTool("read_audit_outbox", { count: 1, status: "completed" });+ const queued = next.toolCalls.find((call) => call.name === "read_audit_outbox")?.output;+ await t.require(+ queued,+ satisfies(+ (value: unknown) =>+ Array.isArray(value) &&+ [turnStarted, stepStarted].every(+ (event) =>+ event !== undefined &&+ (value as QueuedAuditEvent[]).some(+ (entry) => entry.eventId === event.meta.id && entry.type === event.type,+ ),+ ),+ "the audit hook queued the first turn's turn.started and step.started before throwing",+ ),+ );+ },+});diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/boundary-hook-failure.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/boundary-hook-failure.eval.tsdeleted file mode 100644index cf0d7660a..000000000--- a/e2e/fixtures/agent-basic-runtime/evals/runtime/boundary-hook-failure.eval.ts+++ /dev/null@@ -1,20 +0,0 @@-import { defineEval } from "eve/evals";--export default defineEval({- description: "Boundary hook failures end one turn while the conversation remains resumable.",- async test(t) {- for (const boundary of ["turn.started", "step.started"]) {- const session = await t.session();- const failed = await session.send("Deny this turn.", {- headers: { "x-e2e-deny-boundary": boundary },- });- failed.event("turn.failed", { count: 1, data: { code: "EVENT_HANDLER_FAILED" } });- failed.event("session.waiting", { count: 1 });- failed.notEvent("session.failed");- const recovered = await session.send("Reply with ready.");- recovered.expectOk();- recovered.event("turn.started", { count: 1, data: { sequence: 1 } });- recovered.notEvent("session.started");- }- },-});diff --git a/e2e/fixtures/agent-basic-runtime/evals/runtime/workspace-credentials-cancel.eval.ts b/e2e/fixtures/agent-basic-runtime/evals/runtime/workspace-credentials-cancel.eval.tsnew file mode 100644index 000000000..5aea0adc4--- /dev/null+++ b/e2e/fixtures/agent-basic-runtime/evals/runtime/workspace-credentials-cancel.eval.ts@@ -0,0 +1,44 @@+import { defineEval } from "eve/evals";++export default [+ defineEval({+ description:+ "A workspace member whose credential grant was revoked has the turn cancelled before the model runs.",+ async test(t) {+ const session = await t.session();+ const turn = await session.send(+ "Bob asks for a one-sentence status update. Reply without calling tools.",+ {+ headers: { authorization: "Bearer workspace-bob" },+ },+ );+ turn.event("turn.cancelled", { count: 1 });+ turn.eventOrder([+ { type: "turn.started" },+ { type: "turn.cancelled" },+ { type: "session.waiting" },+ ]);+ turn.notEvent("step.started");+ turn.notEvent("message.completed");+ turn.notEvent("turn.completed");+ turn.notEvent("turn.failed");+ turn.notEvent("session.failed");+ },+ }),+ defineEval({+ description: "A workspace member whose credentials load runs the turn normally.",+ async test(t) {+ const session = await t.session();+ const turn = await session.send(+ "Alice asks for a one-sentence status update. Reply without calling tools.",+ {+ headers: { authorization: "Bearer workspace-alice" },+ },+ );+ turn.expectOk();+ turn.event("step.started");+ turn.event("turn.completed", { count: 1 });+ turn.notEvent("turn.cancelled");+ },+ }),+];diff --git a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.tsindex d6b177e1f..326093220 100644--- a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-context.eval.ts@@ -3,7 +3,7 @@ import type { SubagentHookObservation } from "../subagent-hook-audit";export default (["direct", "waiting", "background"] as const).map((mode) =>defineEval({- description: `${mode} subagent hooks preserve parent context, skills, and sandbox writes.`,+ description: `${mode} delegation and later wildcard hooks continue after a typed hook writes parent state and throws.`,async test(t) {const initial = await t.send(`Alice asks Bob to review a short report and return his result. SUBAGENT-HOOKS:${mode}`,@@ -88,6 +88,7 @@ export default (["direct", "waiting", "background"] as const).map((mode) =>t.event("subagent.called", { data: { name: "workflow-marker" }, count: 1 });t.event("subagent.completed", { data: { subagentName: "workflow-marker" }, count: 1 });t.notEvent("session.failed");+ t.notEvent("turn.failed");t.noFailedActions();t.succeeded();},diff --git a/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts b/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.tsindex 22424a390..c4a1c4245 100644--- a/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts+++ b/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts@@ -40,4 +40,7 @@ export async function recordSubagentHook(output: event.type === "subagent.completed" ? event.data.output : undefined,},]);+ if (subscriber === "typed") {+ throw new Error("Fixture subagent observer failed after recording its event.");+ }}diff --git a/packages/eve/extension-contracts/compatibility/hook/v28.ts b/packages/eve/extension-contracts/compatibility/hook/v28.tsnew file mode 100644index 000000000..5d3faf71f--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v28.ts@@ -0,0 +1,14 @@+import { defineHook } from "#public/hooks/index.js";++// Epoch 29 hook contexts add cancel(); hooks written before it keep working unchanged.+export default defineHook({+ events: {+ async "step.started"(event, ctx) {+ const sandbox = await ctx.getSandbox();+ await sandbox.writeTextFile({+ content: `${event.data.turnId}:${String(event.data.stepIndex)}`,+ path: "last-step.txt",+ });+ },+ },+});diff --git a/packages/eve/extension-contracts/reports/hook/v29.json b/packages/eve/extension-contracts/reports/hook/v29.jsonnew file mode 100644index 000000000..76a678d19--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v29.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 29,+ "sha256": "f394605752390060cc321c4927eeeb558feba07eab06bf52f795e1122fc61392",+ "exports": ["defineHook"]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 835cbacb2..2d90f01f1 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -151,8 +151,8 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},hook: {- current: 28,- supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 27, 28],+ current: 29,+ supported: [10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 27, 28, 29],dropped: {1: "Model identity moved from session.started runtime metadata to step.started call attribution.",2: "Model identity moved from session.started runtime metadata to step.started call attribution.",diff --git a/packages/eve/src/context/hook-lifecycle.integration.test.ts b/packages/eve/src/context/hook-lifecycle.integration.test.tsindex 4825de3aa..61c7d4128 100644--- a/packages/eve/src/context/hook-lifecycle.integration.test.ts+++ b/packages/eve/src/context/hook-lifecycle.integration.test.ts@@ -1,8 +1,10 @@-import { describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { setLogRecordSubscriber, type LogRecord } from "#internal/logging.js";import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";import type { ResolvedHookDefinition } from "#runtime/types.js";import {+ createSessionFailedEvent,createStepStartedEvent,createTurnStartedEvent,type UnstampedMessageStreamEvent,@@ -18,6 +20,13 @@ import {} from "#runtime/sessions/runtime-context-keys.js";import { ContinuationTokenKey, SandboxKey, SessionIdKey, SessionKey } from "./keys.js";+const records: LogRecord[] = [];+beforeEach(() => {+ records.length = 0;+ setLogRecordSubscriber((record) => records.push(record));+});+afterEach(() => setLogRecordSubscriber(undefined));+function createMockBundle(): CompiledBundle {return {adapterRegistry: undefined as never,@@ -65,7 +74,7 @@ function hook(slug: string, hooks: Partial<ResolvedHookDefinition>): ResolvedHoo}describe("dispatchStreamEventHooks", () => {- it("invokes typed then wildcard subscribers and propagates errors", async () => {+ it("invokes typed then wildcard subscribers", async () => {const calls: string[] = [];const registry = createRuntimeHookRegistry([hook("audit", {@@ -88,6 +97,7 @@ describe("dispatchStreamEventHooks", () => {await contextStorage.run(ctx, () =>dispatchStreamEventHooks({+ cancelTurn: undefined,ctx,registry,event: stampTestEvent({ type: "session.completed" }),@@ -95,61 +105,184 @@ describe("dispatchStreamEventHooks", () => {);expect(calls).toEqual(["typed", "wildcard:session.completed"]);- const brokenRegistry = createRuntimeHookRegistry([- hook("broken", {+ expect(records).toEqual([]);+ });++ it.each([+ createTurnStartedEvent({ sequence: 0, turnId: "turn_0" }),+ createStepStartedEvent({ sequence: 0, turnId: "turn_0", stepIndex: 0, modelId: "test" }),+ { type: "session.completed" } as const,+ createSessionFailedEvent({+ code: "TEST_FAILURE",+ message: "Runtime failure",+ sessionId: "session_test",+ }),+ ])("continues typed and wildcard subscribers after failures for $type", async (event) => {+ const calls: string[] = [];+ const registry = createRuntimeHookRegistry([+ hook("broken-typed", {+ events: {+ [event.type]: () => {+ calls.push("broken-typed");+ throw new Error("typed hook failed");+ },+ },+ }),+ hook("healthy-typed", {+ events: {+ [event.type]: () => {+ calls.push("healthy-typed");+ },+ },+ }),+ hook("broken-wildcard", {+ events: {+ "*": async () => {+ calls.push("broken-wildcard");+ throw new Error("wildcard hook failed");+ },+ },+ }),+ hook("healthy-wildcard", {+ events: {+ "*": () => {+ calls.push("healthy-wildcard");+ },+ },+ }),+ ]);+ const ctx = buildCtx();+ const stamped = stampTestEvent(event);+ await contextStorage.run(ctx, () =>+ dispatchStreamEventHooks({ cancelTurn: undefined, ctx, registry, event: stamped }),+ );+ expect(calls).toEqual(["broken-typed", "healthy-typed", "broken-wildcard", "healthy-wildcard"]);+ expect(records).toMatchObject([+ {+ level: "error",+ fields: {+ hook: "broken-typed",+ subscription: event.type,+ eventId: stamped.meta.id,+ eventType: event.type,+ sessionId: "session_test",+ error: { message: expect.stringMatching(/^(?:Error: )?typed hook failed$/) },+ },+ },+ {+ level: "error",+ fields: {+ hook: "broken-wildcard",+ subscription: "*",+ eventId: stamped.meta.id,+ eventType: event.type,+ sessionId: "session_test",+ error: { message: expect.stringMatching(/^(?:Error: )?wildcard hook failed$/) },+ },+ },+ ]);+ });++ it("forwards ctx.cancel() without skipping later subscribers", async () => {+ const calls: string[] = [];+ const registry = createRuntimeHookRegistry([+ hook("gate", {+ events: {+ "turn.started": (_event, hookContext) => {+ calls.push("gate");+ hookContext.cancel();+ },+ },+ }),+ hook("audit", { events: { "*": () => void calls.push("audit") } }),+ ]);+ const ctx = buildCtx();+ await contextStorage.run(ctx, () =>+ dispatchStreamEventHooks({+ cancelTurn: () => calls.push("cancelTurn"),+ ctx,+ registry,+ event: stampTestEvent(createTurnStartedEvent({ sequence: 0, turnId: "turn_0" })),+ }),+ );+ expect(calls).toEqual(["gate", "cancelTurn", "audit"]);+ expect(records).toEqual([]);+ });++ it("warns and ignores ctx.cancel() after the event's hooks return", async () => {+ let lateCancel: (() => void) | undefined;+ const cancelled: string[] = [];+ const registry = createRuntimeHookRegistry([+ hook("gate", {events: {- "session.completed": async () => {- throw new Error("event hook boom");+ "turn.started": (_event, hookContext) => {+ lateCancel = () => hookContext.cancel();},},}),]);+ const ctx = buildCtx();+ await contextStorage.run(ctx, () =>+ dispatchStreamEventHooks({+ cancelTurn: () => cancelled.push("cancelTurn"),+ ctx,+ registry,+ event: stampTestEvent(createTurnStartedEvent({ sequence: 0, turnId: "turn_0" })),+ }),+ );+ lateCancel?.();+ expect(cancelled).toEqual([]);+ expect(records).toMatchObject([+ {+ level: "warn",+ message: "ctx.cancel() ignored: the event's hooks already returned",+ fields: { hook: "gate", eventType: "turn.started" },+ },+ ]);+ });++ it("warns and ignores ctx.cancel() when the event cannot cancel a turn", async () => {+ const registry = createRuntimeHookRegistry([+ hook("gate", {+ events: { "session.completed": (_event, hookContext) => hookContext.cancel() },+ }),+ ]);+ const ctx = buildCtx();+ const stamped = stampTestEvent({ type: "session.completed" });+ await contextStorage.run(ctx, () =>+ dispatchStreamEventHooks({ cancelTurn: undefined, ctx, registry, event: stamped }),+ );+ expect(records).toMatchObject([+ {+ level: "warn",+ message: "ctx.cancel() ignored: the event is not part of a running turn",+ fields: {+ hook: "gate",+ eventId: stamped.meta.id,+ eventType: "session.completed",+ sessionId: "session_test",+ },+ },+ ]);+ });++ it("still propagates runtime context setup failures", async () => {+ const ctx = new ContextContainer();+ ctx.set(BundleKey, createMockBundle());+ const registry = createRuntimeHookRegistry([hook("audit", { events: { "*": () => {} } })]);await expect(contextStorage.run(ctx, () =>dispatchStreamEventHooks({+ cancelTurn: undefined,ctx,- registry: brokenRegistry,+ registry,event: stampTestEvent({ type: "session.completed" }),}),),- ).rejects.toThrow(/event hook boom/);+ ).rejects.toThrow('Context key "eve.session" is not set.');+ expect(records).toEqual([]);});- it.each(["turn.started", "step.started"] as const)(- "identifies an authored %s rejection for turn recovery",- async (type) => {- const cause = new Error("admission denied");- const registry = createRuntimeHookRegistry([- hook("admission", {- events: {- "*": async () => {- throw cause;- },- },- }),- ]);- const ctx = buildCtx();- await expect(- contextStorage.run(ctx, () =>- dispatchStreamEventHooks({- ctx,- registry,- event: stampTestEvent(- type === "turn.started"- ? createTurnStartedEvent({ sequence: 0, turnId: "turn_0" })- : createStepStartedEvent({- sequence: 0,- turnId: "turn_0",- stepIndex: 0,- modelId: "test",- }),- ),- }),- ),- ).rejects.toMatchObject({ name: "BoundaryHookError", cause, message: "admission denied" });- },- );-it("can delete the runtime sandbox from a session.completed hook", async () => {let deletions = 0;const sandbox = mockSandbox({@@ -172,6 +305,7 @@ describe("dispatchStreamEventHooks", () => {await contextStorage.run(ctx, () =>dispatchStreamEventHooks({+ cancelTurn: undefined,ctx,registry,event: stampTestEvent({ type: "session.completed" }),diff --git a/packages/eve/src/context/hook-lifecycle.ts b/packages/eve/src/context/hook-lifecycle.tsindex 553d38289..e0a11ecad 100644--- a/packages/eve/src/context/hook-lifecycle.ts+++ b/packages/eve/src/context/hook-lifecycle.ts@@ -1,4 +1,4 @@-import { BoundaryHookError } from "#shared/boundary-hook-error.js";+import { createLogger, logError } from "#internal/logging.js";import { getAdapterKind } from "#channel/adapter.js";import type { MessageStreamEvent } from "#protocol/message.js";import type { HookContext } from "#public/definitions/hook.js";@@ -8,16 +8,19 @@ import type { ContextContainer } from "./container.js";import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { ContinuationTokenKey } from "./keys.js";+const log = createLogger("hooks");+/*** Fans one runtime stream event out to every matching subscriber.- * Errors propagate — harness error paths convert them into the- * recoverable `turn.failed` cascade. Caller must hold an active ALS- * scope so hooks see the same context as the rest of the step.+ * Authored handler failures are logged independently. Caller must hold an+ * active ALS scope so hooks see the same context as the rest of the step.*/export async function dispatchStreamEventHooks(input: {readonly ctx: ContextContainer;readonly registry: RuntimeHookRegistry;readonly event: MessageStreamEvent;+ /** Stops the running turn for `ctx.cancel()`; `undefined` when this event cannot stop one. */+ readonly cancelTurn: (() => void) | undefined;}): Promise<void> {const typed = input.registry.streamEventsByType.get(input.event.type) ?? [];const wildcard = input.registry.streamEventsWildcard;@@ -26,24 +29,47 @@ export async function dispatchStreamEventHooks(input: {return;}- const hookCtx = buildHookContext(input.ctx);- try {- for (const entry of typed) {- await entry.handler(input.event, hookCtx);- }- for (const entry of wildcard) {+ const baseCtx = buildHookContext(input.ctx);+ let dispatching = true;+ for (const entry of [...typed, ...wildcard]) {+ const hookCtx: HookContext = {+ ...baseCtx,+ cancel: () => {+ if (dispatching && input.cancelTurn !== undefined) {+ input.cancelTurn();+ return;+ }+ log.warn(+ dispatching+ ? "ctx.cancel() ignored: the event is not part of a running turn"+ : "ctx.cancel() ignored: the event's hooks already returned",+ {+ hook: entry.slug,+ eventId: input.event.meta.id,+ eventType: input.event.type,+ sessionId: baseCtx.session.id,+ },+ );+ },+ };+ try {await entry.handler(input.event, hookCtx);+ } catch (error) {+ logError(log, "stream event hook failed", error, {+ hook: entry.slug,+ subscription: entry.eventType,+ eventId: input.event.meta.id,+ eventType: input.event.type,+ sessionId: baseCtx.session.id,+ });}- } catch (error) {- if (input.event.type === "turn.started" || input.event.type === "step.started") {- throw new BoundaryHookError(error);- }- throw error;}+ // Work a hook did not await could otherwise cancel at an arbitrary later point, or never.+ dispatching = false;}-/** Builds the {@link HookContext} surfaced to one handler. */-function buildHookContext(ctx: ContextContainer): HookContext {+/** Builds the {@link HookContext} fields shared by every handler of one event. */+function buildHookContext(ctx: ContextContainer): Omit<HookContext, "cancel"> {const bundle = ctx.require(BundleKey);const channelAdapter = ctx.get(ChannelKey);const continuationToken = ctx.get(ContinuationTokenKey);diff --git a/packages/eve/src/execution/publish-channel-event.ts b/packages/eve/src/execution/publish-channel-event.tsindex d85d6f088..05f9f4ffb 100644--- a/packages/eve/src/execution/publish-channel-event.ts+++ b/packages/eve/src/execution/publish-channel-event.ts@@ -30,6 +30,8 @@ interface ChannelEventInput {export async function publishChannelEvent(input: ChannelEventInput): Promise<MessageStreamEvent> {const stamped = await writeChannelEvent(input);await dispatchStreamEventHooks({+ // Only turn-step events can cancel the running turn; see turn-event-handler.ts.+ cancelTurn: undefined,ctx: input.ctx,registry: input.ctx.require(BundleKey).hookRegistry,event: stamped,diff --git a/packages/eve/src/execution/session/turn-event-handler.test.ts b/packages/eve/src/execution/session/turn-event-handler.test.tsnew file mode 100644index 000000000..4cf6f7f60--- /dev/null+++ b/packages/eve/src/execution/session/turn-event-handler.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { isHookCancellableEvent } from "./turn-event-handler.js";++describe("isHookCancellableEvent", () => {+ it.each([+ "session.started",+ "turn.started",+ "step.started",+ "message.received",+ "actions.requested",+ "action.result",+ "authorization.required",+ "input.requested",+ "message.completed",+ "step.completed",+ "result.completed",+ ])("lets a %s hook cancel the running turn", (type) => {+ expect(isHookCancellableEvent(type)).toBe(true);+ });++ it.each([+ "step.failed",+ "turn.completed",+ "turn.failed",+ "turn.cancelled",+ "session.waiting",+ "session.completed",+ "session.failed",+ "context.cleared",+ "subagent.called",+ "subagent.completed",+ "subagent.event",+ "subagent.started",+ "internal.unlisted",+ ])("ignores cancellation from a %s hook", (type) => {+ expect(isHookCancellableEvent(type)).toBe(false);+ });+});diff --git a/packages/eve/src/execution/session/turn-event-handler.ts b/packages/eve/src/execution/session/turn-event-handler.tsnew file mode 100644index 000000000..4202a3d20--- /dev/null+++ b/packages/eve/src/execution/session/turn-event-handler.ts@@ -0,0 +1,145 @@+import { dispatchDynamicInstructionEvent } from "#context/dynamic-instruction-lifecycle.js";+import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";+import { dispatchDynamicSkillEvent } from "#context/dynamic-skill-lifecycle.js";+import { dispatchDynamicSubagentEvent } from "#context/dynamic-subagent-lifecycle.js";+import { dispatchDynamicToolEvent } from "#context/dynamic-tool-lifecycle.js";+import type { ContextContainer } from "#context/container.js";+import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";+import { dispatchMemoryLifecycleEvent } from "#context/memory-event-lifecycle.js";+import type { bindDynamicConnections } from "#execution/dynamic-connections.js";+import type { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";+import type { SessionEventSink } from "#execution/session/event-sink.js";+import { throwIfTurnAborted, TurnCancelledError } from "#harness/turn-cancellation.js";+import type { HandleEventFn } from "#harness/types.js";+import type { HookEventType } from "#public/definitions/hook.js";+import type { ExecutionInstrumentation } from "#instrumentation/runtime.js";+import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";++/**+ * Whether `ctx.cancel()` from a hook on each event may stop the running turn.+ * Total over hook events, so a new event must be classified before it compiles.+ * Settlement events stay false: cancelling there would give the turn a second terminal.+ */+const HOOK_CANCELLABLE_EVENTS = {+ "action.input.appended": true,+ "action.partial": true,+ "action.result": true,+ "actions.requested": true,+ "approval.candidate": true,+ "approval.settled": true,+ "authorization.completed": true,+ "authorization.required": true,+ "compaction.completed": true,+ "compaction.requested": true,+ "context.cleared": false,+ "input.requested": true,+ "input.resolved": true,+ "message.appended": true,+ "message.completed": true,+ "message.received": true,+ "reasoning.appended": true,+ "reasoning.completed": true,+ "result.completed": true,+ "session.completed": false,+ "session.failed": false,+ "session.started": true,+ "session.waiting": false,+ "step.completed": true,+ "step.failed": false,+ "step.started": true,+ "subagent.called": false,+ "subagent.completed": false,+ "subagent.event": false,+ "subagent.started": false,+ "turn.cancelled": false,+ "turn.completed": false,+ "turn.failed": false,+ "turn.started": true,+} as const satisfies Record<HookEventType, boolean>;++/** True when a hook on this event type may cancel the running turn. */+export function isHookCancellableEvent(type: string): boolean {+ return (HOOK_CANCELLABLE_EVENTS as Readonly<Record<string, boolean>>)[type] === true;+}++/**+ * Publishes one turn event, then runs memory, hooks, and model preparation for it.+ * A hook's `ctx.cancel()` aborts the turn signal at once; the event's remaining+ * hooks still run, then the handler stops the turn before the next model call.+ */+export function createTurnEventHandler(input: {+ readonly abortSignal: AbortSignal;+ readonly bundle: CompiledBundle;+ /** False for clear and compact requests, which run outside any turn. */+ readonly canCancelTurn: boolean;+ readonly hookCancellation: AbortController;+ readonly ctx: ContextContainer;+ readonly dynamicConnections: ReturnType<typeof bindDynamicConnections>;+ readonly effectiveAgent: ReturnType<typeof resolveEffectiveAgentRuntime>;+ readonly effectiveNode: CompiledBundle["graph"]["root"];+ readonly instrumentation: ExecutionInstrumentation | undefined;+ readonly sink: SessionEventSink;+}): HandleEventFn {+ const { abortSignal, bundle, ctx, effectiveAgent, effectiveNode } = input;+ return async (event, messages) => {+ const emitted = await input.sink.emit(event);+ const lifecycleMessages = await dispatchMemoryLifecycleEvent({+ abortSignal,+ appRoot: effectiveNode.agent?.metadata?.appRoot ?? "",+ ctx,+ event,+ instrumentation: input.instrumentation?.memory,+ memories: effectiveNode.agent?.memories ?? [],+ messages,+ nodeId: bundle.nodeId ?? "__root__",+ });+ const cancelTurn =+ input.canCancelTurn && isHookCancellableEvent(emitted.event.type)+ ? () => input.hookCancellation.abort(new TurnCancelledError())+ : undefined;+ if (!emitted.suppressed) {+ await dispatchStreamEventHooks({+ cancelTurn,+ ctx,+ registry: bundle.hookRegistry,+ event: emitted.event,+ });+ }+ if (emitted.event.type !== "step.started") {+ await dispatchDynamicModelEvent({+ abortSignal,+ ctx,+ dynamicModel: effectiveAgent.turnAgent.dynamicModel,+ event: emitted.event,+ messages: lifecycleMessages,+ scope: { moduleMap: bundle.moduleMap, nodeId: bundle.nodeId },+ });+ }+ await input.dynamicConnections.dispatch(emitted.event);+ await dispatchDynamicSubagentEvent({+ ctx,+ resolvers: bundle.subagentRegistry.dynamicResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ await dispatchDynamicToolEvent({+ ctx,+ resolvers: bundle.resolvedAgent.dynamicToolResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ await dispatchDynamicSkillEvent({+ ctx,+ resolvers: bundle.resolvedAgent.dynamicSkillResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ await dispatchDynamicInstructionEvent({+ ctx,+ resolvers: bundle.resolvedAgent.dynamicInstructionsResolvers ?? [],+ event: emitted.event,+ messages: lifecycleMessages,+ });+ if (cancelTurn !== undefined) throwIfTurnAborted(input.hookCancellation.signal);+ };+}diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.tsindex e4950d515..048ac45d5 100644--- a/packages/eve/src/execution/session/turn-step.test.ts+++ b/packages/eve/src/execution/session/turn-step.test.ts@@ -47,9 +47,13 @@ import {createMessageAppendedEvent,createMessageCompletedEvent,createResultCompletedEvent,+ createStepStartedEvent,+ createTurnCompletedEvent,createTurnStartedEvent,type UnstampedMessageStreamEvent,} from "#protocol/message.js";+import { setLogRecordSubscriber, type LogRecord } from "#internal/logging.js";+import type { HookContext } from "#public/definitions/hook.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import {createDurableSessionState,@@ -2521,6 +2525,145 @@ describe("turnStep", () => {});});+ describe("hook ctx.cancel()", () => {+ const records: LogRecord[] = [];+ beforeEach(() => {+ records.length = 0;+ setLogRecordSubscriber((record) => records.push(record));+ });+ afterEach(() => setLogRecordSubscriber(undefined));++ function installHooks(+ events: Record<string, (event: never, ctx: HookContext) => void>,+ turnAgent: object = TestTurnAgent,+ ) {+ const bundle = Object.assign({}, createTurnStepTestBundle() as object, {+ turnAgent,+ hookRegistry: createRuntimeHookRegistry([+ {+ events,+ logicalPath: "hooks/gate.ts",+ slug: "gate",+ sourceId: "hooks/gate.ts",+ sourceKind: "module",+ } as never,+ ]),+ }) as never;+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(bundle);+ }++ it("cancels the running turn after every subscriber sees the event", async () => {+ const seen: string[] = [];+ installHooks({+ "step.started": (_event, ctx) => {+ seen.push("typed");+ ctx.cancel();+ },+ "*": (event: UnstampedMessageStreamEvent) => {+ seen.push(`wildcard:${event.type}`);+ },+ });+ installSessionStoreMocks([createStubSession()]);+ let stepSignal: AbortSignal | undefined;+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => {+ return async (session): Promise<StepResult> => {+ stepSignal = input.abortSignal;+ const turn = { sequence: 0, stepIndex: 0, turnId: "turn_0" };+ await input.handleEvent?.(+ createStepStartedEvent({ ...turn, modelId: "test" }),+ session.history,+ );+ await input.handleEvent?.(+ createMessageCompletedEvent({ ...turn, message: "unreachable" }),+ session.history,+ );+ return { next: null, session, settledTurn: { output: "unreachable" } };+ };+ });++ const result = await turnStep({+ input: { kind: "deliver", payloads: [{ message: "hello" }] },+ sessionWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(result.action).toBe("cancelled");+ expect(stepSignal?.aborted).toBe(true);+ expect(seen).toEqual(["typed", "wildcard:step.started"]);+ expect(records.filter((record) => record.level !== "debug")).toEqual([]);+ });++ it("still cancels when a later consumer of the event throws", async () => {+ installHooks(+ { "turn.started": (_event, ctx) => ctx.cancel() },+ {+ ...TestTurnAgent,+ // An unloadable resolver makes dynamic model dispatch throw after the hooks run.+ dynamicModel: {+ eventNames: ["turn.started"],+ logicalPath: "agent.ts",+ sourceId: "agent.ts",+ sourceKind: "module",+ },+ },+ );+ installSessionStoreMocks([createStubSession()]);+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => {+ return async (session): Promise<StepResult> => {+ await input.handleEvent?.(+ createTurnStartedEvent({ sequence: 0, turnId: "turn_0" }),+ session.history,+ );+ return { next: null, session, settledTurn: { output: "unreachable" } };+ };+ });++ const result = await turnStep({+ input: { kind: "deliver", payloads: [{ message: "hello" }] },+ sessionWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(result.action).toBe("cancelled");+ });++ it("keeps a settled turn and warns when a terminal event hook cancels", async () => {+ installHooks({+ "turn.completed": (_event, ctx) => {+ ctx.cancel();+ },+ });+ installSessionStoreMocks([createStubSession()]);+ vi.mocked(createExecutionNodeStep).mockImplementation((input) => {+ return async (session): Promise<StepResult> => {+ await input.handleEvent?.(+ createTurnCompletedEvent({ sequence: 0, turnId: "turn_0" }),+ session.history,+ );+ return { next: null, session, settledTurn: { output: "settled answer" } };+ };+ });++ const result = await turnStep({+ input: { kind: "deliver", payloads: [{ message: "hello" }] },+ sessionWritable: createTestWritable(),+ serializedContext: createSerializedContext(),+ sessionState: createStubSessionState(),+ });++ expect(result).toMatchObject({ action: "park", settled: { output: "settled answer" } });+ expect(records).toMatchObject([+ {+ level: "warn",+ message: "ctx.cancel() ignored: the event is not part of a running turn",+ fields: { hook: "gate", eventType: "turn.completed" },+ },+ ]);+ });+ });+it("reports each settled turn's usage as a delta, not the cumulative session totals", async () => {const usageStateAfterTurn = (totals: Readonly<Record<string, number>>,diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex 29033db1b..605a769f7 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -1,24 +1,15 @@-import { dispatchDynamicModelEvent } from "#context/dynamic-model-lifecycle.js";-import { dispatchDynamicSkillEvent } from "#context/dynamic-skill-lifecycle.js";-import { dispatchStreamEventHooks } from "#context/hook-lifecycle.js";-import { dispatchMemoryLifecycleEvent } from "#context/memory-event-lifecycle.js";import { bindDynamicConnections } from "#execution/dynamic-connections.js";import { deriveSessionTitle } from "#execution/eve-workflow-attributes.js";import { setEveAttributes } from "#runtime/attributes/emit.js";import { defaultDeliverResult } from "#channel/adapter.js";-import { contextStorage, type ContextContainer } from "#context/container.js";+import { contextStorage } from "#context/container.js";import {- dispatchDynamicInstructionEvent,drainDynamicInstructionUserMessages,prepareDynamicInstructionPreamble,} from "#context/dynamic-instruction-lifecycle.js";-import {- dispatchDynamicSubagentEvent,- refreshDynamicSessionSubagentsForRuntimeRevision,-} from "#context/dynamic-subagent-lifecycle.js";+import { refreshDynamicSessionSubagentsForRuntimeRevision } from "#context/dynamic-subagent-lifecycle.js";import { drainMemoryCommit, prepareMemoryPreamble } from "#context/memory-lifecycle.js";import {- dispatchDynamicToolEvent,rebindMissingCompiledDynamicToolCallbacks,refreshDynamicSessionToolsForRuntimeRevision,} from "#context/dynamic-tool-lifecycle.js";@@ -37,11 +28,7 @@ import {TaskDeliveryPolicyKey,TurnDeliveryIdsKey,} from "#context/keys.js";-import {- BundleKey,- ChannelKey,- type CompiledBundle,-} from "#runtime/sessions/runtime-context-keys.js";+import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";import { deserializeContext, serializeContext } from "#context/serialize.js";import {emitTurnPreamble,@@ -49,10 +36,7 @@ import {isHarnessBetweenTurns,setHarnessEmissionState,} from "#harness/emission.js";-import {- bindSessionInstrumentation,- type ExecutionInstrumentation,-} from "#instrumentation/runtime.js";+import { bindSessionInstrumentation } from "#instrumentation/runtime.js";import { RuntimeActionSettlementTimesKey } from "#harness/runtime-action-settlement-state.js";import * as agentTraceState from "#tracing/agent-trace-context-store.js";import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";@@ -66,10 +50,11 @@ import {type UserModelMessage,} from "#harness/messages.js";import { consumeDeferredStepInput } from "#harness/pending-input-batches.js";-import type { HandleEventFn, HarnessSession, StepInput, StepResult } from "#harness/types.js";+import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";import type { DurableStepResult, TurnStepInput } from "#execution/session/turn-step-types.js";import { resolveSessionStepResult } from "#execution/session/turn-step-result.js";-import { createSessionEventSink, type SessionEventSink } from "#execution/session/event-sink.js";+import { createSessionEventSink } from "#execution/session/event-sink.js";+import { createTurnEventHandler } from "#execution/session/turn-event-handler.js";import { derivePendingState } from "#execution/session/pending-turn-state.js";import {createAuthorizationCompletedEvent,@@ -257,12 +242,21 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>sessionId: initialSession.sessionId,});const { adapterCtx } = sink;+ // A hook's `ctx.cancel()` aborts the same signal the harness already honors+ // for `session.cancel()`, so both settle through one cancellation path.+ const hookCancellation = new AbortController();+ const abortSignal =+ input.abortSignal === undefined+ ? hookCancellation.signal+ : AbortSignal.any([input.abortSignal, hookCancellation.signal]);try {const dynamicConnections = bindDynamicConnections(ctx, bundle.resolvedAgent);const effectiveNode = { ...bundle.graph.root, turnAgent: effectiveAgent.turnAgent };const handleEvent = createTurnEventHandler({- abortSignal: input.abortSignal,+ abortSignal,bundle,+ canCancelTurn: input.input?.control === undefined,+ hookCancellation,ctx,dynamicConnections,effectiveAgent,@@ -469,7 +463,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>const step = createExecutionNodeStep({steeringSignal: input.steeringSignal,- abortSignal: input.abortSignal,+ abortSignal,capabilities,clearOnly: input.input?.control === "clear",compactOnly: input.input?.control === "compact",@@ -494,7 +488,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>// A signal already aborted at entry (cancellation during an in-line// runtime-action wait) must settle before the park-resume stages run,// or the pending batch would re-park and later re-dispatch.- throwIfTurnAborted(input.abortSignal);+ throwIfTurnAborted(abortSignal);stepResult = await runModelCallBatch({steeringSignal: input.steeringSignal,initialInput: resolved,@@ -583,13 +577,13 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>});// The waiting boundary may reach the client before this step returns.// Its settled result wins over a cancellation of that completed turn.- if (result.settledTurn === undefined) throwIfTurnAborted(input.abortSignal);+ if (result.settledTurn === undefined) throwIfTurnAborted(abortSignal);completedModelCall = { result, serializedContext: serializeContext(ctx) };return result;},});} catch (error) {- if (!isTurnCancellation(error) && input.abortSignal?.aborted !== true) {+ if (!isTurnCancellation(error) && !abortSignal.aborted) {await failChannelDeliveries(error);throw error;}@@ -623,68 +617,3 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>sink.release();}}--/** Publishes one turn event, then runs memory, hooks, and model preparation for it. */-function createTurnEventHandler(input: {- readonly abortSignal: AbortSignal | undefined;- readonly bundle: CompiledBundle;- readonly ctx: ContextContainer;- readonly dynamicConnections: ReturnType<typeof bindDynamicConnections>;- readonly effectiveAgent: ReturnType<typeof resolveEffectiveAgentRuntime>;- readonly effectiveNode: CompiledBundle["graph"]["root"];- readonly instrumentation: ExecutionInstrumentation | undefined;- readonly sink: SessionEventSink;-}): HandleEventFn {- const { abortSignal, bundle, ctx, effectiveAgent, effectiveNode } = input;- return async (event, messages) => {- const emitted = await input.sink.emit(event);- const lifecycleMessages = await dispatchMemoryLifecycleEvent({- abortSignal,- appRoot: effectiveNode.agent?.metadata?.appRoot ?? "",- ctx,- event,- instrumentation: input.instrumentation?.memory,- memories: effectiveNode.agent?.memories ?? [],- messages,- nodeId: bundle.nodeId ?? "__root__",- });- if (!emitted.suppressed) {- await dispatchStreamEventHooks({ ctx, registry: bundle.hookRegistry, event: emitted.event });- }- if (emitted.event.type !== "step.started") {- await dispatchDynamicModelEvent({- abortSignal,- ctx,- dynamicModel: effectiveAgent.turnAgent.dynamicModel,- event: emitted.event,- messages: lifecycleMessages,- scope: { moduleMap: bundle.moduleMap, nodeId: bundle.nodeId },- });- }- await input.dynamicConnections.dispatch(emitted.event);- await dispatchDynamicSubagentEvent({- ctx,- resolvers: bundle.subagentRegistry.dynamicResolvers ?? [],- event: emitted.event,- messages: lifecycleMessages,- });- await dispatchDynamicToolEvent({- ctx,- resolvers: bundle.resolvedAgent.dynamicToolResolvers ?? [],- event: emitted.event,- messages: lifecycleMessages,- });- await dispatchDynamicSkillEvent({- ctx,- resolvers: bundle.resolvedAgent.dynamicSkillResolvers ?? [],- event: emitted.event,- messages: lifecycleMessages,- });- await dispatchDynamicInstructionEvent({- ctx,- resolvers: bundle.resolvedAgent.dynamicInstructionsResolvers ?? [],- event: emitted.event,- messages: lifecycleMessages,- });- };-}diff --git a/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts b/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.tsindex 456fedecd..8840dc1a8 100644--- a/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts+++ b/packages/eve/src/execution/tools/subagent/emit-event-step.integration.test.ts@@ -1,4 +1,6 @@-import { beforeEach, expect, it, vi } from "vitest";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { setLogRecordSubscriber, type LogRecord } from "#internal/logging.js";import { ContextContainer, contextStorage, loadContext } from "#context/container.js";import {@@ -28,7 +30,13 @@ vi.mock("#context/serialize.js", () => ({serializeContext: vi.fn(),}));-beforeEach(() => vi.resetAllMocks());+const records: LogRecord[] = [];+beforeEach(() => {+ vi.resetAllMocks();+ records.length = 0;+ setLogRecordSubscriber((record) => records.push(record));+});+afterEach(() => setLogRecordSubscriber(undefined));const events: UnstampedMessageStreamEvent[] = [{@@ -94,8 +102,8 @@ it.each(expect(received).toEqual(JSON.parse(new TextDecoder().decode(chunks[0])));expect(ctx.has(SandboxKey)).toBe(true);calls.push(kind);- if (fails) throw new Error("subagent subscriber failed");ctx.set(SessionTitleKey, "Research event received");+ if (fails) throw new Error("subagent subscriber failed");};const handlers: Record<string, StreamEventHook<MessageStreamEvent>> = {};if (subscription !== "wildcard") handlers[event.type] = handler("typed");@@ -147,26 +155,36 @@ it.each(sessionState,});const firstHandler = subscription === "wildcard" ? "wildcard" : "typed";- if (fails) {- await expect(emitted).rejects.toThrow("subagent subscriber failed");- expect(calls).toEqual(["adapter", "stream", firstHandler]);- } else {- const result = await emitted;- expect(result.serializedContext[SessionTitleKey.name]).toBe("Research event received");- expect(result.serializedContext[SessionKey.name]).toBeUndefined();- expect(result.serializedContext[SandboxKey.name]).toBeUndefined();- expect(result.sessionState.snapshot.session.sandboxState).toEqual({ session: null });- expect(result.serializedContext[DynamicSkillManifestKey.name]).toEqual(- ctx.require(DynamicSkillManifestKey),- );- expect(ctx.require(ChannelKey).state).toEqual({ delivered: true });- expect(calls).toEqual([- "adapter",- "stream",- firstHandler,- ...(subscription === "both" ? ["wildcard"] : []),- ]);- }+ const result = await emitted;+ expect(result.serializedContext[SessionTitleKey.name]).toBe("Research event received");+ expect(result.serializedContext[SessionKey.name]).toBeUndefined();+ expect(result.serializedContext[SandboxKey.name]).toBeUndefined();+ expect(result.sessionState.snapshot.session.sandboxState).toEqual({ session: null });+ expect(result.serializedContext[DynamicSkillManifestKey.name]).toEqual(+ ctx.require(DynamicSkillManifestKey),+ );+ expect(ctx.require(ChannelKey).state).toEqual({ delivered: true });+ expect(calls).toEqual([+ "adapter",+ "stream",+ firstHandler,+ ...(subscription === "both" ? ["wildcard"] : []),+ ]);+ const subscribers = [firstHandler, ...(subscription === "both" ? ["wildcard"] : [])];+ expect(records).toMatchObject(+ fails+ ? subscribers.map((subscriber) => ({+ level: "error",+ fields: {+ hook: "subagent-events",+ subscription: subscriber === "typed" ? event.type : "*",+ eventType: event.type,+ sessionId: "parent",+ error: { message: expect.stringMatching(/^(?:Error: )?subagent subscriber failed$/) },+ },+ }))+ : [],+ );expect(chunks).toHaveLength(1);expect(new TextDecoder().decode(chunks[0])).toContain(`"type":"${event.type}"`);expect(stream.locked).toBe(false);diff --git a/packages/eve/src/execution/tools/subagent/emit-event-step.ts b/packages/eve/src/execution/tools/subagent/emit-event-step.tsindex 464e19b70..ece8b081f 100644--- a/packages/eve/src/execution/tools/subagent/emit-event-step.ts+++ b/packages/eve/src/execution/tools/subagent/emit-event-step.ts@@ -66,7 +66,12 @@ export async function emitSubagentEventStep(input: {const scoped = await withContextScope(ctx, session, async (enriched) => {const emitted = await publish();if (!emitted.suppressed) {- await dispatchStreamEventHooks({ ctx, registry, event: emitted.event });+ await dispatchStreamEventHooks({+ cancelTurn: undefined,+ ctx,+ registry,+ event: emitted.event,+ });}return { result: undefined, session: enriched };});diff --git a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.tsindex 728e61b40..28f62a3a0 100644--- a/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts+++ b/packages/eve/src/execution/tools/subagent/task-agent-requests.test.ts@@ -66,7 +66,7 @@ describe("workflow-owned agent requests", () => {});it.each([false, true])(- "waits for notification hooks before acknowledgement and retains their state (fails: %s)",+ "waits for notification completion before acknowledgement and retains its state (fails: %s)",async (fails) => {const updatedState = { sessionId: "updated" } as never;const hookState = { sessionId: "hooked" } as never;@@ -90,8 +90,8 @@ describe("workflow-owned agent requests", () => {await vi.waitFor(() => expect(emitSubagentEventStep).toHaveBeenCalledOnce());expect(resumeHookStep).not.toHaveBeenCalled();if (fails) {- const rejected = expect(applying).rejects.toThrow("hook failed");- notification.reject(new Error("hook failed"));+ const rejected = expect(applying).rejects.toThrow("notification runtime failed");+ notification.reject(new Error("notification runtime failed"));await rejected;expect(emitSubagentEventStep).toHaveBeenCalledOnce();expect(resumeHookStep).not.toHaveBeenCalled();diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex 8575e5e6f..9ae4ded1b 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -22,6 +22,7 @@ import type { RouteHandlerArgs } from "#channel/routes.js";import { createSession } from "#channel/session.js";import { none } from "#public/channels/auth.js";import { eveChannel } from "#public/channels/eve.js";+import { defineHook } from "#public/definitions/hook.js";import { defineMemory } from "#public/memory/index.js";import type { ToolContext } from "#tools/definition.js";import type { ResolvedToolDefinition } from "#runtime/types.js";@@ -399,6 +400,85 @@ describe("turn cancellation integration", () => {});}, 60_000);+ it.each(["turn.started", "step.started"] as const)(+ "cancels a turn from a %s hook's ctx.cancel() and accepts the next message",+ async (boundary) => {+ const runtime = await createTestRuntime({+ agent: { name: `turn-hook-cancel-${boundary}` },+ modules: [+ {+ loadNamespace: async () => ({+ default: defineHook({+ events: {+ "*"(event, ctx) {+ if (event.type === boundary && event.data.sequence === 0) ctx.cancel();+ },+ },+ }),+ }),+ logicalPath: "hooks/gate.ts",+ },+ ],+ });+ const rawToken = `turn-hook-cancel-${boundary}`;+ const continuationToken = `http:${rawToken}`;+ const address = createChannelAddress({+ adapter: { kind: "http" },+ channelName: "http",+ continuationToken: rawToken,+ runtime: createWorkflowRuntime({+ compiledArtifactsSource: createBundledRuntimeCompiledArtifactsSource(),+ }),+ });++ await runtime.run(async () => {+ const run = await start(workflowEntry, [+ {+ kind: "initial",+ ownerDeploymentId: "dpl_inline",+ input: { message: "Alice asks for the weekly summary." },+ serializedContext: buildSerializedContext({+ channelKind: "http",+ continuationToken,+ }),+ },+ ]);+ const stream = captureTurnEvents(run);++ try {+ const cancelledTurn = await stream.nextTurn();+ expect(+ containsEventSequence(cancelledTurn, [+ "turn.started",+ "turn.cancelled",+ "session.waiting",+ ]),+ ).toBe(true);+ expect(filterEventsByType(cancelledTurn, "step.started")).toHaveLength(+ boundary === "step.started" ? 1 : 0,+ );+ expect(filterEventsByType(cancelledTurn, "message.completed")).toHaveLength(0);+ expect(filterEventsByType(cancelledTurn, "step.completed")).toHaveLength(0);+ expectNoFailureEvents(cancelledTurn);+ await expectNoStepRetries(run.runId);++ await waitForHookByToken(sessionInboxHookToken(continuationToken));+ await address.send("Bob asks for the summary again.", { auth: null });+ const nextTurn = await stream.nextTurn();+ expect(filterEventsByType(nextTurn, "turn.started")).toMatchObject([+ { data: { sequence: 1 } },+ ]);+ expect(filterEventsByType(nextTurn, "turn.completed")).toHaveLength(1);+ expectNoFailureEvents(nextTurn);+ } finally {+ stream.dispose();+ await run.cancel();+ }+ });+ },+ 60_000,+ );+it("keeps an abort-shaped memory recall error terminal while the turn signal is active", async () => {const output = captureConsoleOutput();const fixture = await createAbortRecallRuntime("turn-active-memory-abort", {diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 65160dd4a..d58ce8273 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -1,4 +1,3 @@-import { BoundaryHookError } from "#shared/boundary-hook-error.js";import { context as otelContext, trace } from "#compiled/@opentelemetry/api/index.js";import {type FilePart,@@ -12665,113 +12664,6 @@ describe("appendMissingToolResultMessages", () => {});describe("boundary event failures", () => {- it.each(["turn.started", "step.started"] as const)(- "parks a failed %s and accepts the next turn",- async (boundary) => {- const logs = captureLogRecords();- const events: UnstampedMessageStreamEvent[] = [];- let denied = true;- const emit: HarnessEmitFn = async (event) => {- events.push(event);- if (denied && event.type === boundary)- throw new BoundaryHookError(new Error("admission denied"));- };- const runStep = createToolLoopHarness(createTestConfig(emit));- const result = await runStep(createTestSession({ outputSchema: { type: "object" } }), {- message: "Denied request",- });- expect(result.next).toBeNull();- expect(result.settledTurn).toEqual({- isError: true,- output: "admission denied",- });- expect(result.session.outputSchema).toBeUndefined();- expect(ToolLoopAgent).not.toHaveBeenCalled();- expect(events.filter((event) => event.type === "turn.failed")).toMatchObject([- { data: { turnId: "turn_0", sequence: 0, code: "EVENT_HANDLER_FAILED" } },- ]);- expect(events.map((event) => event.type)).toContain("session.waiting");- expect(events.map((event) => event.type)).not.toContain("session.failed");- expect(getHarnessEmissionState(result.session.state)).toEqual({- sessionStarted: true,- sequence: 1,- stepIndex: 0,- turnId: "",- });- denied = false;- setupMockAgent({- finishReason: "stop",- response: { messages: [{ role: "assistant", content: "recovered" }] },- text: "recovered",- toolCalls: [],- toolResults: [],- });- const recovered = await runStep(- JSON.parse(JSON.stringify(result.session)) as HarnessSession,- { message: "Try again" },- );- expect(recovered.next).toBeNull();- expect(events.filter((event) => event.type === "turn.completed")).toMatchObject([- { data: { turnId: "turn_1", sequence: 1 } },- ]);- expect(events.filter((event) => event.type === "session.started")).toHaveLength(1);- expect(logs.records).toContainEqual(- expect.objectContaining({- level: "error",- message: "turn boundary handler failed — parking session",- }),- );- },- );-- it("fails the current later step without invoking another model", async () => {- const logs = captureLogRecords();- const events: UnstampedMessageStreamEvent[] = [];- const emit: HarnessEmitFn = async (event) => {- events.push(event);- if (event.type === "step.started")- throw new BoundaryHookError(new Error("step budget exhausted"));- };- const session = setHarnessEmissionState(createTestSession(), {- sessionStarted: true,- sequence: 2,- stepIndex: 3,- turnId: "turn_2",- });- const result = await createToolLoopHarness(createTestConfig(emit))(session);- expect(result.next).toBeNull();- expect(events[1]).toMatchObject({- type: "step.failed",- data: { stepIndex: 3, turnId: "turn_2" },- });- expect(ToolLoopAgent).not.toHaveBeenCalled();- expect(logs.records).toContainEqual(- expect.objectContaining({- level: "error",- message: "turn boundary handler failed — parking session",- }),- );- });-- it("lets a failed failure handler escalate", async () => {- const logs = captureLogRecords();- const emit: HarnessEmitFn = async (event) => {- if (event.type === "turn.started") throw new BoundaryHookError(new Error("admission denied"));- if (event.type === "turn.failed") throw new Error("failure handler failed");- };- await expect(- createToolLoopHarness(createTestConfig(emit))(createTestSession(), {- message: "Hi",- }),- ).rejects.toThrow("failure handler failed");- expect(logs.records).toContainEqual(- expect.objectContaining({- level: "error",- message: "turn boundary handler failed — parking session",- }),- );- });-it("keeps runtime preamble failures terminal", async () => {const failure = new Error("memory recall failed");const emit: HarnessEmitFn = async (event) => {diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 99a3d4c1c..ed582f585 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -1,5 +1,4 @@import { setTimeout as delay } from "node:timers/promises";-import { BoundaryHookError } from "#shared/boundary-hook-error.js";import { GenerationSteering } from "#harness/generation-steering.js";import { interruptStreamOnFailure } from "#harness/interruptible-stream.js";import {@@ -559,30 +558,7 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {throwIfTurnAborted(config.abortSignal);if (isTurnCancellation(error)) throw error;if (isDynamicModelSelectionError(error)) return failModelSelection(error, failureState);- if (!emit || !(error instanceof BoundaryHookError)) {- throw error;- }-- stepInstrumentation?.recordError(error);- const errorId = createErrorId();- const message = toErrorMessage(error);- log.error("turn boundary handler failed — parking session", {- error,- errorId,- sessionId: session.sessionId,- turnId: failureState.turnId,- });- emissionState = await emitRecoverableFailedTurn(emit, failureState, {- code: "EVENT_HANDLER_FAILED",- continuationToken: session.continuationToken,- details: { errorId },- message,- });- return {- next: null,- session: setHarnessEmissionState({ ...session, outputSchema: undefined }, emissionState),- settledTurn: { isError: true, output: message },- };+ throw error;};const preparePreambleTrace = async (): Promise<RuntimeTraceContext | undefined> => {return await stepInstrumentation?.preparePreamble({diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.tsindex 48e2bc3b5..f9e4ca1c5 100644--- a/packages/eve/src/public/definitions/hook.ts+++ b/packages/eve/src/public/definitions/hook.ts@@ -77,6 +77,18 @@ export interface HookContext extends SessionContext {readonly kind?: string;readonly continuationToken?: string;};+ /**+ * Cancels the running turn. The event's remaining subscribers still run,+ * then the turn settles like `session.cancel()`: `turn.cancelled`, then+ * `session.waiting`. Returns `void` because the turn stops after the hook+ * returns; call it before the handler's promise settles.+ *+ * eve logs a warning and ignores the call when the event cannot stop a+ * running turn (`step.failed`, turn and session terminal events,+ * `context.cleared`, `subagent.*`, and clear or compact requests) or when+ * it arrives after the event's hooks returned.+ */+ cancel(): void;}/**diff --git a/packages/eve/src/shared/boundary-hook-error.ts b/packages/eve/src/shared/boundary-hook-error.tsdeleted file mode 100644index 2b328f8a6..000000000--- a/packages/eve/src/shared/boundary-hook-error.ts+++ /dev/null@@ -1,9 +0,0 @@-import { toErrorMessage } from "#shared/errors.js";--/** Distinguishes authored admission failures from failed runtime lifecycle work. */-export class BoundaryHookError extends Error {- constructor(cause: unknown) {- super(toErrorMessage(cause), { cause });- this.name = "BoundaryHookError";- }-}diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex 3352ca88e..6952cf3b4 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -205,14 +205,17 @@ describe("proxied stream hooks", () => {]);});- it("propagates hook failures after publication and releases the writer", async () => {+ it("isolates 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();+ f.typed.mockRejectedValueOnce(new Error("audit unavailable"));+ await emitProxiedSubagentEvent(f);+ expect(f.events.map((event) => event.type)).toEqual([+ "input.requested",+ "turn.completed",+ "session.waiting",+ ]);+ expect(f.typed).toHaveBeenCalledTimes(3);+ expect(f.wildcard).toHaveBeenCalledTimes(3);expect(f.sessionWritable.locked).toBe(false);});});diff --git a/research/hook-turn-cancellation.md b/research/hook-turn-cancellation.mdnew file mode 100644index 000000000..ece03626d--- /dev/null+++ b/research/hook-turn-cancellation.md@@ -0,0 +1,85 @@+---+issue: "None (follows hook failure isolation from PR #3684, which removed the turn veto added in #3091)"+status: in-progress+last_updated: "2026-09-23"+---++# Hook turn cancellation++## Summary++#3091 let a `turn.started` or `step.started` hook reject a turn by throwing: the turn failed with `EVENT_HANDLER_FAILED` and the session parked. That coupled two unrelated intents. An audit or metrics hook that crashed could stop the agent, and a hook that meant to stop the turn had to express it as a failure.++#3684 makes stream-event hooks isolated observers: eve logs a thrown handler and keeps executing, so throwing no longer vetoes anything. This plan gives hooks an explicit replacement, `ctx.cancel()`, which stops the running turn through the same durable path as `session.cancel()`.++## Authoring API++`HookContext` gains one method:++```ts+interface HookContext extends SessionContext {+ readonly agent: { readonly name: string; readonly nodeId?: string };+ readonly channel: { readonly kind?: string; readonly continuationToken?: string };+ cancel(): void;+}+```++```ts title="agent/hooks/require-credentials.ts"+import { defineHook } from "eve/hooks";+import { loadWorkspaceCredentials } from "../lib/credentials";++export default defineHook({+ events: {+ async "turn.started"(_event, ctx) {+ try {+ await loadWorkspaceCredentials(ctx.session.auth.current);+ } catch (error) {+ console.warn("cancelling turn: workspace credentials unavailable", { error });+ ctx.cancel();+ }+ },+ },+});+```++### Why `void`, not `Promise<void>`++`session.cancel()` returns a promise because it crosses a durable inbox and reports `accepted` or `no_active_turn`. `ctx.cancel()` runs inside the turn it stops, and that turn cannot settle while eve is still awaiting the hook. A promise would either resolve before the cancellation takes effect or never resolve. `void` states the real contract: the request is recorded now and applied when the event's hooks return. `await ctx.cancel()` still type-checks and behaves the same.++`cancel()` also does not throw. Throwing would route through the failure isolation catch and hide the intent in an error log. The handler keeps running and returns when appropriate.++## Semantics++```mermaid+flowchart LR+ Hook["ctx.cancel() in a hook"] --> Abort["Turn signal aborts"]+ Abort --> Rest["Remaining hooks for the event run"]+ Rest --> Settle["turn.cancelled then session.waiting"]+```++- **Aborts at once, stops after the event's hooks.** The call aborts the turn signal immediately. The remaining hook subscribers for the event still run, so an audit hook sees the event that caused the cancellation. Turn-level consumers that honor the signal, such as dynamic model resolution, may stop early. If one of them throws, the turn still settles as cancelled because the signal was already aborted.+- **Same outcome as `session.cancel()`.** In-flight model and tool work is aborted, delegated child turns are cancelled, and the turn settles as `turn.cancelled` followed by `session.waiting`. No failure event is emitted and no step is retried. A conversation accepts the next message as a new turn. A delegated task reports the cancellation to its caller.+- **Task sessions with no caller end.** A scheduled or invoked task-mode session has no one left to send it work. Parking it after a cancel would leave the run open until its timeout, so it ends with `session.completed`. The workflow result, the session callback (as `failed`), and any delegated parent carry the error "The turn was cancelled." This also applies to `session.cancel()`.+- **Deterministic before the model.** A cancel from `turn.started` or `step.started` stops the turn before that model call is sent.+- **Fails closed on events.** Eligibility is a total map over hook event types, so a new event does not compile until it is classified. `step.failed`, turn and session terminal events, `context.cleared`, and `subagent.*` are not cancellable, and neither are clear or compact requests. Cancelling after a terminal event would give the turn a second terminal. eve logs a warning and ignores these calls.+- **Only during dispatch.** A call from work the handler did not await, made after the event's hooks returned, is ignored with a warning. Otherwise it could cancel at an arbitrary later point, or never.+- **Hook exceptions stay isolated.** Throwing from a hook is logged with the hook slug, subscription, event type, event ID, and session ID, and execution continues. Only `ctx.cancel()` stops a turn.++Internally, each turn step combines the workflow-owned turn signal with a step-local signal that `ctx.cancel()` aborts. The harness already checks that signal at every model, tool, and error-recovery boundary, so hook cancellation adds no new settlement path.++## Scope++- `cancel()` is on `HookContext` only. Tools, dynamic resolvers, and channel adapters do not gain it. Tool errors pass through tool-result handling, so a tool-level cancel would need its own contract.+- `cancel()` targets the current turn only. It does not cancel background tasks (`session.cancel({ tasks: true })`) and does not end the session.+- There is no reason or payload. `turn.cancelled` carries the same shape as other cancellations. Hooks that need an audit trail record it themselves before calling `cancel()`.++## Compatibility++- Hooks that relied on throwing from `turn.started` or `step.started` to reject a turn now observe that the turn continues. They migrate to `ctx.cancel()`. The #3684 changeset is `minor` for this break.+- Adding `cancel()` bumps the hook extension contract to epoch 28 and retains epoch 27. eve always constructs `HookContext`, and handlers compiled against epoch 27 never call `cancel()`.++## Validation++- Unit: eligibility is table-tested across settlement, subagent, and unknown event types. A `step.started` cancel returns a cancelled step result with the turn signal aborted after both typed and wildcard subscribers run. A cancel followed by a throwing dynamic model resolver still returns a cancelled result. A `turn.completed` cancel keeps the settled turn and logs the warning.+- Integration: the dispatcher forwards `cancel()` without skipping later subscribers, and warns on ineligible events and on calls after the hooks returned. Full workflow sessions cancelled from `turn.started` and from `step.started` emit `turn.cancelled` then `session.waiting`, no model output, no failure events, and no step retries, and the next message completes. A task-mode session with no caller cancelled from `turn.started` ends with `session.completed` and returns "The turn was cancelled." instead of staying parked.+- E2E (`agent-basic-runtime`): the fixture authenticates workspace members by bearer token. `require-credentials` cancels Bob's turn because his credential grant was revoked: no `step.started` and no failure events. Alice's credentials load, and her turn completes. In `audit-export-failure`, Carol's audit sink is unreachable, so the audit hook queues each `turn.started` and `step.started` event in a durable outbox and rethrows. Both of her turns complete, and a `read_audit_outbox` tool call in the second turn must return the first turn's two event IDs. That proves the hook ran, threw, and kept its side effect. Each case starts a fresh session.