The Open Framework for Building Agents
feat: add manual session compaction (#1508)
Casey Gowrie3dce30a18d24
diff --git a/.changeset/calm-ravens-compact.md b/.changeset/calm-ravens-compact.mdnew file mode 100644index 000000000..0c8165f7f--- /dev/null+++ b/.changeset/calm-ravens-compact.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add manual session compaction through custom-channel helpers, the eve HTTP client, and the `eve dev` TUI's `/compact` command. Compaction preserves the session, queues behind an active turn, and does not send synthetic model input.diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex ecce8e1d7..520d7d9d6 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -48,6 +48,7 @@ Declare routes with the `POST()` and `GET()` helpers. Each route handler receive- `send(message, { auth, continuationToken, state?, title? })` starts or resumes a session. `title` overrides the new workflow session's display title without changing the model message. Returns a `Session`.- `cancel({ continuationToken, turnId? })` requests cancellation of the active turn on the session that owns the token. See [Cancel a turn](#cancel-a-turn).+- `compact({ continuationToken })` queues context compaction for the session that owns the token without sending model input. See [Compact a session](#compact-a-session).- `reset({ continuationToken, reason? })` retires the session that owns the token so the next `send()` starts a fresh session. See [Reset a session](#reset-a-session).- `getSession(sessionId)` looks up an existing session. The returned `Session` exposes `getEventStream({ startIndex? })` for streaming, `getStreamTailIndex()` for resolving the durable tail when a route wants to serve bounded reads, and `cancel({ turnId? })` for session-id-addressed cancellation.- `receive(channel, ...)` hands inbound work to a different channel for cross-channel hand-off.@@ -86,6 +87,25 @@ Semantics:When you already hold a `Session` — returned by `send()` or `getSession(sessionId)` — call `session.cancel({ turnId? })` to request the same cancellation addressed by session id.+## Compact a session++Call `compact` with the channel-local continuation token to summarize durable conversation history without delivering a command to the model:++```ts+import { defineChannel, POST } from "eve/channels";++export default defineChannel({+ routes: [+ POST("/threads/:threadId/compact", async (_req, { compact, params }) => {+ const result = await compact({ continuationToken: params.threadId });+ return Response.json(result);+ }),+ ],+});+```++`"accepted"` means the durable session queued the operation. A successful compaction emits `compaction.requested` followed by `compaction.completed`, then the operation returns through `session.waiting`. If summarization fails, the stream returns through `session.waiting` without `compaction.completed` and preserves the previous history. If a turn is active, eve runs the compaction after that turn settles; it does not cancel the turn. `"no_active_session"` means the token has no current owner. Both outcomes are successful, and compaction never starts a session or appends a synthetic user message.+## Reset a sessionIdentity-addressed channels can consume commands such as `/new` in their route, without sending the command to the model. Call `reset` with the same channel-local continuation token used by `send()`:@@ -160,7 +180,7 @@ export default defineChannel({});```-`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `cancel`, `reset`, `getSession`, `receive`, `params`, `waitUntil`, and `requestIp`. The returned hooks are eve-owned structural types compatible with Nitro/H3 websocket routing, including `upgrade`, `open`, `message`, `close`, and `error`.+`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `cancel`, `compact`, `reset`, `getSession`, `receive`, `params`, `waitUntil`, and `requestIp`. The returned hooks are eve-owned structural types compatible with Nitro/H3 websocket routing, including `upgrade`, `open`, `message`, `close`, and `error`.### Node upgrade server escape hatchdiff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex 0c8f7e6e3..1e290fbda 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -18,13 +18,15 @@ export default eveChannel({## Routes-The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, cancel turns, and stream events:+The application exposes a health route plus eve channel routes that inspect the agent, create sessions, send follow-ups, cancel turns, compact or reset sessions, and stream events:- `GET /eve/v1/health`- `GET /eve/v1/info`- `POST /eve/v1/session` (start a session)- `POST /eve/v1/session/:sessionId` (send a follow-up)- `POST /eve/v1/session/:sessionId/cancel` (cancel the in-flight turn)+- `POST /eve/v1/session/compact` (compact the continuation owner's context)+- `POST /eve/v1/session/reset` (retire the continuation owner)- `GET /eve/v1/session/:sessionId/stream` (stream events, NDJSON)Start a session with a minimal body. The response returns `sessionId` and the `continuationToken` you reuse for follow-ups:@@ -54,6 +56,17 @@ curl -X POST https://<deployment>/eve/v1/session/ses_01h.../cancelCancellation is asynchronous: `"accepted"` means a cancellation hook accepted the request. Confirm the effective outcome on the stream as `turn.cancelled` followed by `session.waiting` — never as a failure. Active local and remote subagents are cancelled recursively before the parent settles; their own streams carry their cancellation boundaries, and cancelled work does not emit `subagent.completed` on the parent. Content emitted before the cancel stays on the event stream, while durable model history keeps only content that had already settled. The session accepts the next message normally. When there is no resumable cancellation target (including an unknown session, a settled turn, or a duplicate cancel), the route responds with `"no_active_turn"` — also a success, so a stop button can fire and forget. A `turnId` naming any other turn is accepted and consumed as a no-op, so a guarded cancel racing a turn boundary cannot stop a turn the caller never saw.+Compact the session that owns a continuation token without sending a message:++```bash+curl -X POST https://<deployment>/eve/v1/session/compact \+ -H "Content-Type: application/json" \+ -d '{"continuationToken":"eve:7f3c..."}'+# {"ok":true,"sessionId":"ses_01h...","status":"accepted"}+```++Compaction is asynchronous. A successful operation emits `compaction.requested` and `compaction.completed`, then returns through `session.waiting`; when a turn is active, the operation waits for it to settle. If summarization fails, the session still returns to `session.waiting` with its previous history. `"no_active_session"` is the successful no-op response when the token has no owner.+See [Sessions, runs & streaming](../concepts/sessions-runs-and-streaming) for the full request and stream flow, including the complete event set.## CORSdiff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.mdindex 847e7d43e..4d88e0c32 100644--- a/docs/concepts/default-harness.md+++ b/docs/concepts/default-harness.md@@ -20,6 +20,8 @@ export default defineAgent({Compaction also preserves the framework's own tool state automatically. It resets read-before-write tracking (so a write afterward re-reads the file whose read evidence was summarized away) and re-injects the active todo list, so the model keeps its task list across the summary. There is no per-tool hook to configure.+Clients and channels can also request compaction between turns. Call `ClientSession.compact()` or a custom route's `compact({ continuationToken })` helper. The request does not append a user message; if a turn is running, eve queues it until that turn settles. A successful manual compaction emits the same `compaction.requested` and `compaction.completed` events as automatic compaction, followed by `session.waiting`.+## Built-in toolsBuilt-in tools require no imports. The exact set depends on the agent and session. `agent` is available only in the root session; `load_skill` and `connection_search` appear only when the agent declares the corresponding resources; `ask_question` requires a session that can request user input; and `web_search` requires a supported model provider. The harness advertises only the tools available to the current session.diff --git a/docs/guides/client/streaming.mdx b/docs/guides/client/streaming.mdxindex 12180a1f5..c12ccda3d 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -19,6 +19,13 @@ const result = await response.result();Cancellation does not replace stream consumption. Continue reading the response to observe its terminal `turn.cancelled` and `session.waiting` boundary and to advance the client session cursor normally.+Between turns, `session.compact()` queues context compaction without sending model input. An accepted request reports the session id; consume the durable stream through the following `session.waiting` boundary before sending the next turn. `compaction.completed` confirms that summarization succeeded; without it, eve preserves the previous history. A never-started session returns `no_active_session` as a successful no-op.++```ts+const compaction = await session.compact();+console.log(compaction.status);+```+## Aggregate a turnUse `result()` when you only need the final turn summary:diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex f25364bb1..c32724bd3 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -42,6 +42,7 @@ Each command echoes as an invocation line, asks through a bordered panel that ta| `/loglevel` | Switches which logs the transcript shows. See [Control what logs show](#control-what-logs-show). || `/traces` | Opens the full-screen local trace viewer. See [Inspect traces](#inspect-traces). || `/new` | Starts a fresh session. |+| `/compact` | Queues context compaction for the current session without sending a message. || `/exit` | Quits the TUI. || `/help` | Lists the commands available for the current local or remote session. |diff --git a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts b/e2e/fixtures/agent-cancellation/agent/channels/threads.tsindex e192c49f9..94a2bddbc 100644--- a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts+++ b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts@@ -8,11 +8,11 @@ const AUTH = {} as const;/**- * Chat-style channel for the continuation-addressed cancellation eval.+ * Chat-style channel for continuation-addressed session-control evals.** Messages address a thread by channel-local continuation token. The stop- * and reset routes act through public channel helpers without knowing the- * runtime session id.+ * and session-control routes act through public channel helpers without+ * knowing the runtime session id.*/export default defineChannel({routes: [@@ -35,6 +35,10 @@ export default defineChannel({});return Response.json({ acknowledgement: "Started a new conversation.", ...result });}),+ POST("/threads/:threadId/compact", async (_request, { compact, params }) => {+ const result = await compact({ continuationToken: params.threadId ?? "" });+ return Response.json(result);+ }),POST("/threads/:threadId/owner", async (_request, { params, resolveActiveSession }) => {const owner = await resolveActiveSession({ continuationToken: params.threadId ?? "" });return Response.json({ sessionId: owner?.sessionId ?? null });diff --git a/e2e/fixtures/agent-cancellation/evals/cancellation/compact-channel-session.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/compact-channel-session.eval.tsnew file mode 100644index 000000000..a31cf72ad--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/compact-channel-session.eval.ts@@ -0,0 +1,119 @@+import { defineEval, type EveEvalTargetHandle } from "eve/evals";+import { satisfies } from "eve/evals/expect";++interface MessageResponse {+ readonly ok: boolean;+ readonly sessionId?: string;+}++interface CompactResponse {+ readonly sessionId?: string;+ readonly status?: "accepted" | "no_active_session";+}++async function postJson<T>(target: EveEvalTargetHandle, path: string, body: unknown): Promise<T> {+ const response = await target.fetch(path, {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+ const text = await response.text();+ if (!response.ok) {+ throw new Error(`POST ${path} failed (${response.status}): ${text}`);+ }+ return JSON.parse(text) as T;+}++/**+ * Compact a parked conversation through a custom channel route.+ *+ * The compact request uses only the channel-local continuation token. It+ * emits the compaction lifecycle without a synthetic model turn, preserves+ * the session owner, and allows the next ordinary message to resume normally.+ */+export default defineEval({+ description: "Compact a custom-channel session without creating a synthetic turn.",+ timeoutMs: 240_000,++ async test(t) {+ const unknownThread = await postJson<CompactResponse>(+ t.target,+ `/threads/${crypto.randomUUID()}/compact`,+ {},+ );+ await t.require(+ unknownThread,+ satisfies(+ (value: CompactResponse) => value.status === "no_active_session",+ "compacting an unknown thread reports no_active_session",+ ),+ );++ const threadId = crypto.randomUUID();+ const started = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {+ message: "Reply with exactly COMPACT-INITIAL-OK.",+ });+ await t.require(+ started,+ satisfies(+ (value: MessageResponse) => value.ok === true && typeof value.sessionId === "string",+ "the initial message starts a session",+ ),+ );+ const sessionId = started.sessionId!;++ const initial = await t.target.watchTurn(sessionId).result();+ initial.notEvent("turn.failed");+ initial.notEvent("session.failed");++ const liveCompaction = t.target.watchTurn(sessionId, {+ startIndex: initial.events.length,+ });+ const compactedResponse = await postJson<CompactResponse>(+ t.target,+ `/threads/${threadId}/compact`,+ {},+ );+ await t.require(+ compactedResponse,+ satisfies(+ (value: CompactResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "the channel accepts compaction for the active session",+ ),+ );++ const compacted = await liveCompaction.result();+ compacted.event("compaction.requested", { count: 1 });+ compacted.event("compaction.completed", { count: 1 });+ compacted.eventOrder([+ { type: "compaction.requested" },+ { type: "compaction.completed" },+ { type: "session.waiting" },+ ]);+ compacted.notEvent("turn.started");+ compacted.notEvent("turn.failed");+ compacted.notEvent("session.failed");++ const resumed = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {+ message: "Reply with exactly COMPACT-FOLLOW-UP-OK.",+ });+ await t.require(+ resumed,+ satisfies(+ (value: MessageResponse) => value.sessionId === sessionId,+ "the thread resumes the same session after compaction",+ ),+ );++ const followUp = await t.target+ .watchTurn(sessionId, {+ startIndex: initial.events.length + compacted.events.length,+ })+ .result();+ followUp.notEvent("turn.failed");+ followUp.notEvent("session.failed");+ followUp.messageIncludes(/COMPACT-FOLLOW-UP-OK/i);++ t.succeeded();+ },+});diff --git a/packages/eve/src/channel/cancel.test.ts b/packages/eve/src/channel/cancel.test.tsindex fae22203f..ef0244f43 100644--- a/packages/eve/src/channel/cancel.test.ts+++ b/packages/eve/src/channel/cancel.test.ts@@ -6,6 +6,7 @@ import type { Runtime } from "#channel/types.js";function createRuntime(overrides?: Partial<Runtime>): Runtime {return {cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),+ compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),diff --git a/packages/eve/src/channel/compact-session.test.ts b/packages/eve/src/channel/compact-session.test.tsnew file mode 100644index 000000000..6ead0fb2f--- /dev/null+++ b/packages/eve/src/channel/compact-session.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it, vi } from "vitest";++import { createCompactFn } from "#channel/compact-session.js";+import type { Runtime } from "#channel/types.js";++function createRuntime(): Runtime {+ return {+ cancelTurn: vi.fn(),+ compactSession: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),+ deliver: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveSession: vi.fn(),+ run: vi.fn(),+ terminateSession: vi.fn(),+ };+}++describe("createCompactFn", () => {+ it("namespaces the channel-local token and returns the runtime result", async () => {+ const runtime = createRuntime();++ await expect(+ createCompactFn(runtime, "slack")({ continuationToken: "C1:T1" }),+ ).resolves.toEqual({ sessionId: "sess_1", status: "accepted" });+ expect(runtime.compactSession).toHaveBeenCalledWith({+ continuationToken: "slack:C1:T1",+ });+ });+});diff --git a/packages/eve/src/channel/compact-session.ts b/packages/eve/src/channel/compact-session.tsnew file mode 100644index 000000000..2ab4516ae--- /dev/null+++ b/packages/eve/src/channel/compact-session.ts@@ -0,0 +1,10 @@+import type { CompactFn, CompactOptions } from "#channel/routes.js";+import type { CompactSessionResult, Runtime } from "#channel/types.js";++/** Builds a channel-scoped manual compaction helper. */+export function createCompactFn(runtime: Runtime, channelName: string): CompactFn {+ return async (options: CompactOptions): Promise<CompactSessionResult> =>+ await runtime.compactSession({+ continuationToken: `${channelName}:${options.continuationToken}`,+ });+}diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.tsindex 4edea0e26..a1686fa9e 100644--- a/packages/eve/src/channel/cross-channel-receive.test.ts+++ b/packages/eve/src/channel/cross-channel-receive.test.ts@@ -11,6 +11,7 @@ import type { Runtime } from "#channel/types.js";function makeRuntime(): Runtime {return {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),diff --git a/packages/eve/src/channel/reset-session.test.ts b/packages/eve/src/channel/reset-session.test.tsindex 62bb07a03..524edf2a5 100644--- a/packages/eve/src/channel/reset-session.test.ts+++ b/packages/eve/src/channel/reset-session.test.ts@@ -6,6 +6,7 @@ import type { Runtime } from "#channel/types.js";function createRuntime(overrides?: Partial<Runtime>): Runtime {return {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn().mockResolvedValue(-1),diff --git a/packages/eve/src/channel/resolve-active-session.test.ts b/packages/eve/src/channel/resolve-active-session.test.tsindex 53ca66773..175a3377b 100644--- a/packages/eve/src/channel/resolve-active-session.test.ts+++ b/packages/eve/src/channel/resolve-active-session.test.ts@@ -6,6 +6,7 @@ import type { Runtime } from "#channel/types.js";function runtime(): Runtime {return {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),getStreamTailIndex: vi.fn().mockResolvedValue(-1),diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex d2f5f2bfc..ed41f7541 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -1,7 +1,12 @@import type { UserContent } from "ai";import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";-import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";+import type {+ CancelTurnResult,+ CompactSessionResult,+ SessionAuthContext,+ SessionCallback,+} from "#channel/types.js";import type { InputResponse } from "#runtime/input/types.js";import type { Session } from "#channel/session.js";import type { RunMode } from "#shared/run-mode.js";@@ -13,7 +18,8 @@ type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Recor/*** Second argument passed to every route handler. `send` starts or continues a* session on this channel; `cancel` stops the active turn on a session- * addressed by continuation token; `reset` retires a session so its+ * addressed by continuation token; `compact` summarizes its context without+ * sending model input; `reset` retires a session so its* token can start a fresh session; `getSession` looks one up by id; `receive`* hands inbound work to a different channel; `params` contains the matched* path parameters; `waitUntil` keeps background work alive past the response;@@ -27,6 +33,7 @@ export interface RouteHandlerArgs<TState = undefined> {*/resolveActiveSession: ResolveActiveSessionFn;cancel: CancelFn;+ compact: CompactFn;reset: ResetFn;getSession: GetSessionFn;/**@@ -132,6 +139,20 @@ export interface CancelOptions {*/export type CancelFn = (options: CancelOptions) => Promise<CancelTurnResult>;+/** Options for {@link CompactFn}. */+export interface CompactOptions {+ /** Channel-local raw token, in the same format accepted by {@link SendFn}. */+ readonly continuationToken: string;+}++/**+ * Queues context compaction for the session owning a continuation token.+ * Never sends model input or starts a new session. An accepted request returns+ * to `session.waiting`; successful compaction emits `compaction.requested`+ * followed by `compaction.completed` on the session stream.+ */+export type CompactFn = (options: CompactOptions) => Promise<CompactSessionResult>;+/** Options for {@link ResetFn}. */export interface ResetOptions {/** Channel-local raw token, in the same format accepted by {@link SendFn}. */diff --git a/packages/eve/src/channel/schedule.test.ts b/packages/eve/src/channel/schedule.test.tsindex fa4c68f96..ccfb18a3e 100644--- a/packages/eve/src/channel/schedule.test.ts+++ b/packages/eve/src/channel/schedule.test.ts@@ -25,6 +25,7 @@ function createMockRunHandle(): RunHandle {function createMockRuntime(): Runtime {return {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockRejectedValue(new RuntimeNoActiveSessionError("schedule:token")),resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.tsindex 17c078cb0..9ac1dba8a 100644--- a/packages/eve/src/channel/send.test.ts+++ b/packages/eve/src/channel/send.test.ts@@ -17,6 +17,7 @@ function createMockRunHandle(): RunHandle {function createRuntime(deliverError: unknown): Runtime {return {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockRejectedValue(deliverError),resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),@@ -81,6 +82,7 @@ describe("createSendFn", () => {const context = ["thread background"];const deliverRuntime: Runtime = {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),@@ -116,6 +118,7 @@ describe("createSendFn", () => {it("adds channel request ids to deliver and run inputs when provided", async () => {const deliverRuntime: Runtime = {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),@@ -146,6 +149,7 @@ describe("createSendFn", () => {} as const;const deliverRuntime: Runtime = {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),resolveSession: vi.fn(),run: vi.fn().mockResolvedValue(createMockRunHandle()),diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex 16f3612e8..f814feaa0 100644--- a/packages/eve/src/channel/session.test.ts+++ b/packages/eve/src/channel/session.test.ts@@ -8,6 +8,7 @@ import { AuthKey, ContinuationTokenKey, InitiatorAuthKey, SessionIdKey } from "#function createRuntime(): Runtime {return {cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),+ compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex f1165c6a6..b55c13cf0 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -37,6 +37,16 @@ export interface CancelTurnResult {readonly reason?: string;}+/** Identifies the continuation hook whose durable session should compact. */+export interface CompactSessionInput {+ readonly continuationToken: string;+}++/** Result of queueing manual context compaction for a session. */+export type CompactSessionResult =+ | { readonly status: "accepted"; readonly sessionId: string }+ | { readonly status: "no_active_session" };+/** Identifies a session to transition permanently to a terminal state. */export interface TerminateSessionInput {/** Human-readable reason recorded on the terminal workflow transition. */@@ -181,6 +191,11 @@ export interface SessionTimeoutHookPayload {readonly kind: "session-timeout";}+/** Requests a context compaction without delivering model input. */+export interface CompactSessionHookPayload {+ readonly kind: "compact";+}+/*** Runtime-action results resumed back into a parked parent workflow.*/@@ -243,6 +258,7 @@ export interface SubagentAuthorizationEventHookPayload {* Serializable payload sent through the workflow `resumeHook`.*/export type HookPayload =+ | CompactSessionHookPayload| DeliverHookPayload| RuntimeActionResultHookPayload| SessionTimeoutHookPayload@@ -438,6 +454,9 @@ export interface Runtime {/** Requests cancellation of a session's in-flight turn. */cancelTurn(input: CancelTurnInput): Promise<CancelTurnResult>;+ /** Queues context compaction on the session owning a continuation token. */+ compactSession(input: CompactSessionInput): Promise<CompactSessionResult>;+/** Terminally retires a session and releases its non-retained continuation hooks. */terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult>;diff --git a/packages/eve/src/cli/dev/tui/prompt-commands.ts b/packages/eve/src/cli/dev/tui/prompt-commands.tsindex a7502c953..46c558391 100644--- a/packages/eve/src/cli/dev/tui/prompt-commands.ts+++ b/packages/eve/src/cli/dev/tui/prompt-commands.ts@@ -5,6 +5,7 @@ type PromptCommandTarget = "local" | "remote";/** The slash commands the prompt accepts. */export type PromptCommand =| { type: "new" }+ | { type: "compact" }| { type: "exit" }| { type: "help" }| { type: "loglevel"; argument: string }@@ -58,6 +59,14 @@ const PROMPT_COMMAND_DEFINITIONS = [build: () => ({ type: "new" }),targets: ["local", "remote"],},+ {+ name: "compact",+ aliases: [],+ description: "Compact the current session context",+ takesArgument: false,+ build: () => ({ type: "compact" }),+ targets: ["local", "remote"],+ },{name: "vc:install",aliases: [],@@ -147,7 +156,7 @@ export function isPromptCommandAvailableFor(/*** Recognizes the slash commands the prompt accepts. `/new` clears the- * session and transcript; `/exit` (and `/quit`) terminate the TUI like+ * session and transcript; `/compact` queues context compaction; `/exit` (and `/quit`) terminate the TUI like* Ctrl+C; extension commands are dispatched outside the runner. Anything* else — including unknown `/text` — is a normal message.*/diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 5fab3909e..d6daad994 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -197,8 +197,9 @@ describe("parsePromptCommand", () => {});});- it("recognizes /new, /exit, and /quit", () => {+ it("recognizes /new, /compact, /exit, and /quit", () => {expect(parsePromptCommand("/new")).toEqual({ type: "new" });+ expect(parsePromptCommand("/compact")).toEqual({ type: "compact" });expect(parsePromptCommand("/exit")).toEqual({ type: "exit" });expect(parsePromptCommand("/quit")).toEqual({ type: "exit" });});@@ -655,6 +656,46 @@ describe("EveTUIRunner development session continuity", () => {expect(newSession.send).toHaveBeenCalledOnce();});+ it("compacts the active session without sending a prompt", async () => {+ const session = sessionYielding([]);+ const compact = vi+ .spyOn(session, "compact")+ .mockResolvedValue({ sessionId: "session_1", status: "accepted" });+ const stream = vi.spyOn(session, "stream").mockReturnValue(+ (async function* () {+ yield stampTestEvent(+ {+ data: { continuationToken: "eve:test", wait: "next-user-message" },+ type: "session.waiting",+ },+ 0,+ );+ })(),+ );+ const results: string[] = [];+ const prompts: Array<string | undefined> = ["/compact", undefined];+ const runner = new EveTUIRunner({+ name: "Weather Agent",+ renderer: fakeRenderer({+ readPrompt: vi.fn(async () => prompts.shift()),+ renderCommandResult: (message) => results.push(message),+ renderStream: vi.fn(async (result) => {+ for await (const event of result.events) {+ void event;+ }+ }),+ }),+ session,+ });++ await runner.run();++ expect(compact).toHaveBeenCalledOnce();+ expect(stream).toHaveBeenCalledOnce();+ expect(session.send).not.toHaveBeenCalled();+ expect(results).toEqual(["Compaction requested."]);+ });+it("keeps the current transcript and session when /new cannot reset the owner", async () => {const session = sessionYielding([]);const reset = vi.spyOn(session, "reset").mockRejectedValue(new Error("World unavailable"));diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 161d8eb42..63473c271 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -711,6 +711,7 @@ export class EveTUIRunner {let prompt: string | undefined;let pendingInputResponses: readonly InputResponse[] | undefined;let hasRunTurn = false;+ let followCurrentSession = false;let streamWithoutPrompt = false;// `--input` seed: applied to the first prompt's editable buffer, then// cleared so later prompts open empty.@@ -801,6 +802,35 @@ export class EveTUIRunner {continue;}+ if (command?.type === "compact") {+ try {+ const result = await this.#session.compact();+ this.#renderCommandOutcome(+ result.status === "accepted"+ ? "Compaction requested."+ : "No active session to compact.",+ );+ if (result.status === "no_active_session") {+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }+ } catch (error) {+ this.#renderCommandOutcome(`Couldn't compact the session: ${toErrorMessage(error)}`);+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }+ pendingInputResponses = undefined;+ followCurrentSession = true;+ streamWithoutPrompt = false;+ prompt = undefined;+ }+// Help renders locally; unlike extension commands it must work even// without a prompt-command handler (e.g. remote --url sessions).if (command?.type === "help") {@@ -847,10 +877,12 @@ export class EveTUIRunner {hasRunTurn = true;}- let result = await this.#streamTurn({- prompt: streamWithoutPrompt ? undefined : prompt,- inputResponses: pendingInputResponses,- });+ let result = followCurrentSession+ ? this.#streamCurrentSession()+ : await this.#streamTurn({+ prompt: streamWithoutPrompt ? undefined : prompt,+ inputResponses: pendingInputResponses,+ });// The session id becomes known once the send is accepted; keep the// renderer's copy fresh so the parting line can name the session.const acceptedSessionId = this.#session.state.sessionId;@@ -935,7 +967,7 @@ export class EveTUIRunner {}if (this.#enterPendingConnectionAuthorization(result)) {- result = this.#streamConnectionAuthorization();+ result = this.#streamCurrentSession();submittedPrompt = undefined;continue;}@@ -966,6 +998,7 @@ export class EveTUIRunner {continue;}+ followCurrentSession = false;streamWithoutPrompt = false;pendingInputResponses = undefined;prompt = undefined;@@ -1193,12 +1226,8 @@ export class EveTUIRunner {}}- /**- * Follows the same session after an interactive authorization callback.- * `send()` stops at the parked `session.waiting` boundary; the callback's- * completion events arrive in the next durable turn on `session.stream()`.- */- #streamConnectionAuthorization(): AgentTUIStreamResult {+ /** Follows the current session without dispatching another turn. */+ #streamCurrentSession(): AgentTUIStreamResult {const abortController = new AbortController();return this.#createTUIStreamResult(this.#session.stream({ signal: abortController.signal }),diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex 46a6d2c94..a41dd1a9b 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -43,6 +43,7 @@ export type {AgentInfoToolEntry,AgentInfoTools,CancelSessionResult,+ CompactResult,ClientAuth,ClientOptions,ClientRedirectPolicy,diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex dd3db326b..b02589310 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -295,6 +295,42 @@ describe("ClientSession", () => {await expect(session.cancel()).rejects.toThrow("Cancel route returned an invalid response");});+ it("queues compaction without clearing the local session cursor", async () => {+ const state = { continuationToken: "eve:test", sessionId: "session_1", streamIndex: 4 };+ const requests: Array<{ body?: string; method: string; url: string }> = [];+ vi.spyOn(globalThis, "fetch").mockImplementation(async (request, init) => {+ const url =+ typeof request === "string" ? request : request instanceof URL ? request.href : request.url;+ requests.push({+ body: typeof init?.body === "string" ? init.body : undefined,+ method: init?.method ?? "GET",+ url,+ });+ return Response.json(+ { ok: true, sessionId: "session_1", status: "accepted" },+ { status: 202 },+ );+ });+ const session = createSession(state);++ await expect(session.compact()).resolves.toEqual({+ sessionId: "session_1",+ status: "accepted",+ });++ expect(session.state).toEqual(state);+ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/compact");+ expect(requests[0]!.method).toBe("POST");+ expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({ continuationToken: "eve:test" });+ });++ it("treats compacting a never-started session as a successful no-op", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");++ await expect(createSession().compact()).resolves.toEqual({ status: "no_active_session" });+ expect(fetchMock).not.toHaveBeenCalled();+ });+it("resets the continuation owner and clears the local session state", async () => {let headerResolution = 0;const requests: Array<{ headers: Headers; method: string; url: string; body?: string }> = [];diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex dabf733fe..1cee038bf 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -1,9 +1,11 @@import type { MessageStreamEvent } from "#protocol/message.js";import { EVE_SESSION_ID_HEADER, isCurrentTurnBoundaryEvent } from "#protocol/message.js";import { CancelTurnResponseSchema } from "#protocol/cancel-turn.js";+import { CompactResponseSchema } from "#protocol/compact-session.js";import { ResetResponseSchema } from "#protocol/reset-session.js";import {EVE_CREATE_SESSION_ROUTE_PATH,+ EVE_COMPACT_SESSION_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,createEveContinueSessionRoutePath,@@ -16,6 +18,7 @@ import { serializeOutputSchema } from "#shared/tool-schema.js";import { createClientUrl } from "#client/url.js";import type {CancelSessionResult,+ CompactResult,ClientRedirectPolicy,ResetResult,SendTurnInput,@@ -195,6 +198,68 @@ export class ClientSession {return { sessionId: result.data.sessionId, status: result.data.status };}+ /**+ * Queues context compaction without sending model input. The request is+ * asynchronous; consume the durable event stream through its next session+ * boundary before sending another turn. `compaction.completed` confirms that+ * summarization succeeded. A never-started handle is a successful no-op.+ */+ async compact(): Promise<CompactResult> {+ const state = this.#state;+ const continuationToken = state.continuationToken;++ if (continuationToken === undefined) {+ if (state.sessionId !== undefined) {+ throw new Error(+ "Session has no continuation token. Consume its event stream before compacting.",+ );+ }+ return { status: "no_active_session" };+ }++ const url = createClientUrl(this.#context.host, EVE_COMPACT_SESSION_ROUTE_PATH);+ const headers = await this.#context.resolveHeaders();+ headers.set("content-type", "application/json");++ const response = await fetch(+ url,+ withRedirectPolicy(+ {+ body: JSON.stringify({ continuationToken }),+ headers,+ method: "POST",+ },+ this.#context.redirect,+ ),+ );+ const body = await response.text();++ if (!response.ok) {+ throw new ClientError(response.status, body, response.headers);+ }++ let payload: unknown;+ try {+ payload = JSON.parse(body);+ } catch {+ throw new Error(`Compact route returned invalid JSON (${response.status}).`);+ }++ const result = CompactResponseSchema.safeParse(payload);+ if (+ !result.success ||+ (result.data.status === "accepted" &&+ state.sessionId !== undefined &&+ result.data.sessionId !== state.sessionId)+ ) {+ throw new Error(`Compact route returned an invalid response (${response.status}).`);+ }++ return result.data.status === "accepted"+ ? { sessionId: result.data.sessionId, status: "accepted" }+ : { status: "no_active_session" };+ }+/*** Terminally retires the session that owns this handle's continuation token.*diff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex f18e5887c..f6a2e08c5 100644--- a/packages/eve/src/client/types.ts+++ b/packages/eve/src/client/types.ts@@ -3,6 +3,7 @@ import type { StandardJSONSchemaV1 } from "#compiled/@standard-schema/spec/indeximport type { MessageStreamEvent } from "#protocol/message.js";import type { CancelTurnStatus } from "#protocol/cancel-turn.js";+import type { CompactStatus } from "#protocol/compact-session.js";import type { ResetStatus } from "#protocol/reset-session.js";import type { InputRequest, InputResponse } from "#runtime/input/types.js";import type { JsonObject } from "#shared/json.js";@@ -237,6 +238,18 @@ export interface CancelSessionResult {readonly status: CancelTurnStatus;}+/** Result of requesting context compaction for a client session. */+export type CompactResult =+ | {+ /** Session whose compaction request was queued. */+ readonly sessionId: string;+ readonly status: Extract<CompactStatus, "accepted">;+ }+ | {+ /** The client had no continuation token or the token was already free. */+ readonly status: Extract<CompactStatus, "no_active_session">;+ };+/** Result of terminally resetting a client session. */export type ResetResult =| {diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex aaee7a448..96de7d68a 100644--- a/packages/eve/src/execution/node-step.test.ts+++ b/packages/eve/src/execution/node-step.test.ts@@ -219,6 +219,7 @@ function createTestNode(function createNoopRuntime(): Runtime {return {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn(),resolveSession: vi.fn(),run: vi.fn().mockRejectedValue(new Error("runtime.run should not be called in this test")),diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex ecef7812f..9ea5ca9d2 100644--- a/packages/eve/src/execution/node-step.ts+++ b/packages/eve/src/execution/node-step.ts@@ -53,6 +53,8 @@ export interface CreateExecutionNodeStepInput {* current run.*/readonly capabilities?: SessionCapabilities;+ /** Runs only a forced context compaction and returns to the parked session. */+ readonly compactOnly?: boolean;/*** Runtime constructor used by the subagent tool executor to start* delegated child runs on the same workflow runtime as the parent.@@ -87,6 +89,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): Stconst step = createToolLoopHarness({abortSignal: input.abortSignal,capabilities: input.capabilities,+ compactOnly: input.compactOnly,workflow: input.node.agent.workflowTool !== undefined,workflowMaxSubagents: input.workflowMaxSubagents,handleEvent: input.handleEvent,diff --git a/packages/eve/src/execution/session-delivery-hook.test.ts b/packages/eve/src/execution/session-delivery-hook.test.tsindex 6b77207fb..8de29d7b9 100644--- a/packages/eve/src/execution/session-delivery-hook.test.ts+++ b/packages/eve/src/execution/session-delivery-hook.test.ts@@ -99,6 +99,20 @@ describe("createSessionDeliveryHook", () => {await deliveryHook.dispose();});+ it("latches compaction requests consumed while a turn owns delivery reads", async () => {+ const hook = createMockHook({ reads: [Promise.resolve(compact())], token: "active" });+ installHooks(hook);+ const deliveryHook = createSessionDeliveryHook([]);++ await deliveryHook.rekey("active");+ await expect(deliveryHook.next()).resolves.toEqual(compact());+ deliveryHook.consumeNext();++ expect(deliveryHook.consumeCompactRequest()).toBe(true);+ expect(deliveryHook.consumeCompactRequest()).toBe(false);+ await deliveryHook.dispose();+ });+it("disposes a conflicting candidate without releasing the active hook", async () => {const oldHook = createMockHook({ token: "old" });const candidateHook = createMockHook({@@ -272,6 +286,10 @@ function sessionTimeout(): IteratorResult<HookPayload> {return { done: false, value: { kind: "session-timeout" } };}+function compact(): IteratorResult<HookPayload> {+ return { done: false, value: { kind: "compact" } };+}+function createDeferred<T>(): { readonly promise: Promise<T>; resolve(value: T): void } {let resolve!: (value: T) => void;const promise = new Promise<T>((next) => {diff --git a/packages/eve/src/execution/session-delivery-hook.ts b/packages/eve/src/execution/session-delivery-hook.tsindex a063febc3..3208e7638 100644--- a/packages/eve/src/execution/session-delivery-hook.ts+++ b/packages/eve/src/execution/session-delivery-hook.ts@@ -21,6 +21,7 @@ interface SessionDeliveryHookState {/** Reads and rekeys the public delivery hook for one session driver. */export interface SessionDeliveryHook {+ consumeCompactRequest(): boolean;consumeNext(): void;consumeSessionTimeout(): boolean;next(): Promise<IteratorResult<HookPayload>>;@@ -50,6 +51,7 @@ export function createSessionDeliveryHook(let offered: Promise<IteratorResult<HookPayload>> | null = null;let offeredRead: HookRead | undefined;let sessionTimedOut = false;+ let compactRequested = false;let wake: (() => void) | undefined;const enqueue = (read: HookRead): void => {@@ -115,10 +117,14 @@ export function createSessionDeliveryHook(if (read.result.done) {read.state.closed = true;- } else if (read.result.value.kind === "deliver") {- bufferedDeliveries.push(read.result.value);- } else if (read.result.value.kind === "session-timeout") {- sessionTimedOut = true;+ } else {+ if (read.result.value.kind === "deliver") {+ bufferedDeliveries.push(read.result.value);+ } else if (read.result.value.kind === "session-timeout") {+ sessionTimedOut = true;+ } else if (read.result.value.kind === "compact") {+ compactRequested = true;+ }}arm(read.state);@@ -127,6 +133,12 @@ export function createSessionDeliveryHook(};return {+ consumeCompactRequest(): boolean {+ const requested = compactRequested;+ compactRequested = false;+ return requested;+ },+consumeNext(): void {if (offeredRead === undefined) {throw new Error("Cannot consume a public delivery before it resolves.");@@ -135,6 +147,9 @@ export function createSessionDeliveryHook(if (!offeredRead.result.done && offeredRead.result.value.kind === "session-timeout") {sessionTimedOut = true;}+ if (!offeredRead.result.done && offeredRead.result.value.kind === "compact") {+ compactRequested = true;+ }offeredRead.state.pending = false;offeredRead.state.resolved = undefined;if (offeredRead.result.done) offeredRead.state.closed = true;diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex 857750b00..ec078526b 100644--- a/packages/eve/src/execution/turn-cancellation.integration.test.ts+++ b/packages/eve/src/execution/turn-cancellation.integration.test.ts@@ -252,6 +252,9 @@ function createCancelRouteCaller(): (cancel: () => {throw new Error("cancel route must not use the channel cancel helper");},+ compact: () => {+ throw new Error("cancel route must not compact a session");+ },reset: () => {throw new Error("cancel route must not reset a session");},diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.tsindex dda25c0f5..17c0e6ab6 100644--- a/packages/eve/src/execution/turn-control-receiver.test.ts+++ b/packages/eve/src/execution/turn-control-receiver.test.ts@@ -125,6 +125,7 @@ function parkResult(): Extract<TurnControlPayload, { readonly kind: "turn-resultfunction createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {return {+ consumeCompactRequest: vi.fn(() => false),consumeNext: vi.fn(),consumeSessionTimeout: vi.fn(() => false),next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.tsindex 1839a0a95..3923e4e00 100644--- a/packages/eve/src/execution/turn-dispatch.test.ts+++ b/packages/eve/src/execution/turn-dispatch.test.ts@@ -217,6 +217,7 @@ describe("dispatchAndAwaitTurn", () => {function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {return {+ consumeCompactRequest: vi.fn(() => false),consumeNext: vi.fn(),consumeSessionTimeout: vi.fn(() => false),next: vi.fn(() => new Promise<IteratorResult<HookPayload>>(() => {})),diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex f5ea3c340..ef792c081 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -355,6 +355,34 @@ describe("workflowEntry", () => {});});+ it("dispatches a compact control without converting it into a delivery", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [{ kind: "compact" }, { kind: "session-timeout" }],+ },+ ],+ turnControls: [+ turnResult({ action: "park", sessionState }),+ turnResult({ action: "park", sessionState }),+ ],+ });++ await expect(+ workflowEntry({+ input: { message: "hello there" },+ serializedContext: createSerializedContext(),+ }),+ ).resolves.toEqual({ output: "" });++ expect(dispatchTurnStep).toHaveBeenCalledTimes(2);+ expect(vi.mocked(dispatchTurnStep).mock.calls[1]?.[0].delivery).toEqual({ kind: "compact" });+ expect(routeDeliverToChildren).not.toHaveBeenCalled();+ });+it("does not complete at the deadline until the active turn settles", async () => {const sessionState = createBaseSessionState();const dispose = vi.fn();diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex 43f545917..e91a2b4f4 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -71,6 +71,7 @@ type DriverLoopOutcome =};type NextSessionAction =+ | { readonly kind: "compact" }| {readonly delivery: DeliverHookPayload | null;readonly kind: "delivery";@@ -337,6 +338,15 @@ async function runDriverLoop(input: {};}+ if (nextAction.kind === "compact") {+ action = await runTurn({+ delivery: { kind: "compact" },+ serializedContext: action.serializedContext,+ sessionState: action.sessionState,+ });+ continue;+ }+const nextDeliver = nextAction.delivery;if (nextDeliver === null) {return { kind: "result", result: { output: "" } };@@ -402,6 +412,10 @@ async function waitForNextSessionAction(input: {return { kind: "expired" };}+ if (input.deliveryHook.consumeCompactRequest()) {+ return { kind: "compact" };+ }+if (input.bufferedDeliveries.length > 0) {return {delivery: coalesceDeliveries(input.bufferedDeliveries.splice(0)),@@ -421,6 +435,11 @@ async function waitForNextSessionAction(input: {return { kind: "expired" };}+ if (first.value.kind === "compact") {+ input.deliveryHook.consumeCompactRequest();+ return { kind: "compact" };+ }+if (first.value.kind !== "deliver") {continue;}@@ -447,6 +466,10 @@ async function waitForNextSessionAction(input: {input.deliveryHook.consumeNext();+ if (ready.value.kind === "compact") {+ continue;+ }+if (ready.value.kind !== "deliver") {continue;}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex 526ed367e..05aa1e226 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -199,6 +199,39 @@ describe("createWorkflowRuntime#cancelTurn", () => {});});+describe("createWorkflowRuntime#compactSession", () => {+ function buildRuntime() {+ return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });+ }++ it("queues compaction on the continuation hook and returns its owner", async () => {+ resumeHookMock.mockResolvedValue({ runId: "session-1" });++ await expect(+ buildRuntime().compactSession({ continuationToken: "eve:token" }),+ ).resolves.toEqual({ sessionId: "session-1", status: "accepted" });+ expect(resumeHookMock).toHaveBeenCalledWith("eve:token", { kind: "compact" });+ });++ it("reports a missing continuation hook as an inactive session", async () => {+ const { HookNotFoundError } = await import("#compiled/@workflow/errors/index.js");+ resumeHookMock.mockRejectedValue(new HookNotFoundError("eve:missing"));++ await expect(+ buildRuntime().compactSession({ continuationToken: "eve:missing" }),+ ).resolves.toEqual({ status: "no_active_session" });+ });++ it("treats a terminal owner race as an inactive session", async () => {+ const { RunExpiredError } = await import("#compiled/@workflow/errors/index.js");+ resumeHookMock.mockRejectedValue(new RunExpiredError("session already completed"));++ await expect(+ buildRuntime().compactSession({ continuationToken: "eve:completed" }),+ ).resolves.toEqual({ status: "no_active_session" });+ });+});+describe("createWorkflowRuntime#terminateSession", () => {function buildRuntime() {return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex 8ff4a4446..6ab771c91 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -8,6 +8,8 @@ import {import type {CancelTurnInput,CancelTurnResult,+ CompactSessionInput,+ CompactSessionResult,DeliverInput,GetEventStreamOptions,HookPayload,@@ -194,6 +196,23 @@ export function createWorkflowRuntime(config: {return await requestWorkflowTurnCancellation(input);},+ async compactSession(input: CompactSessionInput): Promise<CompactSessionResult> {+ try {+ const hook = normalizeWorkflowHook(+ await resumeHook(input.continuationToken, { kind: "compact" }),+ );+ return { sessionId: hook.runId, status: "accepted" };+ } catch (error) {+ if (HookNotFoundError.is(error) || isAlreadyTerminalSessionError(error)) {+ return { status: "no_active_session" };+ }+ logError(log, "failed to request session compaction", error, {+ continuationToken: input.continuationToken,+ });+ throw error;+ }+ },+async terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult> {try {await cancelRun(await getWorld(), input.sessionId, {diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex bc8755b82..41508c7ad 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -420,6 +420,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResuconst step = createExecutionNodeStep({abortSignal: input.abortSignal,capabilities,+ compactOnly: input.input?.kind === "compact",createRuntime: createWorkflowRuntime,handleEvent,mode,diff --git a/packages/eve/src/harness/compaction.test.ts b/packages/eve/src/harness/compaction.test.tsindex d5229b3ea..9032e29b9 100644--- a/packages/eve/src/harness/compaction.test.ts+++ b/packages/eve/src/harness/compaction.test.ts@@ -547,6 +547,30 @@ describe("compactMessages: tool-result cap heuristic", () => {});});+describe("compactMessages: forced summary", () => {+ it("summarizes the full conversation even when it is already under the threshold", async () => {+ const { generateText } = await import("ai");+ vi.mocked(generateText).mockResolvedValue({+ text: "forced checkpoint",+ } as Awaited<ReturnType<typeof generateText>>);+ const messages = [user("old message"), assistant("old reply")];++ const result = await compactMessages(+ messages,+ {} as Parameters<typeof compactMessages>[1],+ { recentWindowSize: 10, threshold: ROOMY },+ undefined,+ undefined,+ undefined,+ undefined,+ true,+ );++ expect(generateText).toHaveBeenCalledOnce();+ expect(result).toContainEqual({ content: "forced checkpoint", role: "assistant" });+ });+});+describe("compactMessages: summarization fallback", () => {it("summarizes when capping cannot free enough space", async () => {// All bulk is conversational prose — capping removes nothing — and thediff --git a/packages/eve/src/harness/compaction.ts b/packages/eve/src/harness/compaction.tsindex 2a94bcf09..054d98c0f 100644--- a/packages/eve/src/harness/compaction.ts+++ b/packages/eve/src/harness/compaction.ts@@ -184,11 +184,13 @@ export async function compactMessages(telemetry?: TelemetryOptions,headers?: Record<string, string>,abortSignal?: AbortSignal,+ forceSummary = false,): Promise<ModelMessage[]> {const { conversation, previousCheckpoint } = extractPreviousCheckpoint(messages);- let keep = selectRecentWindowSize(conversation, config);+ const recentConfig = forceSummary ? { ...config, recentWindowSize: 1 } : config;+ let keep = selectRecentWindowSize(conversation, recentConfig);- {+ if (!forceSummary) {const { older, recent } = splitMessagesForCompaction(conversation, keep);if (older.length === 0 && previousCheckpoint === undefined) {return keepNonToolResultMessages(recent);diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex bb57c9c23..7a1abeaa8 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -7775,6 +7775,116 @@ describe("createToolLoopHarness", () => {});});+ it("forces compaction without starting a model turn", async () => {+ const compactedHistory: ModelMessage[] = [+ { content: "Summary of our conversation so far:", role: "user" },+ { content: "summary", role: "assistant" },+ ];+ vi.mocked(compactMessages).mockResolvedValue(compactedHistory);++ const { emit, events } = createEventCollector();+ const onCompaction = vi.fn(() => []);+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ compactOnly: true,+ onCompaction,+ resolveModel: vi+ .fn()+ .mockResolvedValue({ modelId: "gpt-4", provider: "openai" } as LanguageModel),+ }),+ );+ const session = createTestSession({+ compaction: {+ lastKnownInputTokens: 9000,+ lastKnownPromptMessageCount: 2,+ recentWindowSize: 10,+ threshold: 100_000,+ },+ history: [+ { content: "old message", role: "user" },+ { content: "old reply", role: "assistant" },+ ],+ });++ const result = await runStep(session);++ expect(result.next).toBeNull();+ expect(result.session.history).toEqual(compactedHistory);+ expect(result.session.compaction).toEqual({ recentWindowSize: 10, threshold: 100_000 });+ expect(shouldCompact).not.toHaveBeenCalled();+ expect(compactMessages).toHaveBeenCalledOnce();+ expect(onCompaction).toHaveBeenCalledOnce();+ expect(ToolLoopAgent).not.toHaveBeenCalled();+ expect(getCompatibilityEventTypes(events)).toEqual([+ "compaction.requested",+ "compaction.completed",+ "session.waiting",+ ]);+ });++ it("returns an empty session to its waiting boundary after manual compaction", async () => {+ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ compactOnly: true,+ }),+ );+ const session = createTestSession({ history: [] });++ const result = await runStep(session);++ expect(result.next).toBeNull();+ expect(result.session).toBe(session);+ expect(getCompatibilityEventTypes(events)).toEqual(["session.waiting"]);+ expect(ToolLoopAgent).not.toHaveBeenCalled();+ expect(compactMessages).not.toHaveBeenCalled();+ });++ it("returns a failed manual compaction to its waiting boundary", async () => {+ vi.mocked(compactMessages).mockRejectedValueOnce(new Error("summary failed"));++ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ compactOnly: true,+ resolveModel: vi+ .fn()+ .mockResolvedValue({ modelId: "gpt-4", provider: "openai" } as LanguageModel),+ }),+ );+ const session = createTestSession({+ history: [{ content: "old message", role: "user" }],+ });++ const result = await runStep(session);++ expect(result.next).toBeNull();+ expect(result.session).toBe(session);+ expect(getCompatibilityEventTypes(events)).toEqual(["compaction.requested", "session.waiting"]);+ expect(ToolLoopAgent).not.toHaveBeenCalled();+ });++ it("returns a failed manual model resolution to its waiting boundary", async () => {+ const { emit, events } = createEventCollector();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ compactOnly: true,+ resolveModel: vi.fn().mockRejectedValueOnce(new Error("model unavailable")),+ }),+ );+ const session = createTestSession({+ history: [{ content: "old message", role: "user" }],+ });++ const result = await runStep(session);++ expect(result.next).toBeNull();+ expect(result.session).toBe(session);+ expect(getCompatibilityEventTypes(events)).toEqual(["session.waiting"]);+ expect(compactMessages).not.toHaveBeenCalled();+ expect(ToolLoopAgent).not.toHaveBeenCalled();+ });+it("uses the authored compaction model when one is configured", async () => {vi.mocked(shouldCompact).mockReturnValue(true);vi.mocked(compactMessages).mockResolvedValue([diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex a3cc7675b..8d809b65d 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -43,6 +43,7 @@ import {createCompactionRequestedEvent,createInputRequestedEvent,createResultCompletedEvent,+ createSessionWaitingEvent,createStepStartedEvent,} from "#protocol/message.js";import type { InstrumentationDefinition } from "#public/instrumentation/index.js";@@ -572,6 +573,49 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {turnId: activeTurnId(emissionState),});+ if (config.compactOnly === true) {+ if (session.history.length > 0) {+ try {+ const ctx = contextStorage.getStore();+ const resolvedModel = await resolveActiveRuntimeModel({ config, ctx, session });+ session = resolvedModel.session;++ const compacted = await maybeCompact({+ abortSignal: config.abortSignal,+ emit,+ emissionState: {+ ...emissionState,+ turnId: activeTurnId(emissionState),+ },+ force: true,+ messages: [...session.history],+ model: resolvedModel.model,+ onCompaction: config.onCompaction,+ resolveModel: config.resolveModel,+ runtimeIdentity: config.runtimeIdentity,+ session,+ telemetry: enrichTelemetry(telemetryConfig, agentName) ?? undefined,+ });++ session = {+ ...compacted.session,+ compaction: {+ recentWindowSize: compacted.session.compaction.recentWindowSize,+ threshold: compacted.session.compaction.threshold,+ },+ history: compacted.messages,+ };+ } catch (error) {+ logError(log, "manual session compaction failed", error, {+ sessionId: session.sessionId,+ });+ }+ }++ await emit?.(createSessionWaitingEvent(session.continuationToken));+ return { next: null, session };+ }+// Resolve deferred input, runtime actions, then HITL input; each stage// may park when its resume payload has not arrived.@@ -2514,6 +2558,7 @@ async function maybeCompact(input: {readonly abortSignal?: AbortSignal;readonly emit?: ToolLoopHarnessConfig["handleEvent"];readonly emissionState: ReturnType<typeof getHarnessEmissionState>;+ readonly force?: boolean;readonly messages: ModelMessage[];readonly model: LanguageModel;readonly onCompaction?: ToolLoopHarnessConfig["onCompaction"];@@ -2526,7 +2571,7 @@ async function maybeCompact(input: {let messages = input.messages;const session = input.session;- if (!shouldCompact(messages, session.compaction)) {+ if (input.force !== true && !shouldCompact(messages, session.compaction)) {return { messages, session };}@@ -2557,6 +2602,7 @@ async function maybeCompact(input: {input.telemetry,buildGatewayAttributionHeaders(compaction.model, input.runtimeIdentity),input.abortSignal,+ input.force === true,);if (input.onCompaction) {diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex 7e77321fa..f6909c404 100644--- a/packages/eve/src/harness/types.ts+++ b/packages/eve/src/harness/types.ts@@ -238,6 +238,8 @@ export interface ToolLoopHarnessConfig {* per-step toolset to decide whether `ask_question` is available.*/readonly capabilities?: SessionCapabilities;+ /** Forces one context-compaction pass without running a model turn. */+ readonly compactOnly?: boolean;/*** Exposes the `Workflow` orchestration tool — an isolated JavaScript sandbox* whose only callable operations are this agent's subagents and remotediff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 3b18322e6..69b916fcd 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts@@ -265,6 +265,7 @@ describe("dispatchChannelRequest", () => {it("tags route sends with Vercel's request id", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),resolveSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),@@ -314,6 +315,7 @@ describe("dispatchChannelRequest", () => {it("supplies a channel-scoped reset helper", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),getStreamTailIndex: vi.fn(),@@ -366,6 +368,7 @@ describe("dispatchChannelRequest", () => {it("does not invent a channel request id when Vercel did not send one", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),+ compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),resolveSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),@@ -410,6 +413,7 @@ describe("dispatchChannelRequest", () => {it("does not mutate route-owned run and deliver inputs", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),+ compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),resolveSession: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex f8d3ffd3b..af5d57406 100644--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts@@ -8,6 +8,7 @@ import {import type { DeliverInput, RunInput, Runtime } from "#channel/types.js";import type { RouteHandlerArgs, WebSocketRouteHooks } from "#channel/routes.js";import { createCancelFn } from "#channel/cancel.js";+import { createCompactFn } from "#channel/compact-session.js";import { createResetFn } from "#channel/reset-session.js";import { createSendFn } from "#channel/send.js";import { createResolveActiveSessionFn } from "#channel/resolve-active-session.js";@@ -214,6 +215,7 @@ function buildRouteArgs(const send = createSendFn(bundle.runtime, adapter, channelName, { requestId });const resolveActiveSession = createResolveActiveSessionFn(bundle.runtime, channelName);const cancel = createCancelFn(bundle.runtime, channelName);+ const compact = createCompactFn(bundle.runtime, channelName);const reset = createResetFn(bundle.runtime, channelName);const getSession = createGetSessionFn(bundle.runtime);const receive = createCrossChannelReceiveFn(@@ -227,6 +229,7 @@ function buildRouteArgs(send,resolveActiveSession,cancel,+ compact,reset,getSession,receive,diff --git a/packages/eve/src/protocol/compact-session.test.ts b/packages/eve/src/protocol/compact-session.test.tsnew file mode 100644index 000000000..9742ecc91--- /dev/null+++ b/packages/eve/src/protocol/compact-session.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import { CompactResponseSchema } from "#protocol/compact-session.js";++describe("CompactResponseSchema", () => {+ it("accepts both successful outcomes", () => {+ expect(+ CompactResponseSchema.parse({ ok: true, sessionId: "sess_1", status: "accepted" }),+ ).toEqual({ ok: true, sessionId: "sess_1", status: "accepted" });+ expect(CompactResponseSchema.parse({ ok: true, status: "no_active_session" })).toEqual({+ ok: true,+ status: "no_active_session",+ });+ });++ it("requires a session id for accepted requests", () => {+ expect(CompactResponseSchema.safeParse({ ok: true, status: "accepted" }).success).toBe(false);+ });+});diff --git a/packages/eve/src/protocol/compact-session.ts b/packages/eve/src/protocol/compact-session.tsnew file mode 100644index 000000000..24cf561c9--- /dev/null+++ b/packages/eve/src/protocol/compact-session.ts@@ -0,0 +1,29 @@+import { z } from "#compiled/zod/index.js";++/** Outcome of queueing manual context compaction. */+export type CompactStatus = "accepted" | "no_active_session";++/** Successful response returned by the standard session-compaction route. */+export type CompactResponse =+ | {+ readonly ok: true;+ readonly sessionId: string;+ readonly status: "accepted";+ }+ | {+ readonly ok: true;+ readonly status: "no_active_session";+ };++/** Validates successful responses from the standard session-compaction route. */+export const CompactResponseSchema: z.ZodType<CompactResponse> = z.discriminatedUnion("status", [+ z.object({+ ok: z.literal(true),+ sessionId: z.string().min(1),+ status: z.literal("accepted"),+ }),+ z.object({+ ok: z.literal(true),+ status: z.literal("no_active_session"),+ }),+]);diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.tsindex e93d85fd3..2cf6ab38f 100644--- a/packages/eve/src/protocol/routes.ts+++ b/packages/eve/src/protocol/routes.ts@@ -27,6 +27,12 @@ export const EVE_CREATE_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session`;*/export const EVE_RESET_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/reset`;+/**+ * Stable framework-owned route for compacting the session that owns a client+ * continuation token. The request body supplies the channel-local token.+ */+export const EVE_COMPACT_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/compact`;+/*** Stable framework-owned route pattern for sending a message to an existing* session.diff --git a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.tsindex fdf51b3c4..f06eb3a6f 100644--- a/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts+++ b/packages/eve/src/public/channels/chat-sdk/chatSdkChannel.test.ts@@ -124,6 +124,7 @@ async function firePost(getSession: vi.fn() as any,resolveActiveSession: async () => undefined,cancel,+ compact: vi.fn(),reset: vi.fn(),params: {},receive: vi.fn() as any,@@ -181,6 +182,7 @@ describe("chatSdkChannel", () => {getSession: vi.fn() as any,resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),params: {},receive: vi.fn() as any,diff --git a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.tsindex db6813587..56e1fd0c4 100644--- a/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts+++ b/packages/eve/src/public/channels/eve-forwarded-principal.integration.test.ts@@ -75,6 +75,7 @@ function createEveCreateHandler(input: EveChannelInput) {send: mockSend,resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),getSession: vi.fn(),receive: vi.fn() as never,diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 909fcf753..c908f9c16 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -79,6 +79,7 @@ function createEveCreateHandler(input: EveChannelInput) {send: mockSend,resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),getSession: vi.fn(),receive: vi.fn() as any,@@ -126,6 +127,7 @@ function createEveContinueHandler(input: EveChannelInput) {send: mockSend,resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),getSession: mockGetSession,receive: vi.fn() as any,@@ -160,6 +162,7 @@ function createEveCancelHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),getSession: vi.fn(),receive: vi.fn() as any,@@ -206,6 +209,7 @@ function createEveResetHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset,getSession: vi.fn(),receive: vi.fn() as any,@@ -226,6 +230,39 @@ function resetRequest(body: unknown): Request {});}+/** Creates a POST handler test harness for the continuation-addressed compact route. */+function createEveCompactHandler(input: EveChannelInput) {+ const channel = eveChannel(input);+ const compactRoute = channel.routes.find(+ (route) => route.method === "POST" && route.path === "/eve/v1/session/compact",+ );+ if (!compactRoute) throw new Error("No session compact POST route found");++ const compact = vi.fn().mockResolvedValue({+ sessionId: "test-session-id",+ status: "accepted",+ });++ return {+ compact,+ async fetch(req: Request) {+ const args: RouteHandlerArgs = {+ send: vi.fn(),+ resolveActiveSession: async () => undefined,+ cancel: vi.fn(),+ compact,+ reset: vi.fn(),+ getSession: vi.fn(),+ receive: vi.fn() as any,+ params: {},+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ };+ return (compactRoute as any).handler(req, args);+ },+ };+}+/** Creates a GET handler test harness for the durable session stream route. */function createEveStreamHandler(input: EveChannelInput) {const channel = eveChannel(input);@@ -252,6 +289,7 @@ function createEveStreamHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),getSession: mockGetSession,receive: vi.fn() as any,@@ -1538,6 +1576,33 @@ describe("eveChannel — reset session", () => {});});+describe("eveChannel — compact session", () => {+ it("queues compaction for the supplied channel-local continuation token", async () => {+ const handler = createEveCompactHandler({ auth: none() });++ const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));++ expect(response.status).toBe(202);+ expect(response.headers.get("cache-control")).toBe("no-store");+ await expect(response.json()).resolves.toEqual({+ ok: true,+ sessionId: "test-session-id",+ status: "accepted",+ });+ expect(handler.compact).toHaveBeenCalledWith({ continuationToken: "eve:token" });+ });++ it("reports a token that no active session owns", async () => {+ const handler = createEveCompactHandler({ auth: none() });+ handler.compact.mockResolvedValue({ status: "no_active_session" });++ const response = await handler.fetch(resetRequest({ continuationToken: "eve:token" }));++ expect(response.status).toBe(200);+ await expect(response.json()).resolves.toEqual({ ok: true, status: "no_active_session" });+ });+});+describe("eveChannel — forwarded principal", () => {const ROUTER_CALLER: SessionAuthContext = {attributes: {},diff --git a/packages/eve/src/public/channels/eve.ts b/packages/eve/src/public/channels/eve.tsindex cba4629c6..579ee1508 100644--- a/packages/eve/src/public/channels/eve.ts+++ b/packages/eve/src/public/channels/eve.ts@@ -2,6 +2,7 @@ import { type FilePart, type TextPart, type UserContent } from "ai";import type { CancelTurnResult, SessionAuthContext, SessionCallback } from "#channel/types.js";import type { CancelTurnResponse } from "#protocol/cancel-turn.js";+import type { CompactResponse } from "#protocol/compact-session.js";import type { ResetResponse } from "#protocol/reset-session.js";import type { SendOptions } from "#channel/routes.js";import { resolveForwardedPrincipal, type TrustedForwarders } from "#channel/forwarded-principal.js";@@ -23,6 +24,7 @@ import {} from "#protocol/message.js";import {EVE_CANCEL_TURN_ROUTE_PATTERN,+ EVE_COMPACT_SESSION_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,} from "#protocol/routes.js";@@ -310,6 +312,34 @@ export function eveChannel(input: EveChannelInput): EveChannel {});}),+ POST(EVE_COMPACT_SESSION_ROUTE_PATH, async (req, { compact }) => {+ const authResult = await routeAuth(req, input.auth);+ if (authResult instanceof Response) return authResult;++ const body = await parseResetSessionBody(req);+ if (body instanceof Response) return body;++ let result: Awaited<ReturnType<typeof compact>>;+ try {+ result = await compact({ continuationToken: body.continuationToken });+ } catch (error) {+ const errorId = logError(log, "session-compaction request failed", error);+ return Response.json(+ { error: "Failed to compact the session.", errorId, ok: false },+ { status: 500 },+ );+ }++ const response: CompactResponse =+ result.status === "accepted"+ ? { ok: true, sessionId: result.sessionId, status: "accepted" }+ : { ok: true, status: "no_active_session" };+ return Response.json(response, {+ headers: { "cache-control": "no-store" },+ status: result.status === "accepted" ? 202 : 200,+ });+ }),+POST("/eve/v1/session/:sessionId", async (req, { send, getSession, params }) => {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.tsindex 62c7bc8d6..a7866355d 100644--- a/packages/eve/src/public/channels/github/githubChannel.test.ts+++ b/packages/eve/src/public/channels/github/githubChannel.test.ts@@ -172,6 +172,7 @@ async function firePost(const response = await post.handler(request, {cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),resolveActiveSession: async () => undefined,getSession: vi.fn() as any,diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex 7357800f3..0535c9140 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -9,6 +9,9 @@ export {type CancelFn,type CancelOptions,type CancelTurnResult,+ type CompactFn,+ type CompactOptions,+ type CompactSessionResult,type Channel,type ChannelCors,type ChannelCorsOptions,diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex dfb8123cb..1313a319b 100644--- a/packages/eve/src/public/channels/linear/linearChannel.test.ts+++ b/packages/eve/src/public/channels/linear/linearChannel.test.ts@@ -127,6 +127,7 @@ async function firePost(const response = await post.handler(request, {cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),resolveActiveSession: async () => undefined,getSession: vi.fn() as any,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex fba2ea53c..195bad67b 100644--- a/packages/eve/src/public/channels/teams/teamsChannel.test.ts+++ b/packages/eve/src/public/channels/teams/teamsChannel.test.ts@@ -48,6 +48,7 @@ async function firePost(getSession: vi.fn(),resolveActiveSession: overrides.resolveActiveSession ?? vi.fn().mockResolvedValue(undefined),cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),params: {},receive: vi.fn(),diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex 7e0b09579..538507803 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -22,13 +22,20 @@ import type { GenericChannelDefinition, GenericReceiveInput } from "#shared/chandeclare const CHANNEL_METADATA_TYPE: unique symbol;-export type { CancelTurnInput, CancelTurnResult, GetEventStreamOptions } from "#channel/types.js";+export type {+ CancelTurnInput,+ CancelTurnResult,+ CompactSessionResult,+ GetEventStreamOptions,+} from "#channel/types.js";export type { Session, SessionHandle } from "#channel/session.js";export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";export type {CancelFn,CancelOptions,+ CompactFn,+ CompactOptions,ResetFn,ResetOptions,ResetResult,@@ -236,6 +243,8 @@ type ChannelSessionFailedHandler<TCtx> = (* and the channel context, with no `ctx`.*/export interface ChannelEvents<TCtx = void> {+ readonly "compaction.requested"?: ChannelEventHandler<"compaction.requested", TCtx>;+ readonly "compaction.completed"?: ChannelEventHandler<"compaction.completed", TCtx>;readonly "turn.started"?: ChannelEventHandler<"turn.started", TCtx>;readonly "actions.requested"?: ChannelEventHandler<"actions.requested", TCtx>;readonly "action.result"?: ChannelEventHandler<"action.result", TCtx>;@@ -339,6 +348,8 @@ export function defineChannel<// The Record type fails to compile if this map drifts from the ChannelEvents// keys in either direction.const channelEventTypes: Record<keyof ChannelEvents, null> = {+ "compaction.requested": null,+ "compaction.completed": null,"turn.started": null,"actions.requested": null,"action.result": null,diff --git a/packages/eve/test/eve-run-stream-channel.test.ts b/packages/eve/test/eve-run-stream-channel.test.tsindex 26b839aa3..1bb2b9b74 100644--- a/packages/eve/test/eve-run-stream-channel.test.ts+++ b/packages/eve/test/eve-run-stream-channel.test.ts@@ -191,6 +191,7 @@ function createArgs(input: {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ compact: vi.fn(),reset: vi.fn(),getSession: input.getSession,receive: vi.fn() as any,diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.tsindex 30250f14c..47fab9cc8 100644--- a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts+++ b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts@@ -83,6 +83,9 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {async cancelTurn() {throw new Error("cancelTurn should not be called in this scenario");},+ async compactSession() {+ throw new Error("compactSession should not be called in this scenario");+ },async resolveSession() {throw new Error("resolveSession should not be called in this scenario");},@@ -185,6 +188,9 @@ describe("cross-channel receive end-to-end", () => {cancel: async () => {throw new Error("webhook should not cancel turns");},+ compact: async () => {+ throw new Error("webhook should not compact sessions");+ },reset: async () => {throw new Error("webhook should not reset sessions");},diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.tsindex d005a1008..f2a1e7c79 100644--- a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts+++ b/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts@@ -60,6 +60,9 @@ function createCapturingRuntime(captured: CapturedRun[]): Runtime {async cancelTurn() {throw new Error("cancelTurn should not be called in this scenario");},+ async compactSession() {+ throw new Error("compactSession should not be called in this scenario");+ },async resolveSession() {throw new Error("resolveSession should not be called in this scenario");},