Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add session snapshots (#1404)

Timo Lins6f3daca2a115
diff --git a/.changeset/session-snapshot.md b/.changeset/session-snapshot.md
new file mode 100644
index 000000000..599747a2a
--- /dev/null
+++ b/.changeset/session-snapshot.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Add `ClientSession.snapshot()` for reading a finite, cursor-consistent session event prefix that can hydrate server-rendered applications.
diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdx
index 3442e847c..12180a1f5 100644
--- a/docs/guides/client/streaming.mdx
+++ b/docs/guides/client/streaming.mdx
@@ -180,6 +180,30 @@ Because a tail-relative cursor cannot be bounded, `follow: false` throws when co
`stream()` throws if the session has no `sessionId`, because there's no stream to attach to before the first send.
+## Snapshot a session
+
+Use `snapshot()` when you need the complete event prefix and its matching cursor
+as one value, such as when hydrating a server-rendered chat:
+
+```ts
+const session = client.session({ sessionId, streamIndex: 0 });
+const snapshot = await session.snapshot();
+
+// snapshot.events contains event indexes 0 through snapshot.session.streamIndex - 1.
+```
+
+The read pins the durable tail when it opens, just like
+`stream({ follow: false })`. Events written afterward are not included, and
+`snapshot.session.streamIndex` is the exact index from which a live consumer can
+continue. `snapshot()` always reads from index `0`; use a bounded stream directly
+when you only need the unread suffix from an existing cursor.
+
+Unlike `stream()`, `snapshot()` does not advance or reset the originating
+`ClientSession`. Its returned session includes a continuation token only when
+the captured prefix ends in `session.waiting`, or when completed sessions are
+explicitly preserved by the client. Active and terminal snapshots remain
+inspectable at their returned stream cursor but cannot accept another turn.
+
## Abort a request
Pass an `AbortSignal` to cancel the POST or stream. Aborting is local transport cancellation: turns are resumable across disconnects, so detaching never stops the server-side turn — it keeps running and remains attachable by index. To stop the turn itself, POST the session's [cancel route](../../channels/eve#routes) and watch the stream settle with `turn.cancelled` followed by `session.waiting`.
diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.ts
index 1555e66a0..46a6d2c94 100644
--- a/packages/eve/src/client/index.ts
+++ b/packages/eve/src/client/index.ts
@@ -53,6 +53,7 @@ export type {
ResolvedStreamReconnectPolicy,
SendTurnInput,
SendTurnPayload,
+ SessionSnapshot,
SessionState,
StreamOptions,
StreamReconnectPolicy,
diff --git a/packages/eve/src/client/open-stream.ts b/packages/eve/src/client/open-stream.ts
index 1637b435c..19ccaaa0b 100644
--- a/packages/eve/src/client/open-stream.ts
+++ b/packages/eve/src/client/open-stream.ts
@@ -234,6 +234,7 @@ export async function openStreamBody(
let response: Response;
try {
response = await fetch(url, {
+ cache: "no-store",
headers,
redirect: input.redirect,
signal: input.signal ?? null,
diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.ts
index 58e47565c..dd3db326b 100644
--- a/packages/eve/src/client/session.test.ts
+++ b/packages/eve/src/client/session.test.ts
@@ -72,6 +72,12 @@ function createStreamResponse(events: readonly unknown[]) {
);
}
+function createBoundedStreamResponse(events: readonly unknown[]) {
+ const response = createStreamResponse(events);
+ response.headers.set("x-eve-stream-tail-index", String(events.length - 1));
+ return response;
+}
+
describe("ClientSession", () => {
it("cancels an accepted turn before its stream settles with freshly resolved auth", async () => {
let headerResolution = 0;
@@ -119,6 +125,164 @@ describe("ClientSession", () => {
await expect(createSession().cancel()).rejects.toThrow("Session has no session ID");
});
+ it("snapshots the session from the start through one pinned durable tail", async () => {
+ const requests: string[] = [];
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {
+ const url =
+ typeof request === "string" ? request : request instanceof URL ? request.href : request.url;
+ requests.push(url);
+ expect(init?.cache).toBe("no-store");
+ const events = [
+ { type: "turn.started", data: { turnId: "turn_1" } },
+ {
+ type: "session.waiting",
+ data: { continuationToken: "eve:current", wait: "next-user-message" },
+ },
+ ];
+ return createBoundedStreamResponse(events);
+ });
+ const initialState = {
+ continuationToken: "eve:stale",
+ sessionId: "session_1",
+ streamIndex: 9,
+ };
+ const session = createSession(initialState);
+
+ const snapshot = await session.snapshot();
+
+ const requestUrl = new URL(requests[0]!);
+ expect(requestUrl.searchParams.get("startIndex")).toBeNull();
+ expect(requestUrl.searchParams.get("includeTailIndex")).toBe("1");
+ expect(snapshot.events.map((event) => event.type)).toEqual(["turn.started", "session.waiting"]);
+ expect(snapshot.session).toEqual({
+ continuationToken: "eve:current",
+ sessionId: "session_1",
+ streamIndex: 2,
+ });
+ expect(session.state).toBe(initialState);
+ });
+
+ it("returns a completed stream cursor without resetting the handle", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ createBoundedStreamResponse([
+ {
+ type: "session.completed",
+ data: { reason: "completed" },
+ },
+ ]),
+ );
+ const initialState = { sessionId: "session_1", streamIndex: 0 };
+ const session = createSession(initialState);
+
+ const snapshot = await session.snapshot();
+
+ expect(snapshot.session).toEqual({ sessionId: "session_1", streamIndex: 1 });
+ expect(session.state).toBe(initialState);
+ });
+
+ it("returns a failed stream cursor without resetting the handle", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ createBoundedStreamResponse([
+ {
+ type: "session.failed",
+ data: { code: "failed", message: "The session failed." },
+ },
+ ]),
+ );
+ const initialState = {
+ continuationToken: "eve:stale",
+ sessionId: "session_1",
+ streamIndex: 4,
+ };
+ const session = createSession(initialState);
+
+ const snapshot = await session.snapshot();
+
+ expect(snapshot.session).toEqual({ sessionId: "session_1", streamIndex: 1 });
+ expect(session.state).toBe(initialState);
+ });
+
+ it("omits the continuation token while the snapshotted turn is active", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ createBoundedStreamResponse([{ type: "turn.started", data: { turnId: "turn_1" } }]),
+ );
+ const initialState = {
+ continuationToken: "eve:previous",
+ sessionId: "session_1",
+ streamIndex: 4,
+ };
+ const session = createSession(initialState);
+
+ const snapshot = await session.snapshot();
+
+ expect(snapshot.session).toEqual({ sessionId: "session_1", streamIndex: 1 });
+ expect(session.state).toBe(initialState);
+ });
+
+ it("preserves an empty session without mutating its handle", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(createBoundedStreamResponse([]));
+ const initialState = {
+ continuationToken: "eve:pending",
+ sessionId: "session_1",
+ streamIndex: 0,
+ };
+ const session = createSession(initialState);
+
+ const snapshot = await session.snapshot();
+
+ expect(snapshot).toEqual({
+ events: [],
+ session: { sessionId: "session_1", streamIndex: 0 },
+ });
+ expect(session.state).toBe(initialState);
+ });
+
+ it("does not mutate the handle when a snapshot is aborted", async () => {
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (_request, init) => {
+ if (init?.signal?.aborted) {
+ throw init.signal.reason;
+ }
+ return createBoundedStreamResponse([]);
+ });
+ const initialState = {
+ continuationToken: "eve:current",
+ sessionId: "session_1",
+ streamIndex: 3,
+ };
+ const session = createSession(initialState);
+ const controller = new AbortController();
+ controller.abort(new DOMException("Aborted", "AbortError"));
+
+ await expect(session.snapshot({ signal: controller.signal })).rejects.toThrow("Aborted");
+ expect(session.state).toBe(initialState);
+ });
+
+ it("preserves completed-session continuation when configured", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ createBoundedStreamResponse([
+ {
+ type: "session.completed",
+ data: { reason: "completed" },
+ },
+ ]),
+ );
+ const initialState = {
+ continuationToken: "eve:current",
+ sessionId: "session_1",
+ streamIndex: 3,
+ };
+ const session = createSession(initialState, { preserveCompletedSessions: true });
+
+ const snapshot = await session.snapshot();
+
+ expect(snapshot.session).toEqual({
+ continuationToken: "eve:current",
+ sessionId: "session_1",
+ streamIndex: 1,
+ });
+ expect(session.state).toBe(initialState);
+ });
+
it("rejects a cancel response for a different session", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
Response.json(
diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.ts
index c1f92cde8..dabf733fe 100644
--- a/packages/eve/src/client/session.ts
+++ b/packages/eve/src/client/session.ts
@@ -20,6 +20,7 @@ import type {
ResetResult,
SendTurnInput,
SendTurnPayload,
+ SessionSnapshot,
SessionState,
StreamOptions,
} from "#client/types.js";
@@ -64,6 +65,54 @@ export class ClientSession {
return this.#state;
}
+ /**
+ * Reads a finite, point-in-time prefix of this session's durable event stream.
+ *
+ * The read starts at the beginning of the session and stops at the durable
+ * tail observed when it opens. The returned cursor points exactly after the
+ * returned events, so it can hydrate a UI and resume without a gap.
+ * Reading a snapshot does not advance or reset this handle's state.
+ *
+ * @throws {Error} If the session has no session ID (no message has been sent
+ * yet).
+ */
+ async snapshot(options?: { readonly signal?: AbortSignal }): Promise<SessionSnapshot> {
+ options?.signal?.throwIfAborted();
+
+ const initialState = this.#state;
+ const sessionId = initialState.sessionId;
+ if (!sessionId) {
+ throw new Error("Session has no session ID. Send a message first.");
+ }
+
+ const events: MessageStreamEvent[] = [];
+
+ for await (const event of this.#readStream({
+ follow: false,
+ sessionId,
+ signal: options?.signal,
+ startIndex: 0,
+ })) {
+ events.push(event);
+ }
+
+ options?.signal?.throwIfAborted();
+
+ const lastEvent = events.at(-1);
+ const continuationToken =
+ lastEvent?.type === "session.waiting"
+ ? lastEvent.data.continuationToken
+ : lastEvent?.type === "session.completed" && this.#context.preserveCompletedSessions
+ ? initialState.continuationToken
+ : undefined;
+ const session: SessionState =
+ continuationToken === undefined
+ ? { sessionId, streamIndex: events.length }
+ : { continuationToken, sessionId, streamIndex: events.length };
+
+ return { events, session };
+ }
+
/**
* Sends one turn payload to the agent.
*
@@ -316,10 +365,8 @@ export class ClientSession {
const events: MessageStreamEvent[] = [];
try {
- for await (const event of followStreamIterable({
- host: this.#context.host,
- resolveHeaders: () => this.#context.resolveHeaders(input.headers),
- redirect: this.#context.redirect,
+ for await (const event of this.#readStream({
+ headers: input.headers,
streamReconnectPolicy: input.streamReconnectPolicy,
sessionId,
signal: input.signal,
@@ -352,15 +399,12 @@ export class ClientSession {
const events: MessageStreamEvent[] = [];
try {
- for await (const event of followStreamIterable({
+ for await (const event of this.#readStream({
follow: options?.follow,
- host: this.#context.host,
- resolveHeaders: () => this.#context.resolveHeaders(),
- redirect: this.#context.redirect,
- streamReconnectPolicy: options?.streamReconnectPolicy,
sessionId,
signal: options?.signal,
startIndex: streamIndex,
+ streamReconnectPolicy: options?.streamReconnectPolicy,
})) {
events.push(event);
yield event;
@@ -377,6 +421,26 @@ export class ClientSession {
}
}
}
+
+ #readStream(input: {
+ readonly follow?: boolean;
+ readonly headers?: Readonly<Record<string, string>>;
+ readonly sessionId: string;
+ readonly signal?: AbortSignal;
+ readonly startIndex: number;
+ readonly streamReconnectPolicy?: StreamOptions["streamReconnectPolicy"];
+ }): AsyncIterable<MessageStreamEvent> {
+ return followStreamIterable({
+ follow: input.follow,
+ host: this.#context.host,
+ resolveHeaders: () => this.#context.resolveHeaders(input.headers),
+ redirect: this.#context.redirect,
+ streamReconnectPolicy: input.streamReconnectPolicy,
+ sessionId: input.sessionId,
+ signal: input.signal,
+ startIndex: input.startIndex,
+ });
+ }
}
async function postTurnWithRetry(input: {
diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.ts
index d95a91fce..f18e5887c 100644
--- a/packages/eve/src/client/types.ts
+++ b/packages/eve/src/client/types.ts
@@ -311,3 +311,14 @@ export interface SessionState {
readonly sessionId?: string;
readonly streamIndex: number;
}
+
+/**
+ * Finite, cursor-consistent prefix of one durable session stream.
+ */
+export interface SessionSnapshot {
+ /** Events from the start of the session through the durable tail observed when the read opened. */
+ readonly events: readonly MessageStreamEvent[];
+
+ /** Session cursor advanced exactly past {@link events}. */
+ readonly session: SessionState;
+}