The Open Framework for Building Agents
fix(eve): publish agent.started from the step that owns the session (#4001)
Andrew Barbabbbf9fcc98be
diff --git a/.changeset/agent-started-during-model-step.md b/.changeset/agent-started-during-model-step.mddeleted file mode 100644index 4cf1939d6..000000000--- a/.changeset/agent-started-during-model-step.md+++ /dev/null@@ -1,5 +0,0 @@-----"eve": patch------The parent stream now publishes `agent.started` for a session a task opens as soon as the session opens, even while the parent's model is still generating, so clients can follow the child while it works instead of after the parent's next step.diff --git a/.changeset/agent-started-hooks-keep-state.md b/.changeset/agent-started-hooks-keep-state.mdnew file mode 100644index 000000000..08958fdc9--- /dev/null+++ b/.changeset/agent-started-hooks-keep-state.md@@ -0,0 +1,5 @@+---+"eve": patch+---++`agent.started` hooks keep the session state and sandbox changes they make. A child session that opens while the parent's model is generating appears on the parent stream when that model step ends.diff --git a/docs/guides/hooks.md b/docs/guides/hooks.mdindex e7dfba381..09d2fe9e9 100644--- a/docs/guides/hooks.md+++ b/docs/guides/hooks.md@@ -91,12 +91,9 @@ For `task.started`, `task.settled`, and `agent.started`, `ctx.session.id`identifies the session that started the task or opened the subagent session.Typed handlers and `*` handlers receive this context even when the eventarrives between turns. These hooks can use `ctx.getSandbox()` against that-session. For `task.started` and `task.settled`, sandbox changes they make are-kept for its next turn. eve publishes `agent.started` as soon as the child-session opens, even while the parent's model step is still running, and-changes an `agent.started` hook makes to session state at that point are not-kept. Use `agent.started` hooks to observe the event, not to change session-state.+session. Session state and sandbox changes they make are kept for the+session's next turn. `agent.started` appears when the child session opens, or+when the parent's current model step ends if one is running.### Narrowing tool results@@ -178,11 +175,12 @@ See [the event envelope](../concepts/sessions-runs-and-streaming#the-event-envel## Execution order-When a stream event fires, three things happen in order:+When a session publishes a stream event while it runs, the step that owns the session does four things in order:-1. Emit. The channel adapter handler runs, the event is stamped with its `meta` envelope, then it is written to the durable stream.-2. Hooks. Stream-event hooks fire (typed handlers first, then the `*` wildcard). Return values are ignored.-3. Model preparation, for model lifecycle events. Dynamic resolvers subscribed to those events update the model context. Subagent notifications do not run model preparation.+1. Channel delivery. The channel adapter handler runs.+2. Write. The event is stamped with its `meta` envelope, then written to the durable stream.+3. Hooks. Stream-event hooks fire (typed handlers first, then the `*` wildcard). Return values are ignored.+4. Model preparation, for model lifecycle events. Dynamic resolvers subscribed to those events update the model context. Subagent notifications do not run model preparation.Hooks always run after the event is durably recorded, so if a hook throws, the stream stays consistent. The persisted event and every hook observe the same `meta.id`.diff --git a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.tsindex 36a996a05..09d117394 100644--- a/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts+++ b/e2e/fixtures/agent-subagents/evals/dynamic-workflow.eval.ts@@ -1,3 +1,4 @@+import type { MessageStreamEvent } from "eve/client";import { defineEval } from "eve/evals";const SUBAGENT_TOKEN = "SUBAGENT_TOKEN=echo-marker-9F2X";@@ -41,7 +42,17 @@ export default defineEval({firstChild,secondChild,]);- const latestCallAt = [firstStarted.meta.at, secondStarted.meta.at].sort().at(-1)!;+ // Each child's own turn start, not the parent's `agent.started`: the parent+ // publishes that at its next step boundary, which can be after a quick child+ // finished.+ const childStartedAt = (events: readonly MessageStreamEvent[]) =>+ (events.find((event) => event.type === "turn.started") ?? events[0])!.meta.at;+ const latestCallAt = [+ childStartedAt(firstChildTurn.events),+ childStartedAt(secondChildTurn.events),+ ]+ .sort()+ .at(-1)!;t.succeeded();t.calledTool("workflow", { input: isFanOutProgram, count: 1 });diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.tsindex 28c6aef49..25efb3f23 100644--- a/e2e/fixtures/agent-workflow-tools/agent/agent.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts@@ -3,13 +3,25 @@ import { latestTaskResult } from "@eve-e2e/config/mock-script";import { defineAgent } from "eve";import { mockModel, type MockModelRequest, type MockModelResponse } from "eve/evals";+import { RESEARCH_INTERIM_MESSAGE } from "../task-scenario-text.ts";import { respondToTaskScenario } from "./lib/task-scenarios.ts";+/**+ * The child-opening call each SUBAGENT-HOOKS mode makes: an agent call the+ * model waits on, a task whose run opens a helper while the model keeps+ * answering, or a waiting workflow tool.+ */+const HOOK_SCENARIO_CALLS = {+ direct: { name: "workflow-marker", input: { message: "Alice's hook audit" } },+ background: { name: "research_brief", input: { topic: "Alice's hook audit" } },+ waiting: { name: "blocking_agent", input: { service: "hook-audit" } },+} as const;+/*** Deterministic script: each directive names the workflow tool to call with* service "api"; once the turn holds a tool result the reply echoes it.*/-function respond(request: MockModelRequest): MockModelResponse | string {+async function respond(request: MockModelRequest): Promise<MockModelResponse | string> {const hookScenario = request.userMessages.find((entry) => entry.includes("SUBAGENT-HOOKS:"));if (hookScenario !== undefined) {const auditing = request.lastUserMessage?.includes("SUBAGENT-HOOKS:AUDIT");@@ -19,7 +31,8 @@ function respond(request: MockModelRequest): MockModelResponse | string {toolCalls: [{ id: skillCallId, name: "load_skill", input: { skill: "delegation-policy" } }],};}- const mode = /SUBAGENT-HOOKS:(direct|waiting)/u.exec(hookScenario)?.[1];+ const mode = (/SUBAGENT-HOOKS:(direct|background|waiting)/u.exec(hookScenario)?.[1] ??+ "waiting") as keyof typeof HOOK_SCENARIO_CALLS;if (auditing) {const auditTool = request.lastUserMessage?.includes("DYNAMIC-SKILL-CONTEXT")? "read_dynamic_skill_context"@@ -29,24 +42,24 @@ function respond(request: MockModelRequest): MockModelResponse | string {? { toolCalls: [{ name: auditTool, input: {} }] }: JSON.stringify(audit.output);}- const tool = mode === "direct" ? "workflow-marker" : "blocking_agent";- if (!request.toolResults.some((entry) => entry.name === tool)) {- return {- toolCalls: [- {- name: tool,- input:- mode === "direct" ? { message: "Alice's hook audit" } : { service: "hook-audit" },- },- ],- };- }- // The agent call returned a receipt; its result arrives in a <task_result> message.+ const { name: tool, input } = HOOK_SCENARIO_CALLS[mode];+ const call = request.toolResults.find((entry) => entry.name === tool);+ if (call === undefined) return { toolCalls: [{ name: tool, input }] };+ // An agent call or task returned a receipt; its result arrives in a <task_result> message.if (mode === "direct") {return latestTaskResult(request, tool) ?? { toolCalls: [{ name: "task_wait", input: {} }] };}- const result = request.toolResults.find((entry) => entry.name === tool);- return typeof result?.output === "string" ? result.output : JSON.stringify(result?.output);+ // Ends the step with text while the task works, which holds the turn. The+ // step takes a few seconds, so the task's helper most likely opens while it+ // runs; that is likely, not guaranteed, and the hook assertions hold+ // whether the helper opens mid-step or while the turn is held.+ if (mode === "background") {+ const result = latestTaskResult(request, tool);+ if (result !== undefined) return result;+ await new Promise((resolve) => setTimeout(resolve, 3_000));+ return RESEARCH_INTERIM_MESSAGE;+ }+ return typeof call.output === "string" ? call.output : JSON.stringify(call.output);}const message =diff --git a/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.ts b/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.tsindex b41e3bc68..11e1da37c 100644--- a/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.ts+++ b/e2e/fixtures/agent-workflow-tools/agent/hooks/subagent-audit.ts@@ -5,6 +5,7 @@ export default defineHook({events: {"task.started": (event, ctx) => recordSubagentHook("typed", event, ctx),"task.settled": (event, ctx) => recordSubagentHook("typed", event, ctx),+ "agent.started": (event, ctx) => recordSubagentHook("typed", event, ctx),"*": (event, ctx) => recordSubagentHook("wildcard", event, ctx),},});diff --git a/e2e/fixtures/agent-workflow-tools/agent/tools/research_brief.ts b/e2e/fixtures/agent-workflow-tools/agent/tools/research_brief.tsnew file mode 100644index 000000000..976209f6e--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/agent/tools/research_brief.ts@@ -0,0 +1,24 @@+import { defineWorkflowTool } from "eve/tools";+import { sleep } from "workflow";+import { z } from "zod";++/**+ * A task whose run opens a helper agent right away, then waits a few seconds+ * before it settles. The parent's next model step is slow, so the helper+ * usually opens while that step runs. The sleep keeps the task working when+ * that step starts, so the step writes its interim reply instead of the+ * task's result and the turn is held.+ */+export default defineWorkflowTool({+ description: "Research a topic in the background with a helper agent and report its findings.",+ inputSchema: z.strictObject({ topic: z.string() }),+ async task({ topic }, ctx) {+ "use workflow";++ const helper = await ctx.agent("workflow-marker").send(topic);+ const result = await helper.result();+ if (result.status === "failed") throw new Error('Agent "workflow-marker" failed.');+ await sleep("3s");+ return result.message ?? null;+ },+});diff --git a/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.tsindex 5e37a7557..04fe1859f 100644--- a/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts+++ b/e2e/fixtures/agent-workflow-tools/evals/agent-fanout.wait.eval.ts@@ -1,11 +1,15 @@import { defineEval } from "eve/evals";+import { readHookAudit, recordsEveryAgentStart } from "./subagent-hook-audit.shared";+export default defineEval({description:- "An authored waiting workflow tool blocks on two parallel ctx.agent sessions and returns both inline results.",+ "An authored waiting workflow tool blocks on two parallel ctx.agent sessions, returns both inline results, and agent.started hooks record both sessions.",timeoutMs: 60_000,async test(t) {- const turn = await t.send("WORKFLOW-AGENT-FANOUT-START");+ const turn = await t.send(+ "WORKFLOW-AGENT-FANOUT-START Bob asks two planners to draft the api rollout and waits for both drafts.",+ );turn.expectOk();turn.calledTool("fanout_agents", { count: 1, status: "completed" });turn.event("agent.started", { data: { name: "workflow-marker" }, count: 2 });@@ -33,6 +37,17 @@ export default defineEval({);return called.length === 2 && toolResult >= 0 && Math.max(...called) < toolResult;});++ const audit = await turn.session.send(+ "Bob reviews the recorded hook observations for both planners. SUBAGENT-HOOKS:AUDIT",+ );+ audit.expectOk();+ audit.calledTool("read_subagent_hooks", { count: 1, status: "completed" });+ const records = readHookAudit(audit);+ turn.eventsSatisfy(+ "both hook subscriptions record each opened session in parent state and sandbox",+ (events) => recordsEveryAgentStart(records, events, turn.sessionId),+ );t.noFailedActions();},});diff --git a/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-audit.shared.ts b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-audit.shared.tsnew file mode 100644index 000000000..3b046f35f--- /dev/null+++ b/e2e/fixtures/agent-workflow-tools/evals/subagent-hook-audit.shared.ts@@ -0,0 +1,48 @@+import type { MessageStreamEvent } from "eve/client";+import type { EveEvalTurn } from "eve/evals";++import type { SubagentHookObservation } from "../subagent-hook-audit";++/** One observation as `read_subagent_hooks` returns it, with the sandbox file its hook wrote. */+export type AuditedHookObservation = SubagentHookObservation & {+ readonly sandboxCallId: string | null;+};++/** The observations the turn's `read_subagent_hooks` call read back from the parent session. */+export function readHookAudit(turn: EveEvalTurn): readonly AuditedHookObservation[] {+ const output = turn.toolCalls.find((call) => call.name === "read_subagent_hooks")?.output;+ if (!Array.isArray(output)) throw new Error("The recorded hook observations are missing.");+ return output as AuditedHookObservation[];+}++/**+ * Whether the typed and `*` hooks each recorded every `agent.started` in+ * `events` exactly once, in the parent session's state and sandbox, under the+ * event's published ID.+ */+export function recordsEveryAgentStart(+ records: readonly AuditedHookObservation[],+ events: readonly MessageStreamEvent[],+ parentSessionId: string,+): boolean {+ const starts = events.flatMap((event) => (event.type === "agent.started" ? [event] : []));+ const recorded = records.filter((record) => record.type === "agent.started");+ return (+ starts.length > 0 &&+ recorded.length === starts.length * 2 &&+ starts.every((start) =>+ (["typed", "wildcard"] as const).every(+ (subscriber) =>+ recorded.filter(+ (record) =>+ record.subscriber === subscriber &&+ record.eventId === start.meta.id &&+ record.childSessionId === start.data.sessionId &&+ record.callId === start.data.callId &&+ record.sandboxCallId === start.data.callId &&+ record.sessionId === parentSessionId,+ ).length === 1,+ ),+ )+ );+}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 661c2061a..767da1af6 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@@ -1,86 +1,111 @@import { defineEval } from "eve/evals";-import type { SubagentHookObservation } from "../subagent-hook-audit";-// An agent tool call is a task: task.started and task.settled carry its callId.-export default defineEval({- description:- "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:direct",- );- initial.expectOk();- initial.calledTool("load_skill", { count: 1, status: "completed" });- initial.messageIncludes("Alice's hook audit");+import { RESEARCH_INTERIM_MESSAGE } from "../task-scenario-text";+import { readHookAudit, recordsEveryAgentStart } from "./subagent-hook-audit.shared";- const audit = await initial.session.send(+const SCENARIOS = {+ // An agent call is a task: task.started and task.settled carry its callId,+ // and agent.started announces the session the call opened.+ direct: {+ description:+ "Delegation and later wildcard hooks continue after a typed hook writes parent state and throws.",+ task: "workflow-marker",+ request: "Alice asks Bob to review a short report and return his result. SUBAGENT-HOOKS:direct",+ audit:"Alice reviews the recorded hook observations for Bob's completed report. SUBAGENT-HOOKS:AUDIT",- );- audit.expectOk();- audit.calledTool("load_skill", { count: 1, status: "completed" });- t.eventsSatisfy("the parent's dynamic skill remains loadable after delegation", () =>- [initial, audit].every((turn) =>- String(turn.toolCalls.find((call) => call.name === "load_skill")?.output).includes(- "DELEGATION-POLICY:",+ },+ // A task whose run opens a helper agent while the parent keeps answering.+ // The parent's slow model step makes a mid-step open likely, not certain;+ // either way the helper's hooks' state and sandbox writes must reach+ // Alice's next turn.+ background: {+ description:+ "agent.started hooks keep the parent state and sandbox writes they make for a helper a background task opens.",+ task: "research_brief",+ request:+ "Alice starts background research on a short report while she keeps planning with the assistant. SUBAGENT-HOOKS:background",+ audit:+ "Alice reviews the recorded hook observations for the finished research. SUBAGENT-HOOKS:AUDIT",+ },+} as const;++export default (["direct", "background"] as const).map((mode) =>+ defineEval({+ description: SCENARIOS[mode].description,+ async test(t) {+ const scenario = SCENARIOS[mode];+ const initial = await t.send(scenario.request);+ initial.expectOk();+ initial.calledTool("load_skill", { count: 1, status: "completed" });+ initial.messageIncludes("Alice's hook audit");+ if (mode === "background") {+ initial.event("message.completed", {+ count: 1,+ data: { message: RESEARCH_INTERIM_MESSAGE },+ });+ initial.notCalledTool("task_wait");+ }++ const audit = await initial.session.send(scenario.audit);+ audit.expectOk();+ audit.calledTool("load_skill", { count: 1, status: "completed" });+ t.eventsSatisfy("the parent's dynamic skill remains loadable after delegation", () =>+ [initial, audit].every((turn) =>+ String(turn.toolCalls.find((call) => call.name === "load_skill")?.output).includes(+ "DELEGATION-POLICY:",+ ),),- ),- );- audit.calledTool("read_subagent_hooks", { count: 1, status: "completed" });- const observations = audit.toolCalls.find(- (call) => call.name === "read_subagent_hooks",- )?.output;- t.eventsSatisfy(- "both hook subscriptions receive the parent's exact child result once",- (events) => {- if (!Array.isArray(observations) || observations.length !== 4) return false;- const completion = events.find((event) => event.type === "task.settled");- if (completion?.type !== "task.settled") return false;- const output = completion.data.output;- if (typeof output !== "string" || !output.startsWith("WORKFLOW-CHILD:")) return false;- if (!initial.message?.includes(output)) return false;- const records = observations as SubagentHookObservation[];- return (- records.every(- (record) =>- record.sessionId === initial.sessionId && record.callId === completion.data.callId,- ) &&- (["typed", "wildcard"] as const).every(- (subscriber) =>- records.filter(- (record) => record.subscriber === subscriber && record.type === "task.started",- ).length === 1 &&- records.filter(- (record) =>- record.subscriber === subscriber &&- record.type === "task.settled" &&- record.output === output,- ).length === 1,- )- );- },- );- t.eventsSatisfy(- "hooks receive the exact published event IDs",- (events) =>- Array.isArray(observations) &&- observations.every((record: SubagentHookObservation) =>+ );+ audit.calledTool("read_subagent_hooks", { count: 1, status: "completed" });+ const records = readHookAudit(audit);+ t.eventsSatisfy(+ "both hook subscriptions receive the parent's exact child result once",+ (events) => {+ if (records.length !== 6) return false;+ const completion = events.find((event) => event.type === "task.settled");+ if (completion?.type !== "task.settled") return false;+ const output = completion.data.output;+ if (typeof output !== "string" || !output.startsWith("WORKFLOW-CHILD:")) return false;+ if (!initial.message?.includes(output)) return false;+ return (+ records.every(+ (record) =>+ record.sessionId === initial.sessionId && record.callId === completion.data.callId,+ ) &&+ (["typed", "wildcard"] as const).every(+ (subscriber) =>+ records.filter(+ (record) => record.subscriber === subscriber && record.type === "task.started",+ ).length === 1 &&+ records.filter(+ (record) =>+ record.subscriber === subscriber &&+ record.type === "task.settled" &&+ record.output === output,+ ).length === 1,+ )+ );+ },+ );+ t.eventsSatisfy(+ "both hook subscriptions record the opened session in parent state and sandbox",+ (events) => recordsEveryAgentStart(records, events, initial.sessionId),+ );+ t.eventsSatisfy("hooks receive the exact published event IDs", (events) =>+ records.every((record) =>events.some((event) => event.meta.id === record.eventId && event.type === record.type),),- );- t.eventsSatisfy(- "hooks persist parent sandbox files for the next turn",- () =>- Array.isArray(observations) &&- observations.every(- (record: SubagentHookObservation & { sandboxCallId: string | null }) =>- record.sandboxCallId === record.callId,- ),- );- t.event("task.started", { data: { name: "workflow-marker" }, count: 1 });- t.event("task.settled", { data: { status: "completed" }, count: 1 });- t.notEvent("session.failed");- t.notEvent("turn.failed");- t.noFailedActions();- t.succeeded();- },-});+ );+ t.eventsSatisfy("hooks persist parent sandbox files for the next turn", () =>+ records.every((record) => record.sandboxCallId === record.callId),+ );+ t.event("task.started", { data: { name: scenario.task }, count: 1 });+ t.event("agent.started", { data: { name: "workflow-marker" }, count: 1 });+ t.event("task.settled", { data: { status: "completed" }, 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 8ed8b60a3..cd3e14349 100644--- a/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts+++ b/e2e/fixtures/agent-workflow-tools/subagent-hook-audit.ts@@ -3,11 +3,13 @@ import type { HookContext, HookEvent } from "eve/hooks";export interface SubagentHookObservation {readonly subscriber: "typed" | "wildcard";- readonly type: "task.started" | "task.settled";+ readonly type: "task.started" | "task.settled" | "agent.started";readonly callId: string;readonly eventId: string;readonly sessionId: string;readonly output?: string;+ /** The session an `agent.started` event announced. */+ readonly childSessionId?: string;}export const subagentHookAudit = defineState<SubagentHookObservation[]>(@@ -20,7 +22,13 @@ export async function recordSubagentHook(event: HookEvent,ctx: HookContext,): Promise<void> {- if (event.type !== "task.started" && event.type !== "task.settled") return;+ if (+ event.type !== "task.started" &&+ event.type !== "task.settled" &&+ event.type !== "agent.started"+ ) {+ return;+ }const sandbox = await ctx.getSandbox();await sandbox.writeTextFile({path: `subagent-hook-${event.meta.id}-${subscriber}.txt`,@@ -35,6 +43,7 @@ export async function recordSubagentHook(eventId: event.meta.id,sessionId: ctx.session.id,output: event.type === "task.settled" ? readOutput(event.data.output) : undefined,+ childSessionId: event.type === "agent.started" ? event.data.sessionId : undefined,},]);if (subscriber === "typed") {diff --git a/e2e/fixtures/agent-workflow-tools/task-scenario-text.ts b/e2e/fixtures/agent-workflow-tools/task-scenario-text.tsindex a6efdc5fc..695ce2afe 100644--- a/e2e/fixtures/agent-workflow-tools/task-scenario-text.ts+++ b/e2e/fixtures/agent-workflow-tools/task-scenario-text.ts@@ -13,5 +13,9 @@ export const SIGN_OFF_INTERIM_MESSAGE = "Asked for sign-off on the api plan; I'l/** The root agent's text before its turn waits on the `workflow-stager` agent. */export const DELEGATE_INTERIM_MESSAGE = "Asked workflow-stager to stage api; I'll report back.";+/** The root agent's text while `research_brief` works in the background. */+export const RESEARCH_INTERIM_MESSAGE =+ "Researching Alice's report in the background; I'll share the findings when they arrive.";+/** The `workflow-stager` child's text before its own turn waits on its staging task. */export const STAGER_INTERIM_MESSAGE = "Staging api for the parent now.";diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.tsindex e73613909..931cb881e 100644--- a/packages/eve/src/execution/publish-session-events.ts+++ b/packages/eve/src/execution/publish-session-events.ts@@ -69,7 +69,7 @@ export async function publishSessionEvents(target: SessionStepState,events: readonly UnstampedMessageStreamEvent[],): Promise<PublishedSessionEvents> {- return await publishFromStep(target, "own", events);+ return await publishEventsFromStep(target, "own", events);}/** Publishes events of an exchange this session relays; see {@link SessionEventOrigin}. */@@ -77,10 +77,10 @@ export async function relaySessionEvents(target: SessionStepState,events: readonly UnstampedMessageStreamEvent[],): Promise<PublishedSessionEvents> {- return await publishFromStep(target, "relayed", events);+ return await publishEventsFromStep(target, "relayed", events);}-async function publishFromStep(+async function publishEventsFromStep(target: SessionStepState,origin: SessionEventOrigin,events: readonly UnstampedMessageStreamEvent[],@@ -88,55 +88,92 @@ async function publishFromStep(if (events.length === 0) {return { serializedContext: target.serializedContext, sessionState: target.sessionState };}- const ctx = await deserializeContext(target.serializedContext);- const { session } = await withSessionEventEmitter(- {- ctx,- durableSession: readDurableSession(target.sessionState),- origin,- sessionWritable: target.sessionWritable,- },- async (emit, scopedSession) => {+ const { published } = await publishFromSessionStep(await restoreSessionStep(target), {+ origin,+ async publish(emit) {for (const event of events) await emit(event);- return { result: undefined, session: scopedSession };},- );+ });+ return published;+}++/** A session step's context and session, restored so the step can publish. */+export interface RestoredSessionStep {+ readonly ctx: ContextContainer;+ readonly durableSession: DurableSession;+ readonly sessionWritable: WritableStream<Uint8Array>;+}++export async function restoreSessionStep(step: SessionStepState): Promise<RestoredSessionStep> {+ return {+ ctx: await deserializeContext(step.serializedContext),+ durableSession: readDurableSession(step.sessionState),+ sessionWritable: step.sessionWritable,+ };+}++/** What a session step publishes, and how it changes the session the publication leaves. */+export interface SessionStepPublication<T, R> {+ readonly origin: SessionEventOrigin;+ /** Where a relayed input batch came from; the channel adapter and its forwarding see it. */+ readonly inputSource?: string;+ /** Emits the step's events in the session's context scope. */+ publish(emit: HandleEventFn, session: HarnessSession): Promise<T>;+ /**+ * Changes the step makes to the session once the scope has committed it,+ * before its continuation token is reconciled.+ */+ updateSession?(session: HarnessSession, published: T): SessionUpdate<R>;+}++/** The session a step keeps, and anything it derived while changing it. */+export interface SessionUpdate<R> {+ readonly session: HarnessSession;+ readonly result?: R;+}++/**+ * Publishes from a step that owns the session. Returns the context and session+ * state to adopt, and the result of `updateSession`. `step.ctx` is updated in place.+ */+export async function publishFromSessionStep<T, R = undefined>(+ step: RestoredSessionStep,+ publication: SessionStepPublication<T, R>,+): Promise<{ readonly published: PublishedSessionEvents; readonly result: R | undefined }> {+ const { ctx } = step;+ const scoped = await publishInSessionScope(step, publication);+ const update: SessionUpdate<R> = publication.updateSession?.(scoped.session, scoped.result) ?? {+ session: scoped.session,+ };return {- serializedContext: serializeContext(ctx),- sessionState: createDurableSessionState({- session: reconcileSessionContinuationToken(ctx, session),- }),+ published: {+ serializedContext: serializeContext(ctx),+ sessionState: createDurableSessionState({+ session: reconcileSessionContinuationToken(ctx, update.session),+ }),+ },+ result: update.result,};}/**- * Runs `emitEvents` in the session's context scope with an emit that publishes- * each event with the given origin. `ctx` is updated in place; the returned- * session is the one `emitEvents` returns after the scope commits.+ * Runs `publication.publish` in the session's context scope with an emit that+ * publishes each event in order. Returns its result and the session the scope+ * commits.*/-export async function withSessionEventEmitter<T>(- input: {- readonly ctx: ContextContainer;- readonly durableSession: DurableSession;- readonly origin: SessionEventOrigin;- readonly sessionWritable: WritableStream<Uint8Array>;- readonly inputSource?: string;- },- emitEvents: (- emit: HandleEventFn,- session: HarnessSession,- ) => Promise<{ readonly result: T; readonly session: HarnessSession }>,+async function publishInSessionScope<T>(+ step: RestoredSessionStep,+ publication: SessionStepPublication<T, unknown>,): Promise<{ readonly result: T; readonly session: HarnessSession }> {- const { ctx } = input;- const bundle = ctx.require(BundleKey);- const effectiveAgent = resolveEffectiveAgentRuntime(bundle, ctx);+ const { ctx } = step;+ const effectiveAgent = resolveEffectiveAgentRuntime(ctx.require(BundleKey), ctx);const session = hydrateDurableSession({compactionOverrides: { thresholdPercent: effectiveAgent.thresholdPercent },- durable: input.durableSession,+ durable: step.durableSession,turnAgent: effectiveAgent.turnAgent,});const instrumentation =- input.origin === "own"+ publication.origin === "own"? bindSessionInstrumentation({agentName: effectiveAgent.turnAgent.id,ctx,@@ -145,110 +182,175 @@ export async function withSessionEventEmitter<T>(}): undefined;- const sink = openSessionEventStream({+ const publisher = openSessionEventPublisher({ctx,- origin: input.origin,+ inputSource: publication.inputSource,+ origin: publication.origin,sessionId: session.sessionId,- sessionWritable: input.sessionWritable,- inputSource: input.inputSource,+ sessionWritable: step.sessionWritable,});try {return await withContextScope(ctx, session, async (enrichedSession) => {- const publish: HandleEventFn = async (event) => {- const stamped = await sink.emit(event);- // Only turn-step events can cancel the running turn; see turn-event-handler.ts.- await dispatchStreamEventHooks({- cancelTurn: undefined,- ctx,- registry: bundle.hookRegistry,- event: stamped,- });- };const emit =instrumentation?.createHandleEvent({- handleEvent: publish,- turnId: activeTurnId(getHarnessEmissionState(input.durableSession.state)),- }) ?? publish;- return await emitEvents(emit, enrichedSession);+ handleEvent: publisher.publish,+ turnId: activeTurnId(getHarnessEmissionState(step.durableSession.state)),+ }) ?? publisher.publish;+ return { result: await publication.publish(emit, enrichedSession), session: enrichedSession };});} finally {await instrumentation?.flush();- sink.release();+ publisher.writer.release();}}-/** A session's stream held by one step. */-export interface SessionEventSink {- readonly adapterCtx: ChannelAdapterContext;- /**- * Routes one event through the channel adapter, then stamps and writes it.- * Stream-event hooks and instrumentation belong to the caller.- */- emit(event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent>;+/**+ * Holds a session's stream for one step, which keeps its writer lock until it+ * releases it. Events reach the stream through `SessionEventPublisher.emit`.+ */+export interface SessionEventWriter {/** Closes the session stream; only a terminal `done` step does this. */close(): Promise<void>;/** Releases the writer lock so the next step can acquire it. Safe after `close()`. */release(): void;}-/**- * The turn step's sink for its own events. A turn composes the rest of the- * publication itself: its tool loop binds instrumentation to each model call,- * and an event's hooks run after that event's memory lifecycle.- */-export function createSessionEventSink(input: {+interface StreamWriter extends SessionEventWriter {+ /** Stamps the event, then writes it; returns the event as written. */+ write(event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent>;+}++/** Dispatches a session's events to its channel, activity, and stream-event hooks. */+export interface SessionEventDispatcher {+ /** The context delivery hands the channel adapter; a turn step also hands it to `adapter.deliver`. */+ readonly adapterCtx: ChannelAdapterContext;+ /**+ * Runs the stream-event hooks for a written event. Only a turn step passes+ * `cancelTurn`; see `turn-event-handler.ts`.+ */+ runHooks(event: MessageStreamEvent, cancelTurn?: () => void): Promise<void>;+}++interface EventDispatcher extends SessionEventDispatcher {+ /**+ * Channel delivery: the activity state update, then `forwardSessionInput` or+ * the channel adapter's handler, then the channel context. Returns the event+ * as the handler left it.+ */+ deliver(event: UnstampedMessageStreamEvent): Promise<UnstampedMessageStreamEvent>;+ /** Projects a written event onto the session's activity. */+ projectActivity(event: MessageStreamEvent): void;+}++/** A session's stream held by one step, with the dispatch of the events that step publishes. */+export interface SessionEventPublisher {+ readonly dispatcher: SessionEventDispatcher;+ readonly writer: SessionEventWriter;+ /**+ * Delivers, writes, and projects one event the step produced, and returns it+ * as written for its hooks. Delivery comes first so the channel adapter's+ * handler shapes what is written.+ */+ emit(event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent>;+ /** `emit`, then the event's stream-event hooks. */+ publish(event: UnstampedMessageStreamEvent): Promise<void>;+}++export function openSessionEventPublisher(input: {readonly ctx: ContextContainer;+ readonly origin: SessionEventOrigin;readonly sessionId: string;readonly sessionWritable: WritableStream<Uint8Array>;-}): SessionEventSink {- return openSessionEventStream({ ...input, origin: "own" });+ readonly inputSource?: string;+}): SessionEventPublisher {+ const { ctx, origin } = input;+ const dispatcher = createSessionEventDispatcher(input);+ // Opened after the dispatcher, so a context that cannot build one leaves the+ // stream unlocked for the terminal event's fallback write.+ const writer = openSessionEventWriter({+ deliveryIds: () => (origin === "own" ? ctx.get(TurnDeliveryIdsKey) : undefined),+ sessionWritable: input.sessionWritable,+ });+ const emit = async (event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent> => {+ const written = await writer.write(await dispatcher.deliver(event));+ dispatcher.projectActivity(written);+ return written;+ };+ return {+ dispatcher,+ writer,+ emit,+ async publish(event) {+ await dispatcher.runHooks(await emit(event));+ },+ };}-function openSessionEventStream(input: {+function createSessionEventDispatcher(input: {readonly ctx: ContextContainer;readonly origin: SessionEventOrigin;readonly sessionId: string;- readonly sessionWritable: WritableStream<Uint8Array>;readonly inputSource?: string;-}): SessionEventSink {- const { ctx, origin } = input;+}): EventDispatcher {+ const { ctx, inputSource, origin } = input;const adapter = ctx.require(ChannelKey);const adapterCtx = buildAdapterContext(adapter, ctx);- const writer = input.sessionWritable.getWriter();- let released = false;- const release = (): void => {- if (released) return;- released = true;- writer.releaseLock();- };return {adapterCtx,- async emit(event) {+ async deliver(event) {if (origin === "own") activityCohort.updateActivityState(ctx, event);- const forwarded = await forwardSessionInput(ctx, event, input.inputSource);+ const forwarded = await forwardSessionInput(ctx, event, inputSource);const routed = forwarded? event: await callAdapterEventHandler(adapter,event,- input.inputSource === undefined- ? adapterCtx- : { ...adapterCtx, inputSource: input.inputSource },+ inputSource === undefined ? adapterCtx : { ...adapterCtx, inputSource },);setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });- const stamped = stampMessageStreamEvent(- routed,- origin === "own" ? ctx.get(TurnDeliveryIdsKey) : undefined,- );- await writer.write(encodeMessageStreamEvent(stamped));- if (origin === "own") {- void observeSessionActivity({ ctx, event: stamped, sessionId: input.sessionId });- }+ return routed;+ },+ projectActivity(event) {+ if (origin === "own") void observeSessionActivity({ ctx, event, sessionId: input.sessionId });+ },+ async runHooks(event, cancelTurn) {+ // Read here rather than when the dispatcher is built: terminal delivery+ // runs no hooks and must not require the bundle.+ await dispatchStreamEventHooks({+ cancelTurn,+ ctx,+ event,+ registry: ctx.require(BundleKey).hookRegistry,+ });+ },+ };+}++function openSessionEventWriter(input: {+ /**+ * The delivery ids stamped on each event. Read at each write because a turn+ * step records its delivery ids after it opens the stream.+ */+ readonly deliveryIds: () => readonly string[] | undefined;+ readonly sessionWritable: WritableStream<Uint8Array>;+}): StreamWriter {+ const streamWriter = input.sessionWritable.getWriter();++ let released = false;+ const release = (): void => {+ if (released) return;+ released = true;+ streamWriter.releaseLock();+ };+ return {+ async write(event) {+ const stamped = stampMessageStreamEvent(event, input.deliveryIds());+ await streamWriter.write(encodeMessageStreamEvent(stamped));return stamped;},close: async () => {- await writer.close();+ await streamWriter.close();release();},release,@@ -282,10 +384,15 @@ export async function publishTerminalSessionEvent(input: {const { type } = input.event;let ctx: ContextContainer;- let sink: SessionEventSink;+ let publisher: SessionEventPublisher;try {ctx = await deserializeContext(input.serializedContext);- sink = createSessionEventSink({ ctx, sessionId, sessionWritable: input.sessionWritable });+ publisher = openSessionEventPublisher({+ ctx,+ origin: "own",+ sessionId,+ sessionWritable: input.sessionWritable,+ });} catch (error) {log.error(`failed to restore context for terminal ${type} event`, { ...fields, error });await writeUnroutedSessionEvent(input.sessionWritable, input.event).catch((writeError) =>@@ -294,8 +401,9 @@ export async function publishTerminalSessionEvent(input: {return;}+ // Emitted without its hooks; see above.const publish: HandleEventFn = async (event) => {- await sink.emit(event);+ await publisher.emit(event);};let instrumentation: ReturnType<typeof bindSessionInstrumentation>;try {@@ -315,7 +423,7 @@ export async function publishTerminalSessionEvent(input: {} catch (error) {log.error(`failed to publish terminal ${type} event`, { ...fields, error });} finally {- sink.release();+ publisher.writer.release();try {await instrumentation?.flush();} catch (error) {@@ -331,10 +439,10 @@ async function writeUnroutedSessionEvent(sessionWritable: WritableStream<Uint8Array>,event: UnstampedMessageStreamEvent,): Promise<void> {- const writer = sessionWritable.getWriter();+ const writer = openSessionEventWriter({ deliveryIds: () => undefined, sessionWritable });try {- await writer.write(encodeMessageStreamEvent(stampMessageStreamEvent(event)));+ await writer.write(event);} finally {- writer.releaseLock();+ writer.release();}}diff --git a/packages/eve/src/execution/session-inbox/inbox.ts b/packages/eve/src/execution/session-inbox/inbox.tsindex 2ae2aef48..78233f5e7 100644--- a/packages/eve/src/execution/session-inbox/inbox.ts+++ b/packages/eve/src/execution/session-inbox/inbox.ts@@ -48,11 +48,6 @@ export interface SessionInboxReader {onInterrupt(handler: (payload: SessionInboxPayload) => void): () => void;/** Observes deliveries without consuming them; replays unread deliveries on subscription. */onDelivery(handler: (payload: SessionInboxPayload) => void): () => void;- /**- * Observes runs' `agent-started` messages without consuming them; replays- * unread ones on subscription. Handlers must be synchronous.- */- onAgentStarted(handler: (message: WorkflowToolRunAgentStarted) => void): () => void;restore(payloads: readonly SessionInboxPayload[]): void;}@@ -87,7 +82,6 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {const waiters = new Set<() => void>();const interruptHandlers = new Set<(payload: SessionInboxPayload) => void>();const deliveryHandlers = new Set<(payload: SessionInboxPayload) => void>();- const agentStartedHandlers = new Set<(message: WorkflowToolRunAgentStarted) => void>();let failure: { error: unknown } | undefined;const notify = (): void => {@@ -110,8 +104,6 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {for (const handler of deliveryHandlers) handler(result.value);if (isInterrupt(result.value))for (const handler of interruptHandlers) handler(result.value);- if (isAgentStarted(result.value))- for (const handler of agentStartedHandlers) handler(result.value);notify();}} catch (error) {@@ -197,11 +189,6 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {if (payload.kind === "send" || payload.kind === "deliver") handler(payload);return () => deliveryHandlers.delete(handler);},- onAgentStarted(handler) {- agentStartedHandlers.add(handler);- for (const payload of queue) if (isAgentStarted(payload)) handler(payload);- return () => agentStartedHandlers.delete(handler);- },restore(payloads) {if (sources.length === 0)throw new Error("Cannot restore session commands before reclaiming the session hooks.");@@ -229,16 +216,6 @@ export function createSessionInbox(sessionId: string): SessionInboxHandle {};}-/** A run's report that it opened a session, which the session publishes as `agent.started`. */-export type WorkflowToolRunAgentStarted = Extract<- WorkflowToolRunMessage,- { readonly kind: "agent-started" }->;--function isAgentStarted(value: SessionInboxPayload): value is WorkflowToolRunAgentStarted {- return value.kind === "agent-started";-}-export function isWorkflowMessage(value: SessionInboxPayload): value is WorkflowToolRunMessage {return (value.kind === "agent-started" ||diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.tsindex 754033592..80b52e5a3 100644--- a/packages/eve/src/execution/session-workflow-tool-run.ts+++ b/packages/eve/src/execution/session-workflow-tool-run.ts@@ -5,6 +5,7 @@ import {} from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";import type {WorkflowToolAskRequest,+ WorkflowToolRunAgentStartedMessage,WorkflowToolRunMessage,WorkflowToolRunOutcomeMessage,WorkflowToolRunRef,@@ -54,11 +55,30 @@ export async function handleWorkflowToolRunMessage();return undefined;case "agent-started":- await input.cursor.advance((state) => emitAgentStartedStep({ ...state, message }));+ await input.cursor.advance((state) =>+ emitAgentStartedStep({ ...state, messages: [message] }),+ );return undefined;}}+/** Boundary messages in admission order, with consecutive `agent-started` messages grouped. */+type BoundaryBatch =+ | { readonly kind: "agent-started"; readonly messages: WorkflowToolRunAgentStartedMessage[] }+ | { readonly kind: "message"; readonly message: WorkflowToolRunMessage };++/** Groups consecutive `agent-started` messages so one `emitAgentStartedStep` publishes each group. */+export function batchAgentStarts(messages: readonly WorkflowToolRunMessage[]): BoundaryBatch[] {+ const batches: BoundaryBatch[] = [];+ for (const message of messages) {+ const last = batches.at(-1);+ if (message.kind !== "agent-started") batches.push({ kind: "message", message });+ else if (last?.kind === "agent-started") last.messages.push(message);+ else batches.push({ kind: "agent-started", messages: [message] });+ }+ return batches;+}+/*** Settles a workflow tool run outcome against the turn's recorded runs and* returns the runtime action result the turn should accept, or `undefined`diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.tsindex 78431433e..5f4f90fef 100644--- a/packages/eve/src/execution/session/handoff.test.ts+++ b/packages/eve/src/execution/session/handoff.test.ts@@ -290,7 +290,6 @@ function createInbox(input: { released?: SessionInboxPayload[] } = {}): SessionIwhenPending: () => new Promise<void>(() => {}),next: vi.fn(),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),release: vi.fn(async () => input.released ?? []),restore: vi.fn(),diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.tsindex a3799c3d2..74b9ab578 100644--- a/packages/eve/src/execution/session/next-input.test.ts+++ b/packages/eve/src/execution/session/next-input.test.ts@@ -47,7 +47,6 @@ function createMockInbox(reads: readonly ScriptedRead[]): SessionInbox {onDelivery() {return () => {};},- onAgentStarted: () => () => {},onInterrupt() {return () => {};},diff --git a/packages/eve/src/execution/session/principal.ts b/packages/eve/src/execution/session/principal.tsindex 593db93eb..36dff26fe 100644--- a/packages/eve/src/execution/session/principal.ts+++ b/packages/eve/src/execution/session/principal.ts@@ -1,4 +1,6 @@import type { SessionAuthContext } from "#channel/types.js";+import { AuthKey } from "#context/keys.js";+import type { TurnStepPayload } from "#execution/session/turn-step-types.js";/** Every anonymous caller shares this one principal. */export const ANONYMOUS_PRINCIPAL = "anonymous";@@ -18,3 +20,16 @@ export function principalOf(auth: SessionAuthContext | null | undefined): stringauth.principalId,]);}++/**+ * The principal of the delivery that starts or continues a turn. A delivery+ * without auth keeps the session's current identity, as the turn step does.+ */+export function resolveTurnPrincipal(+ payload: TurnStepPayload | undefined,+ serializedContext: Record<string, unknown>,+): string {+ const auth = payload?.delivery?.auth;+ if (auth !== undefined) return principalOf(auth);+ return principalOf(serializedContext[AuthKey.name] as SessionAuthContext | null | undefined);+}diff --git a/packages/eve/src/execution/session/state-cursor.ts b/packages/eve/src/execution/session/state-cursor.tsindex 38503c13d..b8a59ab2e 100644--- a/packages/eve/src/execution/session/state-cursor.ts+++ b/packages/eve/src/execution/session/state-cursor.ts@@ -61,7 +61,7 @@ export class SessionStateCursor {}/** The session's stream and current state, spread into a step's input. */- stepState(): SessionStepState {+ private stepState(): SessionStepState {return { ...this.values, sessionWritable: this.sessionWritable };}}diff --git a/packages/eve/src/execution/session/step-agent-starts.ts b/packages/eve/src/execution/session/step-agent-starts.tsdeleted file mode 100644index 14d6f9bcc..000000000--- a/packages/eve/src/execution/session/step-agent-starts.ts+++ /dev/null@@ -1,64 +0,0 @@-import type {- SessionInboxPayload,- SessionInboxReader,- WorkflowToolRunAgentStarted,-} from "#execution/session-inbox/inbox.js";-import type { SessionStateCursor } from "#execution/session/state-cursor.js";-import { emitAgentStartedStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";--/**- * Publishes a run's `agent.started` as it arrives while a model step runs. The- * step lasts as long as the model thinks, and clients follow a child from its- * `agent.started`, so the event can't wait for the boundary.- *- * The step's delta applies to the state the step was given, so nothing- * published during it may change that state. `agent.started` reaches no- * channel handler and changes no activity, so its publication leaves the- * state as it found it and is not adopted. Every other run message waits for- * the boundary.- */-export class StepAgentStarts {- private readonly cursor: SessionStateCursor;- private readonly inbox: SessionInboxReader;- private readonly published = new Set<SessionInboxPayload>();-- constructor(inbox: SessionInboxReader, cursor: SessionStateCursor) {- this.cursor = cursor;- this.inbox = inbox;- }-- async publishWhile<T>(step: Promise<T>): Promise<T> {- const arrivals: WorkflowToolRunAgentStarted[] = [];- let wake: (() => void) | undefined;- const unsubscribe = this.inbox.onAgentStarted((message) => {- arrivals.push(message);- wake?.();- });- const stepSettled = step.then(- () => "settled" as const,- () => "settled" as const,- );- try {- while (true) {- const message = arrivals.shift();- if (message !== undefined) {- await emitAgentStartedStep({ ...this.cursor.stepState(), message });- this.published.add(message);- continue;- }- const arrived = new Promise<"arrived">((resolve) => {- wake = () => resolve("arrived");- });- if ((await Promise.race([stepSettled, arrived])) === "settled") break;- }- } finally {- unsubscribe();- }- return await step;- }-- /** Whether the payload was published already, so admission skips it. */- consume(payload: SessionInboxPayload): boolean {- return this.published.delete(payload);- }-}diff --git a/packages/eve/src/execution/session/turn-event-handler.ts b/packages/eve/src/execution/session/turn-event-handler.tsindex ada491949..d4b083eea 100644--- a/packages/eve/src/execution/session/turn-event-handler.ts+++ b/packages/eve/src/execution/session/turn-event-handler.ts@@ -4,11 +4,10 @@ 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/publish-session-events.js";+import type { SessionEventPublisher } from "#execution/publish-session-events.js";import { throwIfTurnAborted, TurnCancelledError } from "#harness/turn-cancellation.js";import type { HandleEventFn } from "#harness/types.js";import type { HookEventType } from "#public/definitions/hook.js";@@ -78,11 +77,14 @@ export function createTurnEventHandler(input: {readonly effectiveAgent: ReturnType<typeof resolveEffectiveAgentRuntime>;readonly effectiveNode: CompiledBundle["graph"]["root"];readonly instrumentation: ExecutionInstrumentation | undefined;- readonly sink: SessionEventSink;+ readonly publisher: SessionEventPublisher;}): HandleEventFn {const { abortSignal, bundle, ctx, effectiveAgent, effectiveNode } = input;+ const { publisher } = input;return async (event, messages) => {- const emitted = await input.sink.emit(event);+ // An event's memory lifecycle runs after its write and before its hooks, so+ // a turn emits the event and runs its hooks itself instead of calling `publish`.+ const emitted = await publisher.emit(event);const lifecycleMessages = await dispatchMemoryLifecycleEvent({abortSignal,appRoot: effectiveNode.agent?.metadata?.appRoot ?? "",@@ -97,12 +99,7 @@ export function createTurnEventHandler(input: {input.canCancelTurn && isHookCancellableEvent(emitted.type)? () => input.hookCancellation.abort(new TurnCancelledError()): undefined;- await dispatchStreamEventHooks({- cancelTurn,- ctx,- registry: bundle.hookRegistry,- event: emitted,- });+ await publisher.dispatcher.runHooks(emitted, cancelTurn);if (emitted.type !== "step.started") {await dispatchDynamicModelEvent({abortSignal,diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.tsindex c41628b53..4d822044a 100644--- a/packages/eve/src/execution/session/turn-step.ts+++ b/packages/eve/src/execution/session/turn-step.ts@@ -57,7 +57,7 @@ import type {} from "#execution/session/turn-step-types.js";import { resolveSessionStepResult } from "#execution/session/turn-step-result.js";import { withSessionStateDelta } from "#execution/session/state-delta.js";-import { createSessionEventSink } from "#execution/publish-session-events.js";+import { openSessionEventPublisher } from "#execution/publish-session-events.js";import { createTurnEventHandler } from "#execution/session/turn-event-handler.js";import { derivePendingState } from "#execution/session/pending-turn-state.js";import {@@ -230,12 +230,13 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>);await instrumentation?.flush();};- const sink = createSessionEventSink({+ const publisher = openSessionEventPublisher({ctx,+ origin: "own",sessionWritable: input.sessionWritable,sessionId: initialSession.sessionId,});- const { adapterCtx } = sink;+ const { adapterCtx } = publisher.dispatcher;// 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();@@ -256,7 +257,7 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>effectiveAgent,effectiveNode,instrumentation,- sink,+ publisher,});const previousAdapterState =delivery !== undefined && !isHarnessBetweenTurns(initialSession)@@ -561,9 +562,9 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>stepResult = { ...stepResult, session: aliased };const durableResult = resolveSessionStepResult(stepResult, nextSerializedContext);- if (durableResult.action === "done") await sink.close();+ if (durableResult.action === "done") await publisher.writer.close();return durableResult;} finally {- sink.release();+ publisher.writer.release();}}diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.tsindex e5ca7eaaf..d6c16f4dd 100644--- a/packages/eve/src/execution/session/turn.test.ts+++ b/packages/eve/src/execution/session/turn.test.ts@@ -29,6 +29,14 @@ import {import { getSessionTokenUsage } from "#harness/turn-tag-state.js";import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";+import {+ emitAgentStartedStep,+ emitWorkflowToolRunReportStep,+} from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";+import type {+ WorkflowToolRunMessage,+ WorkflowToolRunRef,+} from "#execution/tools/workflow/messages.js";import type { TokenUsage } from "#shared/token-usage.js";vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({@@ -52,6 +60,10 @@ vi.mock("#execution/tools/workflow/interrupt.js", () => ({vi.mock("#execution/session/turn-waiting-step.js", () => ({publishTurnWaitingStep: vi.fn(async () => ({ stateDelta: {} })),}));+vi.mock("#execution/tools/workflow/emit-workflow-tool-run-report-step.js", () => ({+ emitAgentStartedStep: vi.fn(),+ emitWorkflowToolRunReportStep: vi.fn(),+}));beforeEach(() => {vi.mocked(routeDeliverToChildren)@@ -92,7 +104,6 @@ describe("SessionExecution checkpoints", () => {next: vi.fn(),restore: vi.fn(),onDelivery: () => () => {},- onAgentStarted: () => () => {},onInterrupt: () => () => {},};let signal: AbortSignal | undefined;@@ -140,7 +151,6 @@ describe("SessionExecution checkpoints", () => {deliver = handler;return () => {};},- onAgentStarted: () => () => {},onInterrupt: (handler) => {interrupt = handler;return () => {};@@ -200,7 +210,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),- onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -258,7 +267,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),- onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -330,7 +338,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),- onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -391,7 +398,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(),restore: vi.fn(),- onAgentStarted: () => () => {},onInterrupt: () => () => {},onDelivery: (handler) => {notify = handler;@@ -428,7 +434,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -484,7 +489,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn((handler) => {interrupt = handler;return () => {};@@ -535,7 +539,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -600,7 +603,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -651,7 +653,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(() => new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -703,7 +704,6 @@ describe("SessionExecution checkpoints", () => {next: vi.fn(),restore: vi.fn(),onDelivery: () => () => {},- onAgentStarted: () => () => {},onInterrupt: (handler) => {interrupt = handler;return () => {};@@ -754,7 +754,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(async () => runtimePayloads.shift()),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -831,7 +830,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(async () => runtimePayloads.shift()),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -917,7 +915,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(async () => runtimePayloads.shift()),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -1002,7 +999,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(async () => payloads.shift()),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -1097,7 +1093,6 @@ describe("SessionExecution checkpoints", () => {whenPending: () => new Promise<void>(() => {}),next: vi.fn(async () => payloads.shift() ?? new Promise<never>(() => {})),onDelivery: vi.fn(() => () => {}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -1173,7 +1168,6 @@ describe("SessionExecution checkpoints", () => {signalDelivery = handler;return () => {};}),- onAgentStarted: () => () => {},onInterrupt: vi.fn(() => () => {}),restore: vi.fn(),};@@ -1218,21 +1212,198 @@ describe("SessionExecution checkpoints", () => {expect(continuation).toEqual({ delivery: steering, steered: false });});++ it("publishes and adopts consecutive boundary agent-started messages in one step, keeping admission order", async () => {+ const { inbox, planner, progress, reviewer, writer } = boundaryRunMessages();+ const cursor = createCursor({ inbox, sessionState: state("") });+ publishIntoContext();+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(+ turnStepWork(async (input) => ({+ action: "park",+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ serializedContext: input.serializedContext,+ sessionState: input.sessionState,+ settled: { output: "Done." },+ })),+ );+ inbox.drain = vi+ .fn()+ .mockReturnValueOnce([planner, reviewer, progress, writer])+ .mockReturnValue([]);++ await expect(+ createExecution({ cursor, inbox, sessionState: cursor.sessionState }).runTurn(undefined),+ ).resolves.toMatchObject({ kind: "park", settled: { output: "Done." } });++ expect(cursor.serializedContext[PUBLISHED]).toEqual([+ "planner-session+reviewer-session",+ "Halfway through the sources.",+ "writer-session",+ ]);+ });++ it("announces no child when the step ends the session, whose stream it closed", async () => {+ const { inbox, planner, progress } = boundaryRunMessages();+ const sessionState = state("");+ const cursor = createCursor({ inbox, sessionState });+ publishIntoContext();+ inbox.drain = vi.fn().mockReturnValueOnce([planner, progress]).mockReturnValue([]);+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementationOnce(+ turnStepWork(async () => ({ action: "done", serializedContext: {}, sessionState })),+ );++ await expect(+ createExecution({ cursor, inbox, sessionState }).runTurn(undefined),+ ).resolves.toMatchObject({ kind: "done" });++ // The boundary still ran: it handled the task's report and dropped only the child.+ expect(cursor.serializedContext[PUBLISHED]).toEqual(["Halfway through the sources."]);+ expect(emitAgentStartedStep).not.toHaveBeenCalled();+ });++ it("announces a child opened before a cancel ahead of cancelling the turn's work", async () => {+ const { inbox, planner } = boundaryRunMessages();+ const sessionState = state("");+ let interrupt: (payload: SessionInboxPayload) => void = () => {};+ inbox.onInterrupt = (handler) => {+ interrupt = handler;+ return () => {};+ };+ // Bob cancels while the turn waits, just as Alice's run opens a planner.+ inbox.next = vi.fn(async () => {+ interrupt({ kind: "cancel" });+ return planner;+ });+ publishIntoContext();+ vi.mocked(turnStep)+ .mockReset()+ .mockImplementation(+ turnStepWork(async () => ({+ action: "park",+ pendingCoordinationCallIds: ["hold-call"],+ hasPendingAuthorization: false,+ hasPendingInputBatch: false,+ serializedContext: {},+ sessionState,+ })),+ );+ vi.mocked(dispatchCoordinationStep).mockImplementation(+ dispatchWork(async () => ({ results: [], serializedContext: {}, sessionState })),+ );++ await expect(createExecution({ inbox, sessionState }).runTurn(undefined)).resolves.toEqual({+ cancelled: true,+ kind: "park",+ });++ const [announced] = vi.mocked(emitAgentStartedStep).mock.invocationCallOrder;+ const [cancelled] = vi.mocked(cancelDescendantTurnsStep).mock.invocationCallOrder;+ expect(announced).toBeLessThan(cancelled!);+ });});-function createExecution(input: {- readonly capabilities?: SessionCapabilities;+/** The context key the mocked publishing steps append to, as a hook's state write would. */+const PUBLISHED = "test.published";++/** Mocks the run-message publishing steps to record what they publish in the session context. */+function publishIntoContext(): void {+ const append = (context: Record<string, unknown>, entry: string) => ({+ serializedContext: {+ ...context,+ [PUBLISHED]: [...((context[PUBLISHED] as string[] | undefined) ?? []), entry],+ },+ });+ vi.mocked(emitAgentStartedStep)+ .mockReset()+ .mockImplementation(+ stepWork(async (input: Parameters<typeof emitAgentStartedStep>[0]) =>+ append(+ input.serializedContext,+ input.messages.map((message) => message.session.sessionId).join("+"),+ ),+ ),+ );+ vi.mocked(emitWorkflowToolRunReportStep)+ .mockReset()+ .mockImplementation(+ stepWork(async (input: Parameters<typeof emitWorkflowToolRunReportStep>[0]) =>+ append(input.serializedContext, String(input.update)),+ ),+ );+}++/**+ * Alice's runs open a planner, a reviewer, and a writer, and her research task+ * reports progress, with an inbox that has nothing else to admit.+ */+function boundaryRunMessages() {+ const from = (callId: string, taskId?: string): WorkflowToolRunRef => ({+ callId,+ input: {},+ runId: `run-${callId}`,+ sequence: 0,+ stepIndex: 0,+ ...(taskId !== undefined && { taskId }),+ toolName: "execute",+ turnId: "turn_0",+ });+ const opened = (callId: string, name: string): WorkflowToolRunMessage => ({+ from: from(callId),+ kind: "agent-started",+ session: { kind: "local", name, nodeId: name, sessionId: `${name}-session` },+ });+ const inbox: SessionInbox = {+ claimedTokens: [],+ claimSessionHook: vi.fn(),+ claimSessionHooks: vi.fn(),+ drain: () => [],+ hasPending: () => false,+ whenPending: () => new Promise<void>(() => {}),+ next: vi.fn(() => new Promise<never>(() => {})),+ restore: vi.fn(),+ onDelivery: () => () => {},+ onInterrupt: () => () => {},+ };+ return {+ inbox,+ planner: opened("call-1", "planner"),+ progress: {+ from: from("call-3", "research"),+ kind: "report",+ update: "Halfway through the sources.",+ } satisfies WorkflowToolRunMessage,+ reviewer: opened("call-2", "reviewer"),+ writer: opened("call-4", "writer"),+ };+}++function createCursor(input: {readonly inbox: SessionInbox;- readonly queue?: SessionInputQueue;readonly serializedContext?: Record<string, unknown>;readonly sessionState: DurableSessionState;-}): SessionExecution {- const cursor = new SessionStateCursor({+}): SessionStateCursor {+ return new SessionStateCursor({inbox: input.inbox,sessionWritable: new WritableStream<Uint8Array>(),serializedContext: input.serializedContext ?? {},sessionState: input.sessionState,});+}++function createExecution(input: {+ readonly capabilities?: SessionCapabilities;+ readonly cursor?: SessionStateCursor;+ readonly inbox: SessionInbox;+ readonly queue?: SessionInputQueue;+ readonly serializedContext?: Record<string, unknown>;+ readonly sessionState: DurableSessionState;+}): SessionExecution {+ const cursor = input.cursor ?? createCursor(input);return new SessionExecution({capabilities: input.capabilities,cursor,diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.tsindex eb6fcabee..0f892b419 100644--- a/packages/eve/src/execution/session/turn.ts+++ b/packages/eve/src/execution/session/turn.ts@@ -1,11 +1,6 @@import { sleep } from "#compiled/@workflow/core/index.js";-import type {- DeliverHookPayload,- SessionAuthContext,- SessionCapabilities,- TurnCaller,-} from "#channel/types.js";+import type { DeliverHookPayload, SessionCapabilities, TurnCaller } from "#channel/types.js";import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";import { routeDeliverToChildren } from "#execution/route-child-delivery.js";@@ -15,10 +10,9 @@ import {type SessionInputQueue,type SteeringTurn,} from "#execution/session/input-queue.js";-import { AuthKey } from "#context/keys.js";import { taskToolResult, type TaskToolCall } from "#execution/tasks/calls.js";import { TASK_WAIT_TOOL_NAME } from "#protocol/task-tools.js";-import { principalOf } from "#execution/session/principal.js";+import { resolveTurnPrincipal } from "#execution/session/principal.js";import { renderTaskWaitResult } from "#execution/tasks/render.js";import {answerTaskCancel,@@ -36,7 +30,11 @@ import type { SessionInboxPayload, SessionInboxReader } from "#execution/sessionimport { publishTurnWaitingStep } from "#execution/session/turn-waiting-step.js";import { admitSessionInboxPayload } from "#execution/session/admission.js";import type { SessionStateCursor } from "#execution/session/state-cursor.js";-import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-run.js";+import {+ batchAgentStarts,+ handleWorkflowToolRunMessage,+} from "#execution/session-workflow-tool-run.js";+import { emitAgentStartedStep } from "#execution/tools/workflow/emit-workflow-tool-run-report-step.js";import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";import type {@@ -44,7 +42,6 @@ import type {TurnOutcome,TurnStepPayload,} from "#execution/session/turn-step-types.js";-import { StepAgentStarts } from "#execution/session/step-agent-starts.js";import { turnStep } from "#execution/session/turn-step.js";import { activeTurnId } from "#harness/active-turn-id.js";import { coalesceDeliveries } from "#harness/messages.js";@@ -111,8 +108,9 @@ export class SessionExecution {});try {const outcome = await this.runTurnSteps(turn, delivery);- // Tasks run beside the turn, so their runs' messages still reach the session.- await this.handleAdmittedTaskEvents(turn);+ // Tasks run beside the turn, and a run can open a session after its call+ // returns, so these messages still reach the session.+ await this.handleBoundaryMessages(turn.takeBoundaryMessages(), outcome.kind === "done");// The turn rule holds a turn while its tasks work, so a turn that ends// anyway, such as by failing, cancels them.if (outcome.kind === "park" && outcome.settled !== undefined) {@@ -124,9 +122,25 @@ export class SessionExecution {}}- /** Applies what task runs reported while the model step ran, so the next step sees it. */- private async handleAdmittedTaskEvents(turn: ActiveTurn): Promise<void> {- for (const message of turn.takeTaskMessages()) await this.handleWorkflowMessage(message);+ /**+ * Applies what runs reported while the model step ran, so the next step sees+ * it. Consecutive `agent-started` messages, such as a fan-out's, share one step.+ * An ending session drops them: its stream is closed, and finalizing the+ * session terminates the children.+ */+ private async handleBoundaryMessages(+ messages: readonly WorkflowToolRunMessage[],+ ending = false,+ ): Promise<void> {+ for (const batch of batchAgentStarts(messages)) {+ if (batch.kind === "message") {+ await this.handleWorkflowMessage(batch.message);+ } else if (!ending) {+ await this.input.cursor.advance((state) =>+ emitAgentStartedStep({ ...state, messages: batch.messages }),+ );+ }+ }}private async runTurnSteps(@@ -138,25 +152,23 @@ export class SessionExecution {while (true) {const { cursor } = this.input;const result = await cursor.advance((state) =>- turn.agentStarts.publishWhile(- turnStep({- ...state,- abortSignal: turn.signal,- input: nextStepInput,- steeringSignal: turn.steeringSignal,- }),- ),+ turnStep({+ ...state,+ abortSignal: turn.signal,+ input: nextStepInput,+ steeringSignal: turn.steeringSignal,+ }),);const pendingCallIds =result.action === "park" ? result.pendingCoordinationCallIds : undefined;const turnCompleted = result.action === "park" && result.settled !== undefined;await turn.admitBoundary();- await this.handleAdmittedTaskEvents(turn);+ await this.handleBoundaryMessages(turn.takeBoundaryMessages(), result.action === "done");- if (result.action === "cancelled") return await this.finishCancelledTurn();+ if (result.action === "cancelled") return await this.finishCancelledTurn(turn);if (!turnCompleted && turn.signal.aborted && pendingCallIds === undefined) {- return await this.finishCancelledTurn();+ return await this.finishCancelledTurn(turn);}if (result.action === "done") {@@ -171,7 +183,7 @@ export class SessionExecution {if (result.action === "held") {const woke = await this.waitForHeldTurn(turn);- if (woke === "cancelled") return await this.finishCancelledTurn();+ if (woke === "cancelled") return await this.finishCancelledTurn(turn);const steering = await turn.takeSteering();nextStepInput = steering === undefined ? undefined : { delivery: steering };continue;@@ -196,7 +208,7 @@ export class SessionExecution {pendingCallIds,turn,});- if (runtimeResults === "cancelled") return await this.finishCancelledTurn();+ if (runtimeResults === "cancelled") return await this.finishCancelledTurn(turn);// Steering accepted during the wait is appended ahead of the result in// the same step, so the model sees it before the blocking action resolves.nextStepInput = { delivery: await turn.takeSteering(), runtimeResults };@@ -237,8 +249,10 @@ export class SessionExecution {}/** `session.cancel()` stops the turn, the calls it waits on, and every working task. */- private async finishCancelledTurn(): Promise<TurnOutcome> {+ private async finishCancelledTurn(turn: ActiveTurn): Promise<TurnOutcome> {const { cursor } = this.input;+ // A child a run opened before the cancel appears before its task settles as cancelled.+ await this.handleBoundaryMessages(turn.takeBoundaryMessages("agent-started"));await cancelDescendantTurnsStep({sessionState: cursor.sessionState,});@@ -441,19 +455,6 @@ type RuntimeEvent =| { readonly kind: "timeout"; readonly callId: string }| "cancelled";-/**- * The principal of the delivery that starts or continues a turn. A delivery- * without auth keeps the session's current identity, as the turn step does.- */-function resolveTurnPrincipal(- payload: TurnStepPayload | undefined,- serializedContext: Record<string, unknown>,-): string {- const auth = payload?.delivery?.auth;- if (auth !== undefined) return principalOf(auth);- return principalOf(serializedContext[AuthKey.name] as SessionAuthContext | null | undefined);-}-/*** Admission policy, cancellation, and steering for one active turn.* Deliveries admitted while a model step runs stay in the shared queue until@@ -475,7 +476,6 @@ class ActiveTurn {private readonly identity: SteeringTurn;private readonly unsubscribe: () => void;private unsubscribeDelivery: () => void;- readonly agentStarts: StepAgentStarts;private steeringController = new AbortController();/** The delegated caller of the latest message the turn read. */caller: TurnCaller | undefined;@@ -492,7 +492,6 @@ class ActiveTurn {if (this.cancelsThisTurn(payload)) this.abort();});this.unsubscribeDelivery = input.inbox.onDelivery(this.signalSteering);- this.agentStarts = new StepAgentStarts(input.inbox, input.cursor);}private readonly signalSteering = (payload: SessionInboxPayload): void => {@@ -563,13 +562,16 @@ class ActiveTurn {return delivery;}- /** Removes the admitted task run messages, which the session applies to the task table at once. */- takeTaskMessages(): WorkflowToolRunMessage[] {+ /**+ * Removes the admitted run messages the session applies at once instead of+ * in a runtime wait, or only those of `kind`.+ */+ takeBoundaryMessages(kind?: "agent-started"): WorkflowToolRunMessage[] {const taken: WorkflowToolRunMessage[] = [];const kept: RuntimeEvent[] = [];for (const event of this.runtimeResults) {- const message = asTaskMessage(event);- if (message === undefined) kept.push(event);+ const message = asBoundaryMessage(event);+ if (message === undefined || (kind !== undefined && message.kind !== kind)) kept.push(event);else taken.push(message);}this.runtimeResults.splice(0, this.runtimeResults.length, ...kept);@@ -614,7 +616,6 @@ class ActiveTurn {}private async admit(value: SessionInboxPayload): Promise<void> {- if (this.agentStarts.consume(value)) return;const admitted = await admitSessionInboxPayload(value, this.input);switch (admitted.kind) {case "delivery":@@ -677,10 +678,13 @@ class ActiveTurn {}}-function asTaskMessage(event: RuntimeEvent): WorkflowToolRunMessage | undefined {- if (event === "cancelled") return undefined;+function asBoundaryMessage(event: RuntimeEvent): WorkflowToolRunMessage | undefined {+ if (event === "cancelled" || event.kind !== "workflow") return undefined;// Tasks run beside the turn, so everything their runs send, such as a// question, reaches the session at the next boundary rather than at turn end.- if (event.kind === "workflow" && event.message.from.taskId !== undefined) return event.message;+ if (event.message.from.taskId !== undefined) return event.message;+ // An `execute` run can open a session after its call returns, when the turn+ // may have no wait left to take the message, and publishing it needs none.+ if (event.message.kind === "agent-started") return event.message;return undefined;}diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tssimilarity index 65%rename from packages/eve/src/execution/settle-cancelled-turn-step.test.tsrename to packages/eve/src/execution/settle-cancelled-turn-step.integration.test.tsindex 7a861a163..b3e510e59 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts@@ -1,8 +1,5 @@-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it } from "vitest";-import { ContextContainer } from "#context/container.js";-import { ActivityPendingBlockersKey } from "#context/keys.js";-import { deserializeContext } from "#context/serialize.js";import type { HarnessSession, SessionStateMap } from "#harness/types.js";import { readDurableSession } from "#execution/durable-session-store.js";import { appendPendingInputBatch } from "#harness/pending-input-batches.js";@@ -14,26 +11,31 @@ import {setTurnUsageState,takeSessionUsageDelta,} from "#harness/turn-tag-state.js";+import { createTestRuntime } from "#internal/testing/app-harness.js";import { createTestSessionState } from "#internal/testing/session-state.js";import { runSessionStateStep } from "#internal/testing/session-state-step.js";+import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-// The turn's stream events and channel context are not under test; the usage-// the step reports and the session it persists are.-vi.mock("#context/serialize.js", () => ({- deserializeContext: vi.fn(async () => new ContextContainer()),- serializeContext: () => ({}),-}));-vi.mock("#execution/publish-session-events.js", () => ({- withSessionEventEmitter: async (- input: { readonly durableSession: HarnessSession },- emitEvents: (- emit: () => Promise<void>,- session: HarnessSession,- ) => Promise<{ readonly result: unknown; readonly session: HarnessSession }>,- // Hydration of a session with no compaction history yields empty compaction state.- ) =>- await emitEvents(async () => {}, { ...input.durableSession, compaction: {} } as HarnessSession),-}));+const serializedContext = {+ "eve.auth": null,+ "eve.bundle": { source: createBundledRuntimeCompiledArtifactsSource() },+ "eve.channel": { kind: "http", state: {} },+ "eve.continuationToken": "test-token",+ "eve.sessionId": "test-session",+};++/** Runs the step in a real runtime, so it publishes through the session's real publication path. */+async function settleCancelledTurn(+ input: Omit<Parameters<typeof settleCancelledTurnStep>[0], "sessionWritable">,+) {+ const runtime = await createTestRuntime({ agent: { name: "settle-cancelled-turn" } });+ return await runtime.run(() =>+ runSessionStateStep(+ { ...input, sessionWritable: new WritableStream<Uint8Array>() },+ settleCancelledTurnStep,+ ),+ );+}function spend<T extends { readonly state?: SessionStateMap }>(session: T,@@ -73,18 +75,16 @@ describe("settleCancelledTurnStep", () => {(session, requests) => appendPendingInputBatch({ requests, responseMessages: [], session }),{ state: base.snapshot.session.state } as HarnessSession,);- const ctx = new ContextContainer();- ctx.set(ActivityPendingBlockersKey, ["child-question-1", "approval-1", "limit-1"]);- vi.mocked(deserializeContext).mockResolvedValueOnce(ctx);-- await settleCancelledTurnStep({+ const result = await settleCancelledTurn({reportUsage: false,- serializedContext: {},+ serializedContext: {+ ...serializedContext,+ "eve.activityPendingBlockers": ["child-question-1", "approval-1", "limit-1"],+ },sessionState: { ...base, snapshot: { session: { ...base.snapshot.session, ...parked } } },- sessionWritable: new WritableStream<Uint8Array>(),});- expect(ctx.get(ActivityPendingBlockersKey)).toEqual(["approval-1"]);+ expect(result.serializedContext["eve.activityPendingBlockers"]).toEqual(["approval-1"]);});it.each([@@ -102,15 +102,11 @@ describe("settleCancelledTurnStep", () => {// Its next turn spent 50 more before Alice cancelled it.const cancelling = spend(settled, 50, "turn_2");- const result = await runSessionStateStep(- {- reportUsage,- serializedContext: {},- sessionState: { ...base, snapshot: { session: cancelling } },- sessionWritable: new WritableStream<Uint8Array>(),- },- settleCancelledTurnStep,- );+ const result = await settleCancelledTurn({+ reportUsage,+ serializedContext,+ sessionState: { ...base, snapshot: { session: cancelling } },+ });expect(result.usage?.inputTokens).toBe(reported);// The next settled turn reports whatever the cancel didn't.diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.tsindex a36af5f2e..7b429118d 100644--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts@@ -2,15 +2,9 @@ import {commitCancelledCoordinationBatch,getPendingCoordinationBatch,} from "#harness/coordination.js";-import { deserializeContext, serializeContext } from "#context/serialize.js";import { retainAnswerableActivityBlockers } from "#execution/activity-cohort.js";-import {- createDurableSessionState,- type DurableSessionState,- readDurableSession,-} from "#execution/durable-session-store.js";-import { withSessionEventEmitter } from "#execution/publish-session-events.js";-import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";+import type { DurableSessionState } from "#execution/durable-session-store.js";+import { publishFromSessionStep, restoreSessionStep } from "#execution/publish-session-events.js";import {withSessionStateDelta,type WithSessionStateDelta,@@ -58,52 +52,41 @@ export async function settleCancelledTurnStep(export async function settleCancelledTurn(input: CancelledTurnSettleInput,): Promise<CancelledTurnSettleResult> {- const durableSession = readDurableSession(input.sessionState);- const ctx = await deserializeContext(input.serializedContext);+ const step = await restoreSessionStep(input);+ const durableState = step.durableSession.state;// Before `turn.cancelled` projects, so only what stays answerable holds the work open.- retainAnswerableActivityBlockers(ctx, durableSession.state);- const emitted = await withSessionEventEmitter(- { ctx, durableSession, origin: "own", sessionWritable: input.sessionWritable },- async (emit, scopedSession) => ({- result: await emitCancelledTurn(emit, getHarnessEmissionState(durableSession.state)),- session: scopedSession,- }),- );- const emissionState = emitted.result;- const session = emitted.session;-- // `clearPendingSessionLimitPrompt`: cancellation settles with the step's- // input snapshot, which can resurrect an already-answered session-limit- // prompt (the decline that cancelled this turn consumed the answer in the- // discarded turn state). The pre-model gate re-raises the prompt while the- // violation holds, so the next delivery gets a fresh prompt instead of- // queueing forever behind a stale one.- const owningTurnId =- getPendingCoordinationBatch(session.state)?.event.turnId ??- input.sessionState.emissionState.turnId;- const cancelledSession = reconcileSessionContinuationToken(- ctx,- setHarnessEmissionState(- clearPendingSessionLimitPrompt(- clearAllProxyInputRequests(- commitCancelledCoordinationBatch(- removeBlockingWorkflowToolRuns({ ...session, outputSchema: undefined }, owningTurnId),+ retainAnswerableActivityBlockers(step.ctx, durableState);+ const { published, result: usage } = await publishFromSessionStep(step, {+ origin: "own",+ publish: (emit) => emitCancelledTurn(emit, getHarnessEmissionState(durableState)),+ updateSession(session, emissionState) {+ // `clearPendingSessionLimitPrompt`: cancellation settles with the step's+ // input snapshot, which can resurrect an already-answered session-limit+ // prompt (the decline that cancelled this turn consumed the answer in the+ // discarded turn state). The pre-model gate re-raises the prompt while the+ // violation holds, so the next delivery gets a fresh prompt instead of+ // queueing forever behind a stale one.+ const owningTurnId =+ getPendingCoordinationBatch(session.state)?.event.turnId ??+ input.sessionState.emissionState.turnId;+ const cancelledSession = setHarnessEmissionState(+ clearPendingSessionLimitPrompt(+ clearAllProxyInputRequests(+ commitCancelledCoordinationBatch(+ removeBlockingWorkflowToolRuns({ ...session, outputSchema: undefined }, owningTurnId),+ ),),),- ),- emissionState,- ),- );- const base = { serializedContext: serializeContext(ctx) };- if (!input.reportUsage || getTurnUsageState(session.state) === undefined) {- return { ...base, sessionState: createDurableSessionState({ session: cancelledSession }) };- }- // Reported like a settled turn, as usage since the last report, so the- // caller counts each turn once whether it settled or was cancelled.- const reported = takeSessionUsageDelta(cancelledSession);- return {- ...base,- sessionState: createDurableSessionState({ session: reported.session }),- usage: reported.delta,- };+ emissionState,+ );+ if (!input.reportUsage || getTurnUsageState(session.state) === undefined) {+ return { session: cancelledSession };+ }+ // Reported like a settled turn, as usage since the last report, so the+ // caller counts each turn once whether it settled or was cancelled.+ const reported = takeSessionUsageDelta(cancelledSession);+ return { result: reported.delta, session: reported.session };+ },+ });+ return usage === undefined ? published : { ...published, usage };}diff --git a/packages/eve/src/execution/tasks/task-run-usage.test.ts b/packages/eve/src/execution/tasks/task-run-usage.test.tsindex 5bef3a24b..3d6c57c64 100644--- a/packages/eve/src/execution/tasks/task-run-usage.test.ts+++ b/packages/eve/src/execution/tasks/task-run-usage.test.ts@@ -80,7 +80,6 @@ function sessionWithTask(input: {);const inbox = {claimSessionHooks: vi.fn(),- onAgentStarted: () => () => {},onDelivery: () => () => {},onInterrupt: () => () => {},} as Partial<SessionInbox> as SessionInbox;diff --git a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.tsindex e42b68c5b..c86393978 100644--- a/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts+++ b/packages/eve/src/execution/tools/workflow/emit-workflow-tool-run-report-step.ts@@ -33,29 +33,30 @@ export async function emitWorkflowToolRunReportStep(return await withSessionStateDelta(input, (target) => publishSessionEvents(target, [event]));}-/** Publishes `agent.started` for a session a workflow tool run opened. */+/** Publishes `agent.started`, in order, for sessions workflow tool runs opened. */export async function emitAgentStartedStep(input: SessionStepState & {- readonly message: WorkflowToolRunAgentStartedMessage;+ readonly messages: readonly WorkflowToolRunAgentStartedMessage[];},): Promise<SessionStateTransition> {"use step";- const { from, session } = input.message;- const event = createAgentStartedEvent({- callId: from.callId,- name: session.name,- parentSessionId: input.sessionState.sessionId,- remote:- session.kind === "remote"- ? {- url: session.url,- ...(session.resolverId !== undefined && { resolverId: session.resolverId }),- }- : undefined,- sessionId: session.sessionId,- ...(from.taskId !== undefined && { taskId: from.taskId }),- turnId: from.turnId,- });- return await withSessionStateDelta(input, (target) => publishSessionEvents(target, [event]));+ const events = input.messages.map(({ from, session }) =>+ createAgentStartedEvent({+ callId: from.callId,+ name: session.name,+ parentSessionId: input.sessionState.sessionId,+ remote:+ session.kind === "remote"+ ? {+ url: session.url,+ ...(session.resolverId !== undefined && { resolverId: session.resolverId }),+ }+ : undefined,+ sessionId: session.sessionId,+ ...(from.taskId !== undefined && { taskId: from.taskId }),+ turnId: from.turnId,+ }),+ );+ return await withSessionStateDelta(input, (target) => publishSessionEvents(target, events));}diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex b01e88658..39f4fa96c 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -11,7 +11,7 @@ import {SessionInboxKey,} from "#context/keys.js";import type { DurableSession } from "#execution/durable-session-store.js";-import { createSessionEventSink } from "#execution/publish-session-events.js";+import { openSessionEventPublisher } from "#execution/publish-session-events.js";import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";import { getProxyInputRequests } from "#harness/proxy-input-requests.js";import type { MessageStreamEvent } from "#protocol/message.js";@@ -184,13 +184,14 @@ describe("proxied stream hooks", () => {Response.json({ ok: true }, { status: 202 }),);vi.stubGlobal("fetch", fetchMock);- const sink = createSessionEventSink({+ const publisher = openSessionEventPublisher({ctx: f.ctx,+ origin: "own",sessionId: "parent-session",sessionWritable: f.sessionWritable,});try {- await sink.emit({ type: "input.requested", data: f.hookPayload.event });+ await publisher.emit({ type: "input.requested", data: f.hookPayload.event });expect(fetchMock).toHaveBeenCalledOnce();const forwarded = JSON.parse(fetchMock.mock.calls[0]![1]!.body as string);expect(forwarded).toMatchObject({@@ -202,7 +203,7 @@ describe("proxied stream hooks", () => {expect(f.order).not.toContain("channel:input.requested");expect(f.events.map((event) => event.type)).toEqual(["input.requested"]);} finally {- sink.release();+ publisher.writer.release();vi.unstubAllGlobals();}});@@ -221,13 +222,14 @@ describe("proxied stream hooks", () => {Response.json({ ok: true }, { status: 202 }),);vi.stubGlobal("fetch", fetchMock);- const sink = createSessionEventSink({+ const publisher = openSessionEventPublisher({ctx: f.ctx,+ origin: "own",sessionId: "parent-session",sessionWritable: f.sessionWritable,});try {- await sink.emit({ type: "input.requested", data: f.hookPayload.event });+ await publisher.emit({ type: "input.requested", data: f.hookPayload.event });const forwarded = JSON.parse(fetchMock.mock.calls[0]![1]!.body as string);expect(forwarded).toMatchObject({childContinuationToken: "eve:session:parent-session:inbox",@@ -236,7 +238,7 @@ describe("proxied stream hooks", () => {});expect(f.order).not.toContain("channel:input.requested");} finally {- sink.release();+ publisher.writer.release();vi.unstubAllGlobals();}});diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.tsindex df82adde6..e49a541a1 100644--- a/packages/eve/src/subagents/event-proxy-step.ts+++ b/packages/eve/src/subagents/event-proxy-step.ts@@ -2,23 +2,17 @@ import type {SubagentAuthorizationEventHookPayload,SubagentInputRequestHookPayload,} from "#channel/types.js";-import type { ContextContainer } from "#context/container.js";-import { deserializeContext, serializeContext } from "#context/serialize.js";import {- createDurableSessionState,- type DurableSession,- readDurableSession,-} from "#execution/durable-session-store.js";-import {- withSessionEventEmitter,+ publishFromSessionStep,+ restoreSessionStep,type PublishedSessionEvents,+ type RestoredSessionStep,type SessionStepState,} from "#execution/publish-session-events.js";import {withSessionStateDelta,type SessionStateTransition,} from "#execution/session/state-delta.js";-import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";import { emitProxiedAuthorizationEvent, emitProxiedInputRequest } from "#subagents/hitl-proxy.js";import { upsertProxyInputRequests } from "#harness/proxy-input-requests.js";import type { WorkflowAskRoute } from "#harness/proxy-input-requests.js";@@ -38,64 +32,50 @@ export async function runProxySubagentEventStep(return await withSessionStateDelta(input, async (target) =>emitProxiedSubagentEvent({+ ...(await restoreSessionStep(target)),workflowAsk: target.workflowAsk,- ctx: await deserializeContext(target.serializedContext),- durableSession: readDurableSession(target.sessionState),hookPayload: target.hookPayload,- sessionWritable: target.sessionWritable,}),);}/** Relays one child event through the parent session's channel. */-export async function emitProxiedSubagentEvent(input: {- readonly workflowAsk?: WorkflowAskRoute;- readonly ctx: ContextContainer;- readonly durableSession: DurableSession;- readonly hookPayload: SubagentEventHookPayload;- readonly sessionWritable: WritableStream<Uint8Array>;-}): Promise<PublishedSessionEvents> {- const { ctx, hookPayload } = input;- const relayed = await withSessionEventEmitter(- {- ctx,- durableSession: input.durableSession,- origin: "relayed",- sessionWritable: input.sessionWritable,- inputSource:- hookPayload.kind === "subagent-input-request"- ? JSON.stringify([hookPayload.childContinuationToken, hookPayload.inputSource ?? null])- : undefined,- },- async (emit, session) => {+export async function emitProxiedSubagentEvent(+ input: RestoredSessionStep & {+ readonly workflowAsk?: WorkflowAskRoute;+ readonly hookPayload: SubagentEventHookPayload;+ },+): Promise<PublishedSessionEvents> {+ const { hookPayload, workflowAsk } = input;+ const { published } = await publishFromSessionStep(input, {+ origin: "relayed",+ inputSource:+ hookPayload.kind === "subagent-input-request"+ ? JSON.stringify([hookPayload.childContinuationToken, hookPayload.inputSource ?? null])+ : undefined,+ async publish(emit, session) {if (hookPayload.kind === "subagent-authorization-event") {await emitProxiedAuthorizationEvent({ emit, hookPayload, session });- return { result: undefined, session };+ return undefined;}-- const entries = await emitProxiedInputRequest({ emit, hookPayload, session });- return { result: entries, session };+ return await emitProxiedInputRequest({ emit, hookPayload, session });},- );-- let scopedSession = relayed.session;- if (relayed.result !== undefined && hookPayload.kind === "subagent-input-request") {- const workflowAsk = input.workflowAsk;- scopedSession = upsertProxyInputRequests({- entries:- workflowAsk === undefined- ? relayed.result- : relayed.result.map(([requestId, route]) => [requestId, { ...route, workflowAsk }]),- forChildContinuationToken: hookPayload.childContinuationToken,- inputSource: hookPayload.inputSource,- session: scopedSession,- });- }-- const nextSession = reconcileSessionContinuationToken(ctx, scopedSession);-- return {- serializedContext: serializeContext(ctx),- sessionState: createDurableSessionState({ session: nextSession }),- };+ updateSession(session, entries) {+ if (entries === undefined || hookPayload.kind !== "subagent-input-request") {+ return { session };+ }+ return {+ session: upsertProxyInputRequests({+ entries:+ workflowAsk === undefined+ ? entries+ : entries.map(([requestId, route]) => [requestId, { ...route, workflowAsk }]),+ forChildContinuationToken: hookPayload.childContinuationToken,+ inputSource: hookPayload.inputSource,+ session,+ }),+ };+ },+ });+ return published;}