Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

perf(eve): keep conversation history out of session steps that don't use it (#4128)

Andrew Barba384af578b310
diff --git a/.changeset/session-history-cursor-value.md b/.changeset/session-history-cursor-value.md
new file mode 100644
index 000000000..fe08705f9
--- /dev/null
+++ b/.changeset/session-history-cursor-value.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Session workflow steps that only publish events or update session state, such as a workflow tool's progress report, no longer store the conversation history in their Workflow step input, so their stored size stops growing with the conversation. The session handoff checkpoint changed shape, so an idle session does not move between deployments on either side of this release; its current owner keeps running it.
diff --git a/packages/eve/src/context/provider.ts b/packages/eve/src/context/provider.ts
index 4e64caaeb..ebf0a29cd 100644
--- a/packages/eve/src/context/provider.ts
+++ b/packages/eve/src/context/provider.ts
@@ -1,19 +1,15 @@
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
import type { ContextContainer } from "#context/container.js";
import type { ContextKey } from "#context/key.js";
export type { ContextReader } from "#context/key.js";
/**
- * Value returned by a framework provider's `create` method.
- *
- * `value` is the live step-local instance stored on the context. `session`
- * carries an optional harness session patch produced while deriving that
- * value.
+ * Value returned by a framework provider's `create` method: the live
+ * step-local instance stored on the context.
*/
export interface ProviderResult<T> {
readonly value: T;
- readonly session?: HarnessSession;
}
/**
@@ -28,10 +24,10 @@ export interface FrameworkContextProvider<T> {
create(
ctx: ContextContainer,
- session: HarnessSession,
+ session: HarnessSessionBase,
): ProviderResult<T> | undefined | Promise<ProviderResult<T> | undefined>;
- commit?(value: T, session: HarnessSession): HarnessSession | Promise<HarnessSession>;
+ commit?<S extends HarnessSessionBase>(value: T, session: S): S | Promise<S>;
/** Rolls back provider-owned effects when the callback or a later commit fails. */
rollback?(value: T, cause: unknown): void | Promise<void>;
diff --git a/packages/eve/src/context/providers/sandbox.ts b/packages/eve/src/context/providers/sandbox.ts
index 2afbe1c16..45cc047d7 100644
--- a/packages/eve/src/context/providers/sandbox.ts
+++ b/packages/eve/src/context/providers/sandbox.ts
@@ -1,5 +1,5 @@
import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
import type { SandboxAccess, SandboxState } from "#sandbox/state.js";
import type { ContextContainer } from "#context/container.js";
import { SandboxKey, SessionIdKey } from "#context/keys.js";
@@ -10,7 +10,7 @@ import type { FrameworkContextProvider } from "#context/provider.js";
export const sandboxProvider: FrameworkContextProvider<SandboxAccess> = {
key: SandboxKey,
- async create(ctx: ContextContainer, session: HarnessSession) {
+ async create(ctx: ContextContainer, session: HarnessSessionBase) {
const bundle = ctx.get(BundleKey);
if (bundle === undefined) return undefined;
const node = getActiveRuntimeNode(ctx);
diff --git a/packages/eve/src/context/run-step.ts b/packages/eve/src/context/run-step.ts
index 8cf06bf9e..f7fc94123 100644
--- a/packages/eve/src/context/run-step.ts
+++ b/packages/eve/src/context/run-step.ts
@@ -1,4 +1,4 @@
-import type { HarnessSession, StepResult } from "#harness/types.js";
+import type { HarnessSession, HarnessSessionBase, StepResult } from "#harness/types.js";
import { type ContextContainer, contextStorage } from "#context/container.js";
import type { FrameworkContextProvider } from "#context/provider.js";
import { connectionProvider } from "#context/providers/connection.js";
@@ -17,9 +17,9 @@ const frameworkProviders: readonly FrameworkContextProvider<any>[] = [
sandboxProvider,
];
-interface ContextScopeResult<T> {
+interface ContextScopeResult<T, S extends HarnessSessionBase> {
readonly result: T;
- readonly session: HarnessSession;
+ readonly session: S;
}
/**
@@ -30,12 +30,11 @@ interface ContextScopeResult<T> {
* result and the (possibly mutated) session so provider commit hooks can
* persist provider-owned state (e.g. sandbox snapshots).
*/
-export async function withContextScope<T>(
+export async function withContextScope<T, S extends HarnessSessionBase>(
ctx: ContextContainer,
- harnessSession: HarnessSession,
- callback: (session: HarnessSession) => Promise<ContextScopeResult<T>>,
-): Promise<ContextScopeResult<T>> {
- let session = harnessSession;
+ session: S,
+ callback: (session: S) => Promise<ContextScopeResult<T, S>>,
+): Promise<ContextScopeResult<T, S>> {
const createdProviders: FrameworkContextProvider<any>[] = [];
ctx.clearVirtualContext();
@@ -46,9 +45,6 @@ export async function withContextScope<T>(
if (result !== undefined) {
ctx.setVirtualContext(provider.key, result.value);
createdProviders.push(provider);
- if (result.session !== undefined) {
- session = result.session;
- }
}
}
diff --git a/packages/eve/src/execution/cancelled-model-call-batch.ts b/packages/eve/src/execution/cancelled-model-call-batch.ts
index 01d400ad9..55a513559 100644
--- a/packages/eve/src/execution/cancelled-model-call-batch.ts
+++ b/packages/eve/src/execution/cancelled-model-call-batch.ts
@@ -3,7 +3,7 @@ import { TurnDeliveryIdsKey } from "#context/keys.js";
import { preserveSerializedSessionDynamicModelSelection } from "#context/serialized-dynamic-model-selection.js";
import { serializeContext } from "#context/serialize.js";
import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";
-import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { createDurableSessionValues } from "#execution/durable-session-store.js";
import type { DurableStepResult } from "#execution/session/turn-step-types.js";
import type { HarnessSession, StepInput, StepResult } from "#harness/types.js";
import { preserveSerializedInstrumentationState } from "#instrumentation/state.js";
@@ -44,6 +44,6 @@ export async function createCancelledModelCallBatchResult(input: {
),
interruptedContext,
),
- sessionState: createDurableSessionState({ session: cancelledSession }),
+ ...createDurableSessionValues(cancelledSession),
};
}
diff --git a/packages/eve/src/execution/coordination-dispatch-shared.ts b/packages/eve/src/execution/coordination-dispatch-shared.ts
index af9cbdd44..6a2f2083b 100644
--- a/packages/eve/src/execution/coordination-dispatch-shared.ts
+++ b/packages/eve/src/execution/coordination-dispatch-shared.ts
@@ -19,7 +19,7 @@ import {
type CompiledBundle,
} from "#runtime/sessions/runtime-context-keys.js";
import { deserializeContext } from "#context/serialize.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
import {
assertUniqueCoordinationCallIds,
getPendingCoordinationBatch,
@@ -78,7 +78,7 @@ export interface PreparedCoordinationDispatch<PlanEntry = RuntimeWorkflowTaskReq
readonly sandboxSessionId: string;
readonly serializedContext: Record<string, unknown>;
readonly plan: readonly PlanEntry[];
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
readonly sessionState: DurableSessionState;
readonly workflowAgents: Readonly<Record<string, WorkflowAgentMetadata>>;
}
@@ -146,7 +146,7 @@ export async function prepareActionDispatch<PlanEntry>(input: {
readonly bundle: CompiledBundle;
readonly ctx: ContextContainer;
readonly requests: DispatchBatch["requests"];
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
}) => readonly PlanEntry[];
readonly serializedContext: Record<string, unknown>;
}): Promise<Omit<PreparedCoordinationDispatch<PlanEntry>, "sessionState">> {
diff --git a/packages/eve/src/execution/coordination-dispatch-step.ts b/packages/eve/src/execution/coordination-dispatch-step.ts
index 70de96399..00bcf7dca 100644
--- a/packages/eve/src/execution/coordination-dispatch-step.ts
+++ b/packages/eve/src/execution/coordination-dispatch-step.ts
@@ -19,7 +19,7 @@ import {
} from "#execution/agent-sessions/context.js";
import type { TaskStartedStreamEvent } from "#protocol/message.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
type CoordinationDispatchStepInput = CoordinationDispatchInput & {
readonly action: "park";
@@ -89,7 +89,7 @@ async function dispatchCoordination(
*/
async function dispatchWorkflowCall(start: StartWorkflowTaskInput): Promise<{
readonly result?: RuntimeActionResult;
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
readonly started?: TaskStartedStreamEvent;
}> {
const { entry } = start.task;
diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.ts
index 361c09e41..bea17411a 100644
--- a/packages/eve/src/execution/create-session-step.ts
+++ b/packages/eve/src/execution/create-session-step.ts
@@ -4,9 +4,10 @@ import {
resolveDurableCompiledArtifactsSource,
} from "#runtime/durable-compiled-artifacts-source.js";
import {
- createDurableSessionState,
+ createDurableSessionValues,
type DurableSessionState,
} from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { createSession } from "#execution/session.js";
import { resolveInheritedTokenLimit } from "#execution/run-session-limits.js";
import type { RunSessionLimits } from "#channel/types.js";
@@ -17,10 +18,11 @@ import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agen
/**
* Result returned by {@link createSessionStep}.
*
- * Exposes the projected {@link DurableSessionState} the owner needs to
- * drive the turn loop.
+ * Exposes the projected {@link DurableSessionState} and the history the
+ * owner needs to drive the turn loop.
*/
export interface CreateSessionStepResult {
+ readonly history: HarnessModelMessage[];
readonly state: DurableSessionState;
}
@@ -82,5 +84,6 @@ export async function createSessionStep(input: {
turnAgent: effectiveAgent.turnAgent,
});
- return { state: createDurableSessionState({ session }) };
+ const { history, sessionState } = createDurableSessionValues(session);
+ return { history, state: sessionState };
}
diff --git a/packages/eve/src/execution/durable-session-store.test.ts b/packages/eve/src/execution/durable-session-store.test.ts
index 2fe8dd8ba..c012cf93d 100644
--- a/packages/eve/src/execution/durable-session-store.test.ts
+++ b/packages/eve/src/execution/durable-session-store.test.ts
@@ -27,6 +27,7 @@ describe("durable session checkpoints", () => {
});
expect(readDurableSession(state)).toBe(state.snapshot.session);
expect(state.snapshot.session.agent).toEqual({ system: "test system" });
+ expect(state.snapshot.session).not.toHaveProperty("history");
});
it("refreshes projections when replacing session program memory", () => {
@@ -40,7 +41,7 @@ describe("durable session checkpoints", () => {
expect(state.continuationToken).toBe("old");
});
- it.each([{ version: 2, snapshot: { session: {} } }, { version: 1 }])(
+ it.each([{ version: 1, snapshot: { session: {} } }, { version: DURABLE_SESSION_VERSION }])(
"rejects unsupported checkpoints without a storage fallback",
(state) => {
expect(() => readDurableSession(state as DurableSessionState)).toThrow(
diff --git a/packages/eve/src/execution/durable-session-store.ts b/packages/eve/src/execution/durable-session-store.ts
index 0e7d3c17b..73a22d0a7 100644
--- a/packages/eve/src/execution/durable-session-store.ts
+++ b/packages/eve/src/execution/durable-session-store.ts
@@ -1,13 +1,13 @@
import { getHarnessEmissionState, type HarnessEmissionState } from "#harness/emission.js";
import type { HarnessModelMessage } from "#harness/messages.js";
import { hasProxyInputRequests } from "#harness/proxy-input-requests.js";
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { HarnessSession, HarnessSessionBase, SessionStateMap } from "#harness/types.js";
import { projectToDurableSession } from "#execution/session.js";
import type { SandboxState } from "#sandbox/state.js";
import type { JsonObject } from "#shared/json.js";
/** Explicit checkpoint contract shared by deployment handoffs. */
-export const DURABLE_SESSION_VERSION = 1;
+export const DURABLE_SESSION_VERSION = 2;
/**
* Serializable handle to a durable session.
@@ -40,6 +40,8 @@ export interface DurableSessionState {
* `agent.compactionModelReference`, and the `compaction` thresholds —
* those are rebuilt every turn from `bundle.turnAgent` by
* {@link import("#execution/session.js").hydrateDurableSession}.
+ * Omits `history` too: the session workflow carries it as its own value, so
+ * only the steps that read or change it receive it as input.
* `agent.system` is the last applied prompt snapshot. Before each model step,
* the execution layer replaces it from the current deployment's
* `bundle.turnAgent`.
@@ -54,7 +56,6 @@ export interface DurableSession {
*/
readonly rootSessionId?: string;
readonly continuationToken: string;
- readonly history: HarnessModelMessage[];
readonly limits?: HarnessSession["limits"];
readonly outputSchema?: JsonObject;
readonly state?: SessionStateMap;
@@ -86,11 +87,19 @@ export function readDurableSession(state: DurableSessionState): DurableSession {
* snapshot embedded in the Workflow step result.
*/
export function createDurableSessionState(input: {
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
}): DurableSessionState {
return projectDurableSessionState(projectToDurableSession(input.session));
}
+/** The session state and history a step that ran with the history leaves. */
+export function createDurableSessionValues(session: HarnessSession): {
+ readonly history: HarnessModelMessage[];
+ readonly sessionState: DurableSessionState;
+} {
+ return { history: session.history, sessionState: createDurableSessionState({ session }) };
+}
+
/** Replaces session program memory and refreshes its workflow projections. */
export function replaceDurableSessionSnapshot(input: {
readonly session: DurableSession;
diff --git a/packages/eve/src/execution/legacy-session/completion-step.test.ts b/packages/eve/src/execution/legacy-session/completion-step.test.ts
index 3626008d8..e090f1821 100644
--- a/packages/eve/src/execution/legacy-session/completion-step.test.ts
+++ b/packages/eve/src/execution/legacy-session/completion-step.test.ts
@@ -17,7 +17,7 @@ function fixture() {
close,
completionToken: "old:completion",
serializedContext: { "eve.sessionCallback": { url: "https://example.com/callback" } },
- sessionState: importConversation(session),
+ ...importConversation(session),
sessionWritable: new WritableStream<Uint8Array>({ close }),
};
}
@@ -39,7 +39,10 @@ describe("original driver finalization", () => {
serializedContext: prepared.serializedContext,
sessionState: {
...prepared.sessionState,
- snapshot: { version: 1, session: prepared.sessionState.snapshot.session },
+ snapshot: {
+ version: 1,
+ session: { ...prepared.sessionState.snapshot.session, history: prepared.history },
+ },
},
},
});
diff --git a/packages/eve/src/execution/legacy-session/completion-step.ts b/packages/eve/src/execution/legacy-session/completion-step.ts
index 2dcc87fdb..c2431278b 100644
--- a/packages/eve/src/execution/legacy-session/completion-step.ts
+++ b/packages/eve/src/execution/legacy-session/completion-step.ts
@@ -1,11 +1,13 @@
import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { resumeHook } from "#internal/workflow/runtime.js";
import type { WorkflowEntryResult } from "#execution/session/entry-input.js";
/** The old driver owns final notifications for the dispatch that became this session. */
export async function completeLegacyDriverStep(input: {
readonly completionToken: string;
+ readonly history: HarnessModelMessage[];
readonly result: WorkflowEntryResult;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -27,7 +29,10 @@ export async function completeLegacyDriverStep(input: {
serializedContext: input.serializedContext,
sessionState: {
...input.sessionState,
- snapshot: { version: 1, session: input.sessionState.snapshot.session },
+ snapshot: {
+ version: 1,
+ session: { ...input.sessionState.snapshot.session, history: input.history },
+ },
},
},
});
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 043dc3f4b..c45955cfc 100644
--- a/packages/eve/src/execution/legacy-session/import.integration.test.ts
+++ b/packages/eve/src/execution/legacy-session/import.integration.test.ts
@@ -80,15 +80,16 @@ describe("legacy session import", () => {
async () => {
const checkpoints = await readTurnStepStates(owner.runId);
const saved = checkpoints.find((result) =>
- result.sessionState.snapshot.session.history.some(
+ result.history.some(
(message) =>
message.role === "user" &&
JSON.stringify(message.content).includes("Bob asks for the next update."),
),
- )?.sessionState.snapshot.session;
+ );
expect(saved).toBeDefined();
- expect(saved!.agent.system).not.toBe("previous deployment");
- expect(saved!.state?.["app.color"]).toBe("blue");
+ const session = saved!.sessionState.snapshot.session;
+ expect(session.agent.system).not.toBe("previous deployment");
+ expect(session.state?.["app.color"]).toBe("blue");
expect(
saved!.history.filter(
(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 b8c9d021d..b9418a022 100644
--- a/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
+++ b/packages/eve/src/execution/legacy-session/interrupt-step.test.ts
@@ -31,7 +31,7 @@ function fixture(turnId = ""): PreparedLegacySession {
};
return {
originalSession: session,
- sessionState: importConversation(session),
+ ...importConversation(session),
serializedContext: {},
sessionTimeoutMs: false,
deploymentId: "new",
@@ -85,6 +85,7 @@ describe("legacy pending work", () => {
mocks.settle.mockResolvedValue({ sessionState: prepared.sessionState, serializedContext: {} });
await interruptLegacySessionStep(prepared);
expect(mocks.settle).toHaveBeenCalledExactlyOnceWith({
+ history: prepared.history,
reportUsage: false,
sessionWritable: prepared.input.sessionWritable,
sessionState: prepared.sessionState,
diff --git a/packages/eve/src/execution/legacy-session/interrupt-step.ts b/packages/eve/src/execution/legacy-session/interrupt-step.ts
index c9365c5f2..f4d82c5fd 100644
--- a/packages/eve/src/execution/legacy-session/interrupt-step.ts
+++ b/packages/eve/src/execution/legacy-session/interrupt-step.ts
@@ -14,15 +14,8 @@ import type { PreparedLegacySession } from "./prepare-step.js";
/** Only the elected importer may stop work or append cancellation events. */
export async function interruptLegacySessionStep(prepared: PreparedLegacySession) {
"use step";
- const originalState = {
- ...prepared.sessionState,
- snapshot: {
- session: {
- ...prepared.originalSession,
- history: prepared.sessionState.snapshot.session.history,
- },
- },
- };
+ const { history: _history, ...originalSession } = prepared.originalSession;
+ const originalState = { ...prepared.sessionState, snapshot: { session: originalSession } };
try {
await terminateChildSessionsStep({ sessionState: originalState });
} catch (error) {
@@ -78,10 +71,12 @@ export async function interruptLegacySessionStep(prepared: PreparedLegacySession
}
if (prepared.input.inputCommitted || prepared.sessionState.emissionState.turnId === "")
return {
+ history: prepared.history,
sessionState: prepared.sessionState,
serializedContext: prepared.serializedContext,
};
return await settleCancelledTurn({
+ history: prepared.history,
reportUsage: false,
sessionWritable: prepared.input.sessionWritable,
serializedContext: prepared.serializedContext,
diff --git a/packages/eve/src/execution/legacy-session/prepare-step.ts b/packages/eve/src/execution/legacy-session/prepare-step.ts
index 7f2983aba..7ffeb2ad1 100644
--- a/packages/eve/src/execution/legacy-session/prepare-step.ts
+++ b/packages/eve/src/execution/legacy-session/prepare-step.ts
@@ -11,7 +11,7 @@ export async function prepareLegacySessionStep(rawInput: unknown) {
"use step";
const input = readLegacyTurnInput(rawInput);
const originalSession = readLegacySnapshot(input.sessionState);
- const sessionState = importConversation(originalSession);
+ const { history, sessionState } = importConversation(originalSession);
const world = await getWorld();
const run = await world.runs.get(sessionState.sessionId);
const args: unknown = await hydrateWorkflowArguments(
@@ -47,6 +47,7 @@ export async function prepareLegacySessionStep(rawInput: unknown) {
...input,
retention: input.retention ?? (driverInput.retention as LegacyTurnInput["retention"]),
},
+ history,
originalSession,
sessionState,
serializedContext,
diff --git a/packages/eve/src/execution/legacy-session/snapshot.test.ts b/packages/eve/src/execution/legacy-session/snapshot.test.ts
index e87b81a24..0b96145d1 100644
--- a/packages/eve/src/execution/legacy-session/snapshot.test.ts
+++ b/packages/eve/src/execution/legacy-session/snapshot.test.ts
@@ -23,7 +23,7 @@ describe("conversation import", () => {
},
},
};
- const result = importConversation(session);
+ const { history, sessionState: result } = importConversation(session);
expect(result.snapshot.session).toMatchObject({
sessionId: "old",
limits: session.limits,
@@ -38,7 +38,8 @@ describe("conversation import", () => {
);
expect(result.snapshot.session.state).not.toHaveProperty("eve.agent.handles");
expect(result.emissionState.sequence).toBe(9);
- expect(result.snapshot.session.history[0]).toMatchObject({
+ expect(result.snapshot.session).not.toHaveProperty("history");
+ expect(history[0]).toMatchObject({
kind: "user",
content: "Alice chose blue.",
});
diff --git a/packages/eve/src/execution/legacy-session/snapshot.ts b/packages/eve/src/execution/legacy-session/snapshot.ts
index 066de0268..30ff2e6ab 100644
--- a/packages/eve/src/execution/legacy-session/snapshot.ts
+++ b/packages/eve/src/execution/legacy-session/snapshot.ts
@@ -1,10 +1,15 @@
import type { ModelMessage } from "ai";
import { getHarnessEmissionState } from "#harness/emission.js";
import { isUserMessageKind, validateHarnessModelMessages } from "#harness/messages.js";
-import type { DurableSession, DurableSessionState } from "#execution/durable-session-store.js";
+import {
+ DURABLE_SESSION_VERSION,
+ type DurableSession,
+ type DurableSessionState,
+} from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { isObject } from "#shared/guards.js";
-export type LegacySession = Omit<DurableSession, "history"> & { readonly history: ModelMessage[] };
+export type LegacySession = DurableSession & { readonly history: ModelMessage[] };
const PRESERVED_FRAMEWORK_STATE = new Set([
"eve.harness.emission",
@@ -31,22 +36,26 @@ export function readLegacySnapshot(
}
/** Keep committed conversation data, but no pre-cutover execution registries. */
-export function importConversation(session: LegacySession): DurableSessionState {
+export function importConversation(session: LegacySession): {
+ readonly history: HarnessModelMessage[];
+ readonly sessionState: DurableSessionState;
+} {
+ const { history, ...durable } = session;
const state = Object.fromEntries(
Object.entries(session.state ?? {}).filter(
([key]) => !key.startsWith("eve.") || PRESERVED_FRAMEWORK_STATE.has(key),
),
);
- const history = normalizeHistory(session.history);
- const emissionState = getHarnessEmissionState(state);
- const imported = { ...session, history, state };
return {
- version: 1,
- sessionId: session.sessionId,
- continuationToken: session.continuationToken,
- hasProxyInputRequests: false,
- emissionState,
- snapshot: { session: imported },
+ history: normalizeHistory(history),
+ sessionState: {
+ version: DURABLE_SESSION_VERSION,
+ sessionId: session.sessionId,
+ continuationToken: session.continuationToken,
+ hasProxyInputRequests: false,
+ emissionState: getHarnessEmissionState(state),
+ snapshot: { session: { ...durable, state } },
+ },
};
}
diff --git a/packages/eve/src/execution/legacy-session/turn-workflow.ts b/packages/eve/src/execution/legacy-session/turn-workflow.ts
index ebb48c247..65a51b708 100644
--- a/packages/eve/src/execution/legacy-session/turn-workflow.ts
+++ b/packages/eve/src/execution/legacy-session/turn-workflow.ts
@@ -49,6 +49,7 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
notify: (result) =>
completeLegacyDriverStep({
completionToken: prepared.input.completionToken,
+ history: prepared.history,
result,
serializedContext: prepared.serializedContext,
sessionState: prepared.sessionState,
@@ -58,6 +59,7 @@ export async function turnWorkflow(rawInput: unknown): Promise<void> {
caller: undefined,
capabilities: prepared.input.capabilities,
deploymentId: prepared.deploymentId,
+ history: interrupted.history,
initialInput:
prepared.input.delivery === undefined
? undefined
diff --git a/packages/eve/src/execution/publish-session-events.ts b/packages/eve/src/execution/publish-session-events.ts
index 8337693f4..72f1c2a8c 100644
--- a/packages/eve/src/execution/publish-session-events.ts
+++ b/packages/eve/src/execution/publish-session-events.ts
@@ -18,7 +18,8 @@ import { reconcileSessionContinuationToken } from "#execution/reconcile-session-
import { hydrateDurableSession } from "#execution/session.js";
import { activeTurnId } from "#harness/active-turn-id.js";
import { getHarnessEmissionState } from "#harness/emission.js";
-import type { HandleEventFn, HarnessSession } from "#harness/types.js";
+import { validateHarnessModelMessages, type HarnessModelMessage } from "#harness/messages.js";
+import type { HandleEventFn, HarnessSession, HarnessSessionBase } from "#harness/types.js";
import { bindSessionInstrumentation } from "#instrumentation/runtime.js";
import { createLogger } from "#internal/logging.js";
import {
@@ -52,6 +53,11 @@ export interface SessionStepState {
readonly sessionWritable: WritableStream<Uint8Array>;
}
+/** A {@link SessionStepState} with the conversation history, for a step that reads or changes it. */
+export interface SessionHistoryStepState extends SessionStepState {
+ readonly history: HarnessModelMessage[];
+}
+
/** The context and session state a publication leaves behind. */
export interface PublishedSessionEvents {
readonly serializedContext: Record<string, unknown>;
@@ -102,6 +108,11 @@ export interface RestoredSessionStep {
readonly sessionWritable: WritableStream<Uint8Array>;
}
+/** A {@link RestoredSessionStep} with the history, so its publication sees a whole session. */
+export interface RestoredSessionHistoryStep extends RestoredSessionStep {
+ readonly history: HarnessModelMessage[];
+}
+
export async function restoreSessionStep(step: SessionStepState): Promise<RestoredSessionStep> {
return {
ctx: await deserializeContext(step.serializedContext),
@@ -110,45 +121,64 @@ export async function restoreSessionStep(step: SessionStepState): Promise<Restor
};
}
-/** What a session step publishes, and how it changes the session the publication leaves. */
-export interface SessionStepPublication<T, R> {
+/**
+ * What a session step publishes, and how it changes the session the
+ * publication leaves. `S` is a {@link HarnessSession} only for a step
+ * restored with its history.
+ */
+export interface SessionStepPublication<T, R, S extends HarnessSessionBase = HarnessSessionBase> {
readonly origin: SessionEventOrigin;
/** Where a relayed input batch came from; the channel adapter and its forwarding see it. */
readonly inputSource?: string;
/** Emits the step's events in the session's context scope. */
- publish(emit: HandleEventFn, session: HarnessSession): Promise<T>;
+ publish(emit: HandleEventFn, session: S): Promise<T>;
/**
* Changes the step makes to the session once the scope has committed it,
* before its continuation token is reconciled.
*/
- updateSession?(session: HarnessSession, published: T): SessionUpdate<R>;
+ updateSession?(session: S, published: T): SessionUpdate<R, S>;
}
/** The session a step keeps, and anything it derived while changing it. */
-export interface SessionUpdate<R> {
- readonly session: HarnessSession;
+export interface SessionUpdate<R, S extends HarnessSessionBase = HarnessSessionBase> {
+ readonly session: S;
readonly result?: R;
}
/**
* Publishes from a step that owns the session. Returns the context and session
* state to adopt, and the result of `updateSession`. `step.ctx` is updated in place.
+ * The history is published and returned only when the step was restored with it.
*/
+export async function publishFromSessionStep<T, R = undefined>(
+ step: RestoredSessionHistoryStep,
+ publication: SessionStepPublication<T, R, HarnessSession>,
+): Promise<{
+ readonly published: PublishedSessionEvents & { readonly history: HarnessModelMessage[] };
+ readonly result: R | undefined;
+}>;
export async function publishFromSessionStep<T, R = undefined>(
step: RestoredSessionStep,
publication: SessionStepPublication<T, R>,
-): Promise<{ readonly published: PublishedSessionEvents; readonly result: R | undefined }> {
+): Promise<{ readonly published: PublishedSessionEvents; readonly result: R | undefined }>;
+export async function publishFromSessionStep<T, R>(
+ step: RestoredSessionStep & { readonly history?: HarnessModelMessage[] },
+ publication: SessionStepPublication<T, R>,
+): Promise<{
+ readonly published: PublishedSessionEvents & { readonly history?: HarnessModelMessage[] };
+ readonly result: R | undefined;
+}> {
const { ctx } = step;
const scoped = await publishInSessionScope(step, publication);
const update: SessionUpdate<R> = publication.updateSession?.(scoped.session, scoped.result) ?? {
session: scoped.session,
};
+ const session = reconcileSessionContinuationToken(ctx, update.session);
return {
published: {
serializedContext: serializeContext(ctx),
- sessionState: createDurableSessionState({
- session: reconcileSessionContinuationToken(ctx, update.session),
- }),
+ sessionState: createDurableSessionState({ session }),
+ ...("history" in session && { history: session.history as HarnessModelMessage[] }),
},
result: update.result,
};
@@ -160,16 +190,20 @@ export async function publishFromSessionStep<T, R = undefined>(
* commits.
*/
async function publishInSessionScope<T>(
- step: RestoredSessionStep,
+ step: RestoredSessionStep & { readonly history?: HarnessModelMessage[] },
publication: SessionStepPublication<T, unknown>,
-): Promise<{ readonly result: T; readonly session: HarnessSession }> {
+): Promise<{ readonly result: T; readonly session: HarnessSessionBase }> {
const { ctx } = step;
const effectiveAgent = resolveEffectiveAgentRuntime(ctx.require(BundleKey), ctx);
- const session = hydrateDurableSession({
+ const hydrated = hydrateDurableSession({
compactionOverrides: { thresholdPercent: effectiveAgent.thresholdPercent },
durable: step.durableSession,
turnAgent: effectiveAgent.turnAgent,
});
+ const session =
+ step.history === undefined
+ ? hydrated
+ : { ...hydrated, history: validateHarnessModelMessages(step.history) };
const instrumentation =
publication.origin === "own"
? bindSessionInstrumentation({
diff --git a/packages/eve/src/execution/reconcile-session-continuation-token.ts b/packages/eve/src/execution/reconcile-session-continuation-token.ts
index c3d3491a8..bd94d2d6e 100644
--- a/packages/eve/src/execution/reconcile-session-continuation-token.ts
+++ b/packages/eve/src/execution/reconcile-session-continuation-token.ts
@@ -1,12 +1,12 @@
import type { ContextAccessor } from "#context/key.js";
import { ContinuationTokenKey } from "#context/keys.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
/** Re-stamps a session after a channel handler selects a new current continuation address. */
-export function reconcileSessionContinuationToken(
+export function reconcileSessionContinuationToken<S extends HarnessSessionBase>(
ctx: ContextAccessor,
- session: HarnessSession,
-): HarnessSession {
+ session: S,
+): S {
const next = ctx.get(ContinuationTokenKey);
if (next === undefined || next === session.continuationToken) return session;
return { ...session, continuationToken: next };
diff --git a/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts b/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
index 1b8a4a31d..4e4bb1d99 100644
--- a/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/session-workflow-tool-run.integration.test.ts
@@ -52,6 +52,7 @@ describe("handleWorkflowToolRunMessage", () => {
const events: MessageStreamEvent[] = [];
const decoder = new TextDecoder();
const cursor = new SessionStateCursor({
+ history: [],
inbox: { claimSessionHooks: async () => {} },
serializedContext,
sessionState: {
diff --git a/packages/eve/src/execution/session.test.ts b/packages/eve/src/execution/session.test.ts
index a445edbef..019e3bbbb 100644
--- a/packages/eve/src/execution/session.test.ts
+++ b/packages/eve/src/execution/session.test.ts
@@ -153,16 +153,6 @@ describe("createSession", () => {
expect(refreshed.history).toEqual([
{ content: "Pinned tenant policy.", kind: "user", role: "user" },
]);
-
- const hydrated = hydrateDurableSession({
- durable: projectToDurableSession(refreshed),
- turnAgent: createTestTurnAgent({
- initialMessages: [{ content: "Another deployment policy.", kind: "user", role: "user" }],
- }),
- });
- expect(hydrated.history).toEqual([
- { content: "Pinned tenant policy.", kind: "user", role: "user" },
- ]);
});
it("defaults description and inputSchema when null", () => {
@@ -296,7 +286,6 @@ describe("createSession", () => {
durable: {
agent: { system: "You are a helpful assistant." },
continuationToken: "root-token",
- history: [],
sessionId: "sess-root",
},
turnAgent: createTestTurnAgent(),
@@ -310,7 +299,6 @@ describe("createSession", () => {
durable: {
agent: { system: "You are a helpful assistant." },
continuationToken: "subagent-token",
- history: [],
limits: {},
rootSessionId: "sess-root",
sessionId: "sess-child",
diff --git a/packages/eve/src/execution/session.ts b/packages/eve/src/execution/session.ts
index ce7995db2..fe50f2029 100644
--- a/packages/eve/src/execution/session.ts
+++ b/packages/eve/src/execution/session.ts
@@ -1,8 +1,8 @@
import type { DurableSession } from "#execution/durable-session-store.js";
import { formatAvailableSkillsSection } from "#execution/skills/instructions.js";
-import { validateHarnessModelMessages } from "#harness/messages.js";
import type {
HarnessSession,
+ HarnessSessionBase,
SessionAgent,
SessionLimits,
SessionToolDefinition,
@@ -171,13 +171,13 @@ export function mintSubagentContinuationToken(suffix?: string): string {
}
/**
- * Projects a {@link HarnessSession} to {@link DurableSession}.
+ * Projects a {@link HarnessSessionBase} to {@link DurableSession}.
*
* Drops fields rebuilt every turn from `bundle.turnAgent`; keeps
* `agent.system` and `compaction.lastKnown*` so compaction stays
* informed after rehydration.
*/
-export function projectToDurableSession(session: HarnessSession): DurableSession {
+export function projectToDurableSession(session: HarnessSessionBase): DurableSession {
const durable: {
agent: { system: string };
compaction?: {
@@ -185,7 +185,6 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
lastKnownPromptMessageCount?: number;
};
continuationToken: string;
- history: HarnessSession["history"];
limits?: HarnessSession["limits"];
outputSchema?: HarnessSession["outputSchema"];
rootSessionId?: string;
@@ -195,7 +194,6 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
} = {
agent: { system: session.agent.system },
continuationToken: session.continuationToken,
- history: session.history,
sessionId: session.sessionId,
};
@@ -227,7 +225,7 @@ export function projectToDurableSession(session: HarnessSession): DurableSession
}
/**
- * Rehydrates a {@link HarnessSession} from a {@link DurableSession}
+ * Rehydrates a {@link HarnessSessionBase} from a {@link DurableSession}
* plus the current `turnAgent`, rebuilding the runtime-only agent and
* compaction fields the durable shape omits.
*/
@@ -237,12 +235,12 @@ export function hydrateDurableSession(input: {
readonly compactionOverrides?: {
readonly thresholdPercent?: number;
};
-}): HarnessSession {
+}): HarnessSessionBase {
const { durable, turnAgent } = input;
const tools = createSessionToolDefinitions(turnAgent);
const session: {
- -readonly [K in keyof HarnessSession]: HarnessSession[K];
+ -readonly [K in keyof HarnessSessionBase]: HarnessSessionBase[K];
} = {
agent: createSessionAgent(turnAgent, durable.agent.system, tools),
compaction: createCompactionConfig({
@@ -252,7 +250,6 @@ export function hydrateDurableSession(input: {
thresholdPercent: input.compactionOverrides?.thresholdPercent,
}),
continuationToken: durable.continuationToken,
- history: validateHarnessModelMessages(durable.history),
sessionId: durable.sessionId,
};
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 29bc737c4..9e7cb3f2d 100644
--- a/packages/eve/src/execution/session/entry-handoff.integration.test.ts
+++ b/packages/eve/src/execution/session/entry-handoff.integration.test.ts
@@ -140,9 +140,7 @@ describe("workflowEntry integration", () => {
},
{ timeout: 5000 },
);
- const histories = (await readTurnStepStates(anchor.runId)).map(
- (state) => state.sessionState.snapshot.session.history,
- );
+ const histories = (await readTurnStepStates(anchor.runId)).map((state) => state.history);
const deliveries = histories.map((history) =>
history.filter(
(message) =>
@@ -305,7 +303,7 @@ describe("workflowEntry integration", () => {
// Recorded steps are not returned in turn order; the settled
// history is the one that accumulated every turn.
const settled = (await readTurnStepStates(anchor.runId))
- .map((state) => state.sessionState.snapshot.session.history)
+ .map((state) => state.history)
.reduce<readonly unknown[]>(
(longest, history) => (history.length > longest.length ? history : longest),
[],
@@ -422,7 +420,7 @@ describe("workflowEntry integration", () => {
await vi.waitFor(
async () => {
for (const state of await readTurnStepStates(owner.runId)) {
- const history = JSON.stringify(state.sessionState.snapshot.session.history);
+ const history = JSON.stringify(state.history);
if (history.includes("Bob sends a later sentinel.")) saved = history;
}
expect(saved).toBeDefined();
diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.ts
index 0a863a941..42a7cc636 100644
--- a/packages/eve/src/execution/session/entry.ts
+++ b/packages/eve/src/execution/session/entry.ts
@@ -127,6 +127,7 @@ async function bootInitialOwner(
: undefined,
capabilities: serializedContext["eve.capabilities"] as SessionCapabilities | undefined,
deploymentId: input.ownerDeploymentId,
+ history: sessionCreation.value.history,
initialInput: createInitialDelivery(input, serializedContext),
awaitFirstMessage: input.input.message === undefined,
retention: input.retention,
@@ -192,6 +193,7 @@ async function bootHandoffOwner(
caller: input.delivery.caller,
capabilities: checkpoint.capabilities,
deploymentId: input.ownerDeploymentId,
+ history: checkpoint.history,
initialInput: input.delivery,
awaitFirstMessage: false,
retention: checkpoint.retention,
diff --git a/packages/eve/src/execution/session/handoff-steps.test.ts b/packages/eve/src/execution/session/handoff-steps.test.ts
index 582996a6b..18175b3ca 100644
--- a/packages/eve/src/execution/session/handoff-steps.test.ts
+++ b/packages/eve/src/execution/session/handoff-steps.test.ts
@@ -55,7 +55,7 @@ describe("validateSessionCheckpointStep", () => {
);
});
- it.each([5, 6, 7, 8, 9, 11])(
+ it.each([5, 6, 7, 8, 9, 10, 12])(
"reports checkpoint version %s as incompatible before reading nested state",
async (version) => {
const checkpoint = createCheckpoint();
@@ -86,6 +86,7 @@ describe("validateSessionCheckpointStep", () => {
function createCheckpoint(): SessionCheckpoint {
return {
version: SESSION_CHECKPOINT_VERSION,
+ history: [],
sessionTimeoutMs: false,
serializedContext: {},
sessionState: createTestSessionState({
@@ -93,7 +94,6 @@ function createCheckpoint(): SessionCheckpoint {
emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn_0" },
hasProxyInputRequests: false,
sessionId: "session-1",
- version: 1,
}),
};
}
diff --git a/packages/eve/src/execution/session/handoff.test.ts b/packages/eve/src/execution/session/handoff.test.ts
index 5f4f90fef..8ede9bea1 100644
--- a/packages/eve/src/execution/session/handoff.test.ts
+++ b/packages/eve/src/execution/session/handoff.test.ts
@@ -34,16 +34,20 @@ describe("SessionHandoff", () => {
installActivation({ kind: "active" });
startSessionOwnerStepMock.mockResolvedValue(undefined);
const trigger = selection("deployment-b");
+ const history = [
+ { content: "Alice asks for the status.", kind: "user" as const, role: "user" as const },
+ ];
- await expect(handoff.tryTransfer(trigger, state())).resolves.toEqual({
+ await expect(handoff.tryTransfer(trigger, { ...state(), history })).resolves.toEqual({
kind: "transferred",
});
expect(startSessionOwnerStepMock).toHaveBeenCalledWith({
activationToken: "owner-1:handoff",
anchorRunId: "session-1",
checkpoint: expect.objectContaining({
+ history,
sessionTimeoutMs: 60_000,
- version: 10,
+ version: 11,
}),
delivery: trigger.delivery,
targetDeploymentId: "deployment-b",
@@ -261,6 +265,7 @@ function state(
} = {},
) {
return {
+ history: [],
serializedContext: input.serializedContext ?? {},
sessionState: {
continuationToken: input.continuationToken ?? "",
diff --git a/packages/eve/src/execution/session/handoff.ts b/packages/eve/src/execution/session/handoff.ts
index 2508d4d7f..8b5fbf11a 100644
--- a/packages/eve/src/execution/session/handoff.ts
+++ b/packages/eve/src/execution/session/handoff.ts
@@ -3,6 +3,7 @@ import { createHook, getWorkflowMetadata, type Hook } from "#compiled/@workflow/
import type { DeliverHookPayload, SessionCapabilities } from "#channel/types.js";
import { readAcceptedDeploymentId } from "#execution/session/accepted-deployment.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { claimHookOwnership, disposeHook } from "#execution/hook-ownership.js";
import { sessionHookTokens } from "#execution/session/hook-tokens.js";
import type { SessionInboxHandle, SessionInboxPayload } from "#execution/session-inbox/inbox.js";
@@ -20,12 +21,13 @@ import type { AgentWorkflowRetentionDefinition } from "#shared/agent-definition.
* Mount-owned state requires a new version so older readers reject it rather
* than dropping unrecognized state keys during reverse handoff.
*/
-export const SESSION_CHECKPOINT_VERSION = 10;
+export const SESSION_CHECKPOINT_VERSION = 11;
/** Everything a successor needs to continue an idle session. Hooks are derived from the state. */
export interface SessionCheckpoint {
readonly version: typeof SESSION_CHECKPOINT_VERSION;
readonly capabilities?: SessionCapabilities;
+ readonly history: HarnessModelMessage[];
readonly retention?: AgentWorkflowRetentionDefinition;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
@@ -65,7 +67,10 @@ type SessionTransferOutcome =
};
interface SessionHandoffInput {
- readonly checkpoint: Omit<SessionCheckpoint, "serializedContext" | "sessionState" | "version">;
+ readonly checkpoint: Omit<
+ SessionCheckpoint,
+ "history" | "serializedContext" | "sessionState" | "version"
+ >;
readonly deploymentId: string;
readonly inbox: SessionInboxHandle;
readonly isInitialOwner: boolean;
@@ -104,7 +109,7 @@ export class SessionHandoff {
*/
async tryTransfer(
selection: TurnSelection,
- state: Pick<SessionCheckpoint, "serializedContext" | "sessionState">,
+ state: Pick<SessionCheckpoint, "history" | "serializedContext" | "sessionState">,
): Promise<SessionTransferOutcome> {
const { deploymentId, inbox } = this.input;
const targetDeploymentId = readAcceptedDeploymentId(selection.delivery);
@@ -113,7 +118,7 @@ export class SessionHandoff {
if (this.incompatibleTargetDeploymentIds.has(targetDeploymentId))
return { kind: "retained", reason: "known-incompatible" };
if (!selection.handoffEligible) return { kind: "retained", reason: "busy" };
- if (!(await isSessionIdleForHandoffStep(state)))
+ if (!(await isSessionIdleForHandoffStep({ sessionState: state.sessionState })))
return { kind: "retained", reason: "not-idle" };
const checkpoint: SessionCheckpoint = {
diff --git a/packages/eve/src/execution/session/next-input.test.ts b/packages/eve/src/execution/session/next-input.test.ts
index 74b9ab578..401c86a57 100644
--- a/packages/eve/src/execution/session/next-input.test.ts
+++ b/packages/eve/src/execution/session/next-input.test.ts
@@ -107,6 +107,7 @@ function createCursor(
state = sessionState,
): SessionStateCursor {
return new SessionStateCursor({
+ history: [],
inbox: inbox,
sessionWritable: new WritableStream<Uint8Array>(),
serializedContext: {},
diff --git a/packages/eve/src/execution/session/program.ts b/packages/eve/src/execution/session/program.ts
index f8d2f195e..aeaaab3f5 100644
--- a/packages/eve/src/execution/session/program.ts
+++ b/packages/eve/src/execution/session/program.ts
@@ -7,6 +7,7 @@ import {
resolveInitialTurnCallerStep,
} from "#subagents/parent-notification.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { nextTurnDelivery, type NextTurnInstruction } from "#execution/session/next-input.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { SessionInputQueue } from "#execution/session/input-queue.js";
@@ -48,6 +49,7 @@ export interface SessionBoot {
readonly caller: TurnCaller | undefined;
readonly capabilities?: SessionCapabilities;
readonly deploymentId: string;
+ readonly history: HarnessModelMessage[];
readonly initialInput: DeliverHookPayload | undefined;
/** Parks on the inbox before any session-scoped lifecycle work. */
readonly awaitFirstMessage: boolean;
@@ -83,6 +85,7 @@ export async function runPreparedSession(
inbox: SessionInboxHandle,
): Promise<WorkflowEntryResult> {
const cursor = new SessionStateCursor({
+ history: boot.history,
inbox,
sessionWritable: boot.sessionWritable,
serializedContext: boot.serializedContext,
@@ -248,6 +251,7 @@ async function runSessionLoop(
next: Extract<NextTurnInstruction, { kind: "turn" }>,
): Promise<SessionActionResult> => {
const transfer = await handoff.tryTransfer(next, {
+ history: cursor.history,
serializedContext: cursor.serializedContext,
sessionState: cursor.sessionState,
});
@@ -256,7 +260,7 @@ async function runSessionLoop(
return { action: await runTurn({ delivery: next.delivery }), kind: "action" };
};
const settleCancelledTurn = async (reportUsage: boolean) => {
- const settled = await cursor.advance((state) =>
+ const settled = await cursor.advanceWithHistory((state) =>
settleCancelledTurnStep({ ...state, reportUsage }),
);
progress.caller = undefined;
diff --git a/packages/eve/src/execution/session/state-cursor.test.ts b/packages/eve/src/execution/session/state-cursor.test.ts
index 0edfd5c8d..2fd8dd496 100644
--- a/packages/eve/src/execution/session/state-cursor.test.ts
+++ b/packages/eve/src/execution/session/state-cursor.test.ts
@@ -16,6 +16,7 @@ describe("SessionStateCursor", () => {
};
const initialState = state("channel:initial");
const cursor = new SessionStateCursor({
+ history: [],
inbox,
sessionWritable: new WritableStream<Uint8Array>(),
serializedContext: {
@@ -43,6 +44,7 @@ describe("SessionStateCursor", () => {
it("claims the current continuation when no address history was recorded", async () => {
const claimSessionHooks = vi.fn(async () => {});
const cursor = new SessionStateCursor({
+ history: [],
inbox: {
claimSessionHooks,
},
@@ -58,39 +60,28 @@ describe("SessionStateCursor", () => {
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");
+ it("adopts exactly the values a step returned, including edits it made to its input in place", async () => {
const cursor = new SessionStateCursor({
+ history: [{ content: "Alice asks for the status.", kind: "user", role: "user" }],
inbox: { claimSessionHooks: vi.fn(async () => {}) },
sessionWritable: new WritableStream<Uint8Array>(),
serializedContext: { "eve.channel": { kind: "slack", state: { threadTs: "1.0" } } },
- sessionState: initial,
+ sessionState: state("channel:initial"),
});
let returned: unknown;
- await cursor.advance(async ({ serializedContext, sessionState }) => {
+ await cursor.advanceWithHistory(async ({ history, serializedContext, sessionState }) => {
// The workflow hands the step a deserialized copy and the body a deserialized result.
- const input = structuredClone({ serializedContext, sessionState });
+ const input = structuredClone({ history, 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 = {
+ history: [...values.history, { content: "Bob's reply", role: "assistant" as const }],
serializedContext: values.serializedContext,
- sessionState: {
- ...values.sessionState,
- snapshot: {
- session: {
- ...session,
- history: [
- ...session.history,
- { content: "Bob's reply", role: "assistant" as const },
- ],
- },
- },
- },
+ sessionState: { ...values.sessionState, continuationToken: "channel:next" },
};
returned = structuredClone(next);
return next;
@@ -99,13 +90,33 @@ describe("SessionStateCursor", () => {
});
expect({
+ history: cursor.history,
serializedContext: cursor.serializedContext,
sessionState: cursor.sessionState,
}).toStrictEqual(returned);
});
+ it("rejects a history change from a step that was not given the history", async () => {
+ const history = [
+ { content: "Alice asks for the status.", kind: "user" as const, role: "user" as const },
+ ];
+ const cursor = new SessionStateCursor({
+ history,
+ inbox: { claimSessionHooks: vi.fn(async () => {}) },
+ sessionWritable: new WritableStream<Uint8Array>(),
+ serializedContext: {},
+ sessionState: state("channel:initial"),
+ });
+
+ await expect(
+ cursor.advance((input) => withSessionStateDelta(input, async () => ({ history: [] }))),
+ ).rejects.toThrow("not given the history cannot change it");
+ expect(cursor.history).toBe(history);
+ });
+
it("rejects a step's delta when another step changed the state while it ran", async () => {
const cursor = new SessionStateCursor({
+ history: [],
inbox: { claimSessionHooks: vi.fn(async () => {}) },
sessionWritable: new WritableStream<Uint8Array>(),
serializedContext: {},
@@ -135,6 +146,5 @@ function state(continuationToken: string): DurableSessionState {
emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn_0" },
hasProxyInputRequests: false,
sessionId: "session-1",
- version: 1,
});
}
diff --git a/packages/eve/src/execution/session/state-cursor.ts b/packages/eve/src/execution/session/state-cursor.ts
index b8a59ab2e..6ae761960 100644
--- a/packages/eve/src/execution/session/state-cursor.ts
+++ b/packages/eve/src/execution/session/state-cursor.ts
@@ -1,5 +1,8 @@
import type { DurableSessionState } from "#execution/durable-session-store.js";
-import type { SessionStepState } from "#execution/publish-session-events.js";
+import type {
+ SessionHistoryStepState,
+ SessionStepState,
+} from "#execution/publish-session-events.js";
import { sessionHookTokens } from "#execution/session/hook-tokens.js";
import {
applySessionStateDelta,
@@ -7,13 +10,14 @@ import {
type SessionStateValues,
} from "#execution/session/state-delta.js";
import type { SessionInboxOwnership } from "#execution/session-inbox/inbox.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
/**
- * 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.
+ * The one set of session values owned by the workflow executing a session.
+ * Steps run against it and return deltas; the cursor applies each to the
+ * values 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>;
@@ -21,15 +25,19 @@ export class SessionStateCursor {
private readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
private values: SessionStateValues;
- constructor(input: {
- readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
- }) {
+ constructor(
+ input: SessionStateValues & {
+ readonly inbox: Pick<SessionInboxOwnership, "claimSessionHooks">;
+ readonly sessionWritable: WritableStream<Uint8Array>;
+ },
+ ) {
this.inbox = input.inbox;
this.sessionWritable = input.sessionWritable;
- this.values = { serializedContext: input.serializedContext, sessionState: input.sessionState };
+ this.values = {
+ history: input.history,
+ serializedContext: input.serializedContext,
+ sessionState: input.sessionState,
+ };
}
get serializedContext(): Record<string, unknown> {
@@ -40,17 +48,50 @@ export class SessionStateCursor {
return this.values.sessionState;
}
+ get history(): HarnessModelMessage[] {
+ return this.values.history;
+ }
+
/**
- * 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.
+ * Runs a session-changing step against the current context and session
+ * state and adopts the delta it returns. The step is not given the history,
+ * which is the bulk of a long session, so its Workflow step input stays
+ * small; it cannot change the history either.
*/
async advance<T extends SessionStateTransition>(
step: (state: SessionStepState) => Promise<T>,
+ ): Promise<T> {
+ const { serializedContext, sessionState } = this.values;
+ return await this.adopt(
+ () => step({ serializedContext, sessionState, sessionWritable: this.sessionWritable }),
+ { withHistory: false },
+ );
+ }
+
+ /** {@link advance} for a step that reads or changes the history, such as a turn. */
+ async advanceWithHistory<T extends SessionStateTransition>(
+ step: (state: SessionHistoryStepState) => Promise<T>,
+ ): Promise<T> {
+ return await this.adopt(() => step({ ...this.values, sessionWritable: this.sessionWritable }), {
+ withHistory: true,
+ });
+ }
+
+ /**
+ * A delta describes a change to exactly the values its step was given, so
+ * values that another step changed in the meantime are a sequencing bug,
+ * never a merge.
+ */
+ private async adopt<T extends SessionStateTransition>(
+ run: () => Promise<T>,
+ options: { readonly withHistory: boolean },
): Promise<T> {
const base = this.values;
- const result = await step(this.stepState());
+ const result = await run();
+ // Diffed against a history it never had, the delta would replace the whole history.
+ if (!options.withHistory && result.stateDelta.history !== undefined) {
+ throw new Error("A session step that was not given the history cannot change it.");
+ }
const next = applySessionStateDelta(base, result.stateDelta);
await this.inbox.claimSessionHooks(sessionHookTokens(next));
if (this.values !== base) {
@@ -59,9 +100,4 @@ export class SessionStateCursor {
this.values = next;
return result;
}
-
- /** The session's stream and current state, spread into a step's input. */
- private stepState(): SessionStepState {
- 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
index 6fd5f670f..7c72fbf9f 100644
--- a/packages/eve/src/execution/session/state-delta.ts
+++ b/packages/eve/src/execution/session/state-delta.ts
@@ -1,16 +1,23 @@
import type { DurableSessionState } from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { applyValueDelta, diffValue, snapshotValue, type ValueDelta } from "#shared/value-delta.js";
-/** The durable values a session workflow threads through its steps. */
+/**
+ * The durable values a session workflow threads through its steps. `history`
+ * is separate from `sessionState` so that only the steps that read or change
+ * it receive it as input.
+ */
export interface SessionStateValues {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly history: HarnessModelMessage[];
}
/** How a step changed the session's values; an absent value is unchanged. */
export interface SessionStateDelta {
readonly serializedContext?: ValueDelta;
readonly sessionState?: ValueDelta;
+ readonly history?: ValueDelta;
}
/** A step result the session workflow adopts through its state cursor. */
@@ -23,6 +30,8 @@ export type WithSessionStateDelta<T> = T extends unknown
? Omit<T, keyof SessionStateValues> & SessionStateTransition
: never;
+const SESSION_VALUE_KEYS = ["serializedContext", "sessionState", "history"] as const;
+
/**
* 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.
@@ -43,20 +52,16 @@ 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 base = Object.fromEntries(
+ SESSION_VALUE_KEYS.map((key) => [key, snapshotValue(input[key])]),
+ );
+ const { serializedContext, sessionState, history, ...result } = await work(input);
+ const next = { serializedContext, sessionState, history };
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;
+ for (const key of SESSION_VALUE_KEYS) {
+ const delta = next[key] === undefined ? undefined : diffValue(base[key], next[key]);
+ if (delta !== undefined) stateDelta[key] = delta;
+ }
return { ...result, stateDelta };
}
@@ -68,5 +73,6 @@ export function applySessionStateDelta(
return {
serializedContext: applyValueDelta(values.serializedContext, delta.serializedContext),
sessionState: applyValueDelta(values.sessionState, delta.sessionState),
+ history: applyValueDelta(values.history, delta.history),
};
}
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 a6240b97b..1c791acef 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
@@ -4,7 +4,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { ContextContainer } from "#context/container.js";
import { AuthKey, InitiatorAuthKey, SessionIdKey } from "#context/keys.js";
import { serializeContext } from "#context/serialize.js";
-import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import {
+ createDurableSessionValues,
+ 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";
@@ -266,7 +269,7 @@ function setup(
};
let snapshot = {
serializedContext: serializeContext(ctx),
- sessionState: createDurableSessionState({ session }),
+ ...createDurableSessionValues(session),
};
const events: Array<{ type: string; data: Record<string, unknown> }> = [];
async function step(input?: TurnStepPayload): Promise<DurableStepResult> {
@@ -283,7 +286,11 @@ function setup(
}),
};
const result = await runSessionStateStep(stepInput, turnStep);
- snapshot = { serializedContext: result.serializedContext, sessionState: result.sessionState };
+ snapshot = {
+ history: result.history,
+ serializedContext: result.serializedContext,
+ sessionState: result.sessionState,
+ };
return result;
}
return {
@@ -300,14 +307,15 @@ function setup(
updateSession(update: (session: HarnessSession) => HarnessSession) {
snapshot = {
...snapshot,
- sessionState: createDurableSessionState({
- session: update({
+ ...createDurableSessionValues(
+ update({
...session,
...readDurableSession(snapshot.sessionState),
agent: session.agent,
compaction: session.compaction,
+ history: snapshot.history,
}),
- }),
+ ),
};
},
};
diff --git a/packages/eve/src/execution/session/turn-step-result.ts b/packages/eve/src/execution/session/turn-step-result.ts
index 06bda5c3b..3c25f0130 100644
--- a/packages/eve/src/execution/session/turn-step-result.ts
+++ b/packages/eve/src/execution/session/turn-step-result.ts
@@ -1,4 +1,4 @@
-import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { createDurableSessionValues } from "#execution/durable-session-store.js";
import { derivePendingState } from "#execution/session/pending-turn-state.js";
import type { DurableStepResult } from "#execution/session/turn-step-types.js";
import { getTurnUsageState, takeSessionUsageDelta, toUsage } from "#harness/turn-tag-state.js";
@@ -8,13 +8,11 @@ export function resolveSessionStepResult(
stepResult: StepResult,
nextSerializedContext: Record<string, unknown>,
): DurableStepResult {
- const nextState = createDurableSessionState({ session: stepResult.session });
- if (stepResult.steered)
- return {
- action: "steered",
- serializedContext: nextSerializedContext,
- sessionState: nextState,
- };
+ const values = {
+ serializedContext: nextSerializedContext,
+ ...createDurableSessionValues(stepResult.session),
+ };
+ if (stepResult.steered) return { action: "steered", ...values };
if (
stepResult.next !== null &&
@@ -26,20 +24,14 @@ export function resolveSessionStepResult(
action: "done",
output: stepResult.next.output,
isError: stepResult.next.isError,
- serializedContext: nextSerializedContext,
- sessionState: nextState,
+ ...values,
usage: sessionTotals === undefined ? undefined : toUsage(sessionTotals),
usageDelta: takeSessionUsageDelta(stepResult.session).delta,
};
}
if (stepResult.held !== undefined) {
- return {
- action: "held",
- serializedContext: nextSerializedContext,
- sessionState: nextState,
- taskIds: stepResult.held.taskIds,
- };
+ return { action: "held", ...values, taskIds: stepResult.held.taskIds };
}
if (stepResult.next === null) {
@@ -52,7 +44,7 @@ export function resolveSessionStepResult(
action: "park",
...pending,
serializedContext: nextSerializedContext,
- sessionState: createDurableSessionState({ session: reportedSession }),
+ ...createDurableSessionValues(reportedSession),
settled: {
output: stepResult.settledTurn.output,
isError: stepResult.settledTurn.isError,
@@ -61,17 +53,8 @@ export function resolveSessionStepResult(
};
}
- return {
- action: "park",
- ...pending,
- serializedContext: nextSerializedContext,
- sessionState: nextState,
- };
+ return { action: "park", ...pending, ...values };
}
- return {
- action: "continue",
- serializedContext: nextSerializedContext,
- sessionState: nextState,
- };
+ return { action: "continue", ...values };
}
diff --git a/packages/eve/src/execution/session/turn-step-types.ts b/packages/eve/src/execution/session/turn-step-types.ts
index e4a4c6012..1704caf49 100644
--- a/packages/eve/src/execution/session/turn-step-types.ts
+++ b/packages/eve/src/execution/session/turn-step-types.ts
@@ -2,6 +2,7 @@ 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 { HarnessModelMessage } from "#harness/messages.js";
import type { SettledTurn } from "#harness/types.js";
import type { RuntimeActionResult } from "#shared/action-types.js";
import type { TokenUsage } from "#shared/token-usage.js";
@@ -33,11 +34,13 @@ export interface TurnStepInput {
readonly sessionWritable: WritableStream<Uint8Array>;
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly history: HarnessModelMessage[];
}
interface DurableStepResultFields {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly history: HarnessModelMessage[];
}
/** What one turn step's work produces, with the session state it leaves. */
diff --git a/packages/eve/src/execution/session/turn-step.test.ts b/packages/eve/src/execution/session/turn-step.test.ts
index 2f2aaa435..6304b758b 100644
--- a/packages/eve/src/execution/session/turn-step.test.ts
+++ b/packages/eve/src/execution/session/turn-step.test.ts
@@ -49,6 +49,7 @@ import type { HookContext } from "#public/definitions/hook.js";
import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
import {
createDurableSessionState,
+ createDurableSessionValues,
type DurableSessionState,
readDurableSession,
} from "#execution/durable-session-store.js";
@@ -70,8 +71,16 @@ type LegacyStepPayload =
| { readonly kind: "clear" | "compact" }
| { readonly kind: "runtime-action-result"; readonly results: readonly RuntimeActionResult[] };
-/** Adapts the older single-kind payload shape these fixtures were written against. */
-function turnStep(input: Omit<TurnStepInput, "input"> & { readonly input?: LegacyStepPayload }) {
+/**
+ * Adapts the older single-kind payload shape these fixtures were written
+ * against. A fixture that names no history starts the step with none.
+ */
+function turnStep(
+ input: Omit<TurnStepInput, "history" | "input"> & {
+ readonly history?: TurnStepInput["history"];
+ readonly input?: LegacyStepPayload;
+ },
+) {
let payload: TurnStepPayload | undefined;
if (input.input !== undefined) {
payload =
@@ -81,7 +90,7 @@ function turnStep(input: Omit<TurnStepInput, "input"> & { readonly input?: Legac
? { runtimeResults: { results: input.input.results } }
: { control: input.input.kind };
}
- return runSessionStateStep({ ...input, input: payload }, runTurnStep);
+ return runSessionStateStep({ history: [], ...input, input: payload }, runTurnStep);
}
import { routeProxiedDeliverStep } from "#execution/proxied-deliver-step.js";
import { captureLogRecords } from "#internal/testing/log-records.js";
@@ -129,6 +138,7 @@ vi.mock("../durable-session-store.js", async (importOriginal) => {
return {
...actual,
createDurableSessionState: vi.fn(actual.createDurableSessionState),
+ createDurableSessionValues: vi.fn(actual.createDurableSessionValues),
readDurableSession: vi.fn(),
};
});
@@ -167,7 +177,6 @@ function createStubSessionState(overrides: Partial<DurableSessionState> = {}): D
emissionState: { sequence: 0, sessionStarted: false, stepIndex: 0, turnId: "" },
hasProxyInputRequests: false,
sessionId: "sess-test",
- version: 1,
...overrides,
});
}
@@ -755,6 +764,7 @@ describe("turnStep", () => {
ctx.set(SessionIdKey, "sess-test");
const result = await turnStep({
+ history: session.history,
input: {
auth: correctionAuth,
kind: "deliver",
@@ -819,7 +829,7 @@ describe("turnStep", () => {
undefined,
undefined,
]);
- expect(result.sessionState.snapshot.session.history).toEqual([
+ expect(result.history).toEqual([
{ content: "model call 1", role: "assistant" },
{ content: "model call 2", role: "assistant" },
{ content: "model call 3", role: "assistant" },
@@ -876,8 +886,8 @@ describe("turnStep", () => {
expect(result.action).toBe("cancelled");
expect(callCount).toBe(51);
expect(result.serializedContext).toMatchObject({ [ThreadKey.name]: "completed call 50" });
- expect(result.sessionState.snapshot.session.history).toHaveLength(50);
- expect(result.sessionState.snapshot.session.history.at(-1)).toEqual({
+ expect(result.history).toHaveLength(50);
+ expect(result.history.at(-1)).toEqual({
content: "model call 50",
role: "assistant",
});
@@ -1203,6 +1213,7 @@ describe("turnStep", () => {
vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_new");
await turnStep({
+ history: session.history,
input: { kind: "deliver", payloads: [{ message: "follow up" }] },
sessionWritable: createTestWritable(),
serializedContext: serializeContext(ctx),
@@ -1258,9 +1269,10 @@ describe("turnStep", () => {
turnAgent: TestTurnAgent,
} as never;
vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue(compiledBundle);
- installSessionStoreMocks([
- createStubSession({ history: [{ content: "raw", kind: "user", role: "user" }] }),
- ]);
+ const session = createStubSession({
+ history: [{ content: "raw", kind: "user", role: "user" }],
+ });
+ installSessionStoreMocks([session]);
mockIdentityHistoryViewProjector.mockImplementation(() => {
throw new Error("projection failed");
});
@@ -1275,6 +1287,7 @@ describe("turnStep", () => {
await expect(
turnStep({
+ history: session.history,
input: { kind: "deliver", payloads: [{ message: "hello" }] },
sessionWritable: createTestWritable(),
serializedContext: serializeContext(ctx),
@@ -1427,6 +1440,7 @@ describe("turnStep", () => {
});
const result = await turnStep({
+ history: session.history,
input: {
kind: "deliver",
payloads: [{ message: "cancel this turn" }],
@@ -1460,7 +1474,7 @@ describe("turnStep", () => {
},
});
expect(result.serializedContext).not.toHaveProperty(ThreadKey.name);
- expect(result.sessionState.snapshot.session.history).toEqual([
+ expect(result.history).toEqual([
{ role: "user", content: announcement, kind: "user" },
{ content: "thread=unset; user=cancel this turn", kind: "user", role: "user" },
]);
@@ -1505,7 +1519,7 @@ describe("turnStep", () => {
});
expect(result).toMatchObject({ action: "cancelled" });
- expect(result.sessionState.snapshot.session.history).toEqual([
+ expect(result.history).toEqual([
{
content: [
{ text: "thread=unset; user=look at this", type: "text" },
@@ -2140,9 +2154,9 @@ describe("turnStep", () => {
});
expect(readDurableSession).toHaveBeenCalledWith(sessionState);
- expect(createDurableSessionState).toHaveBeenLastCalledWith({
- session: expect.objectContaining({ sessionId: "turn-step-session" }),
- });
+ expect(createDurableSessionValues).toHaveBeenLastCalledWith(
+ expect.objectContaining({ sessionId: "turn-step-session" }),
+ );
});
it("persists onDeliver context into the next durable step", async () => {
@@ -2352,13 +2366,13 @@ describe("turnStep", () => {
});
expect(observedSystemPrompt).toBe("Updated instructions.\n\nUpdated runtime context.");
- expect(createDurableSessionState).toHaveBeenLastCalledWith({
- session: expect.objectContaining({
+ expect(createDurableSessionValues).toHaveBeenLastCalledWith(
+ expect.objectContaining({
agent: expect.objectContaining({
system: "Updated instructions.\n\nUpdated runtime context.",
}),
}),
- });
+ );
});
it("refreshes session-scoped dynamic tools from the current deployment", async () => {
@@ -2616,6 +2630,7 @@ describe("turnStep", () => {
});
const result = await turnStep({
+ history: session.history,
input: {
kind: "deliver",
payloads: [
@@ -2645,7 +2660,7 @@ describe("turnStep", () => {
if (result.action === "park") {
expect(result.authorizationAttemptIds).toBeUndefined();
}
- const persistedSession = vi.mocked(createDurableSessionState).mock.calls.at(-1)?.[0].session;
+ const persistedSession = vi.mocked(createDurableSessionValues).mock.calls.at(-1)?.[0];
expect(persistedSession?.state?.retained).toBe("yes");
expect(getPendingAuthorization(persistedSession?.state)).toBeUndefined();
expect(instructionHandler).toHaveBeenCalledTimes(2);
diff --git a/packages/eve/src/execution/session/turn-step.ts b/packages/eve/src/execution/session/turn-step.ts
index 12c911cc2..55e32aa80 100644
--- a/packages/eve/src/execution/session/turn-step.ts
+++ b/packages/eve/src/execution/session/turn-step.ts
@@ -74,7 +74,10 @@ import {
} from "#harness/authorization.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
import { countRunUsage } from "#execution/agent-sessions/usage.js";
-import { createDurableSessionState, readDurableSession } from "#execution/durable-session-store.js";
+import {
+ createDurableSessionValues,
+ readDurableSession,
+} from "#execution/durable-session-store.js";
import { buildRuntimeIdentity, createExecutionNodeStep } from "#execution/node-step.js";
import { prepareWorkflowPreambleTrace } from "#execution/workflow-trace-context.js";
import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";
@@ -162,13 +165,16 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
ctx.set(AuthKey, delivery.auth ?? null);
if (!ctx.has(InitiatorAuthKey)) ctx.set(InitiatorAuthKey, delivery.auth ?? null);
}
- const initialSession = hydrateDurableSession({
- compactionOverrides: {
- thresholdPercent: effectiveAgent.thresholdPercent,
- },
- durable: durableSession,
- turnAgent: effectiveAgent.turnAgent,
- });
+ const initialSession: HarnessSession = {
+ ...hydrateDurableSession({
+ compactionOverrides: {
+ thresholdPercent: effectiveAgent.thresholdPercent,
+ },
+ durable: durableSession,
+ turnAgent: effectiveAgent.turnAgent,
+ }),
+ history: validateHarnessModelMessages(input.history),
+ };
const history = createExecutionHistoryView(initialSession);
const instrumentation = bindSessionInstrumentation({
agentName: effectiveAgent.turnAgent.id,
@@ -326,16 +332,16 @@ async function runSessionStep(input: TurnStepInput): Promise<DurableStepResult>
await instrumentation?.flush();
const aliased = reconcileSessionContinuationToken(ctx, initialSession);
const nextSerializedContext = serializeContext(ctx);
- const nextState =
+ const nextValues =
aliased === initialSession
- ? input.sessionState
- : createDurableSessionState({ session: aliased });
+ ? { history: input.history, sessionState: input.sessionState }
+ : createDurableSessionValues(aliased);
return {
action: "park",
...derivePendingState(aliased),
serializedContext: nextSerializedContext,
- sessionState: nextState,
+ ...nextValues,
};
}
diff --git a/packages/eve/src/execution/session/turn.test.ts b/packages/eve/src/execution/session/turn.test.ts
index d6c16f4dd..bdb02e83a 100644
--- a/packages/eve/src/execution/session/turn.test.ts
+++ b/packages/eve/src/execution/session/turn.test.ts
@@ -85,7 +85,13 @@ function stepWork<I extends Partial<SessionStateValues>, R extends Partial<Sessi
): (input: I) => Promise<WithSessionStateDelta<R>> {
return (input) => withSessionStateDelta(input, work);
}
-const turnStepWork = stepWork<TurnStepInput, DurableStepResult>;
+/** These turns leave the history alone, so their work omits it, which the delta reads as unchanged. */
+type TurnStepWorkResult = DurableStepResult extends infer R
+ ? R extends unknown
+ ? Omit<R, "history">
+ : never
+ : never;
+const turnStepWork = stepWork<TurnStepInput, TurnStepWorkResult>;
const dispatchWork = stepWork<
Parameters<typeof dispatchCoordinationStep>[0],
CoordinationDispatchResult
@@ -1020,6 +1026,7 @@ describe("SessionExecution checkpoints", () => {
dispatchWork(async () => ({ results: [], serializedContext: {}, sessionState })),
);
const cursor = new SessionStateCursor({
+ history: [],
inbox,
serializedContext: {},
sessionState,
@@ -1388,6 +1395,7 @@ function createCursor(input: {
readonly sessionState: DurableSessionState;
}): SessionStateCursor {
return new SessionStateCursor({
+ history: [],
inbox: input.inbox,
sessionWritable: new WritableStream<Uint8Array>(),
serializedContext: input.serializedContext ?? {},
@@ -1419,6 +1427,5 @@ function state(continuationToken: string): DurableSessionState {
emissionState: { sequence: 0, sessionStarted: true, stepIndex: 0, turnId: "turn_0" },
hasProxyInputRequests: false,
sessionId: "session-1",
- version: 1,
});
}
diff --git a/packages/eve/src/execution/session/turn.ts b/packages/eve/src/execution/session/turn.ts
index 6296206a7..3d2bcfc86 100644
--- a/packages/eve/src/execution/session/turn.ts
+++ b/packages/eve/src/execution/session/turn.ts
@@ -151,7 +151,7 @@ export class SessionExecution {
while (true) {
const { cursor } = this.input;
- const result = await cursor.advance((state) =>
+ const result = await cursor.advanceWithHistory((state) =>
turnStep({
...state,
abortSignal: turn.signal,
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
index 6b19f4794..de555df10 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.integration.test.ts
@@ -82,6 +82,7 @@ describe("settleCancelledTurnStep", () => {
const cancelling = spend(settled, 50, "turn_2");
const result = await settleCancelledTurn({
+ history: [],
reportUsage,
serializedContext,
sessionState: { ...base, snapshot: { session: cancelling } },
@@ -113,6 +114,7 @@ describe("settleCancelledTurnStep", () => {
);
const result = await settleCancelledTurn({
+ history: [],
reportUsage: false,
serializedContext,
sessionState: { ...base, snapshot: { session: { ...base.snapshot.session, state } } },
diff --git a/packages/eve/src/execution/settle-cancelled-turn-step.ts b/packages/eve/src/execution/settle-cancelled-turn-step.ts
index 354b9d631..c5a42c02c 100644
--- a/packages/eve/src/execution/settle-cancelled-turn-step.ts
+++ b/packages/eve/src/execution/settle-cancelled-turn-step.ts
@@ -3,13 +3,18 @@ import {
getPendingCoordinationBatch,
} from "#harness/coordination.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
-import { publishFromSessionStep, restoreSessionStep } from "#execution/publish-session-events.js";
+import {
+ publishFromSessionStep,
+ restoreSessionStep,
+ type SessionHistoryStepState,
+} from "#execution/publish-session-events.js";
import {
withSessionStateDelta,
type WithSessionStateDelta,
} from "#execution/session/state-delta.js";
import { relayWithdrawnRequests } from "#execution/tools/workflow/withdraw-step.js";
import { emitCancelledTurn } from "#harness/cancelled-turn-emission.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import { clearPendingSessionLimitPrompt } from "#harness/input-requests.js";
import { getHarnessEmissionState, setHarnessEmissionState } from "#harness/emission.js";
import { removeBlockingWorkflowToolRuns } from "#harness/workflow-tool-runs.js";
@@ -19,19 +24,18 @@ import type { TokenUsage } from "#shared/token-usage.js";
export interface CancelledTurnSettleResult {
readonly serializedContext: Record<string, unknown>;
readonly sessionState: DurableSessionState;
+ readonly history: HarnessModelMessage[];
/** What the session spent since its caller's last report, when asked to report it. */
readonly usage?: TokenUsage;
}
-interface CancelledTurnSettleInput {
+/** Takes the history because the turn's pending calls move into it, each answered as cancelled. */
+interface CancelledTurnSettleInput extends SessionHistoryStepState {
/**
* Whether a caller receives the turn's usage. Only then is it marked
* reported; otherwise the next settled turn reports it.
*/
readonly reportUsage: boolean;
- readonly sessionWritable: WritableStream<Uint8Array>;
- readonly serializedContext: Record<string, unknown>;
- readonly sessionState: DurableSessionState;
}
/**
@@ -54,7 +58,10 @@ export async function settleCancelledTurn(
): Promise<CancelledTurnSettleResult> {
// The cancel stopped every descendant and task, so nobody can answer a request the session relays.
const relayed = await relayWithdrawnRequests(input, () => true);
- const step = await restoreSessionStep({ ...relayed, sessionWritable: input.sessionWritable });
+ const step = {
+ ...(await restoreSessionStep({ ...relayed, sessionWritable: input.sessionWritable })),
+ history: input.history,
+ };
const durableState = step.durableSession.state;
const { published, result: usage } = await publishFromSessionStep(step, {
origin: "own",
diff --git a/packages/eve/src/execution/tasks/session.test.ts b/packages/eve/src/execution/tasks/session.test.ts
index 72fd3a081..908339888 100644
--- a/packages/eve/src/execution/tasks/session.test.ts
+++ b/packages/eve/src/execution/tasks/session.test.ts
@@ -166,6 +166,7 @@ describe("applyTaskRunMessageStep", () => {
function cursorFor(session: DurableSession): SessionStateCursor {
return new SessionStateCursor({
+ history: [],
inbox: { claimSessionHooks: vi.fn() } as Partial<SessionInbox> as SessionInbox,
serializedContext: {},
sessionState: {
diff --git a/packages/eve/src/execution/tasks/start.ts b/packages/eve/src/execution/tasks/start.ts
index ee7cdc3c2..866662cac 100644
--- a/packages/eve/src/execution/tasks/start.ts
+++ b/packages/eve/src/execution/tasks/start.ts
@@ -26,7 +26,7 @@ import {
} from "#execution/tools/workflow/start.js";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
import { createTaskStartedEvent, type TaskStartedStreamEvent } from "#protocol/message.js";
import { TOO_MANY_TASKS_CODE, UNKNOWN_TASK_CODE } from "#protocol/task-tools.js";
import type { RuntimeToolResultActionResult, WorkflowToolRunEntry } from "#shared/action-types.js";
@@ -38,7 +38,7 @@ type TaskDispatchInput = StartWorkflowTaskInput & { readonly taskId: string };
/** The call's answer, and the `task.started` event the dispatch step publishes for it. */
interface TaskDispatchResult {
readonly result: RuntimeToolResultActionResult;
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
readonly started?: TaskStartedStreamEvent;
}
diff --git a/packages/eve/src/execution/tasks/task-run-usage.test.ts b/packages/eve/src/execution/tasks/task-run-usage.test.ts
index 3d6c57c64..bd247f6bf 100644
--- a/packages/eve/src/execution/tasks/task-run-usage.test.ts
+++ b/packages/eve/src/execution/tasks/task-run-usage.test.ts
@@ -84,6 +84,7 @@ function sessionWithTask(input: {
onInterrupt: () => () => {},
} as Partial<SessionInbox> as SessionInbox;
const cursor = new SessionStateCursor({
+ history: [],
inbox,
serializedContext: {},
sessionState: { ...base, snapshot: { session: snapshot } },
diff --git a/packages/eve/src/execution/tools/workflow/start.ts b/packages/eve/src/execution/tools/workflow/start.ts
index c2d639a34..e367efbf8 100644
--- a/packages/eve/src/execution/tools/workflow/start.ts
+++ b/packages/eve/src/execution/tools/workflow/start.ts
@@ -3,7 +3,7 @@ import type { AgentSessionContext } from "#execution/agent-sessions/context.js";
import { createRuntimeToolResultFromValue } from "#harness/action-result-helpers.js";
import { registerWorkflowToolRun } from "#harness/workflow-tool-runs.js";
import { createLogger, logError } from "#internal/logging.js";
-import type { HarnessSession } from "#harness/types.js";
+import type { HarnessSessionBase } from "#harness/types.js";
import type {
RuntimeToolResultActionResult,
RuntimeWorkflowTaskRequest,
@@ -58,7 +58,7 @@ export interface StartWorkflowTaskInput {
};
readonly owner: WorkflowToolRunOwner;
readonly parentSession: SessionParent | undefined;
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
readonly task: RuntimeWorkflowTaskRequest;
}
@@ -88,9 +88,10 @@ export async function startWorkflowToolCallRun(
}
/** Starts the run of an `execute` call the turn waits on and records it on the owning session. */
-export async function startWorkflowTask(
- input: StartWorkflowTaskInput,
-): Promise<{ readonly result?: RuntimeToolResultActionResult; readonly session: HarnessSession }> {
+export async function startWorkflowTask(input: StartWorkflowTaskInput): Promise<{
+ readonly result?: RuntimeToolResultActionResult;
+ readonly session: HarnessSessionBase;
+}> {
const { task, batchEvent, session } = input;
try {
const started = await startWorkflowToolCallRun(input, { entryPoint: "execute" });
diff --git a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
index e5153df88..6c97ee831 100644
--- a/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
+++ b/packages/eve/src/execution/tools/workflow/workflow-tool-run.integration.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { start } from "#internal/workflow/runtime.js";
+import { hydrateStepArguments } from "#compiled/@workflow/core/serialization.js";
+import { getWorld, start } from "#internal/workflow/runtime.js";
import {
captureTurnEvents,
containsEventSequence,
@@ -411,4 +412,68 @@ describe("workflow tools", () => {
}
});
}, 30_000);
+
+ it("keeps the conversation out of the step input of a session step that only publishes", async () => {
+ const runtime = await createWorkflowToolRuntime({
+ agentName: "workflow-tool-step-input",
+ execute: reportingDeployWorkflow,
+ toolName: "deploy_service",
+ });
+ // Not the first message, which also becomes the session title in the context.
+ const earlyNote = "Alice notes that the api rollout window opens at noon.";
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ kind: "initial",
+ ownerDeploymentId: "dpl_inline",
+ input: { message: "Alice starts planning the api rollout." },
+ serializedContext: buildWorkflowToolSerializedContext({
+ continuationToken: "http:workflow-tool-step-input",
+ }),
+ },
+ ]);
+ const stream = captureTurnEvents(run);
+ const send = async (message: string) => {
+ await resumeSessionInbox(sessionCommandHookToken(run.runId), {
+ kind: "send",
+ payload: { message },
+ });
+ return await stream.nextTurn();
+ };
+ try {
+ await stream.nextTurn();
+ await send(earlyNote);
+ const settled = await send('Run deploy_service with service "api"');
+ expect(filterEventsByType(settled, "action.partial")).toHaveLength(1);
+
+ const inputs = await readStepInputs(run.runId);
+ const reportInputs = inputs.get("emitWorkflowToolRunReportStep") ?? [];
+ expect(reportInputs).toHaveLength(1);
+ expect(reportInputs[0]).not.toContain(earlyNote);
+ expect(inputs.get("turnStep")?.at(-1)).toContain(earlyNote);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ }, 30_000);
});
+
+/** Each step's persisted `step_created` input, serialized, grouped by step name in creation order. */
+async function readStepInputs(runId: string): Promise<Map<string, string[]>> {
+ const world = await getWorld();
+ const events = await world.events.list({
+ pagination: { limit: 1000 },
+ resolveData: "all",
+ runId,
+ });
+ const inputs = new Map<string, string[]>();
+ for (const event of events.data) {
+ if (event.eventType !== "step_created") continue;
+ const name = event.eventData.stepName.split("//").at(-1) ?? "";
+ const input = await hydrateStepArguments(event.eventData.input, runId, undefined);
+ inputs.set(name, [...(inputs.get(name) ?? []), JSON.stringify(input)]);
+ }
+ return inputs;
+}
diff --git a/packages/eve/src/harness/coordination.ts b/packages/eve/src/harness/coordination.ts
index 9191ac512..734f919cf 100644
--- a/packages/eve/src/harness/coordination.ts
+++ b/packages/eve/src/harness/coordination.ts
@@ -157,12 +157,12 @@ function approvedSiblingCalls(
/**
* Stores one pending coordination batch on the session.
*/
-export function setPendingCoordinationBatch(input: {
+export function setPendingCoordinationBatch<T extends { readonly state?: SessionStateMap }>(input: {
readonly tasks: readonly RuntimeWorkflowTaskRequest[];
readonly event: PendingCoordinationEventMetadata;
readonly responseMessages: readonly ModelMessage[];
- readonly session: HarnessSession;
-}): HarnessSession {
+ readonly session: T;
+}): T {
assertUniqueCoordinationCallIds(input.tasks);
const state = { ...input.session.state };
state[PENDING_COORDINATION_BATCH_KEY] = {
diff --git a/packages/eve/src/harness/proxy-input-requests.ts b/packages/eve/src/harness/proxy-input-requests.ts
index 0990cbef3..bcb9f640f 100644
--- a/packages/eve/src/harness/proxy-input-requests.ts
+++ b/packages/eve/src/harness/proxy-input-requests.ts
@@ -1,6 +1,6 @@
import type { SubagentInputRequestHookPayload } from "#channel/types.js";
import type { PendingInputBatchEvent } from "#harness/pending-input-batches.js";
-import type { HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { HarnessSessionBase, SessionStateMap } from "#harness/types.js";
import { inputOptionSchema, type InputOption, type InputRequestKind } from "#shared/input.js";
import {
isSessionInboxAddress,
@@ -94,12 +94,12 @@ export function hasProxyInputRequests(state: SessionStateMap | undefined): boole
* parent never keeps stale request metadata. Other sources' routes stay
* independently answerable.
*/
-export function upsertProxyInputRequests(input: {
+export function upsertProxyInputRequests<S extends HarnessSessionBase>(input: {
readonly inputSource?: string;
readonly entries: readonly (readonly [requestId: string, route: ProxyInputRequest])[];
readonly forChildContinuationToken: string;
- readonly session: HarnessSession;
-}): HarnessSession {
+ readonly session: S;
+}): S {
return {
...input.session,
state: upsertProxyInputRequestState({
diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.ts
index da2dfdc42..6f51e3a41 100644
--- a/packages/eve/src/harness/types.ts
+++ b/packages/eve/src/harness/types.ts
@@ -70,16 +70,14 @@ export type SessionAgent = SessionAgentBase &
);
/**
- * Serializable session state passed between harness and runtime.
- *
- * Only contains plain data -- no resolved model instances or tool execute
- * functions. The harness resolves those at step time via injected config.
+ * A {@link HarnessSession} without its conversation history. Session steps
+ * that only publish events or change `state` rebuild this, so the history
+ * never becomes part of their Workflow step input.
*/
-export interface HarnessSession {
+export interface HarnessSessionBase {
readonly agent: SessionAgent;
readonly compaction: CompactionConfig;
readonly continuationToken: string;
- readonly history: HarnessModelMessage[];
readonly limits?: SessionLimits;
readonly outputSchema?: JsonObject;
/**
@@ -96,6 +94,16 @@ export interface HarnessSession {
readonly state?: SessionStateMap;
}
+/**
+ * Serializable session state passed between harness and runtime.
+ *
+ * Only contains plain data -- no resolved model instances or tool execute
+ * functions. The harness resolves those at step time via injected config.
+ */
+export interface HarnessSession extends HarnessSessionBase {
+ readonly history: HarnessModelMessage[];
+}
+
export function requireSessionModelReference(session: HarnessSession): RuntimeModelReference {
const reference = session.agent.modelReference;
if (reference === undefined) {
diff --git a/packages/eve/src/internal/testing/durable-session-workflow.ts b/packages/eve/src/internal/testing/durable-session-workflow.ts
index c91e7751b..338cef495 100644
--- a/packages/eve/src/internal/testing/durable-session-workflow.ts
+++ b/packages/eve/src/internal/testing/durable-session-workflow.ts
@@ -1,15 +1,16 @@
/**
- * Test fixture exercising the `createDurableSessionState` /
+ * Test fixture exercising the `createDurableSessionValues` /
* `readDurableSession` round-trip from inside a real workflow runtime.
* The workflow test-time bundle builder discovers this directory.
*/
import { getStepMetadata, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";
import {
- createDurableSessionState,
+ createDurableSessionValues,
type DurableSessionState,
readDurableSession,
} from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
import type { HarnessSession } from "#harness/types.js";
/** Synthetic minimal session for storage-layer round-trips. */
@@ -45,12 +46,17 @@ function buildSyntheticSession(input: {
};
}
-/** Writes one synthetic snapshot into the returned durable state. */
+interface DurableSessionValues {
+ readonly history: HarnessModelMessage[];
+ readonly sessionState: DurableSessionState;
+}
+
+/** Writes one synthetic snapshot into the returned durable values. */
async function durableSessionWriteStep(input: {
readonly marker: string;
readonly historyDepth: number;
readonly sessionId: string;
-}): Promise<DurableSessionState> {
+}): Promise<DurableSessionValues> {
"use step";
const session = buildSyntheticSession({
@@ -59,7 +65,7 @@ async function durableSessionWriteStep(input: {
sessionId: input.sessionId,
});
- return createDurableSessionState({ session });
+ return createDurableSessionValues(session);
}
/**
@@ -71,7 +77,7 @@ async function durableSessionWriteWithRetryStep(input: {
readonly marker: string;
readonly historyDepth: number;
readonly sessionId: string;
-}): Promise<{ readonly attempt: number; readonly sessionState: DurableSessionState }> {
+}): Promise<{ readonly attempt: number; readonly values: DurableSessionValues }> {
"use step";
const meta = getStepMetadata();
@@ -86,15 +92,11 @@ async function durableSessionWriteWithRetryStep(input: {
sessionId: input.sessionId,
});
- const sessionState = createDurableSessionState({ session });
-
- return { attempt: meta.attempt, sessionState };
+ return { attempt: meta.attempt, values: createDurableSessionValues(session) };
}
/** Reads the latest snapshot and projects the fields the test asserts on. */
-async function durableSessionReadStep(input: {
- readonly sessionState: DurableSessionState;
-}): Promise<{
+async function durableSessionReadStep(input: DurableSessionValues): Promise<{
readonly marker: string;
readonly historyDepth: number;
readonly sessionId: string;
@@ -104,7 +106,7 @@ async function durableSessionReadStep(input: {
const durable = readDurableSession(input.sessionState);
return {
- historyDepth: durable.history.length,
+ historyDepth: input.history.length,
marker: durable.agent.system,
sessionId: durable.sessionId,
};
@@ -145,7 +147,7 @@ export async function durableSessionStoreFixtureWorkflow(
historyDepth: number;
sessionId: string;
}[] = [];
- let currentState: DurableSessionState | undefined;
+ let currentState: DurableSessionValues | undefined;
for (const entry of input.markers) {
currentState = await durableSessionWriteStep({
@@ -153,7 +155,7 @@ export async function durableSessionStoreFixtureWorkflow(
marker: entry.marker,
sessionId,
});
- const read = await durableSessionReadStep({ sessionState: currentState });
+ const read = await durableSessionReadStep(currentState);
readsAfterEachWrite.push(read);
}
@@ -161,7 +163,7 @@ export async function durableSessionStoreFixtureWorkflow(
throw new Error("durable-session-store fixture requires at least one marker");
}
- const tailReadAfterAllWrites = await durableSessionReadStep({ sessionState: currentState });
+ const tailReadAfterAllWrites = await durableSessionReadStep(currentState);
return {
readsAfterEachWrite,
@@ -194,13 +196,13 @@ export async function durableSessionRetryFixtureWorkflow(): Promise<DurableSessi
sessionId,
});
- const { attempt: writeAttempt, sessionState } = await durableSessionWriteWithRetryStep({
+ const { attempt: writeAttempt, values } = await durableSessionWriteWithRetryStep({
historyDepth: 9,
marker: "after-retry",
sessionId,
});
- const readAfterRetry = await durableSessionReadStep({ sessionState });
+ const readAfterRetry = await durableSessionReadStep(values);
return {
readAfterRetry,
diff --git a/packages/eve/src/internal/testing/legacy-session-driver-workflow.ts b/packages/eve/src/internal/testing/legacy-session-driver-workflow.ts
index 937f5c950..06ac05ecb 100644
--- a/packages/eve/src/internal/testing/legacy-session-driver-workflow.ts
+++ b/packages/eve/src/internal/testing/legacy-session-driver-workflow.ts
@@ -2,6 +2,7 @@ import { createHook, getWorkflowMetadata, getWritable } from "#compiled/@workflo
import { start } from "#internal/workflow/runtime.js";
import { turnWorkflow } from "#execution/legacy-session/turn-workflow.js";
import type { DurableSession } from "#execution/durable-session-store.js";
+import type { HarnessModelMessage } from "#harness/messages.js";
/** Frozen driver-side protocol: it cannot see the current session inbox. */
export async function legacySessionDriverWorkflow(input: {
@@ -29,7 +30,7 @@ export async function legacySessionDriverWorkflow(input: {
const parentWritable = getWritable<Uint8Array>();
try {
const delivery = await command;
- const session: DurableSession = {
+ const session: DurableSession & { readonly history: HarnessModelMessage[] } = {
sessionId,
continuationToken: input.alias,
agent: { system: "previous deployment" },
diff --git a/packages/eve/src/internal/testing/session-state-step.ts b/packages/eve/src/internal/testing/session-state-step.ts
index b3c68c91c..036c09686 100644
--- a/packages/eve/src/internal/testing/session-state-step.ts
+++ b/packages/eve/src/internal/testing/session-state-step.ts
@@ -19,6 +19,7 @@ export async function runSessionStateStep<
>(input: I, step: (input: I) => Promise<R>): Promise<AppliedSessionStateStep<I, R>> {
const serializedContext = snapshotValue(input.serializedContext);
const sessionState = snapshotValue(input.sessionState);
+ const history = snapshotValue(input.history);
const { stateDelta, ...result } = await step(input);
const applied: Partial<SessionStateValues> = {
...(serializedContext !== undefined && {
@@ -27,6 +28,7 @@ export async function runSessionStateStep<
...(sessionState !== undefined && {
sessionState: applyValueDelta(sessionState, stateDelta.sessionState),
}),
+ ...(history !== undefined && { history: applyValueDelta(history, stateDelta.history) }),
};
return { ...result, ...applied } as AppliedSessionStateStep<I, R>;
}
diff --git a/packages/eve/src/internal/testing/session-state.ts b/packages/eve/src/internal/testing/session-state.ts
index 8a95d3138..11b91b0a5 100644
--- a/packages/eve/src/internal/testing/session-state.ts
+++ b/packages/eve/src/internal/testing/session-state.ts
@@ -17,7 +17,6 @@ export function createTestSessionState(
session: {
agent: { system: "" },
continuationToken: overrides.continuationToken ?? "test-token",
- history: [],
sessionId: overrides.sessionId ?? "test-session",
},
},
diff --git a/packages/eve/src/public/models/openai/chatgpt/model.integration.test.ts b/packages/eve/src/public/models/openai/chatgpt/model.integration.test.ts
index d16a3d5a3..45beb62ee 100644
--- a/packages/eve/src/public/models/openai/chatgpt/model.integration.test.ts
+++ b/packages/eve/src/public/models/openai/chatgpt/model.integration.test.ts
@@ -1,7 +1,7 @@
import { jsonSchema } from "ai";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { createDurableSessionState } from "#execution/durable-session-store.js";
+import { createDurableSessionValues } from "#execution/durable-session-store.js";
import { createToolLoopHarness } from "#harness/tool-loop.js";
import type { HarnessSession } from "#harness/types.js";
import { createCodexSubscriptionModel } from "./model.js";
@@ -75,11 +75,10 @@ describe("ChatGPT streamed reasoning replay", () => {
expect(execute).toHaveBeenCalledOnce();
if (typeof first.next !== "function") throw new Error("Expected a second model step.");
- const stored: ReturnType<typeof createDurableSessionState> = JSON.parse(
- JSON.stringify(createDurableSessionState({ session: first.session })),
+ const stored: ReturnType<typeof createDurableSessionValues> = JSON.parse(
+ JSON.stringify(createDurableSessionValues(first.session)),
);
- if (stored.snapshot === undefined) throw new Error("Expected a durable snapshot.");
- const history = stored.snapshot.session.history;
+ const history = stored.history;
const reasoning = history.flatMap((message) =>
message.role === "assistant" && Array.isArray(message.content)
? message.content.filter((part) => part.type === "reasoning")
diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.ts
index 9db10300c..2a14f9ede 100644
--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts
+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts
@@ -75,7 +75,6 @@ function fixture() {
const durableSession: DurableSession = {
agent: { system: "" },
continuationToken: "http:parent",
- history: [],
sessionId: "parent-session",
state: {
"eve.harness.emission": {
diff --git a/packages/eve/src/subagents/hitl-proxy.ts b/packages/eve/src/subagents/hitl-proxy.ts
index 09ec260cc..c46895f41 100644
--- a/packages/eve/src/subagents/hitl-proxy.ts
+++ b/packages/eve/src/subagents/hitl-proxy.ts
@@ -12,7 +12,7 @@ import {
toProxyInputRequestEntries,
} from "#harness/proxy-input-requests.js";
import type { WorkflowAskRoute, ProxyInputRequest } from "#harness/proxy-input-requests.js";
-import type { HarnessEmitFn, HarnessSession, SessionStateMap } from "#harness/types.js";
+import type { HarnessEmitFn, HarnessSessionBase, SessionStateMap } from "#harness/types.js";
import {
createInputRequestedEvent,
createTurnWaitingEvent,
@@ -35,7 +35,7 @@ import { SESSION_LIMIT_STOP_OPTION_ID } from "#harness/session-limit-continuatio
export async function emitProxiedInputRequest(input: {
readonly emit: HarnessEmitFn;
readonly hookPayload: SubagentInputRequestHookPayload;
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
}): Promise<readonly (readonly [requestId: string, route: ProxyInputRequest])[]> {
await input.emit(
createInputRequestedEvent({
@@ -59,7 +59,7 @@ export async function emitProxiedInputRequest(input: {
export async function emitProxiedAuthorizationEvent(input: {
readonly emit: HarnessEmitFn;
readonly hookPayload: SubagentAuthorizationEventHookPayload;
- readonly session: HarnessSession;
+ readonly session: HarnessSessionBase;
}): Promise<void> {
await input.emit(input.hookPayload.event);
if (input.hookPayload.event.type === "authorization.required") {
@@ -67,7 +67,7 @@ export async function emitProxiedAuthorizationEvent(input: {
}
}
-async function emitTurnWaiting(emit: HarnessEmitFn, session: HarnessSession): Promise<void> {
+async function emitTurnWaiting(emit: HarnessEmitFn, session: HarnessSessionBase): Promise<void> {
const turn = getHarnessEmissionState(session.state);
await emit(createTurnWaitingEvent({ sequence: turn.sequence, turnId: turn.turnId }));
}