Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

perf(eve): return session state deltas from workflow steps (#3988)

Andrew Barba99b41661111c
diff --git a/.changeset/session-step-state-deltas.md b/.changeset/session-step-state-deltas.md
new file mode 100644
index 000000000..c4a39c6ea
--- /dev/null
+++ b/.changeset/session-step-state-deltas.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Session workflow steps now return only the session state they changed, and the workflow applies that change to the state it passed in. Each step used to return a full copy of the session, so stored step output and the data a workflow replay reads grew with conversation length on every step; they now grow only with what each step changes.
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
index 5d7576c30..70de96399 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -7,6 +7,10 @@ import {
} from "#execution/coordination-dispatch-shared.js";
import { createDurableSessionState } from "#execution/durable-session-store.js";
import { publishSessionEvents } from "#execution/publish-session-events.js";
+import {
+ withSessionStateDelta,
+ type WithSessionStateDelta,
+} from "#execution/session/state-delta.js";
import { startWorkflowTask, type StartWorkflowTaskInput } from "#execution/tools/workflow/start.js";
import { sendToTask, startTaskRun } from "#execution/tasks/start.js";
import {
@@ -23,9 +27,14 @@ type CoordinationDispatchStepInput = CoordinationDispatchInput & {
export async function dispatchCoordinationStep(
input: CoordinationDispatchStepInput,
-): Promise<CoordinationDispatchResult> {
+): Promise<WithSessionStateDelta<CoordinationDispatchResult>> {
"use step";
+ return await withSessionStateDelta(input, dispatchCoordination);
+}
+async function dispatchCoordination(
+ input: CoordinationDispatchStepInput,
+): Promise<CoordinationDispatchResult> {
const prepared = await prepareCoordinationDispatch({
serializedContext: input.serializedContext,
sessionState: input.sessionState,
diff --git a/packages/eve/src/execution/legacy-session/import.integration.test.ts b/packages/eve/src/execution/legacy-session/import.integration.test.ts
index 1b3ef2e1d..4a46ae8d7 100644
--- a/packages/eve/src/execution/legacy-session/import.integration.test.ts
+++ b/packages/eve/src/execution/legacy-session/import.integration.test.ts
@@ -2,11 +2,12 @@ import { describe, expect, it, vi } from "vitest";
import { createTestRuntime } from "#internal/testing/app-harness.js";
import { legacySessionDriverWorkflow } from "#internal/testing/legacy-session-driver-workflow.js";
import { waitForHook } from "#internal/testing/workflow-test-helpers.js";
-import { waitForParkedTurnStep } from "#internal/testing/session-test-helpers.js";
+import {
+ readTurnStepStates,
+ waitForParkedTurnStep,
+} from "#internal/testing/session-test-helpers.js";
import { captureTurnEvents, filterEventsByType } from "#internal/testing/events.js";
-import { hydrateStepReturnValue } from "#compiled/@workflow/core/serialization.js";
-import type { DurableStepResult } from "#execution/session/turn-step-types.js";
-import { getWorld, getHookByToken, start } from "#internal/workflow/runtime.js";
+import { getHookByToken, start } from "#internal/workflow/runtime.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
import { resumeSessionInbox, resolveSessionInbox } from "#execution/session-inbox/resume.js";
@@ -76,21 +77,7 @@ describe("legacy session import", () => {
).toBe(owner.runId);
await vi.waitFor(
async () => {
- const steps = await (
- await getWorld()
- ).steps.list({
- runId: owner.runId,
- resolveData: "all",
- pagination: { limit: 1000 },
- });
- const checkpoints: DurableStepResult[] = [];
- for (const step of steps.data) {
- if (step.stepName.endsWith("//turnStep") && step.output !== undefined) {
- checkpoints.push(
- await hydrateStepReturnValue(step.output, owner.runId, undefined),
- );
- }
- }
+ const checkpoints = await readTurnStepStates(owner.runId);
const saved = checkpoints.find((result) =>
result.sessionState.snapshot.session.history.some(
(message) =>
diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.test.ts b/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
index fbc6c1bce..b8c9d021d 100644
--- a/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
+++ b/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
@@ -13,7 +13,7 @@ vi.mock("#execution/terminate-child-sessions-step.js", () => ({
terminateChildSessionsStep: mocks.children,
}));
vi.mock("#execution/settle-cancelled-turn-step.js", () => ({
- settleCancelledTurnStep: mocks.settle,
+ settleCancelledTurn: mocks.settle,
}));
beforeEach(() => vi.resetAllMocks());
function fixture(turnId = ""): PreparedLegacySession {
diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.ts b/packages/eve/src/execution/legacy-session/interrupt-step.ts
index 302c6149d..c9365c5f2 100644
--- a/packages/eve/src/execution/legacy-session/interrupt-step.ts
+++ b/packages/eve/src/execution/legacy-session/interrupt-step.ts
@@ -8,7 +8,7 @@ import { createLogger, logError } from "#internal/logging.js";
import { walkCauseChain } from "#shared/errors.js";
import { cancelRun, getWorld } from "#internal/workflow/runtime.js";
import { terminateChildSessionsStep } from "#execution/terminate-child-sessions-step.js";
-import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";
+import { settleCancelledTurn } from "#execution/settle-cancelled-turn-step.js";
import type { PreparedLegacySession } from "./prepare-step.js";
/** Only the elected importer may stop work or append cancellation events. */
@@ -81,7 +81,7 @@ export async function interruptLegacySessionStep(prepared: PreparedLegacySession
sessionState: prepared.sessionState,
serializedContext: prepared.serializedContext,
};
- return await settleCancelledTurnStep({
+ return await settleCancelledTurn({
reportUsage: false,
sessionWritable: prepared.input.sessionWritable,
serializedContext: prepared.serializedContext,
diff --git a/packages/eve/src/execution/proxied-deliver-step.ts b/packages/eve/src/execution/proxied-deliver-step.ts
index 16ec7c784..05f462d1b 100644
--- a/packages/eve/src/execution/proxied-deliver-step.ts
+++ b/packages/eve/src/execution/proxied-deliver-step.ts
@@ -8,6 +8,10 @@ import {
replaceDurableSessionSnapshot,
} from "#execution/durable-session-store.js";
import { relaySessionEvents, type SessionStepState } from "#execution/publish-session-events.js";
+import {
+ withSessionStateDelta,
+ type WithSessionStateDelta,
+} from "#execution/session/state-delta.js";
import { deserializeContext } from "#context/serialize.js";
import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
import {
@@ -63,8 +67,14 @@ interface ChildBucket {
*/
export async function routeProxiedDeliverStep(
input: SessionStepState & { readonly delivery: DeliverHookPayload },
-): Promise<RoutedDeliverResult> {
+): Promise<WithSessionStateDelta<RoutedDeliverResult>> {
"use step";
+ return await withSessionStateDelta(input, routeProxiedDeliver);
+}
+
+async function routeProxiedDeliver(
+ input: SessionStepState & { readonly delivery: DeliverHookPayload },
+): Promise<RoutedDeliverResult> {
let durableSession = readDurableSession(input.sessionState);
const sourceDelivery = input.delivery;
const parentPayloads = new Map<number, DeliverPayload>();
diff --git a/packages/eve/src/execution/route-child-delivery.ts b/packages/eve/src/execution/route-child-delivery.ts
index f2eed911c..37b6c5d16 100644
--- a/packages/eve/src/execution/route-child-delivery.ts
+++ b/packages/eve/src/execution/route-child-delivery.ts
@@ -4,6 +4,7 @@ import {
routeProxiedDeliverStep,
type RoutedDeliverResult,
} from "#execution/proxied-deliver-step.js";
+import type { WithSessionStateDelta } from "#execution/session/state-delta.js";
/**
* Routes any descendant-bound input responses down to the owning child. A
@@ -20,14 +21,9 @@ export async function routeDeliverToChildren(input: {
readonly sessionWritable: WritableStream<Uint8Array>;
readonly sessionState: DurableSessionState;
readonly serializedContext: Record<string, unknown>;
-}): Promise<RoutedDeliverResult> {
+}): Promise<WithSessionStateDelta<RoutedDeliverResult>> {
if (!input.sessionState.hasProxyInputRequests) {
- return {
- kind: "continue",
- remainder: input.delivery,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
+ return { kind: "continue", remainder: input.delivery, stateDelta: {} };
}
return await routeProxiedDeliverStep(input);
diff --git a/packages/eve/src/execution/session-workflow-tool-run.ts b/packages/eve/src/execution/session-workflow-tool-run.ts
index 1d595c6b3..754033592 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.ts
@@ -49,18 +49,12 @@ export async function handleWorkflowToolRunMessage(
await handleWorkflowToolRunWithdraw({ ...input, message });
return undefined;
case "report":
- await input.cursor.apply(
- await emitWorkflowToolRunReportStep({
- ...input.cursor.stepState(),
- from: message.from,
- update: message.update,
- }),
+ await input.cursor.advance((state) =>
+ emitWorkflowToolRunReportStep({ ...state, from: message.from, update: message.update }),
);
return undefined;
case "agent-started":
- await input.cursor.apply(
- await emitAgentStartedStep({ ...input.cursor.stepState(), message }),
- );
+ await input.cursor.advance((state) => emitAgentStartedStep({ ...state, message }));
return undefined;
}
}
@@ -98,22 +92,19 @@ async function handleWorkflowToolRunRequest(
if (message.request.kind === "authorization-request") {
const request = message.request;
await deliverWorkflowAuthorization({ ...message, request }, async () => {
- await cursor.apply(
- await runProxySubagentEventStep({
- hookPayload: request.event,
- ...cursor.stepState(),
- }),
+ await cursor.advance((state) =>
+ runProxySubagentEventStep({ hookPayload: request.event, ...state }),
);
});
return;
}
- await cursor.apply(
- await runProxySubagentEventStep({
+ await cursor.advance((state) =>
+ runProxySubagentEventStep({
...(message.request.kind === "ask" && {
workflowAsk: createWorkflowAskRoute(message.from, message.request),
}),
hookPayload: workflowToolRunRequestToInputRequestPayload(message),
- ...cursor.stepState(),
+ ...state,
}),
);
}
@@ -127,9 +118,9 @@ async function handleWorkflowToolRunWithdraw(
input: HandlerInput<WorkflowToolRunWithdrawMessage>,
): Promise<void> {
const { cursor, message } = input;
- await cursor.apply(
- await withdrawWorkflowToolRunQuestionStep({
- ...cursor.stepState(),
+ await cursor.advance((state) =>
+ withdrawWorkflowToolRunQuestionStep({
+ ...state,
control: message.control,
requestId: message.replyTo,
runId: message.from.runId,
diff --git a/packages/eve/src/execution/session/entry-handoff.integration.test.ts b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
index ed253d0b1..f5cd22c8b 100644
--- a/packages/eve/src/execution/session/entry-handoff.integration.test.ts
+++ b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
@@ -2,14 +2,13 @@ import type { HandoffWorkflowEntryInput } from "#execution/session/entry-input.j
import type { RunCreatedEventRequest } from "@workflow/world";
import { assert, describe, expect, it, vi } from "vitest";
import { getWorld, resumeHook, start } from "#internal/workflow/runtime.js";
-import {
- dehydrateWorkflowArguments,
- hydrateStepReturnValue,
- hydrateWorkflowArguments,
-} from "@workflow/core/serialization";
+import { dehydrateWorkflowArguments, hydrateWorkflowArguments } from "@workflow/core/serialization";
import { captureTurnEvents } from "#internal/testing/events.js";
import { createTestRuntime } from "#internal/testing/app-harness.js";
-import { waitForParkedTurnStep } from "#internal/testing/session-test-helpers.js";
+import {
+ readTurnStepStates,
+ waitForParkedTurnStep,
+} from "#internal/testing/session-test-helpers.js";
import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
import { workflowEntry } from "#execution/session/entry.js";
import {
@@ -130,25 +129,18 @@ describe("workflowEntry integration", () => {
).toBe(false);
const candidateHooks = await world.hooks.list({ runId: candidateId });
expect(candidateHooks.data).toEqual([]);
- const turns = await vi.waitFor(
+ await vi.waitFor(
async () => {
const steps = await world.steps.list({ runId: anchor.runId, resolveData: "all" });
const turns = steps.data.filter((step) => step.stepName.endsWith("//turnStep"));
expect(turns).toHaveLength(2);
// The waiting event is streamed before the step's return value is persisted.
expect(turns.every((step) => step.output !== undefined)).toBe(true);
- return turns;
},
{ timeout: 5000 },
);
- const histories = await Promise.all(
- turns.map(async (step) => {
- const output = await hydrateStepReturnValue(step.output, anchor.runId, undefined);
- return output.sessionState.snapshot.session.history as Array<{
- role: string;
- content: unknown;
- }>;
- }),
+ const histories = (await readTurnStepStates(anchor.runId)).map(
+ (state) => state.sessionState.snapshot.session.history,
);
const deliveries = histories.map((history) =>
history.filter(
@@ -254,15 +246,8 @@ describe("workflowEntry integration", () => {
let saved: string | undefined;
await vi.waitFor(
async () => {
- const steps = await world.steps.list({
- runId: owner.runId,
- resolveData: "all",
- pagination: { limit: 1000 },
- });
- for (const step of steps.data) {
- if (!step.stepName.endsWith("//turnStep") || step.output === undefined) continue;
- const result = await hydrateStepReturnValue(step.output, owner.runId, undefined);
- const history = JSON.stringify(result.sessionState.snapshot.session.history);
+ for (const state of await readTurnStepStates(owner.runId)) {
+ const history = JSON.stringify(state.sessionState.snapshot.session.history);
if (history.includes("Bob sends a later sentinel.")) saved = history;
}
expect(saved).toBeDefined();
diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.ts
index f0ad83d42..a3799c3d2 100644
--- a/packages/eve/src/execution/session/next-input.test.ts
+++ b/packages/eve/src/execution/session/next-input.test.ts
@@ -315,14 +315,12 @@ describe("nextTurnDelivery", () => {
.mockResolvedValueOnce({
kind: "continue",
remainder: undefined,
- serializedContext: {},
- sessionState: retiredState,
+ stateDelta: { sessionState: { kind: "value", value: retiredState } },
})
.mockResolvedValueOnce({
kind: "continue",
remainder: { kind: "deliver", payloads: [{ message: "parent turn" }] },
- serializedContext: {},
- sessionState: retiredState,
+ stateDelta: {},
});
const next = await nextTurnDelivery({
@@ -368,13 +366,10 @@ function authenticatedDelivery(message: string, auth: SessionAuthContext): Deliv
function batchingInputFor(bufferedDeliveries: DeliverHookPayload[]) {
const input = waitInput(createMockInbox([]));
- vi.mocked(routeDeliverToChildren).mockImplementation(
- async ({ delivery, serializedContext, sessionState }) => ({
- kind: "continue",
- remainder: delivery,
- serializedContext,
- sessionState,
- }),
- );
+ vi.mocked(routeDeliverToChildren).mockImplementation(async ({ delivery }) => ({
+ kind: "continue",
+ remainder: delivery,
+ stateDelta: {},
+ }));
return { ...input, queue: queueOf(...bufferedDeliveries) };
}
diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.ts
index b6bb5f035..a97132e1f 100644
--- a/packages/eve/src/execution/session/program.ts
+++ b/packages/eve/src/execution/session/program.ts
@@ -235,12 +235,9 @@ async function runSessionLoop(
const runTurn = async (payload: TurnStepPayload | undefined): Promise<TurnOutcome> => {
const caller = progress.caller;
if (caller !== undefined) {
- await cursor.apply({
- serializedContext: await bindTurnCallerContextStep({
- caller,
- serializedContext: cursor.serializedContext,
- }),
- });
+ await cursor.advance((state) =>
+ bindTurnCallerContextStep({ caller, serializedContext: state.serializedContext }),
+ );
}
progress.turnId = `turn_${String(turnIndex++)}`;
const outcome = await execution.runTurn(payload, { caller });
@@ -259,11 +256,9 @@ async function runSessionLoop(
return { action: await runTurn({ delivery: next.delivery }), kind: "action" };
};
const settleCancelledTurn = async (reportUsage: boolean) => {
- const settled = await settleCancelledTurnStep({
- ...cursor.stepState(),
- reportUsage,
- });
- await cursor.apply(settled);
+ const settled = await cursor.advance((state) =>
+ settleCancelledTurnStep({ ...state, reportUsage }),
+ );
progress.caller = undefined;
return settled;
};
diff --git a/packages/eve/src/execution/session/route-selected-delivery.ts b/packages/eve/src/execution/session/route-selected-delivery.ts
index db0d9d134..75b98b8ef 100644
--- a/packages/eve/src/execution/session/route-selected-delivery.ts
+++ b/packages/eve/src/execution/session/route-selected-delivery.ts
@@ -12,11 +12,9 @@ export async function routeSelectedDelivery(
selection: TurnSelection,
cursor: SessionStateCursor,
): Promise<RoutedTurnSelection> {
- const routed = await routeDeliverToChildren({
- delivery: selection.delivery,
- ...cursor.stepState(),
- });
- await cursor.apply(routed);
+ const routed = await cursor.advance((state) =>
+ routeDeliverToChildren({ delivery: selection.delivery, ...state }),
+ );
if (routed.kind === "cancel-turn") return { kind: "cancel-turn" };
if (routed.remainder === undefined) return { kind: "consumed" };
return { ...selection, delivery: routed.remainder };
diff --git a/packages/eve/src/execution/session/state-cursor.test.ts b/packages/eve/src/execution/session/state-cursor.test.ts
index 1c5ecc850..0edfd5c8d 100644
--- a/packages/eve/src/execution/session/state-cursor.test.ts
+++ b/packages/eve/src/execution/session/state-cursor.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import { ContinuationHookTokensKey } from "#context/keys.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import { SessionStateCursor } from "#execution/session/state-cursor.js";
+import { withSessionStateDelta } from "#execution/session/state-delta.js";
const stableToken = "eve:session:session-1:inbox";
@@ -24,17 +25,19 @@ describe("SessionStateCursor", () => {
});
const nextState = state("channel:third");
- await cursor.apply({
- serializedContext: {
- [ContinuationHookTokensKey.name]: ["channel:initial", "channel:second", "channel:third"],
- },
- sessionState: nextState,
- });
+ await cursor.advance((input) =>
+ withSessionStateDelta(input, async () => ({
+ serializedContext: {
+ [ContinuationHookTokensKey.name]: ["channel:initial", "channel:second", "channel:third"],
+ },
+ sessionState: nextState,
+ })),
+ );
expect(claimSessionHooks.mock.calls).toEqual([
[[stableToken, "channel:initial", "channel:second", "channel:third"]],
]);
- expect(cursor.sessionState).toBe(nextState);
+ expect(cursor.sessionState).toEqual(nextState);
});
it("claims the current continuation when no address history was recorded", async () => {
@@ -48,10 +51,82 @@ describe("SessionStateCursor", () => {
sessionState: state(""),
});
- await cursor.apply({ sessionState: state("channel:current") });
+ await cursor.advance((input) =>
+ withSessionStateDelta(input, async () => ({ sessionState: state("channel:current") })),
+ );
expect(claimSessionHooks).toHaveBeenCalledWith([stableToken, "channel:current"]);
});
+
+ it("adopts exactly the state a step returned, including edits it made to its input in place", async () => {
+ const initial = state("channel:initial");
+ const cursor = new SessionStateCursor({
+ inbox: { claimSessionHooks: vi.fn(async () => {}) },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ serializedContext: { "eve.channel": { kind: "slack", state: { threadTs: "1.0" } } },
+ sessionState: initial,
+ });
+ let returned: unknown;
+
+ await cursor.advance(async ({ serializedContext, sessionState }) => {
+ // The workflow hands the step a deserialized copy and the body a deserialized result.
+ const input = structuredClone({ serializedContext, sessionState });
+ const result = await withSessionStateDelta(input, async (values) => {
+ const channel = values.serializedContext["eve.channel"] as {
+ state: Record<string, unknown>;
+ };
+ channel.state.threadTs = "2.0";
+ const session = values.sessionState.snapshot.session;
+ const next = {
+ serializedContext: values.serializedContext,
+ sessionState: {
+ ...values.sessionState,
+ snapshot: {
+ session: {
+ ...session,
+ history: [
+ ...session.history,
+ { content: "Bob's reply", role: "assistant" as const },
+ ],
+ },
+ },
+ },
+ };
+ returned = structuredClone(next);
+ return next;
+ });
+ return structuredClone(result);
+ });
+
+ expect({
+ serializedContext: cursor.serializedContext,
+ sessionState: cursor.sessionState,
+ }).toStrictEqual(returned);
+ });
+
+ it("rejects a step's delta when another step changed the state while it ran", async () => {
+ const cursor = new SessionStateCursor({
+ inbox: { claimSessionHooks: vi.fn(async () => {}) },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state("channel:initial"),
+ });
+ const { promise: released, resolve: release } = Promise.withResolvers<void>();
+
+ const slow = cursor.advance((input) =>
+ withSessionStateDelta(input, async () => {
+ await released;
+ return { sessionState: state("channel:slow") };
+ }),
+ );
+ await cursor.advance((input) =>
+ withSessionStateDelta(input, async () => ({ sessionState: state("channel:fast") })),
+ );
+ release();
+
+ await expect(slow).rejects.toThrow("Session state changed while a step ran");
+ expect(cursor.sessionState.continuationToken).toBe("channel:fast");
+ });
});
function state(continuationToken: string): DurableSessionState {
diff --git a/packages/eve/src/execution/session/state-cursor.ts b/packages/eve/src/execution/session/state-cursor.ts
index 63c96f1d0..38503c13d 100644
--- a/packages/eve/src/execution/session/state-cursor.ts
+++ b/packages/eve/src/execution/session/state-cursor.ts
@@ -1,26 +1,25 @@
import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { SessionStepState } from "#execution/publish-session-events.js";
import { sessionHookTokens } from "#execution/session/hook-tokens.js";
+import {
+ applySessionStateDelta,
+ type SessionStateTransition,
+ type SessionStateValues,
+} from "#execution/session/state-delta.js";
import type { SessionInboxOwnership } from "#execution/session-inbox/inbox.js";
-/** A durable-state transition; absent fields keep the cursor's current value. */
-export interface SessionStateTransition {
- readonly serializedContext?: Record<string, unknown>;
- readonly sessionState?: DurableSessionState;
-}
-
/**
- * The one mutable serialized-context / session-state pair owned by the
- * workflow executing a session. Steps return transitions; the cursor adopts
- * them and claims any continuation address a step introduced, so every hook
- * the session answers to is registered before the next step runs.
+ * The one serialized-context / session-state pair owned by the workflow
+ * executing a session. Steps run against it and return deltas; the cursor
+ * applies each to the state its step was given and claims any continuation
+ * address the step introduced, so every hook the session answers to is
+ * registered before the next step runs.
*/
export class SessionStateCursor {
readonly sessionWritable: WritableStream<Uint8Array>;
private readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
- private currentSerializedContext: Record<string, unknown>;
- private currentSessionState: DurableSessionState;
+ private values: SessionStateValues;
constructor(input: {
readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
@@ -30,33 +29,39 @@ export class SessionStateCursor {
}) {
this.inbox = input.inbox;
this.sessionWritable = input.sessionWritable;
- this.currentSerializedContext = input.serializedContext;
- this.currentSessionState = input.sessionState;
+ this.values = { serializedContext: input.serializedContext, sessionState: input.sessionState };
}
get serializedContext(): Record<string, unknown> {
- return this.currentSerializedContext;
+ return this.values.serializedContext;
}
get sessionState(): DurableSessionState {
- return this.currentSessionState;
+ return this.values.sessionState;
}
- /** Applies a transition after claiming every continuation address it introduced. */
- async apply(transition: SessionStateTransition): Promise<void> {
- const serializedContext = transition.serializedContext ?? this.currentSerializedContext;
- const sessionState = transition.sessionState ?? this.currentSessionState;
- await this.inbox.claimSessionHooks(sessionHookTokens({ serializedContext, sessionState }));
- this.currentSerializedContext = serializedContext;
- this.currentSessionState = sessionState;
+ /**
+ * Runs a session-changing step against the current state and adopts the
+ * delta it returns. A delta describes a change to exactly the state its step
+ * was given, so state that another step changed in the meantime is a
+ * sequencing bug, never a merge.
+ */
+ async advance<T extends SessionStateTransition>(
+ step: (state: SessionStepState) => Promise<T>,
+ ): Promise<T> {
+ const base = this.values;
+ const result = await step(this.stepState());
+ const next = applySessionStateDelta(base, result.stateDelta);
+ await this.inbox.claimSessionHooks(sessionHookTokens(next));
+ if (this.values !== base) {
+ throw new Error("Session state changed while a step ran, so its state delta cannot apply.");
+ }
+ this.values = next;
+ return result;
}
/** The session's stream and current state, spread into a step's input. */
stepState(): SessionStepState {
- return {
- serializedContext: this.currentSerializedContext,
- sessionState: this.currentSessionState,
- sessionWritable: this.sessionWritable,
- };
+ return { ...this.values, sessionWritable: this.sessionWritable };
}
}
diff --git a/packages/eve/src/execution/session/state-delta.ts b/packages/eve/src/execution/session/state-delta.ts
new file mode 100644
index 000000000..6fd5f670f
--- /dev/null
+++ b/packages/eve/src/execution/session/state-delta.ts
@@ -0,0 +1,72 @@
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+import { applyValueDelta, diffValue, snapshotValue, type ValueDelta } from "#shared/value-delta.js";
+
+/** The durable values a session workflow threads through its steps. */
+export interface SessionStateValues {
+ readonly serializedContext: Record<string, unknown>;
+ readonly sessionState: DurableSessionState;
+}
+
+/** How a step changed the session's values; an absent value is unchanged. */
+export interface SessionStateDelta {
+ readonly serializedContext?: ValueDelta;
+ readonly sessionState?: ValueDelta;
+}
+
+/** A step result the session workflow adopts through its state cursor. */
+export interface SessionStateTransition {
+ readonly stateDelta: SessionStateDelta;
+}
+
+/** `T` with its session values replaced by the delta that produces them. */
+export type WithSessionStateDelta<T> = T extends unknown
+ ? Omit<T, keyof SessionStateValues> & SessionStateTransition
+ : never;
+
+/**
+ * Runs a session step's work and returns its result with the session values
+ * it produced replaced by their delta from the values the step was given.
+ *
+ * Workflow replay reads every step's output but no step's input, so a step
+ * that returns only what changed keeps both replay and storage from carrying
+ * the whole session once per step. The workflow body applies the delta to the
+ * values it passed in; see {@link applySessionStateDelta}.
+ *
+ * The input is snapshotted before `work` runs because step code may edit it
+ * in place, as a channel adapter does with its state.
+ */
+export async function withSessionStateDelta<
+ I extends Partial<SessionStateValues>,
+ R extends Partial<SessionStateValues>,
+>(input: I, work: (input: I) => Promise<R>): Promise<WithSessionStateDelta<R>>;
+export async function withSessionStateDelta(
+ input: Partial<SessionStateValues>,
+ work: (input: Partial<SessionStateValues>) => Promise<Partial<SessionStateValues>>,
+): Promise<SessionStateTransition> {
+ const base = {
+ serializedContext: snapshotValue(input.serializedContext),
+ sessionState: snapshotValue(input.sessionState),
+ };
+ const { serializedContext, sessionState, ...result } = await work(input);
+ const stateDelta: { -readonly [K in keyof SessionStateDelta]: SessionStateDelta[K] } = {};
+ const contextDelta =
+ serializedContext === undefined
+ ? undefined
+ : diffValue(base.serializedContext, serializedContext);
+ if (contextDelta !== undefined) stateDelta.serializedContext = contextDelta;
+ const sessionDelta =
+ sessionState === undefined ? undefined : diffValue(base.sessionState, sessionState);
+ if (sessionDelta !== undefined) stateDelta.sessionState = sessionDelta;
+ return { ...result, stateDelta };
+}
+
+/** Applies a step's delta to the values that step was given. */
+export function applySessionStateDelta(
+ values: SessionStateValues,
+ delta: SessionStateDelta,
+): SessionStateValues {
+ return {
+ serializedContext: applyValueDelta(values.serializedContext, delta.serializedContext),
+ sessionState: applyValueDelta(values.sessionState, delta.sessionState),
+ };
+}
diff --git a/packages/eve/src/execution/session/step-agent-starts.ts b/packages/eve/src/execution/session/step-agent-starts.ts
index 601b4d765..14d6f9bcc 100644
--- a/packages/eve/src/execution/session/step-agent-starts.ts
+++ b/packages/eve/src/execution/session/step-agent-starts.ts
@@ -11,7 +11,7 @@ import { emitAgentStartedStep } from "#execution/tools/workflow/emit-workflow-to
* 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 result replaces the session state at the boundary, so nothing
+ * 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
diff --git a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
index 092560b02..2930ac7a3 100644
--- a/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
+++ b/packages/eve/src/execution/session/turn-connection-approval.integration.test.ts
@@ -6,6 +6,7 @@ import { AuthKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";
import { serializeContext } from "#context/serialize.js";
import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
import { turnStep } from "#execution/session/turn-step.js";
+import { runSessionStateStep } from "#internal/testing/session-state-step.js";
import type { DurableStepResult, TurnStepPayload } from "#execution/session/turn-step-types.js";
import {
getApprovalAuditState,
@@ -262,7 +263,7 @@ function setup(
};
const events: Array<{ type: string; data: Record<string, unknown> }> = [];
async function step(input?: TurnStepPayload): Promise<DurableStepResult> {
- const result = await turnStep({
+ const stepInput = {
...snapshot,
input,
sessionWritable: new WritableStream<Uint8Array>({
@@ -273,8 +274,9 @@ function setup(
}
},
}),
- });
- snapshot = result;
+ };
+ const result = await runSessionStateStep(stepInput, turnStep);
+ snapshot = { serializedContext: result.serializedContext, sessionState: result.sessionState };
return result;
}
return {
diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.ts
index 3d83e18ed..e4a4c6012 100644
--- a/packages/eve/src/execution/session/turn-step-types.ts
+++ b/packages/eve/src/execution/session/turn-step-types.ts
@@ -1,5 +1,6 @@
import type { DeliverHookPayload, TurnCaller } from "#channel/types.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { WithSessionStateDelta } from "#execution/session/state-delta.js";
import type { TaskToolCall } from "#execution/tasks/calls.js";
import type { SettledTurn } from "#harness/types.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
@@ -39,7 +40,7 @@ interface DurableStepResultFields {
readonly sessionState: DurableSessionState;
}
-/** Result returned by a session-mutating turn step. */
+/** What one turn step's work produces, with the session state it leaves. */
export type DurableStepResult = (
| {
readonly action: "continue" | "done";
@@ -63,6 +64,9 @@ export type DurableStepResult = (
) &
DurableStepResultFields;
+/** What `turnStep` returns: its result, with the session state as a delta. */
+export type TurnStepResult = WithSessionStateDelta<DurableStepResult>;
+
/** The only two ways a locally executed conversational turn can settle. */
export type TurnOutcome = {
/**
diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.ts
index 873c80588..88f531fd6 100644
--- a/packages/eve/src/execution/session/turn-step.test.ts
+++ b/packages/eve/src/execution/session/turn-step.test.ts
@@ -81,10 +81,11 @@ function turnStep(input: Omit<TurnStepInput, "input"> & { readonly input?: Legac
? { runtimeResults: { results: input.input.results } }
: { control: input.input.kind };
}
- return runTurnStep({ ...input, input: payload });
+ return runSessionStateStep({ ...input, input: payload }, runTurnStep);
}
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
+import { runSessionStateStep } from "#internal/testing/session-state-step.js";
const REQUEST_EVENT = { sequence: 0, stepIndex: 0, turnId: "turn_0" };
@@ -702,7 +703,7 @@ describe("dispatchCoordinationStep", () => {
});
const persisted = vi.mocked(createDurableSessionState).mock.calls.at(-1)?.[0].session;
- expect(result.sessionState).not.toBe(sessionState);
+ expect(result.stateDelta.sessionState).toBeDefined();
expect(getPendingCoordinationBatch(persisted?.state)?.event.turnId).toBe("turn_3");
});
});
@@ -3049,14 +3050,17 @@ describe("runProxySubagentEventStep", () => {
continuationToken: "http:proxy-test",
});
- const result = await runProxySubagentEventStep({
- hookPayload: buildHookPayload(),
- sessionWritable: createTestWritable(),
- serializedContext: buildSerializedContextForAdapter(cachingAdapter, {
- acceptedForwardedTracePolicy: true,
- }),
- sessionState,
- });
+ const result = await runSessionStateStep(
+ {
+ hookPayload: buildHookPayload(),
+ sessionWritable: createTestWritable(),
+ serializedContext: buildSerializedContextForAdapter(cachingAdapter, {
+ acceptedForwardedTracePolicy: true,
+ }),
+ sessionState,
+ },
+ runProxySubagentEventStep,
+ );
// The updated serialized context must carry the adapter state
// mutation so the session loop can thread it into the next
@@ -3118,12 +3122,15 @@ describe("runProxySubagentEventStep", () => {
continuationToken: "http:proxy-test",
});
- const result = await runProxySubagentEventStep({
- hookPayload: buildHookPayload(),
- sessionWritable: createTestWritable(),
- serializedContext: buildSerializedContextForAdapter(aliasingAdapter),
- sessionState,
- });
+ const result = await runSessionStateStep(
+ {
+ hookPayload: buildHookPayload(),
+ sessionWritable: createTestWritable(),
+ serializedContext: buildSerializedContextForAdapter(aliasingAdapter),
+ sessionState,
+ },
+ runProxySubagentEventStep,
+ );
expect(result.sessionState.continuationToken).toBe("http:proxy-second");
expect(result.serializedContext[ContinuationTokenKey.name]).toBe("http:proxy-second");
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index 6560fcf36..7f3c1c9e3 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -50,8 +50,13 @@ import {
} from "#harness/messages.js";
import { consumeDeferredStepInput } from "#harness/pending-input-batches.js";
import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";
-import type { DurableStepResult, TurnStepInput } from "#execution/session/turn-step-types.js";
+import type {
+ DurableStepResult,
+ TurnStepInput,
+ TurnStepResult,
+} 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 { createTurnEventHandler } from "#execution/session/turn-event-handler.js";
import { derivePendingState } from "#execution/session/pending-turn-state.js";
@@ -95,9 +100,9 @@ function channelDeliveryErrorCode(error: unknown): string {
export type { TurnStepInput };
/** Runs a bounded batch of harness model steps inside one durable `"use step"` boundary. */
-export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResult> {
+export async function turnStep(input: TurnStepInput): Promise<TurnStepResult> {
"use step";
- return runSessionStep(rawInput);
+ return await withSessionStateDelta(input, runSessionStep);
}
async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult> {
diff --git a/packages/eve/src/execution/session/turn-waiting-step.ts b/packages/eve/src/execution/session/turn-waiting-step.ts
index 8ec34b3f8..7913c976d 100644
--- a/packages/eve/src/execution/session/turn-waiting-step.ts
+++ b/packages/eve/src/execution/session/turn-waiting-step.ts
@@ -1,16 +1,18 @@
+import { publishSessionEvents, type SessionStepState } from "#execution/publish-session-events.js";
import {
- publishSessionEvents,
- type PublishedSessionEvents,
- type SessionStepState,
-} from "#execution/publish-session-events.js";
+ withSessionStateDelta,
+ type SessionStateTransition,
+} from "#execution/session/state-delta.js";
import { createTurnWaitingEvent } from "#protocol/message.js";
/** Publishes `turn.waiting` for the open turn the session workflow just parked. */
export async function publishTurnWaitingStep(
target: SessionStepState,
-): Promise<PublishedSessionEvents> {
+): Promise<SessionStateTransition> {
"use step";
- const { sequence, turnId } = target.sessionState.emissionState;
- return await publishSessionEvents(target, [createTurnWaitingEvent({ sequence, turnId })]);
+ return await withSessionStateDelta(target, async (input) => {
+ const { sequence, turnId } = input.sessionState.emissionState;
+ return await publishSessionEvents(input, [createTurnWaitingEvent({ sequence, turnId })]);
+ });
}
diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.ts
index f7fdaeef9..0a77330d3 100644
--- a/packages/eve/src/execution/session/turn.test.ts
+++ b/packages/eve/src/execution/session/turn.test.ts
@@ -11,6 +11,14 @@ import type { DeliverHookPayload, SessionCapabilities, TurnCaller } from "#chann
import { dispatchCoordinationStep } from "#execution/coordination-dispatch-step.js";
import { routeDeliverToChildren } from "#execution/route-child-delivery.js";
import { publishTurnWaitingStep } from "#execution/session/turn-waiting-step.js";
+import {
+ withSessionStateDelta,
+ type SessionStateValues,
+ type WithSessionStateDelta,
+} from "#execution/session/state-delta.js";
+import type { DurableStepResult, TurnStepInput } from "#execution/session/turn-step-types.js";
+import type { CoordinationDispatchResult } from "#execution/coordination-dispatch-shared.js";
+import type { RoutedDeliverResult } from "#execution/proxied-deliver-step.js";
import {
createTask,
readTaskTable,
@@ -42,24 +50,36 @@ vi.mock("#execution/tools/workflow/interrupt.js", () => ({
interruptWorkflowToolRun: vi.fn(),
}));
vi.mock("#execution/session/turn-waiting-step.js", () => ({
- publishTurnWaitingStep: vi.fn(async ({ serializedContext, sessionState }) => ({
- serializedContext,
- sessionState,
- })),
+ publishTurnWaitingStep: vi.fn(async () => ({ stateDelta: {} })),
}));
beforeEach(() => {
vi.mocked(routeDeliverToChildren)
.mockReset()
- .mockImplementation(async ({ delivery, serializedContext, sessionState }) => ({
- kind: "continue",
- remainder: delivery,
- serializedContext,
- sessionState,
- }));
+ .mockImplementation(
+ routeWork(async ({ delivery, serializedContext, sessionState }) => ({
+ kind: "continue",
+ remainder: delivery,
+ serializedContext,
+ sessionState,
+ })),
+ );
});
afterEach(() => vi.restoreAllMocks());
+/** A mocked session step whose work returns whole state, as the real step's work does. */
+function stepWork<I extends Partial<SessionStateValues>, R extends Partial<SessionStateValues>>(
+ work: (input: I) => Promise<R>,
+): (input: I) => Promise<WithSessionStateDelta<R>> {
+ return (input) => withSessionStateDelta(input, work);
+}
+const turnStepWork = stepWork<TurnStepInput, DurableStepResult>;
+const dispatchWork = stepWork<
+ Parameters<typeof dispatchCoordinationStep>[0],
+ CoordinationDispatchResult
+>;
+const routeWork = stepWork<Parameters<typeof routeDeliverToChildren>[0], RoutedDeliverResult>;
+
describe("SessionExecution checkpoints", () => {
it("retains the durable steering signal across steps until a correction uses it", async () => {
const inbox: SessionInbox = {
@@ -78,22 +98,26 @@ describe("SessionExecution checkpoints", () => {
let signal: AbortSignal | undefined;
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- signal = input.steeringSignal;
- return {
- action: "continue",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- })
- .mockImplementationOnce(async (input) => {
- expect(input.steeringSignal).toBe(signal);
- return {
- action: "done",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ signal = input.steeringSignal;
+ return {
+ action: "continue",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ expect(input.steeringSignal).toBe(signal);
+ return {
+ action: "done",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);
expect(turnStep).toHaveBeenCalledTimes(2);
});
@@ -124,19 +148,21 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- const correction = { kind: "deliver", payloads: [{ message: "Correction" }] } as const;
- pending.push(correction, { kind });
- deliver(correction);
- interrupt({ kind });
- expect(input.steeringSignal?.aborted).toBe(true);
- expect(input.abortSignal?.aborted).toBe(true);
- return {
- action: "steered",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ const correction = { kind: "deliver", payloads: [{ message: "Correction" }] } as const;
+ pending.push(correction, { kind });
+ deliver(correction);
+ interrupt({ kind });
+ expect(input.steeringSignal?.aborted).toBe(true);
+ expect(input.abortSignal?.aborted).toBe(true);
+ return {
+ action: "steered",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
await expect(
createExecution({ inbox, sessionState: state("") }).runTurn(undefined),
).resolves.toEqual({ cancelled: true, kind: "park" });
@@ -184,33 +210,39 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- pending.push(first);
- notify(first);
- return {
- action: "steered",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- })
- .mockImplementationOnce(async (input) => {
- expect(input.input?.delivery?.payloads).toEqual(first.payloads);
- expect(input.steeringSignal?.aborted).toBe(true);
- return {
- action: "steered",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- })
- .mockImplementationOnce(async (input) => {
- expect(input.input?.delivery?.payloads).toEqual(second.payloads);
- expect(input.steeringSignal?.aborted).toBe(false);
- return {
- action: "done",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ pending.push(first);
+ notify(first);
+ return {
+ action: "steered",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ expect(input.input?.delivery?.payloads).toEqual(first.payloads);
+ expect(input.steeringSignal?.aborted).toBe(true);
+ return {
+ action: "steered",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ expect(input.input?.delivery?.payloads).toEqual(second.payloads);
+ expect(input.steeringSignal?.aborted).toBe(false);
+ return {
+ action: "done",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);
expect(turnStep).toHaveBeenCalledTimes(3);
});
@@ -236,33 +268,37 @@ describe("SessionExecution checkpoints", () => {
vi.mocked(cancelDescendantTurnsStep).mockClear();
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- for (const message of ["Actually 2025", "Include the MVP"]) {
- const delivery = { kind: "deliver", payloads: [{ message }] } as const;
- pending.push(delivery);
- notify(delivery);
- }
- expect(input.steeringSignal?.aborted).toBe(true);
- expect(input.abortSignal?.aborted).toBe(false);
- return {
- action: "steered",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- })
- .mockImplementationOnce(async (input) => {
- expect(input.steeringSignal?.aborted).toBe(false);
- expect(input.input?.delivery?.payloads.map((payload) => payload.message)).toEqual([
- "Actually 2025",
- "Include the MVP",
- ]);
- return {
- action: "done",
- output: "Corrected",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ for (const message of ["Actually 2025", "Include the MVP"]) {
+ const delivery = { kind: "deliver", payloads: [{ message }] } as const;
+ pending.push(delivery);
+ notify(delivery);
+ }
+ expect(input.steeringSignal?.aborted).toBe(true);
+ expect(input.abortSignal?.aborted).toBe(false);
+ return {
+ action: "steered",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ expect(input.steeringSignal?.aborted).toBe(false);
+ expect(input.input?.delivery?.payloads.map((payload) => payload.message)).toEqual([
+ "Actually 2025",
+ "Include the MVP",
+ ]);
+ return {
+ action: "done",
+ output: "Corrected",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
const execution = createExecution({ inbox, sessionState: state("") });
await expect(
execution.runTurn({ delivery: { kind: "deliver", payloads: [{ message: "2026?" }] } }),
@@ -303,24 +339,28 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- pending.push(correction);
- notify(correction);
- expect(input.steeringSignal?.aborted).toBe(true);
- return {
- action: "steered",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- })
- .mockImplementationOnce(async (input) => {
- expect(input.input?.delivery?.payloads).toEqual(correction.payloads);
- return {
- action: "done",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ pending.push(correction);
+ notify(correction);
+ expect(input.steeringSignal?.aborted).toBe(true);
+ return {
+ action: "steered",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ expect(input.input?.delivery?.payloads).toEqual(correction.payloads);
+ return {
+ action: "done",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
await expect(
createExecution({ inbox, sessionState: state("") }).runTurn(
@@ -360,15 +400,17 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- notify(payload as SessionInboxPayload);
- expect(input.steeringSignal?.aborted).toBe(false);
- return {
- action: "done",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ notify(payload as SessionInboxPayload);
+ expect(input.steeringSignal?.aborted).toBe(false);
+ return {
+ action: "done",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
await createExecution({ inbox, sessionState: state("") }).runTurn(undefined);
},
);
@@ -393,19 +435,23 @@ describe("SessionExecution checkpoints", () => {
const execution = createExecution({ inbox, sessionState });
vi.mocked(turnStep)
.mockReset()
- .mockResolvedValue({
- action: "park",
- pendingCoordinationCallIds: ["hold-call"],
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
+ .mockImplementation(
+ turnStepWork(async () => ({
+ action: "park",
+ pendingCoordinationCallIds: ["hold-call"],
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ serializedContext: {},
+ sessionState,
+ })),
+ );
+ vi.mocked(dispatchCoordinationStep).mockImplementation(
+ dispatchWork(async () => ({
+ results: [],
serializedContext: {},
sessionState,
- });
- vi.mocked(dispatchCoordinationStep).mockResolvedValue({
- results: [],
- serializedContext: {},
- sessionState,
- });
+ })),
+ );
await expect(
execution.runTurn({
@@ -446,15 +492,17 @@ describe("SessionExecution checkpoints", () => {
restore: vi.fn(),
};
const execution = createExecution({ inbox, queue, sessionState });
- vi.mocked(turnStep).mockImplementationOnce(async (input) => {
- interrupt?.({ kind: "cancel" });
- await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));
- return {
- action: "cancelled",
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- };
- });
+ vi.mocked(turnStep).mockImplementationOnce(
+ turnStepWork(async (input) => {
+ interrupt?.({ kind: "cancel" });
+ await vi.waitFor(() => expect(input.abortSignal?.aborted).toBe(true));
+ return {
+ action: "cancelled",
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
+ }),
+ );
await expect(
execution.runTurn({
@@ -494,27 +542,33 @@ describe("SessionExecution checkpoints", () => {
const execution = createExecution({ inbox, sessionState });
vi.mocked(turnStep)
.mockReset()
- .mockResolvedValueOnce({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingCoordinationCallIds: ["hold-call"],
- serializedContext: {},
- sessionState,
- })
- .mockResolvedValueOnce({
- action: "done",
- output: "done",
- serializedContext: {},
- sessionState,
- });
+ .mockImplementationOnce(
+ turnStepWork(async () => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["hold-call"],
+ serializedContext: {},
+ sessionState,
+ })),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async () => ({
+ action: "done",
+ output: "done",
+ serializedContext: {},
+ sessionState,
+ })),
+ );
vi.mocked(dispatchCoordinationStep)
.mockReset()
- .mockResolvedValue({
- results: [actionResult],
- serializedContext: {},
- sessionState,
- });
+ .mockImplementation(
+ dispatchWork(async () => ({
+ results: [actionResult],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
await expect(
execution.runTurn({
@@ -553,14 +607,16 @@ describe("SessionExecution checkpoints", () => {
const execution = createExecution({ inbox, queue, sessionState: state("") });
vi.mocked(turnStep)
.mockReset()
- .mockImplementation(async (input) => ({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- settled: { output: "Done." },
- }));
+ .mockImplementation(
+ turnStepWork(async (input) => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ settled: { output: "Done." },
+ })),
+ );
await expect(
execution.runTurn({
@@ -607,13 +663,15 @@ describe("SessionExecution checkpoints", () => {
});
vi.mocked(turnStep)
.mockReset()
- .mockImplementation(async (input) => ({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: true,
- serializedContext: input.serializedContext,
- sessionState: input.sessionState,
- }));
+ .mockImplementation(
+ turnStepWork(async (input) => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: true,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ })),
+ );
const turn = execution.runTurn({
delivery: { kind: "deliver", payloads: [{ message: "Deploy the release." }] },
@@ -656,23 +714,25 @@ describe("SessionExecution checkpoints", () => {
vi.mocked(cancelDescendantTurnsStep).mockClear();
vi.mocked(turnStep)
.mockReset()
- .mockImplementationOnce(async (input) => {
- interrupt(cancel);
- expect(input.abortSignal?.aborted).toBe(true);
- return {
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- serializedContext: input.serializedContext,
- sessionState: completedState,
- settled,
- };
- });
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ interrupt(cancel);
+ expect(input.abortSignal?.aborted).toBe(true);
+ return {
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ serializedContext: input.serializedContext,
+ sessionState: completedState,
+ settled,
+ };
+ }),
+ );
await expect(execution.runTurn(undefined)).resolves.toMatchObject({
kind: "park",
settled,
});
- expect(execution.cursor.sessionState).toBe(completedState);
+ expect(execution.cursor.sessionState).toEqual(completedState);
expect(cancelDescendantTurnsStep).not.toHaveBeenCalled();
expect(queue.pendingCount).toBe(1);
});
@@ -699,25 +759,31 @@ describe("SessionExecution checkpoints", () => {
restore: vi.fn(),
};
const execution = createExecution({ inbox, queue, sessionState });
- vi.mocked(turnStep).mockResolvedValue({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingCoordinationCallIds: ["child-call"],
- serializedContext: {},
- sessionState,
- });
- vi.mocked(dispatchCoordinationStep).mockResolvedValue({
- results: [],
- serializedContext: {},
- sessionState,
- });
- vi.mocked(routeDeliverToChildren).mockResolvedValue({
- kind: "continue",
- remainder: undefined,
- serializedContext: {},
- sessionState: { ...sessionState, hasProxyInputRequests: false },
- });
+ vi.mocked(turnStep).mockImplementation(
+ turnStepWork(async () => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["child-call"],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
+ vi.mocked(dispatchCoordinationStep).mockImplementation(
+ dispatchWork(async () => ({
+ results: [],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
+ vi.mocked(routeDeliverToChildren).mockImplementation(
+ routeWork(async () => ({
+ kind: "continue",
+ remainder: undefined,
+ serializedContext: {},
+ sessionState: { ...sessionState, hasProxyInputRequests: false },
+ })),
+ );
await expect(
execution.runTurn({
@@ -849,20 +915,24 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockResolvedValue({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingCoordinationCallIds: ["wait-call"],
- pendingTaskToolCalls: [{ callId: "wait-call", kind: "task_wait" }],
+ .mockImplementation(
+ turnStepWork(async () => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["wait-call"],
+ pendingTaskToolCalls: [{ callId: "wait-call", kind: "task_wait" }],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
+ vi.mocked(dispatchCoordinationStep).mockImplementation(
+ dispatchWork(async () => ({
+ results: [],
serializedContext: {},
sessionState,
- });
- vi.mocked(dispatchCoordinationStep).mockResolvedValue({
- results: [],
- serializedContext: {},
- sessionState,
- });
+ })),
+ );
await expect(
createExecution({ inbox, sessionState }).runTurn({
@@ -930,17 +1000,21 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockResolvedValue({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingCoordinationCallIds: ["hold-call"],
- serializedContext: {},
- sessionState,
- });
+ .mockImplementation(
+ turnStepWork(async () => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["hold-call"],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
vi.mocked(dispatchCoordinationStep)
.mockReset()
- .mockResolvedValue({ results: [], serializedContext: {}, sessionState });
+ .mockImplementation(
+ dispatchWork(async () => ({ results: [], serializedContext: {}, sessionState })),
+ );
const cursor = new SessionStateCursor({
inbox,
serializedContext: {},
@@ -1021,23 +1095,29 @@ describe("SessionExecution checkpoints", () => {
};
vi.mocked(turnStep)
.mockReset()
- .mockResolvedValueOnce({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingCoordinationCallIds: tools.map((name) => `${name}-call`),
- serializedContext: {},
- sessionState,
- })
- .mockResolvedValueOnce({
- action: "done",
- output: "done",
- serializedContext: {},
- sessionState,
- });
+ .mockImplementationOnce(
+ turnStepWork(async () => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: tools.map((name) => `${name}-call`),
+ serializedContext: {},
+ sessionState,
+ })),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async () => ({
+ action: "done",
+ output: "done",
+ serializedContext: {},
+ sessionState,
+ })),
+ );
vi.mocked(dispatchCoordinationStep)
.mockReset()
- .mockResolvedValue({ results: [], serializedContext: {}, sessionState });
+ .mockImplementation(
+ dispatchWork(async () => ({ results: [], serializedContext: {}, sessionState })),
+ );
await expect(
createExecution({ inbox, sessionState }).runTurn({
@@ -1089,27 +1169,38 @@ describe("SessionExecution checkpoints", () => {
onInterrupt: vi.fn(() => () => {}),
restore: vi.fn(),
};
- vi.mocked(dispatchCoordinationStep).mockReset().mockResolvedValue({
- results: [],
- serializedContext: {},
- sessionState,
- });
+ vi.mocked(dispatchCoordinationStep)
+ .mockReset()
+ .mockImplementation(
+ dispatchWork(async () => ({
+ results: [],
+ serializedContext: {},
+ sessionState,
+ })),
+ );
let continuation: { delivery?: DeliverHookPayload; steered?: boolean } = {};
vi.mocked(turnStep)
.mockReset()
- .mockResolvedValueOnce({
- action: "park",
- hasPendingAuthorization: false,
- hasPendingInputBatch: false,
- pendingCoordinationCallIds: ["wait-call"],
- pendingTaskToolCalls: [{ callId: "wait-call", kind: "task_wait" }],
- serializedContext: {},
- sessionState,
- })
- .mockImplementationOnce(async (input) => {
- continuation = { delivery: input.input?.delivery, steered: input.steeringSignal?.aborted };
- return { action: "done", output: "done", serializedContext: {}, sessionState };
- });
+ .mockImplementationOnce(
+ turnStepWork(async () => ({
+ action: "park",
+ hasPendingAuthorization: false,
+ hasPendingInputBatch: false,
+ pendingCoordinationCallIds: ["wait-call"],
+ pendingTaskToolCalls: [{ callId: "wait-call", kind: "task_wait" }],
+ serializedContext: {},
+ sessionState,
+ })),
+ )
+ .mockImplementationOnce(
+ turnStepWork(async (input) => {
+ continuation = {
+ delivery: input.input?.delivery,
+ steered: input.steeringSignal?.aborted,
+ };
+ return { action: "done", output: "done", serializedContext: {}, sessionState };
+ }),
+ );
await expect(
createExecution({ inbox, sessionState }).runTurn({
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index 9649f0863..eb6fcabee 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -40,7 +40,6 @@ import { handleWorkflowToolRunMessage } from "#execution/session-workflow-tool-r
import { interruptWorkflowToolRun } from "#execution/tools/workflow/interrupt.js";
import type { WorkflowToolRunMessage } from "#execution/tools/workflow/messages.js";
import type {
- DurableStepResult,
RuntimeActionResultStepInput,
TurnOutcome,
TurnStepPayload,
@@ -138,22 +137,20 @@ export class SessionExecution {
while (true) {
const { cursor } = this.input;
- const result: DurableStepResult = await turn.agentStarts.publishWhile(
- turnStep({
- ...cursor.stepState(),
- abortSignal: turn.signal,
- input: nextStepInput,
- steeringSignal: turn.steeringSignal,
- }),
+ const result = await cursor.advance((state) =>
+ turn.agentStarts.publishWhile(
+ 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 cursor.apply({
- serializedContext: result.serializedContext,
- sessionState: result.sessionState,
- });
await turn.admitBoundary();
await this.handleAdmittedTaskEvents(turn);
@@ -181,15 +178,16 @@ export class SessionExecution {
}
if (pendingCallIds !== undefined && result.action === "park") {
- const dispatchResult = await dispatchCoordinationStep({
- action: result.action,
- workflowToolRunOwner: {
- inbox: sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId)),
- },
- ...cursor.stepState(),
- });
+ const dispatchResult = await cursor.advance((state) =>
+ dispatchCoordinationStep({
+ action: result.action,
+ workflowToolRunOwner: {
+ inbox: sessionInboxHookToken(sessionCommandHookToken(this.input.sessionId)),
+ },
+ ...state,
+ }),
+ );
const initialAcceptedAtMs = dispatchResult.results.length === 0 ? undefined : Date.now();
- await cursor.apply(dispatchResult);
const runtimeResults = await this.waitForRuntimeActionResults({
initialAcceptedAtMs,
@@ -229,8 +227,7 @@ export class SessionExecution {
message: WorkflowToolRunMessage,
): Promise<RuntimeActionResult | undefined> {
if (isTaskRunMessage(message)) {
- const { cursor } = this.input;
- await cursor.apply(await applyTaskRunMessageStep({ ...cursor.stepState(), message }));
+ await this.input.cursor.advance((state) => applyTaskRunMessageStep({ ...state, message }));
return undefined;
}
return await handleWorkflowToolRunMessage({
@@ -397,10 +394,7 @@ export class SessionExecution {
else accept(await answerTaskCancel(this.input.cursor, call));
}
const parked = this.resolveTaskWaits(waits, false, accept);
- if (parked.length > 0) {
- const { cursor } = this.input;
- await cursor.apply(await publishTurnWaitingStep(cursor.stepState()));
- }
+ if (parked.length > 0) await this.input.cursor.advance(publishTurnWaitingStep);
return parked;
}
@@ -658,11 +652,9 @@ class ActiveTurn {
continue;
}
this.routedToChildren.add(sequence);
- const routed = await routeDeliverToChildren({
- delivery,
- ...this.input.cursor.stepState(),
- });
- await this.input.cursor.apply(routed);
+ const routed = await this.input.cursor.advance((state) =>
+ routeDeliverToChildren({ delivery, ...state }),
+ );
if (routed.kind === "cancel-turn") {
this.input.queue.replaceDelivery(sequence, undefined);
this.admitted.delete(sequence);
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.test.ts
index 97cab8126..482a84148 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.test.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.test.ts
@@ -10,6 +10,7 @@ import {
takeSessionUsageDelta,
} from "#harness/turn-tag-state.js";
import { createTestSessionState } from "#internal/testing/session-state.js";
+import { runSessionStateStep } from "#internal/testing/session-state-step.js";
// The turn's stream events and channel context are not under test; the usage
// the step reports and the session it persists are.
@@ -60,12 +61,15 @@ describe("settleCancelledTurnStep", () => {
// Its next turn spent 50 more before Alice cancelled it.
const cancelling = spend(settled, 50, "turn_2");
- const result = await settleCancelledTurnStep({
- reportUsage,
- serializedContext: {},
- sessionState: { ...base, snapshot: { session: cancelling } },
- sessionWritable: new WritableStream<Uint8Array>(),
- });
+ const result = await runSessionStateStep(
+ {
+ reportUsage,
+ serializedContext: {},
+ sessionState: { ...base, snapshot: { session: cancelling } },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ },
+ settleCancelledTurnStep,
+ );
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.ts
index a9648d777..5787280c5 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -10,6 +10,10 @@ import {
} from "#execution/durable-session-store.js";
import { withSessionEventEmitter } from "#execution/publish-session-events.js";
import { reconcileSessionContinuationToken } from "#execution/reconcile-session-continuation-token.js";
+import {
+ withSessionStateDelta,
+ type WithSessionStateDelta,
+} from "#execution/session/state-delta.js";
import { emitCancelledTurn } from "#harness/cancelled-turn-emission.js";
import { clearPendingSessionLimitPrompt } from "#harness/input-requests.js";
import { getHarnessEmissionState, setHarnessEmissionState } from "#harness/emission.js";
@@ -25,13 +29,7 @@ export interface CancelledTurnSettleResult {
readonly usage?: TokenUsage;
}
-/**
- * Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,
- * drops pending coordination state, and persists the between-turns
- * session. Runs in the owner, whose wake sources exclude the
- * cancel hook, so a queued cancel wake cannot re-dispatch it.
- */
-export async function settleCancelledTurnStep(input: {
+interface CancelledTurnSettleInput {
/**
* Whether a caller receives the turn's usage. Only then is it marked
* reported; otherwise the next settled turn reports it.
@@ -40,9 +38,25 @@ export async function settleCancelledTurnStep(input: {
readonly sessionWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
-}): Promise<CancelledTurnSettleResult> {
+}
+
+/**
+ * Settles one cancelled turn: emits `turn.cancelled` → `session.waiting`,
+ * drops pending coordination state, and persists the between-turns
+ * session. Runs in the owner, whose wake sources exclude the
+ * cancel hook, so a queued cancel wake cannot re-dispatch it.
+ */
+export async function settleCancelledTurnStep(
+ input: CancelledTurnSettleInput,
+): Promise<WithSessionStateDelta<CancelledTurnSettleResult>> {
"use step";
+ return await withSessionStateDelta(input, settleCancelledTurn);
+}
+/** {@link settleCancelledTurnStep} for a caller that is already a step and adopts the whole state. */
+export async function settleCancelledTurn(
+ input: CancelledTurnSettleInput,
+): Promise<CancelledTurnSettleResult> {
const durableSession = readDurableSession(input.sessionState);
const ctx = await deserializeContext(input.serializedContext);
const emitted = await withSessionEventEmitter(
diff --git a/packages/eve/src/execution/tasks/session.ts b/packages/eve/src/execution/tasks/session.ts
index 1ebdde2c9..215109523 100644
--- a/packages/eve/src/execution/tasks/session.ts
+++ b/packages/eve/src/execution/tasks/session.ts
@@ -39,7 +39,7 @@ export function sessionTaskTable(cursor: SessionStateCursor): TaskTable {
export async function cancelWorkingTasks(cursor: SessionStateCursor): Promise<void> {
const taskIds = workingTasks(sessionTaskTable(cursor)).map((record) => record.id);
if (taskIds.length === 0) return;
- await cursor.apply(await cancelTasksStep({ ...cursor.stepState(), taskIds }));
+ await cursor.advance((state) => cancelTasksStep({ ...state, taskIds }));
}
export async function answerTaskCancel(
@@ -55,7 +55,7 @@ export async function answerTaskCancel(
return { ...taskToolResult(call.callId, TASK_CANCEL_TOOL_NAME, error), isError: true };
}
if (result.status === "cancelled") {
- await cursor.apply(await cancelTasksStep({ ...cursor.stepState(), taskIds: [call.taskId] }));
+ await cursor.advance((state) => cancelTasksStep({ ...state, taskIds: [call.taskId] }));
}
return taskToolResult(
call.callId,
diff --git a/packages/eve/src/execution/tasks/steps.ts b/packages/eve/src/execution/tasks/steps.ts
index 66ecc517d..77cbd4479 100644
--- a/packages/eve/src/execution/tasks/steps.ts
+++ b/packages/eve/src/execution/tasks/steps.ts
@@ -28,6 +28,10 @@ import {
type PublishedSessionEvents,
type SessionStepState,
} from "#execution/publish-session-events.js";
+import {
+ withSessionStateDelta,
+ type SessionStateTransition,
+} from "#execution/session/state-delta.js";
import type {
WorkflowToolRunControlMessage,
WorkflowToolRunMessage,
@@ -50,9 +54,14 @@ const TASK_CANCEL_REASON = "The task was cancelled.";
/** Applies one message from a task's run: started, a reply, usage no reply carried, or the run's outcome. */
export async function applyTaskRunMessageStep(
input: SessionStepState & { readonly message: TaskRunMessage },
-): Promise<PublishedSessionEvents> {
+): Promise<SessionStateTransition> {
"use step";
+ return await withSessionStateDelta(input, applyTaskRunMessage);
+}
+async function applyTaskRunMessage(
+ input: SessionStepState & { readonly message: TaskRunMessage },
+): Promise<PublishedSessionEvents> {
const { message } = input;
const taskId = message.from.taskId;
let session = readDurableSession(input.sessionState);
@@ -104,9 +113,14 @@ export async function applyTaskRunMessageStep(
*/
export async function cancelTasksStep(
input: SessionStepState & { readonly taskIds: readonly string[] },
-): Promise<PublishedSessionEvents> {
+): Promise<SessionStateTransition> {
"use step";
+ return await withSessionStateDelta(input, cancelTasks);
+}
+async function cancelTasks(
+ input: SessionStepState & { readonly taskIds: readonly string[] },
+): Promise<PublishedSessionEvents> {
const session = readDurableSession(input.sessionState);
let table = readTaskTable(session.state);
const events: TaskSettledStreamEvent[] = [];
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.ts
index f3224e84b..e42b68c5b 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
@@ -1,8 +1,8 @@
+import { publishSessionEvents, type SessionStepState } from "#execution/publish-session-events.js";
import {
- publishSessionEvents,
- type PublishedSessionEvents,
- type SessionStepState,
-} from "#execution/publish-session-events.js";
+ withSessionStateDelta,
+ type SessionStateTransition,
+} from "#execution/session/state-delta.js";
import type {
WorkflowToolRunAgentStartedMessage,
WorkflowToolRunRef,
@@ -17,7 +17,7 @@ export async function emitWorkflowToolRunReportStep(
readonly from: WorkflowToolRunRef;
readonly update: JsonValue;
},
-): Promise<PublishedSessionEvents> {
+): Promise<SessionStateTransition> {
"use step";
const event = createActionPartialEvent({
@@ -30,7 +30,7 @@ export async function emitWorkflowToolRunReportStep(
stepIndex: input.from.stepIndex,
turnId: input.from.turnId,
});
- return await publishSessionEvents(input, [event]);
+ return await withSessionStateDelta(input, (target) => publishSessionEvents(target, [event]));
}
/** Publishes `agent.started` for a session a workflow tool run opened. */
@@ -38,7 +38,7 @@ export async function emitAgentStartedStep(
input: SessionStepState & {
readonly message: WorkflowToolRunAgentStartedMessage;
},
-): Promise<PublishedSessionEvents> {
+): Promise<SessionStateTransition> {
"use step";
const { from, session } = input.message;
@@ -57,5 +57,5 @@ export async function emitAgentStartedStep(
...(from.taskId !== undefined && { taskId: from.taskId }),
turnId: from.turnId,
});
- return await publishSessionEvents(input, [event]);
+ return await withSessionStateDelta(input, (target) => publishSessionEvents(target, [event]));
}
diff --git a/packages/eve/src/execution/tools/workflow/withdraw-step.ts b/packages/eve/src/execution/tools/workflow/withdraw-step.ts
index 97a078148..971f812b6 100644
--- a/packages/eve/src/execution/tools/workflow/withdraw-step.ts
+++ b/packages/eve/src/execution/tools/workflow/withdraw-step.ts
@@ -8,6 +8,10 @@ import {
type PublishedSessionEvents,
type SessionStepState,
} from "#execution/publish-session-events.js";
+import {
+ withSessionStateDelta,
+ type SessionStateTransition,
+} from "#execution/session/state-delta.js";
import type { WorkflowToolRunControlMessage } from "#execution/tools/workflow/messages.js";
import { ignoreGoneTarget } from "#execution/tasks/workflow-target.js";
import { resumeHook } from "#internal/workflow/runtime.js";
@@ -22,14 +26,21 @@ import { createInputResolvedEvent, type UnstampedMessageStreamEvent } from "#pro
* first, so the question resolves from the session's first decision.
*/
export async function withdrawWorkflowToolRunQuestionStep(
- input: SessionStepState & {
- readonly control: string;
- readonly requestId: string;
- readonly runId: string;
- },
-): Promise<PublishedSessionEvents> {
+ input: WithdrawQuestionInput,
+): Promise<SessionStateTransition> {
"use step";
+ return await withSessionStateDelta(input, withdrawWorkflowToolRunQuestion);
+}
+type WithdrawQuestionInput = SessionStepState & {
+ readonly control: string;
+ readonly requestId: string;
+ readonly runId: string;
+};
+
+async function withdrawWorkflowToolRunQuestion(
+ input: WithdrawQuestionInput,
+): Promise<PublishedSessionEvents> {
const session = readDurableSession(input.sessionState);
const withdrawn = withdrawWorkflowAsks(
session,
diff --git a/packages/eve/src/internal/testing/session-state-step.ts b/packages/eve/src/internal/testing/session-state-step.ts
new file mode 100644
index 000000000..b3c68c91c
--- /dev/null
+++ b/packages/eve/src/internal/testing/session-state-step.ts
@@ -0,0 +1,32 @@
+import type { SessionStateTransition, SessionStateValues } from "#execution/session/state-delta.js";
+import { applyValueDelta, snapshotValue } from "#shared/value-delta.js";
+
+type SessionValueKey = keyof SessionStateValues;
+
+/** A step result with its state delta applied to the session values its input carried. */
+export type AppliedSessionStateStep<I, R> = R extends unknown
+ ? Omit<R, "stateDelta"> & Pick<SessionStateValues, Extract<keyof I, SessionValueKey>>
+ : never;
+
+/**
+ * Calls a session step as the session workflow does. A test hands the step its
+ * own objects rather than a deserialized copy, so the values the delta applies
+ * to are snapshotted before the step can edit them in place.
+ */
+export async function runSessionStateStep<
+ I extends Partial<SessionStateValues>,
+ R extends SessionStateTransition,
+>(input: I, step: (input: I) => Promise<R>): Promise<AppliedSessionStateStep<I, R>> {
+ const serializedContext = snapshotValue(input.serializedContext);
+ const sessionState = snapshotValue(input.sessionState);
+ const { stateDelta, ...result } = await step(input);
+ const applied: Partial<SessionStateValues> = {
+ ...(serializedContext !== undefined && {
+ serializedContext: applyValueDelta(serializedContext, stateDelta.serializedContext),
+ }),
+ ...(sessionState !== undefined && {
+ sessionState: applyValueDelta(sessionState, stateDelta.sessionState),
+ }),
+ };
+ return { ...result, ...applied } as AppliedSessionStateStep<I, R>;
+}
diff --git a/packages/eve/src/internal/testing/session-test-helpers.ts b/packages/eve/src/internal/testing/session-test-helpers.ts
index ee6ab3f8c..f81e986a4 100644
--- a/packages/eve/src/internal/testing/session-test-helpers.ts
+++ b/packages/eve/src/internal/testing/session-test-helpers.ts
@@ -1,6 +1,10 @@
import { expect, vi } from "vitest";
-import { hydrateStepReturnValue } from "#compiled/@workflow/core/serialization.js";
-import type { DurableStepResult } from "#execution/session/turn-step-types.js";
+import {
+ hydrateStepArguments,
+ hydrateStepReturnValue,
+} from "#compiled/@workflow/core/serialization.js";
+import { applySessionStateDelta, type SessionStateValues } from "#execution/session/state-delta.js";
+import type { TurnStepInput, TurnStepResult } from "#execution/session/turn-step-types.js";
import { getWorld } from "#internal/workflow/runtime.js";
export async function waitForParkedTurnStep(runId: string, count = 1): Promise<void> {
@@ -16,11 +20,7 @@ export async function waitForParkedTurnStep(runId: string, count = 1): Promise<v
let parked = 0;
for (const step of steps.data) {
if (!step.stepName.endsWith("//turnStep") || step.output === undefined) continue;
- const result: DurableStepResult = await hydrateStepReturnValue(
- step.output,
- runId,
- undefined,
- );
+ const result: TurnStepResult = await hydrateStepReturnValue(step.output, runId, undefined);
if (result.action !== "park") continue;
const events = await world.events.listByCorrelationId({
correlationId: step.stepId,
@@ -34,3 +34,23 @@ export async function waitForParkedTurnStep(runId: string, count = 1): Promise<v
{ timeout: 10_000 },
);
}
+
+/**
+ * The session state each completed `turnStep` of a run left, in step order:
+ * the state the step was given with the delta it returned applied, as the
+ * session workflow adopts it.
+ */
+export async function readTurnStepStates(runId: string): Promise<SessionStateValues[]> {
+ const world = await getWorld();
+ const steps = await world.steps.list({ runId, resolveData: "all", pagination: { limit: 1000 } });
+ const states: SessionStateValues[] = [];
+ for (const step of steps.data) {
+ if (!step.stepName.endsWith("//turnStep") || step.output === undefined) continue;
+ const { args } = (await hydrateStepArguments(step.input, runId, undefined)) as {
+ readonly args: readonly [TurnStepInput];
+ };
+ const result: TurnStepResult = await hydrateStepReturnValue(step.output, runId, undefined);
+ states.push(applySessionStateDelta(args[0], result.stateDelta));
+ }
+ return states;
+}
diff --git a/packages/eve/src/shared/value-delta.test.ts b/packages/eve/src/shared/value-delta.test.ts
new file mode 100644
index 000000000..5b72cbe91
--- /dev/null
+++ b/packages/eve/src/shared/value-delta.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, it } from "vitest";
+
+import { applyValueDelta, diffValue, snapshotValue } from "#shared/value-delta.js";
+
+describe("value deltas", () => {
+ it("rebuild the next value exactly after crossing a serialization boundary", () => {
+ for (let seed = 1; seed <= 300; seed++) {
+ const random = seededRandom(seed);
+ const base = randomValue(random, 4);
+ const next = edit(base, random, 4);
+
+ // The workflow body applies a deserialized delta to its deserialized copy of the base.
+ const rebuilt = applyValueDelta(
+ structuredClone(base),
+ structuredClone(diffValue(base, next)),
+ );
+
+ expect(rebuilt, `seed ${seed}`).toStrictEqual(next);
+ expect(layout(rebuilt), `seed ${seed}`).toBe(layout(next));
+ }
+ });
+
+ it("carry only what changed and share every unchanged entry with the base", () => {
+ const history = Array.from({ length: 50 }, (_, index) => ({
+ content: `Alice's message ${index}`,
+ role: "user",
+ }));
+ const base = {
+ sequence: 4,
+ session: { history, system: "You help Alice and Bob plan their projects." },
+ };
+ const next = {
+ ...base,
+ sequence: 5,
+ session: {
+ ...base.session,
+ history: [...history, { content: "Bob's reply", role: "assistant" }],
+ },
+ };
+
+ const delta = diffValue(base, next);
+ const rebuilt = applyValueDelta(base, delta);
+
+ expect(JSON.stringify(delta)).toContain("Bob's reply");
+ expect(JSON.stringify(delta)).not.toMatch(/Alice's message|You help Alice/);
+ expect(rebuilt).toStrictEqual(next);
+ expect(rebuilt.session.history[0]).toBe(history[0]);
+ expect(diffValue(base, snapshotValue(base))).toBeUndefined();
+ });
+});
+
+type Random = () => number;
+
+const KEYS = ["alice", "bob", "status", "history", "turnId", "1", "10"];
+
+function seededRandom(seed: number): Random {
+ let state = seed;
+ return () => {
+ state = (state + 0x6d2b79f5) | 0;
+ let value = Math.imul(state ^ (state >>> 15), 1 | state);
+ value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function pick<T>(random: Random, values: readonly T[]): T {
+ return values[Math.floor(random() * values.length)]!;
+}
+
+function randomValue(random: Random, depth: number): unknown {
+ const kind = depth === 0 ? pick(random, LEAVES) : pick(random, [...LEAVES, "array", "object"]);
+ switch (kind) {
+ case "array":
+ return Array.from({ length: Math.floor(random() * 4) }, () => randomValue(random, depth - 1));
+ case "object":
+ return Object.fromEntries(
+ KEYS.filter(() => random() < 0.4).map((key) => [key, randomValue(random, depth - 1)]),
+ );
+ case "string":
+ return pick(random, ["", "draft", "ready for Bob"]);
+ case "number":
+ return pick(random, [0, -0, 1, 2.5, Number.NaN]);
+ case "date":
+ return new Date(Math.floor(random() * 4) * 86_400_000);
+ case "bytes":
+ return new Uint8Array([Math.floor(random() * 3)]);
+ default:
+ return pick(random, [true, false, null, undefined]);
+ }
+}
+
+const LEAVES = ["string", "number", "date", "bytes", "literal"] as const;
+
+/** A copy of `value` with random edits, sharing what it leaves alone, as a step's result does. */
+function edit(value: unknown, random: Random, depth: number): unknown {
+ if (random() < 0.3) return value;
+ if (Array.isArray(value)) {
+ const next = value.map((entry) => edit(entry, random, depth - 1));
+ if (random() < 0.3) next.push(randomValue(random, depth - 1));
+ if (random() < 0.2) next.pop();
+ if (random() < 0.2) next.unshift(randomValue(random, depth - 1));
+ return next;
+ }
+ if (
+ value !== null &&
+ typeof value === "object" &&
+ !(value instanceof Date) &&
+ !ArrayBuffer.isView(value)
+ ) {
+ const entries = Object.entries(value).flatMap(([key, entry]): [string, unknown][] =>
+ random() < 0.15 ? [] : [[key, edit(entry, random, depth - 1)]],
+ );
+ if (random() < 0.3) entries.push([pick(random, KEYS), randomValue(random, depth - 1)]);
+ if (random() < 0.2) entries.reverse();
+ return Object.fromEntries(entries);
+ }
+ return random() < 0.5 ? randomValue(random, depth) : value;
+}
+
+/** Key order and `undefined` entries, which structural equality ignores. */
+function layout(value: unknown): string {
+ return JSON.stringify(value, (_key, entry: unknown) =>
+ entry === undefined ? "<undefined>" : entry,
+ );
+}
diff --git a/packages/eve/src/shared/value-delta.ts b/packages/eve/src/shared/value-delta.ts
new file mode 100644
index 000000000..2b7aaaa6b
--- /dev/null
+++ b/packages/eve/src/shared/value-delta.ts
@@ -0,0 +1,164 @@
+/**
+ * Structural deltas between serializable values.
+ *
+ * `applyValueDelta(base, diffValue(base, next))` rebuilds `next` as a
+ * serializer sees it: the same entries, in the same key order, including
+ * entries whose value is `undefined`. Plain objects and arrays change entry by
+ * entry, so the result shares every unchanged entry with `base`. Any other
+ * value is compared by identity and carried whole when it differs, so such
+ * values must be replaced rather than edited in place.
+ */
+export type ValueDelta =
+ | { readonly kind: "value"; readonly value: unknown }
+ | (EntryChanges & {
+ readonly kind: "object";
+ /**
+ * The next object's keys, present only when they are not the base's keys
+ * followed by the added ones: an entry was removed or the order changed.
+ */
+ readonly keys?: readonly string[];
+ })
+ | (EntryChanges & { readonly kind: "array"; readonly length: number });
+
+/** Entry changes by key or index: whole next values in `set`, nested deltas in `patch`. */
+interface EntryChanges {
+ readonly patch?: Readonly<Record<string, ValueDelta>>;
+ readonly set?: Readonly<Record<string, unknown>>;
+}
+
+type PlainObject = Readonly<Record<string, unknown>>;
+
+/**
+ * Copies every plain object and array in `value` and keeps any other value by
+ * reference, so editing `value` in place afterwards leaves the copy intact.
+ */
+export function snapshotValue<T>(value: T): T {
+ if (Array.isArray(value)) return value.map((entry: unknown) => snapshotValue(entry)) as T;
+ if (!isPlainObject(value)) return value;
+ return Object.fromEntries(Object.keys(value).map((key) => [key, snapshotValue(value[key])])) as T;
+}
+
+/** The delta from `base` to `next`, or `undefined` when they are equal. */
+export function diffValue(base: unknown, next: unknown): ValueDelta | undefined {
+ if (Object.is(base, next)) return undefined;
+ if (Array.isArray(base) && Array.isArray(next)) return diffArray(base, next);
+ if (isPlainObject(base) && isPlainObject(next)) return diffObject(base, next);
+ return { kind: "value", value: next };
+}
+
+/** Applies a delta from {@link diffValue} to the value it was computed against. */
+export function applyValueDelta<T>(base: T, delta: ValueDelta | undefined): T {
+ if (delta === undefined) return base;
+ switch (delta.kind) {
+ case "value":
+ return delta.value as T;
+ case "array": {
+ if (!Array.isArray(base)) throw deltaMismatch("an array");
+ const next = base.slice(0, delta.length);
+ // Integer keys enumerate in ascending order, so appended entries stay contiguous.
+ for (const [index, value] of Object.entries(delta.set ?? {})) next[Number(index)] = value;
+ for (const [index, change] of Object.entries(delta.patch ?? {})) {
+ next[Number(index)] = applyValueDelta(base[Number(index)], change);
+ }
+ return next as T;
+ }
+ case "object": {
+ if (!isPlainObject(base)) throw deltaMismatch("an object");
+ const baseKeys = Object.keys(base);
+ const set = delta.set ?? {};
+ const patch = delta.patch ?? {};
+ const keys = delta.keys ?? impliedKeys(baseKeys, set);
+ return Object.fromEntries(
+ keys.map((key) => {
+ if (Object.hasOwn(set, key)) return [key, set[key]];
+ if (Object.hasOwn(patch, key)) return [key, applyValueDelta(base[key], patch[key])];
+ return [key, base[key]];
+ }),
+ ) as T;
+ }
+ }
+}
+
+function diffArray(base: readonly unknown[], next: readonly unknown[]): ValueDelta | undefined {
+ const set: [string, unknown][] = [];
+ const patch: [string, ValueDelta][] = [];
+ let kept = 0;
+ for (let index = 0; index < next.length; index++) {
+ // An entry-wise change cannot express a hole, so the array travels whole.
+ if (!(index in next) || (index < base.length && !(index in base))) {
+ return { kind: "value", value: next };
+ }
+ if (index >= base.length) {
+ set.push([String(index), next[index]]);
+ continue;
+ }
+ const change = diffValue(base[index], next[index]);
+ if (change === undefined) kept++;
+ else if (change.kind === "value") set.push([String(index), change.value]);
+ else patch.push([String(index), change]);
+ }
+ if (set.length === 0 && patch.length === 0 && next.length === base.length) return undefined;
+ if (kept === 0 && patch.length === 0) return { kind: "value", value: next };
+ return { ...entryChanges(set, patch), kind: "array", length: next.length };
+}
+
+function diffObject(base: PlainObject, next: PlainObject): ValueDelta | undefined {
+ const baseKeys = Object.keys(base);
+ const nextKeys = Object.keys(next);
+ const set: [string, unknown][] = [];
+ const patch: [string, ValueDelta][] = [];
+ let kept = 0;
+ for (const key of nextKeys) {
+ if (!Object.hasOwn(base, key)) {
+ set.push([key, next[key]]);
+ continue;
+ }
+ const change = diffValue(base[key], next[key]);
+ if (change === undefined) kept++;
+ else if (change.kind === "value") set.push([key, change.value]);
+ else patch.push([key, change]);
+ }
+ const changes = entryChanges(set, patch);
+ const keysChanged = !sameKeys(impliedKeys(baseKeys, changes.set ?? {}), nextKeys);
+ if (set.length === 0 && patch.length === 0 && !keysChanged) return undefined;
+ if (kept === 0 && patch.length === 0) return { kind: "value", value: next };
+ return keysChanged
+ ? { ...changes, keys: nextKeys, kind: "object" }
+ : { ...changes, kind: "object" };
+}
+
+function entryChanges(
+ set: readonly (readonly [string, unknown])[],
+ patch: readonly (readonly [string, ValueDelta])[],
+): EntryChanges {
+ const changes: { -readonly [K in keyof EntryChanges]: EntryChanges[K] } = {};
+ if (set.length > 0) changes.set = Object.fromEntries(set);
+ if (patch.length > 0) changes.patch = Object.fromEntries(patch);
+ return changes;
+}
+
+/** The keys an object delta without `keys` produces: the base's, then the added ones. */
+function impliedKeys(
+ baseKeys: readonly string[],
+ set: Readonly<Record<string, unknown>>,
+): readonly string[] {
+ const baseKeySet = new Set(baseKeys);
+ const added = Object.keys(set).filter((key) => !baseKeySet.has(key));
+ return added.length === 0 ? baseKeys : [...baseKeys, ...added];
+}
+
+function sameKeys(left: readonly string[], right: readonly string[]): boolean {
+ return left.length === right.length && left.every((key, index) => key === right[index]);
+}
+
+/** Whether `value` is an object literal: its prototype is some realm's `Object.prototype`. */
+function isPlainObject(value: unknown): value is PlainObject {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
+ const prototype: unknown = Object.getPrototypeOf(value);
+ // Not `=== Object.prototype`: workflow bodies run in their own VM context.
+ return prototype !== null && Object.getPrototypeOf(prototype) === null;
+}
+
+function deltaMismatch(expected: string): Error {
+ return new Error(`Value delta does not match its base: expected ${expected}.`);
+}
diff --git a/packages/eve/src/subagents/adapter.test.ts b/packages/eve/src/subagents/adapter.test.ts
index 1c9e86392..963b829cb 100644
--- a/packages/eve/src/subagents/adapter.test.ts
+++ b/packages/eve/src/subagents/adapter.test.ts
@@ -9,6 +9,7 @@ import { ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import type { InputRequest } from "#shared/input.js";
import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
import { bindTurnCallerContextStep } from "#subagents/parent-notification.js";
+import { runSessionStateStep } from "#internal/testing/session-state-step.js";
const SUBAGENT_INPUT_REQUESTED = SUBAGENT_ADAPTER["input.requested"];
const SUBAGENT_AUTHORIZATION_REQUIRED = SUBAGENT_ADAPTER["authorization.required"];
@@ -159,21 +160,26 @@ describe("SUBAGENT_ADAPTER input.requested handler", () => {
it("forwards continuation HITL to the newly bound parent turn", async () => {
resumeHookMock.mockClear();
- const rebound = await bindTurnCallerContextStep({
- caller: {
- callId: "call-continued",
- replyTo: { kind: "hook", token: "parent-token-current" },
- subagentName: "linear",
- },
- serializedContext: {
- [ChannelKey.name]: {
- kind: "subagent",
- state: makeContext().state,
+ const rebound = await runSessionStateStep(
+ {
+ caller: {
+ callId: "call-continued",
+ replyTo: { kind: "hook", token: "parent-token-current" },
+ subagentName: "linear",
+ },
+ serializedContext: {
+ [ChannelKey.name]: {
+ kind: "subagent",
+ state: makeContext().state,
+ },
},
},
- });
+ bindTurnCallerContextStep,
+ );
const base = makeContext();
- const channel = rebound[ChannelKey.name] as { readonly state: Record<string, unknown> };
+ const channel = rebound.serializedContext[ChannelKey.name] as {
+ readonly state: Record<string, unknown>;
+ };
await SUBAGENT_INPUT_REQUESTED(
{
diff --git a/packages/eve/src/subagents/event-proxy-step.ts b/packages/eve/src/subagents/event-proxy-step.ts
index 0e95d958d..df82adde6 100644
--- a/packages/eve/src/subagents/event-proxy-step.ts
+++ b/packages/eve/src/subagents/event-proxy-step.ts
@@ -14,6 +14,10 @@ import {
type PublishedSessionEvents,
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";
@@ -29,19 +33,18 @@ export async function runProxySubagentEventStep(
readonly workflowAsk?: WorkflowAskRoute;
readonly hookPayload: SubagentEventHookPayload;
},
-): Promise<PublishedSessionEvents> {
+): Promise<SessionStateTransition> {
"use step";
- const durableSession = readDurableSession(input.sessionState);
- const ctx = await deserializeContext(input.serializedContext);
-
- return emitProxiedSubagentEvent({
- workflowAsk: input.workflowAsk,
- ctx,
- durableSession,
- hookPayload: input.hookPayload,
- sessionWritable: input.sessionWritable,
- });
+ return await withSessionStateDelta(input, async (target) =>
+ emitProxiedSubagentEvent({
+ 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. */
diff --git a/packages/eve/src/subagents/parent-notification.test.ts b/packages/eve/src/subagents/parent-notification.test.ts
index 16e668b11..bd5673834 100644
--- a/packages/eve/src/subagents/parent-notification.test.ts
+++ b/packages/eve/src/subagents/parent-notification.test.ts
@@ -10,6 +10,7 @@ import {
notifyTurnCallerStep,
resolveInitialTurnCallerStep,
} from "#subagents/parent-notification.js";
+import { runSessionStateStep } from "#internal/testing/session-state-step.js";
import { SUBAGENT_ADAPTER } from "#subagents/adapter.js";
import { SUBAGENT_ADAPTER_KIND } from "#subagents/adapter-state.js";
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
@@ -345,32 +346,37 @@ describe("turn caller notification", () => {
describe("turn caller binding", () => {
it("rebinds local adapter forwarding to a continuation caller", async () => {
await expect(
- bindTurnCallerContextStep({
- caller: {
- callId: "call-new",
- replyTo: { kind: "hook", token: "turn-new" },
- subagentName: "research",
- },
- serializedContext: {
- [ChannelKey.name]: {
- kind: SUBAGENT_ADAPTER_KIND,
- state: {
- callId: "call-old",
- parentContinuationToken: "turn-old",
- parentSessionId: "parent",
- subagentName: "research",
+ runSessionStateStep(
+ {
+ caller: {
+ callId: "call-new",
+ replyTo: { kind: "hook", token: "turn-new" },
+ subagentName: "research",
+ },
+ serializedContext: {
+ [ChannelKey.name]: {
+ kind: SUBAGENT_ADAPTER_KIND,
+ state: {
+ callId: "call-old",
+ parentContinuationToken: "turn-old",
+ parentSessionId: "parent",
+ subagentName: "research",
+ },
},
},
},
- }),
+ bindTurnCallerContextStep,
+ ),
).resolves.toEqual({
- [ChannelKey.name]: {
- kind: SUBAGENT_ADAPTER_KIND,
- state: {
- callId: "call-new",
- parentContinuationToken: "turn-new",
- parentSessionId: "parent",
- subagentName: "research",
+ serializedContext: {
+ [ChannelKey.name]: {
+ kind: SUBAGENT_ADAPTER_KIND,
+ state: {
+ callId: "call-new",
+ parentContinuationToken: "turn-new",
+ parentSessionId: "parent",
+ subagentName: "research",
+ },
},
},
});
@@ -378,24 +384,29 @@ describe("turn caller binding", () => {
it("rebinds remote callback forwarding to a continuation caller", async () => {
await expect(
- bindTurnCallerContextStep({
- caller: {
- callId: "call-new",
- replyTo: {
- kind: "callback",
- token: "turn-new",
- url: "https://parent.example/eve/v1/callback/turn-new",
+ runSessionStateStep(
+ {
+ caller: {
+ callId: "call-new",
+ replyTo: {
+ kind: "callback",
+ token: "turn-new",
+ url: "https://parent.example/eve/v1/callback/turn-new",
+ },
+ subagentName: "research",
},
- subagentName: "research",
+ serializedContext: {},
},
- serializedContext: {},
- }),
+ bindTurnCallerContextStep,
+ ),
).resolves.toEqual({
- [SessionCallbackKey.name]: {
- callId: "call-new",
- subagentName: "research",
- token: "turn-new",
- url: "https://parent.example/eve/v1/callback/turn-new",
+ serializedContext: {
+ [SessionCallbackKey.name]: {
+ callId: "call-new",
+ subagentName: "research",
+ token: "turn-new",
+ url: "https://parent.example/eve/v1/callback/turn-new",
+ },
},
});
});
diff --git a/packages/eve/src/subagents/parent-notification.ts b/packages/eve/src/subagents/parent-notification.ts
index 99ffc15c6..7c9af5486 100644
--- a/packages/eve/src/subagents/parent-notification.ts
+++ b/packages/eve/src/subagents/parent-notification.ts
@@ -19,6 +19,10 @@ import { parseJsonValue } from "#shared/json.js";
import type { TokenUsage } from "#shared/token-usage.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import { postSessionCallbackRequest } from "#execution/session-callback-request.js";
+import {
+ withSessionStateDelta,
+ type SessionStateTransition,
+} from "#execution/session/state-delta.js";
const log = createLogger("execution.delegated-parent-notification");
@@ -207,15 +211,23 @@ export async function resolveInitialTurnCallerStep(input: {
export async function bindTurnCallerContextStep(input: {
readonly caller: TurnCaller | undefined;
readonly serializedContext: Record<string, unknown>;
-}): Promise<Record<string, unknown>> {
+}): Promise<SessionStateTransition> {
"use step";
- const caller = input.caller;
- if (caller === undefined) return input.serializedContext;
+ return await withSessionStateDelta(input, async ({ caller, serializedContext }) => ({
+ serializedContext: bindTurnCallerContext(caller, serializedContext),
+ }));
+}
+
+function bindTurnCallerContext(
+ caller: TurnCaller | undefined,
+ serializedContext: Record<string, unknown>,
+): Record<string, unknown> {
+ if (caller === undefined) return serializedContext;
const withActivity =
caller.activityObserver === undefined
- ? input.serializedContext
- : { ...input.serializedContext, [ActivityObserverKey.name]: caller.activityObserver };
+ ? serializedContext
+ : { ...serializedContext, [ActivityObserverKey.name]: caller.activityObserver };
if (caller.replyTo.kind === "callback") {
const callback = {
callId: caller.callId,