The Open Framework for Building Agents
feat: add manual session context clearing (#1511)
Casey Gowrief3bb60dd53fa
diff --git a/.changeset/fresh-dolphins-clear.md b/.changeset/fresh-dolphins-clear.mdnew file mode 100644index 000000000..7b7271527--- /dev/null+++ b/.changeset/fresh-dolphins-clear.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add manual session-context clearing through custom-channel helpers, the eve HTTP client, and the `eve dev` TUI's `/clear` command. Clearing removes model-message history while preserving the session, agent configuration, durable state, limits, and sandbox.diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex 520d7d9d6..f9e048fcf 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).+- `clear({ continuationToken })` removes the model-message history while preserving the session and its durable resources. See [Clear session context](#clear-session-context).- `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.@@ -87,6 +88,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.+## Clear session context++Call `clear` with the channel-local continuation token to remove a session's durable model-message history without replacing the session:++```ts+import { defineChannel, POST } from "eve/channels";++export default defineChannel({+ routes: [+ POST("/threads/:threadId/clear", async (_req, { clear, params }) => {+ const result = await clear({ continuationToken: params.threadId });+ return Response.json(result);+ }),+ ],+});+```++`"accepted"` means the clear was queued. The stream emits `context.cleared` followed by `session.waiting`, after which the next ordinary message resumes the same session with no prior model messages. The system prompt, configured tools and skills, durable state, limits, continuation-token ownership, and session-scoped sandbox remain. `"no_active_session"` means the token has no current owner.+## Compact a sessionCall `compact` with the channel-local continuation token to summarize durable conversation history without delivering a command to the model:@@ -180,7 +200,7 @@ export default defineChannel({});```-`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`.+`WS()` handlers receive the same helpers as HTTP route handlers: `send`, `cancel`, `clear`, `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 1e290fbda..2843c9f9a 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -25,6 +25,7 @@ The application exposes a health route plus eve channel routes that inspect the- `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/clear` (clear the continuation owner's model history)- `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)@@ -56,6 +57,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.+Clear the model-message history of the session that owns a continuation token:++```bash+curl -X POST https://<deployment>/eve/v1/session/clear \+ -H "Content-Type: application/json" \+ -d '{"continuationToken":"eve:7f3c..."}'+# {"ok":true,"sessionId":"ses_01h...","status":"accepted"}+```++An accepted clear emits `context.cleared` followed by `session.waiting`. The next message resumes the same session without prior model messages; the system prompt, tools and skills, durable state, limits, and session-scoped sandbox remain.+Compact the session that owns a continuation token without sending a message:```bashdiff --git a/docs/concepts/default-harness.md b/docs/concepts/default-harness.mdindex 4d88e0c32..46b656c40 100644--- a/docs/concepts/default-harness.md+++ b/docs/concepts/default-harness.md@@ -22,6 +22,8 @@ Compaction also preserves the framework's own tool state automatically. It resetClients 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`.+To discard model-message history instead of summarizing it, call `ClientSession.clear()` or a custom route's `clear({ continuationToken })` helper. Clearing preserves the session identity, system prompt, configured tools and skills, durable state, limits, and sandbox. Its stream boundary is `context.cleared` 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 c12ccda3d..4158e86af 100644--- a/docs/guides/client/streaming.mdx+++ b/docs/guides/client/streaming.mdx@@ -26,6 +26,13 @@ const compaction = await session.compact();console.log(compaction.status);```+Use `session.clear()` to remove model-message history while retaining the session and its durable resources. Consume `context.cleared` and the following `session.waiting` before sending the next turn.++```ts+const cleared = await session.clear();+console.log(cleared.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 c32724bd3..74227f528 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. |+| `/clear` | Clears model-message history while preserving the current session and its durable resources. || `/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 94a2bddbc..1908f9c20 100644--- a/e2e/fixtures/agent-cancellation/agent/channels/threads.ts+++ b/e2e/fixtures/agent-cancellation/agent/channels/threads.ts@@ -39,6 +39,10 @@ export default defineChannel({const result = await compact({ continuationToken: params.threadId ?? "" });return Response.json(result);}),+ POST("/threads/:threadId/clear", async (_request, { clear, params }) => {+ const result = await clear({ 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/clear-channel-session.eval.ts b/e2e/fixtures/agent-cancellation/evals/cancellation/clear-channel-session.eval.tsnew file mode 100644index 000000000..a052daeb3--- /dev/null+++ b/e2e/fixtures/agent-cancellation/evals/cancellation/clear-channel-session.eval.ts@@ -0,0 +1,106 @@+import { defineEval, type EveEvalTargetHandle } from "eve/evals";+import { satisfies } from "eve/evals/expect";++interface MessageResponse {+ readonly ok: boolean;+ readonly sessionId?: string;+}++interface ClearResponse {+ 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;+}++/** Clears a parked conversation through a custom channel route. */+export default defineEval({+ description: "Clear custom-channel context without replacing the durable session.",+ timeoutMs: 240_000,++ async test(t) {+ const unknownThread = await postJson<ClearResponse>(+ t.target,+ `/threads/${crypto.randomUUID()}/clear`,+ {},+ );+ await t.require(+ unknownThread,+ satisfies(+ (value: ClearResponse) => value.status === "no_active_session",+ "clearing 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 CLEAR-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 liveClear = t.target.watchTurn(sessionId, { startIndex: initial.events.length });+ const clearedResponse = await postJson<ClearResponse>(+ t.target,+ `/threads/${threadId}/clear`,+ {},+ );+ await t.require(+ clearedResponse,+ satisfies(+ (value: ClearResponse) => value.status === "accepted" && value.sessionId === sessionId,+ "the channel accepts a clear for the active session",+ ),+ );++ const cleared = await liveClear.result();+ cleared.event("context.cleared", { count: 1 });+ cleared.eventOrder([{ type: "context.cleared" }, { type: "session.waiting" }]);+ cleared.notEvent("turn.started");+ cleared.notEvent("turn.failed");+ cleared.notEvent("session.failed");++ const resumed = await postJson<MessageResponse>(t.target, `/threads/${threadId}/messages`, {+ message: "Reply with exactly CLEAR-FOLLOW-UP-OK.",+ });+ await t.require(+ resumed,+ satisfies(+ (value: MessageResponse) => value.sessionId === sessionId,+ "the thread resumes the same session after clearing context",+ ),+ );++ const followUp = await t.target+ .watchTurn(sessionId, {+ startIndex: initial.events.length + cleared.events.length,+ })+ .result();+ followUp.notEvent("turn.failed");+ followUp.notEvent("session.failed");+ followUp.messageIncludes(/CLEAR-FOLLOW-UP-OK/i);++ t.succeeded();+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicInstructions/v3.ts b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v3.tsnew file mode 100644index 000000000..e0433660b--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicInstructions/v3.ts@@ -0,0 +1,10 @@+import { defineDynamic, defineInstructions } from "#public/instructions/index.js";++export default defineDynamic({+ events: {+ "session.started": () =>+ defineInstructions({+ markdown: "Answer with evidence from the current session.",+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicSkill/v3.ts b/packages/eve/extension-contracts/compatibility/dynamicSkill/v3.tsnew file mode 100644index 000000000..942404504--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicSkill/v3.ts@@ -0,0 +1,11 @@+import { defineDynamic, defineSkill } from "#public/skills/index.js";++export default defineDynamic({+ events: {+ "session.started": () =>+ defineSkill({+ description: "Triage incoming requests.",+ markdown: "# Triage\n\nInspect the request before acting.",+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/dynamicTool/v6.ts b/packages/eve/extension-contracts/compatibility/dynamicTool/v6.tsnew file mode 100644index 000000000..624876617--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/dynamicTool/v6.ts@@ -0,0 +1,12 @@+import { defineDynamic, defineTool } from "#public/tools/index.js";++export default defineDynamic({+ events: {+ "session.started": () =>+ defineTool({+ description: "Return the current status.",+ inputSchema: { type: "object", properties: {} },+ execute: () => ({ status: "ready" }),+ }),+ },+});diff --git a/packages/eve/extension-contracts/compatibility/hook/v4.ts b/packages/eve/extension-contracts/compatibility/hook/v4.tsnew file mode 100644index 000000000..98cd2e775--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/hook/v4.ts@@ -0,0 +1,12 @@+import { defineHook } from "#public/hooks/index.js";++export default defineHook({+ events: {+ "input.requested"(event) {+ console.info(+ "input requested",+ event.data.requests.map((request) => request.requestId),+ );+ },+ },+});diff --git a/packages/eve/extension-contracts/reports/dynamicInstructions/v4.json b/packages/eve/extension-contracts/reports/dynamicInstructions/v4.jsonnew file mode 100644index 000000000..3b9adc9b6--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicInstructions/v4.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicInstructions",+ "epoch": 4,+ "sha256": "fe8552794e226041fead29565795150f75d9ecde8965bdd45c0ebdbd389487ac",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicSkill/v4.json b/packages/eve/extension-contracts/reports/dynamicSkill/v4.jsonnew file mode 100644index 000000000..e03b9f884--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicSkill/v4.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicSkill",+ "epoch": 4,+ "sha256": "fe8552794e226041fead29565795150f75d9ecde8965bdd45c0ebdbd389487ac",+ "exports": ["defineDynamic"]+}diff --git a/packages/eve/extension-contracts/reports/dynamicTool/v7.json b/packages/eve/extension-contracts/reports/dynamicTool/v7.jsonnew file mode 100644index 000000000..f988bf5a8--- /dev/null+++ b/packages/eve/extension-contracts/reports/dynamicTool/v7.json@@ -0,0 +1,13 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "dynamicTool",+ "epoch": 7,+ "sha256": "a463958b4709ca0dbf34b500bbcf3151bde26a87cbc09878e154096743c5600c",+ "exports": [+ "DynamicToolEntry",+ "DynamicToolEvents",+ "DynamicToolResult",+ "DynamicToolSet",+ "defineDynamic"+ ]+}diff --git a/packages/eve/extension-contracts/reports/hook/v5.json b/packages/eve/extension-contracts/reports/hook/v5.jsonnew file mode 100644index 000000000..b307af6e9--- /dev/null+++ b/packages/eve/extension-contracts/reports/hook/v5.json@@ -0,0 +1,7 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "hook",+ "epoch": 5,+ "sha256": "1b9de27017b48c3dcbd1a547a0813fc59814e68f5df077c3ea9eb75c0decef81",+ "exports": ["defineHook"]+}diff --git a/packages/eve/src/channel/cancel.test.ts b/packages/eve/src/channel/cancel.test.tsindex ef0244f43..6ca006393 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" }),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),diff --git a/packages/eve/src/channel/clear-session.test.ts b/packages/eve/src/channel/clear-session.test.tsnew file mode 100644index 000000000..cec2971c4--- /dev/null+++ b/packages/eve/src/channel/clear-session.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from "vitest";++import { createClearFn } from "#channel/clear-session.js";+import type { Runtime } from "#channel/types.js";++function createRuntime(): Runtime {+ return {+ cancelTurn: vi.fn(),+ clearSession: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),+ compactSession: vi.fn(),+ deliver: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveSession: vi.fn(),+ run: vi.fn(),+ terminateSession: vi.fn(),+ };+}++describe("createClearFn", () => {+ it("namespaces the channel-local token and returns the runtime result", async () => {+ const runtime = createRuntime();++ await expect(createClearFn(runtime, "slack")({ continuationToken: "C1:T1" })).resolves.toEqual({+ sessionId: "sess_1",+ status: "accepted",+ });+ expect(runtime.clearSession).toHaveBeenCalledWith({+ continuationToken: "slack:C1:T1",+ });+ });+});diff --git a/packages/eve/src/channel/clear-session.ts b/packages/eve/src/channel/clear-session.tsnew file mode 100644index 000000000..d8ffe7971--- /dev/null+++ b/packages/eve/src/channel/clear-session.ts@@ -0,0 +1,10 @@+import type { ClearFn, ClearOptions } from "#channel/routes.js";+import type { ClearSessionResult, Runtime } from "#channel/types.js";++/** Builds a channel-scoped context-clear helper. */+export function createClearFn(runtime: Runtime, channelName: string): ClearFn {+ return async (options: ClearOptions): Promise<ClearSessionResult> =>+ await runtime.clearSession({+ continuationToken: `${channelName}:${options.continuationToken}`,+ });+}diff --git a/packages/eve/src/channel/compact-session.test.ts b/packages/eve/src/channel/compact-session.test.tsindex 6ead0fb2f..d9ae8a00f 100644--- a/packages/eve/src/channel/compact-session.test.ts+++ b/packages/eve/src/channel/compact-session.test.ts@@ -6,6 +6,7 @@ import type { Runtime } from "#channel/types.js";function createRuntime(): Runtime {return {cancelTurn: vi.fn(),+ clearSession: vi.fn(),compactSession: vi.fn().mockResolvedValue({ sessionId: "sess_1", status: "accepted" }),deliver: vi.fn(),getEventStream: vi.fn(),diff --git a/packages/eve/src/channel/cross-channel-receive.test.ts b/packages/eve/src/channel/cross-channel-receive.test.tsindex a1686fa9e..297689e44 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),diff --git a/packages/eve/src/channel/reset-session.test.ts b/packages/eve/src/channel/reset-session.test.tsindex 524edf2a5..7cc384dc1 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),diff --git a/packages/eve/src/channel/resolve-active-session.test.ts b/packages/eve/src/channel/resolve-active-session.test.tsindex 175a3377b..b70e40123 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn().mockResolvedValue(new ReadableStream()),diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.tsindex ed41f7541..eeb5c91e0 100644--- a/packages/eve/src/channel/routes.ts+++ b/packages/eve/src/channel/routes.ts@@ -3,6 +3,7 @@ import type { UserContent } from "ai";import type { CrossChannelReceiveFn } from "#channel/cross-channel-receive.js";import type {CancelTurnResult,+ ClearSessionResult,CompactSessionResult,SessionAuthContext,SessionCallback,@@ -18,12 +19,13 @@ 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; `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;- * `requestIp` is the client IP, or `null` when the host cannot provide it.+ * addressed by continuation token; `clear` removes its model-message history;+ * `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; `requestIp` is the client IP, or `null` when the host cannot+ * provide it.*/export interface RouteHandlerArgs<TState = undefined> {send: SendFn<TState>;@@ -33,6 +35,7 @@ export interface RouteHandlerArgs<TState = undefined> {*/resolveActiveSession: ResolveActiveSessionFn;cancel: CancelFn;+ clear: ClearFn;compact: CompactFn;reset: ResetFn;getSession: GetSessionFn;@@ -153,6 +156,20 @@ export interface CompactOptions {*/export type CompactFn = (options: CompactOptions) => Promise<CompactSessionResult>;+/** Options for {@link ClearFn}. */+export interface ClearOptions {+ /** Channel-local raw token, in the same format accepted by {@link SendFn}. */+ readonly continuationToken: string;+}++/**+ * Queues removal of the model-message history for the session owning a+ * continuation token. Preserves the session, agent configuration, durable+ * state, limits, and sandbox. Completion is `context.cleared` followed by+ * `session.waiting` on the session stream.+ */+export type ClearFn = (options: ClearOptions) => Promise<ClearSessionResult>;+/** 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 ccfb18a3e..b47abe80a 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockRejectedValue(new RuntimeNoActiveSessionError("schedule:token")),resolveSession: vi.fn(),diff --git a/packages/eve/src/channel/send.test.ts b/packages/eve/src/channel/send.test.tsindex 9ac1dba8a..0db9f50b8 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockRejectedValue(deliverError),resolveSession: vi.fn(),@@ -82,6 +83,7 @@ describe("createSendFn", () => {const context = ["thread background"];const deliverRuntime: Runtime = {cancelTurn: vi.fn(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),resolveSession: vi.fn(),@@ -118,6 +120,7 @@ describe("createSendFn", () => {it("adds channel request ids to deliver and run inputs when provided", async () => {const deliverRuntime: Runtime = {cancelTurn: vi.fn(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),resolveSession: vi.fn(),@@ -149,6 +152,7 @@ describe("createSendFn", () => {} as const;const deliverRuntime: Runtime = {cancelTurn: vi.fn(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "existing-session-id" }),resolveSession: vi.fn(),diff --git a/packages/eve/src/channel/session.test.ts b/packages/eve/src/channel/session.test.tsindex f814feaa0..5edaa11c7 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" }),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex b55c13cf0..b9e5d2d1c 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -47,6 +47,16 @@ export type CompactSessionResult =| { readonly status: "accepted"; readonly sessionId: string }| { readonly status: "no_active_session" };+/** Identifies the continuation hook whose durable session should clear context. */+export interface ClearSessionInput {+ readonly continuationToken: string;+}++/** Result of queueing a manual context clear for a session. */+export type ClearSessionResult =+ | { 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. */@@ -196,6 +206,11 @@ export interface CompactSessionHookPayload {readonly kind: "compact";}+/** Requests a context clear without delivering model input. */+export interface ClearSessionHookPayload {+ readonly kind: "clear";+}+/*** Runtime-action results resumed back into a parked parent workflow.*/@@ -258,6 +273,7 @@ export interface SubagentAuthorizationEventHookPayload {* Serializable payload sent through the workflow `resumeHook`.*/export type HookPayload =+ | ClearSessionHookPayload| CompactSessionHookPayload| DeliverHookPayload| RuntimeActionResultHookPayload@@ -457,6 +473,9 @@ export interface Runtime {/** Queues context compaction on the session owning a continuation token. */compactSession(input: CompactSessionInput): Promise<CompactSessionResult>;+ /** Queues a context clear on the session owning a continuation token. */+ clearSession(input: ClearSessionInput): Promise<ClearSessionResult>;+/** 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 46c558391..ce5b91d10 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: "clear" }| { type: "compact" }| { type: "exit" }| { type: "help" }@@ -59,6 +60,14 @@ const PROMPT_COMMAND_DEFINITIONS = [build: () => ({ type: "new" }),targets: ["local", "remote"],},+ {+ name: "clear",+ aliases: [],+ description: "Clear the current session context",+ takesArgument: false,+ build: () => ({ type: "clear" }),+ targets: ["local", "remote"],+ },{name: "compact",aliases: [],@@ -156,7 +165,7 @@ export function isPromptCommandAvailableFor(/*** Recognizes the slash commands the prompt accepts. `/new` clears the- * session and transcript; `/compact` queues context compaction; `/exit` (and `/quit`) terminate the TUI like+ * session and transcript; `/clear` clears context; `/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 d6daad994..0040d0748 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, /compact, /exit, and /quit", () => {+ it("recognizes /new, /clear, /compact, /exit, and /quit", () => {expect(parsePromptCommand("/new")).toEqual({ type: "new" });+ expect(parsePromptCommand("/clear")).toEqual({ type: "clear" });expect(parsePromptCommand("/compact")).toEqual({ type: "compact" });expect(parsePromptCommand("/exit")).toEqual({ type: "exit" });expect(parsePromptCommand("/quit")).toEqual({ type: "exit" });@@ -696,6 +697,46 @@ describe("EveTUIRunner development session continuity", () => {expect(results).toEqual(["Compaction requested."]);});+ it("clears the active session context without sending a prompt", async () => {+ const session = sessionYielding([]);+ const clear = vi+ .spyOn(session, "clear")+ .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> = ["/clear", 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(clear).toHaveBeenCalledOnce();+ expect(stream).toHaveBeenCalledOnce();+ expect(session.send).not.toHaveBeenCalled();+ expect(results).toEqual(["Context clear 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 63473c271..4b2a3c202 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -831,6 +831,35 @@ export class EveTUIRunner {prompt = undefined;}+ if (command?.type === "clear") {+ try {+ const result = await this.#session.clear();+ this.#renderCommandOutcome(+ result.status === "accepted"+ ? "Context clear requested."+ : "No active session to clear.",+ );+ if (result.status === "no_active_session") {+ pendingInputResponses = undefined;+ followCurrentSession = false;+ streamWithoutPrompt = false;+ prompt = undefined;+ continue;+ }+ } catch (error) {+ this.#renderCommandOutcome(`Couldn't clear 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") {diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex a41dd1a9b..eb36a2bfe 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -43,6 +43,7 @@ export type {AgentInfoToolEntry,AgentInfoTools,CancelSessionResult,+ ClearResult,CompactResult,ClientAuth,ClientOptions,diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex b02589310..425a47f10 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 a context clear 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.clear()).resolves.toEqual({+ sessionId: "session_1",+ status: "accepted",+ });++ expect(session.state).toEqual(state);+ expect(new URL(requests[0]!.url).pathname).toBe("/eve/v1/session/clear");+ expect(requests[0]!.method).toBe("POST");+ expect(JSON.parse(requests[0]!.body ?? "{}")).toEqual({ continuationToken: "eve:test" });+ });++ it("treats clearing a never-started session as a successful no-op", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch");++ await expect(createSession().clear()).resolves.toEqual({ status: "no_active_session" });+ expect(fetchMock).not.toHaveBeenCalled();+ });+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 }> = [];diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex 1cee038bf..fbcbcc287 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -1,10 +1,12 @@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 { ClearResponseSchema } from "#protocol/clear-session.js";import { CompactResponseSchema } from "#protocol/compact-session.js";import { ResetResponseSchema } from "#protocol/reset-session.js";import {EVE_CREATE_SESSION_ROUTE_PATH,+ EVE_CLEAR_SESSION_ROUTE_PATH,EVE_COMPACT_SESSION_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,createEveCancelTurnRoutePath,@@ -18,6 +20,7 @@ import { serializeOutputSchema } from "#shared/tool-schema.js";import { createClientUrl } from "#client/url.js";import type {CancelSessionResult,+ ClearResult,CompactResult,ClientRedirectPolicy,ResetResult,@@ -198,6 +201,68 @@ export class ClientSession {return { sessionId: result.data.sessionId, status: result.data.status };}+ /**+ * Queues removal of this session's durable model-message history. The+ * session identity, agent configuration, state, limits, and sandbox remain.+ * Consume the durable stream through `context.cleared` and its following+ * `session.waiting` boundary before sending another turn.+ */+ async clear(): Promise<ClearResult> {+ 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 clearing.",+ );+ }+ return { status: "no_active_session" };+ }++ const url = createClientUrl(this.#context.host, EVE_CLEAR_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(`Clear route returned invalid JSON (${response.status}).`);+ }++ const result = ClearResponseSchema.safeParse(payload);+ if (+ !result.success ||+ (result.data.status === "accepted" &&+ state.sessionId !== undefined &&+ result.data.sessionId !== state.sessionId)+ ) {+ throw new Error(`Clear route returned an invalid response (${response.status}).`);+ }++ return result.data.status === "accepted"+ ? { sessionId: result.data.sessionId, status: "accepted" }+ : { status: "no_active_session" };+ }+/*** Queues context compaction without sending model input. The request is* asynchronous; consume the durable event stream through its next sessiondiff --git a/packages/eve/src/client/types.ts b/packages/eve/src/client/types.tsindex f6a2e08c5..26b940693 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 { ClearStatus } from "#protocol/clear-session.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";@@ -238,6 +239,18 @@ export interface CancelSessionResult {readonly status: CancelTurnStatus;}+/** Result of requesting a context clear for a client session. */+export type ClearResult =+ | {+ /** Session whose clear request was queued. */+ readonly sessionId: string;+ readonly status: Extract<ClearStatus, "accepted">;+ }+ | {+ /** The client had no continuation token or the token was already free. */+ readonly status: Extract<ClearStatus, "no_active_session">;+ };+/** Result of requesting context compaction for a client session. */export type CompactResult =| {diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex 704f06ac6..093eb5c43 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,13 +22,13 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: { current: 3, supported: [1, 2, 3], dropped: {} },- dynamicTool: { current: 6, supported: [1, 2, 3, 4, 5, 6], dropped: {} },+ dynamicTool: { current: 7, supported: [1, 2, 3, 4, 5, 6, 7], dropped: {} },connection: { current: 2, supported: [1, 2], dropped: {} },- hook: { current: 4, supported: [1, 2, 3, 4], dropped: {} },+ hook: { current: 5, supported: [1, 2, 3, 4, 5], dropped: {} },skill: { current: 1, supported: [1], dropped: {} },- dynamicSkill: { current: 3, supported: [1, 2, 3], dropped: {} },+ dynamicSkill: { current: 4, supported: [1, 2, 3, 4], dropped: {} },instructions: { current: 1, supported: [1], dropped: {} },- dynamicInstructions: { current: 3, supported: [1, 2, 3], dropped: {} },+ dynamicInstructions: { current: 4, supported: [1, 2, 3, 4], dropped: {} },config: { current: 1, supported: [1], dropped: {} },state: { current: 2, supported: [1, 2], dropped: {} },} as const satisfies Record<string, ExtensionCapabilityContract>;diff --git a/packages/eve/src/execution/node-step.test.ts b/packages/eve/src/execution/node-step.test.tsindex 96de7d68a..43ee0bfd9 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),resolveSession: vi.fn(),diff --git a/packages/eve/src/execution/node-step.ts b/packages/eve/src/execution/node-step.tsindex 9ea5ca9d2..a5389e599 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 context clear and returns to the parked session. */+ readonly clearOnly?: boolean;/** Runs only a forced context compaction and returns to the parked session. */readonly compactOnly?: boolean;/**@@ -89,6 +91,7 @@ export function createExecutionNodeStep(input: CreateExecutionNodeStepInput): Stconst step = createToolLoopHarness({abortSignal: input.abortSignal,capabilities: input.capabilities,+ clearOnly: input.clearOnly,compactOnly: input.compactOnly,workflow: input.node.agent.workflowTool !== undefined,workflowMaxSubagents: input.workflowMaxSubagents,diff --git a/packages/eve/src/execution/session-delivery-hook.test.ts b/packages/eve/src/execution/session-delivery-hook.test.tsindex 8de29d7b9..f78300019 100644--- a/packages/eve/src/execution/session-delivery-hook.test.ts+++ b/packages/eve/src/execution/session-delivery-hook.test.ts@@ -108,8 +108,22 @@ describe("createSessionDeliveryHook", () => {await expect(deliveryHook.next()).resolves.toEqual(compact());deliveryHook.consumeNext();- expect(deliveryHook.consumeCompactRequest()).toBe(true);- expect(deliveryHook.consumeCompactRequest()).toBe(false);+ expect(deliveryHook.consumeSessionControl()).toBe("compact");+ expect(deliveryHook.consumeSessionControl()).toBeUndefined();+ await deliveryHook.dispose();+ });++ it("latches clear requests consumed while a turn owns delivery reads", async () => {+ const hook = createMockHook({ reads: [Promise.resolve(clear())], token: "active" });+ installHooks(hook);+ const deliveryHook = createSessionDeliveryHook([]);++ await deliveryHook.rekey("active");+ await expect(deliveryHook.next()).resolves.toEqual(clear());+ deliveryHook.consumeNext();++ expect(deliveryHook.consumeSessionControl()).toBe("clear");+ expect(deliveryHook.consumeSessionControl()).toBeUndefined();await deliveryHook.dispose();});@@ -290,6 +304,10 @@ function compact(): IteratorResult<HookPayload> {return { done: false, value: { kind: "compact" } };}+function clear(): IteratorResult<HookPayload> {+ return { done: false, value: { kind: "clear" } };+}+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 3208e7638..c89885237 100644--- a/packages/eve/src/execution/session-delivery-hook.ts+++ b/packages/eve/src/execution/session-delivery-hook.ts@@ -21,7 +21,7 @@ interface SessionDeliveryHookState {/** Reads and rekeys the public delivery hook for one session driver. */export interface SessionDeliveryHook {- consumeCompactRequest(): boolean;+ consumeSessionControl(): "clear" | "compact" | undefined;consumeNext(): void;consumeSessionTimeout(): boolean;next(): Promise<IteratorResult<HookPayload>>;@@ -51,7 +51,7 @@ export function createSessionDeliveryHook(let offered: Promise<IteratorResult<HookPayload>> | null = null;let offeredRead: HookRead | undefined;let sessionTimedOut = false;- let compactRequested = false;+ const pendingSessionControls = new Set<"clear" | "compact">();let wake: (() => void) | undefined;const enqueue = (read: HookRead): void => {@@ -122,8 +122,8 @@ export function createSessionDeliveryHook(bufferedDeliveries.push(read.result.value);} else if (read.result.value.kind === "session-timeout") {sessionTimedOut = true;- } else if (read.result.value.kind === "compact") {- compactRequested = true;+ } else if (read.result.value.kind === "clear" || read.result.value.kind === "compact") {+ pendingSessionControls.add(read.result.value.kind);}}@@ -133,10 +133,12 @@ export function createSessionDeliveryHook(};return {- consumeCompactRequest(): boolean {- const requested = compactRequested;- compactRequested = false;- return requested;+ consumeSessionControl(): "clear" | "compact" | undefined {+ for (const control of pendingSessionControls) {+ pendingSessionControls.delete(control);+ return control;+ }+ return undefined;},consumeNext(): void {@@ -147,8 +149,11 @@ 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;+ if (+ !offeredRead.result.done &&+ (offeredRead.result.value.kind === "clear" || offeredRead.result.value.kind === "compact")+ ) {+ pendingSessionControls.add(offeredRead.result.value.kind);}offeredRead.state.pending = false;offeredRead.state.resolved = undefined;diff --git a/packages/eve/src/execution/turn-cancellation.integration.test.ts b/packages/eve/src/execution/turn-cancellation.integration.test.tsindex ec078526b..c6dac25c1 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");},+ clear: () => {+ throw new Error("cancel route must not clear session context");+ },compact: () => {throw new Error("cancel route must not compact a session");},diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.tsindex 17c0e6ab6..25db06a22 100644--- a/packages/eve/src/execution/turn-control-receiver.test.ts+++ b/packages/eve/src/execution/turn-control-receiver.test.ts@@ -125,7 +125,7 @@ function parkResult(): Extract<TurnControlPayload, { readonly kind: "turn-resultfunction createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {return {- consumeCompactRequest: vi.fn(() => false),+ consumeSessionControl: vi.fn(() => undefined),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 3923e4e00..735b7e577 100644--- a/packages/eve/src/execution/turn-dispatch.test.ts+++ b/packages/eve/src/execution/turn-dispatch.test.ts@@ -217,7 +217,7 @@ describe("dispatchAndAwaitTurn", () => {function createDeliveryHook(overrides: Partial<SessionDeliveryHook> = {}): SessionDeliveryHook {return {- consumeCompactRequest: vi.fn(() => false),+ consumeSessionControl: vi.fn(() => undefined),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 ef792c081..28e5f9fe4 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -383,6 +383,34 @@ describe("workflowEntry", () => {expect(routeDeliverToChildren).not.toHaveBeenCalled();});+ it("dispatches a clear control without converting it into a delivery", async () => {+ const sessionState = createBaseSessionState();+ vi.mocked(createSessionStep).mockResolvedValue(createSessionStepResultForMock(sessionState));+ installHookMocks({+ deliveryHooks: [+ {+ token: "http:test",+ values: [{ kind: "clear" }, { 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: "clear" });+ 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 e91a2b4f4..9f19f8700 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: "clear" }| { readonly kind: "compact" }| {readonly delivery: DeliverHookPayload | null;@@ -338,9 +339,9 @@ async function runDriverLoop(input: {};}- if (nextAction.kind === "compact") {+ if (nextAction.kind === "clear" || nextAction.kind === "compact") {action = await runTurn({- delivery: { kind: "compact" },+ delivery: { kind: nextAction.kind },serializedContext: action.serializedContext,sessionState: action.sessionState,});@@ -412,8 +413,9 @@ async function waitForNextSessionAction(input: {return { kind: "expired" };}- if (input.deliveryHook.consumeCompactRequest()) {- return { kind: "compact" };+ const pendingSessionControl = input.deliveryHook.consumeSessionControl();+ if (pendingSessionControl !== undefined) {+ return { kind: pendingSessionControl };}if (input.bufferedDeliveries.length > 0) {@@ -435,9 +437,12 @@ async function waitForNextSessionAction(input: {return { kind: "expired" };}- if (first.value.kind === "compact") {- input.deliveryHook.consumeCompactRequest();- return { kind: "compact" };+ if (first.value.kind === "clear" || first.value.kind === "compact") {+ const sessionControl = input.deliveryHook.consumeSessionControl();+ if (sessionControl === undefined) {+ throw new Error("Session control was consumed without being latched.");+ }+ return { kind: sessionControl };}if (first.value.kind !== "deliver") {@@ -466,7 +471,7 @@ async function waitForNextSessionAction(input: {input.deliveryHook.consumeNext();- if (ready.value.kind === "compact") {+ if (ready.value.kind === "clear" || ready.value.kind === "compact") {continue;}diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex 05aa1e226..3c021ad05 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -232,6 +232,31 @@ describe("createWorkflowRuntime#compactSession", () => {});});+describe("createWorkflowRuntime#clearSession", () => {+ function buildRuntime() {+ return createWorkflowRuntime({ compiledArtifactsSource: {} as RuntimeCompiledArtifactsSource });+ }++ it("queues a clear on the continuation hook and returns its owner", async () => {+ resumeHookMock.mockResolvedValue({ runId: "session-1" });++ await expect(buildRuntime().clearSession({ continuationToken: "eve:token" })).resolves.toEqual({+ sessionId: "session-1",+ status: "accepted",+ });+ expect(resumeHookMock).toHaveBeenCalledWith("eve:token", { kind: "clear" });+ });++ 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().clearSession({ continuationToken: "eve:missing" }),+ ).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 6ab771c91..019ebbf8c 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,+ ClearSessionInput,+ ClearSessionResult,CompactSessionInput,CompactSessionResult,DeliverInput,@@ -197,20 +199,11 @@ export function createWorkflowRuntime(config: {},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;- }+ return await requestWorkflowSessionControl(input.continuationToken, "compact");+ },++ async clearSession(input: ClearSessionInput): Promise<ClearSessionResult> {+ return await requestWorkflowSessionControl(input.continuationToken, "clear");},async terminateSession(input: TerminateSessionInput): Promise<TerminateSessionResult> {@@ -286,6 +279,22 @@ export function createWorkflowRuntime(config: {};}+async function requestWorkflowSessionControl(+ continuationToken: string,+ kind: "clear" | "compact",+): Promise<ClearSessionResult> {+ try {+ const hook = normalizeWorkflowHook(await resumeHook(continuationToken, { kind }));+ 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 ${kind}`, error, { continuationToken });+ throw error;+ }+}+/** Requests cancellation through a session's stable workflow hook. */export async function requestWorkflowTurnCancellation(input: CancelTurnInput,diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 41508c7ad..0d0d38a71 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,+ clearOnly: input.input?.kind === "clear",compactOnly: input.input?.kind === "compact",createRuntime: createWorkflowRuntime,handleEvent,diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.tsindex 7a1abeaa8..a6dd48996 100644--- a/packages/eve/src/harness/tool-loop.test.ts+++ b/packages/eve/src/harness/tool-loop.test.ts@@ -7775,6 +7775,58 @@ describe("createToolLoopHarness", () => {});});+ it("clears model history without replacing the session or its durable state", async () => {+ const { emit, events } = createEventCollector();+ const resolveModel = vi.fn();+ const runStep = createToolLoopHarness(+ createTestConfig("conversation", emit, {+ clearOnly: true,+ resolveModel,+ }),+ );+ const state = { retained: "yes" };+ const limits = { maxInputTokensPerSession: 1_000 };+ const outputSchema = { type: "string" };+ const session = createTestSession({+ compaction: {+ lastKnownInputTokens: 9000,+ lastKnownPromptMessageCount: 2,+ recentWindowSize: 10,+ threshold: 100_000,+ },+ history: [+ { content: "old message", role: "user" },+ { content: "old reply", role: "assistant" },+ ],+ limits,+ outputSchema,+ state,+ });++ const result = await runStep(session);++ expect(result.next).toBeNull();+ expect(result.session).toMatchObject({+ agent: session.agent,+ compaction: { recentWindowSize: 10, threshold: 100_000 },+ continuationToken: session.continuationToken,+ history: [],+ limits,+ outputSchema,+ sessionId: session.sessionId,+ state,+ });+ expect(getCompatibilityEventTypes(events)).toEqual(["context.cleared", "session.waiting"]);+ expect(events.find((event) => event.type === "context.cleared")?.data).toEqual({+ sequence: 0,+ sessionId: "test-session",+ turnId: "turn_0",+ });+ expect(resolveModel).not.toHaveBeenCalled();+ expect(compactMessages).not.toHaveBeenCalled();+ expect(ToolLoopAgent).not.toHaveBeenCalled();+ });+it("forces compaction without starting a model turn", async () => {const compactedHistory: ModelMessage[] = [{ content: "Summary of our conversation so far:", role: "user" },diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 8d809b65d..e71e435e1 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -41,6 +41,7 @@ import {createActionResultEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,+ createContextClearedEvent,createInputRequestedEvent,createResultCompletedEvent,createSessionWaitingEvent,@@ -573,6 +574,26 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {turnId: activeTurnId(emissionState),});+ if (config.clearOnly === true) {+ session = {+ ...session,+ compaction: {+ recentWindowSize: session.compaction.recentWindowSize,+ threshold: session.compaction.threshold,+ },+ history: [],+ };+ await emit?.(+ createContextClearedEvent({+ sequence: emissionState.sequence,+ sessionId: session.sessionId,+ turnId: activeTurnId(emissionState),+ }),+ );+ await emit?.(createSessionWaitingEvent(session.continuationToken));+ return { next: null, session };+ }+if (config.compactOnly === true) {if (session.history.length > 0) {try {diff --git a/packages/eve/src/harness/types.ts b/packages/eve/src/harness/types.tsindex f6909c404..78c6b5bb3 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;+ /** Clears model-message history without running a model turn. */+ readonly clearOnly?: boolean;/** Forces one context-compaction pass without running a model turn. */readonly compactOnly?: boolean;/**diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.test.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.test.tsindex 69b916fcd..94195d3ad 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(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),resolveSession: vi.fn(),@@ -315,6 +316,7 @@ describe("dispatchChannelRequest", () => {it("supplies a channel-scoped reset helper", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn(),getEventStream: vi.fn(),@@ -365,9 +367,57 @@ describe("dispatchChannelRequest", () => {});});+ it("supplies a channel-scoped clear helper", async () => {+ const runtimeForTest: Runtime = {+ cancelTurn: vi.fn(),+ clearSession: vi.fn().mockResolvedValue({ sessionId: "sess_active", status: "accepted" }),+ compactSession: vi.fn(),+ deliver: vi.fn(),+ getEventStream: vi.fn(),+ getStreamTailIndex: vi.fn(),+ resolveSession: vi.fn(),+ run: vi.fn(),+ terminateSession: vi.fn(),+ };++ mockedResolveNitroChannelRuntimeBundle.mockResolvedValue({+ channels: [+ {+ handler: async (_req, args) =>+ Response.json(+ await args.clear({ continuationToken: "direct:+15551234567:+15557654321" }),+ ),+ fetch: async () => new Response("ok"),+ logicalPath: "agent/channels/imessage.ts",+ method: "POST",+ name: "imessage",+ sourceId: "channel-imessage",+ sourceKind: "module",+ urlPath: "/imessage",+ } satisfies ResolvedChannelDefinition,+ ],+ runtime: runtimeForTest,+ });++ const response = await dispatchChannelRequest(+ createEvent({ waitUntil: vi.fn() }),+ "POST /imessage",+ {} as never,+ );++ await expect(response.json()).resolves.toEqual({+ sessionId: "sess_active",+ status: "accepted",+ });+ expect(runtimeForTest.clearSession).toHaveBeenCalledWith({+ continuationToken: "imessage:direct:+15551234567:+15557654321",+ });+ });+it("does not invent a channel request id when Vercel did not send one", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn(),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_route" }),resolveSession: vi.fn(),@@ -413,6 +463,7 @@ describe("dispatchChannelRequest", () => {it("does not mutate route-owned run and deliver inputs", async () => {const runtimeForTest: Runtime = {cancelTurn: vi.fn().mockResolvedValue({ status: "accepted" }),+ clearSession: vi.fn(),compactSession: vi.fn(),deliver: vi.fn().mockResolvedValue({ sessionId: "sess_deliver" }),resolveSession: vi.fn(),diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.tsindex af5d57406..a061c2133 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 { createClearFn } from "#channel/clear-session.js";import { createCompactFn } from "#channel/compact-session.js";import { createResetFn } from "#channel/reset-session.js";import { createSendFn } from "#channel/send.js";@@ -215,6 +216,7 @@ function buildRouteArgs(const send = createSendFn(bundle.runtime, adapter, channelName, { requestId });const resolveActiveSession = createResolveActiveSessionFn(bundle.runtime, channelName);const cancel = createCancelFn(bundle.runtime, channelName);+ const clear = createClearFn(bundle.runtime, channelName);const compact = createCompactFn(bundle.runtime, channelName);const reset = createResetFn(bundle.runtime, channelName);const getSession = createGetSessionFn(bundle.runtime);@@ -229,6 +231,7 @@ function buildRouteArgs(send,resolveActiveSession,cancel,+ clear,compact,reset,getSession,diff --git a/packages/eve/src/protocol/clear-session.test.ts b/packages/eve/src/protocol/clear-session.test.tsnew file mode 100644index 000000000..f4d60198a--- /dev/null+++ b/packages/eve/src/protocol/clear-session.test.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import { ClearResponseSchema } from "#protocol/clear-session.js";++describe("ClearResponseSchema", () => {+ it("accepts both successful outcomes", () => {+ expect(+ ClearResponseSchema.parse({ ok: true, sessionId: "sess_1", status: "accepted" }),+ ).toEqual({ ok: true, sessionId: "sess_1", status: "accepted" });+ expect(ClearResponseSchema.parse({ ok: true, status: "no_active_session" })).toEqual({+ ok: true,+ status: "no_active_session",+ });+ });++ it("requires a session id for accepted requests", () => {+ expect(ClearResponseSchema.safeParse({ ok: true, status: "accepted" }).success).toBe(false);+ });+});diff --git a/packages/eve/src/protocol/clear-session.ts b/packages/eve/src/protocol/clear-session.tsnew file mode 100644index 000000000..d972aaa8b--- /dev/null+++ b/packages/eve/src/protocol/clear-session.ts@@ -0,0 +1,29 @@+import { z } from "#compiled/zod/index.js";++/** Outcome of queueing a manual context clear. */+export type ClearStatus = "accepted" | "no_active_session";++/** Successful response returned by the standard session-clear route. */+export type ClearResponse =+ | {+ readonly ok: true;+ readonly sessionId: string;+ readonly status: "accepted";+ }+ | {+ readonly ok: true;+ readonly status: "no_active_session";+ };++/** Validates successful responses from the standard session-clear route. */+export const ClearResponseSchema: z.ZodType<ClearResponse> = 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/message.test.ts b/packages/eve/src/protocol/message.test.tsindex 9e1b9a1e5..3583ab171 100644--- a/packages/eve/src/protocol/message.test.ts+++ b/packages/eve/src/protocol/message.test.ts@@ -8,6 +8,7 @@ import {createActionResultEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,+ createContextClearedEvent,createMessageReceivedEvent,createResultCompletedEvent,createSessionWaitingEvent,@@ -41,6 +42,15 @@ describe("message stream protocol", () => {});});+ it("creates context.cleared events", () => {+ expect(+ createContextClearedEvent({ sequence: 2, sessionId: "session_1", turnId: "turn_2" }),+ ).toEqual({+ data: { sequence: 2, sessionId: "session_1", turnId: "turn_2" },+ type: "context.cleared",+ });+ });+it("creates result.completed events", () => {expect(createResultCompletedEvent({diff --git a/packages/eve/src/protocol/message.ts b/packages/eve/src/protocol/message.tsindex 97b361c0e..3ac53b9b1 100644--- a/packages/eve/src/protocol/message.ts+++ b/packages/eve/src/protocol/message.ts@@ -475,6 +475,19 @@ export interface TurnCancelledStreamEvent {type: "turn.cancelled";}+/**+ * Stream event emitted after the durable model-message history is cleared.+ * The session itself and its non-message state remain active.+ */+export interface ContextClearedStreamEvent {+ data: {+ sequence: number;+ sessionId: string;+ turnId: string;+ };+ type: "context.cleared";+}+/*** Stream event emitted when the workflow decides to compact the current* visible session history before the next model fragment runs.@@ -598,6 +611,7 @@ export interface SessionCompletedStreamEvent {* consumers receive {@link MessageStreamEvent}.*/export type UnstampedMessageStreamEvent =+ | ContextClearedStreamEvent| CompactionCompletedStreamEvent| CompactionRequestedStreamEvent| AuthorizationCompletedStreamEvent@@ -1337,6 +1351,22 @@ export function createTurnCancelledEvent(input: {};}+/** Creates the `context.cleared` event for one manual history clear. */+export function createContextClearedEvent(input: {+ readonly sequence: number;+ readonly sessionId: string;+ readonly turnId: string;+}): ContextClearedStreamEvent {+ return {+ data: {+ sequence: input.sequence,+ sessionId: input.sessionId,+ turnId: input.turnId,+ },+ type: "context.cleared",+ };+}+/*** Creates the `compaction.requested` event for one runtime compaction pass.*/diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.tsindex 2cf6ab38f..36ef897b1 100644--- a/packages/eve/src/protocol/routes.ts+++ b/packages/eve/src/protocol/routes.ts@@ -33,6 +33,12 @@ export const EVE_RESET_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/reset`;*/export const EVE_COMPACT_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/compact`;+/**+ * Stable framework-owned route for clearing the model history of the session+ * that owns a client continuation token.+ */+export const EVE_CLEAR_SESSION_ROUTE_PATH = `${EVE_ROUTE_PREFIX}/session/clear`;+/*** 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 f06eb3a6f..812cd59be 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,+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),params: {},@@ -182,6 +183,7 @@ describe("chatSdkChannel", () => {getSession: vi.fn() as any,resolveActiveSession: async () => undefined,cancel: vi.fn(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),params: {},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 56e1fd0c4..7648bd666 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(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),getSession: vi.fn(),diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex c908f9c16..7603158aa 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(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),getSession: vi.fn(),@@ -127,6 +128,7 @@ function createEveContinueHandler(input: EveChannelInput) {send: mockSend,resolveActiveSession: async () => undefined,cancel: vi.fn(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),getSession: mockGetSession,@@ -162,6 +164,7 @@ function createEveCancelHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),getSession: vi.fn(),@@ -209,6 +212,7 @@ function createEveResetHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ clear: vi.fn(),compact: vi.fn(),reset,getSession: vi.fn(),@@ -230,6 +234,48 @@ function resetRequest(body: unknown): Request {});}+function clearRequest(body: unknown): Request {+ return new Request("https://example.com/eve/v1/session/clear", {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ });+}++/** Creates a POST handler test harness for the continuation-addressed clear route. */+function createEveClearHandler(input: EveChannelInput) {+ const channel = eveChannel(input);+ const clearRoute = channel.routes.find(+ (route) => route.method === "POST" && route.path === "/eve/v1/session/clear",+ );+ if (!clearRoute) throw new Error("No session clear POST route found");++ const clear = vi.fn().mockResolvedValue({+ sessionId: "test-session-id",+ status: "accepted",+ });++ return {+ clear,+ async fetch(req: Request) {+ const args: RouteHandlerArgs = {+ send: vi.fn(),+ resolveActiveSession: async () => undefined,+ cancel: vi.fn(),+ clear,+ compact: vi.fn(),+ reset: vi.fn(),+ getSession: vi.fn(),+ receive: vi.fn() as any,+ params: {},+ waitUntil: () => undefined,+ requestIp: "127.0.0.1",+ };+ return (clearRoute as any).handler(req, args);+ },+ };+}+/** Creates a POST handler test harness for the continuation-addressed compact route. */function createEveCompactHandler(input: EveChannelInput) {const channel = eveChannel(input);@@ -250,6 +296,7 @@ function createEveCompactHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ clear: vi.fn(),compact,reset: vi.fn(),getSession: vi.fn(),@@ -289,6 +336,7 @@ function createEveStreamHandler(input: EveChannelInput) {send: vi.fn(),resolveActiveSession: async () => undefined,cancel: vi.fn(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),getSession: mockGetSession,@@ -1603,6 +1651,33 @@ describe("eveChannel — compact session", () => {});});+describe("eveChannel — clear session context", () => {+ it("queues a clear for the supplied channel-local continuation token", async () => {+ const handler = createEveClearHandler({ auth: none() });++ const response = await handler.fetch(clearRequest({ 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.clear).toHaveBeenCalledWith({ continuationToken: "eve:token" });+ });++ it("reports a token that no active session owns", async () => {+ const handler = createEveClearHandler({ auth: none() });+ handler.clear.mockResolvedValue({ status: "no_active_session" });++ const response = await handler.fetch(clearRequest({ 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 579ee1508..7f58c8cfc 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 { ClearResponse } from "#protocol/clear-session.js";import type { CompactResponse } from "#protocol/compact-session.js";import type { ResetResponse } from "#protocol/reset-session.js";import type { SendOptions } from "#channel/routes.js";@@ -24,6 +25,7 @@ import {} from "#protocol/message.js";import {EVE_CANCEL_TURN_ROUTE_PATTERN,+ EVE_CLEAR_SESSION_ROUTE_PATH,EVE_COMPACT_SESSION_ROUTE_PATH,EVE_INFO_ROUTE_PATH,EVE_RESET_SESSION_ROUTE_PATH,@@ -286,7 +288,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {const authResult = await routeAuth(req, input.auth);if (authResult instanceof Response) return authResult;- const body = await parseResetSessionBody(req);+ const body = await parseContinuationTokenBody(req);if (body instanceof Response) return body;let result: Awaited<ReturnType<typeof reset>>;@@ -312,11 +314,39 @@ export function eveChannel(input: EveChannelInput): EveChannel {});}),+ POST(EVE_CLEAR_SESSION_ROUTE_PATH, async (req, { clear }) => {+ const authResult = await routeAuth(req, input.auth);+ if (authResult instanceof Response) return authResult;++ const body = await parseContinuationTokenBody(req);+ if (body instanceof Response) return body;++ let result: Awaited<ReturnType<typeof clear>>;+ try {+ result = await clear({ continuationToken: body.continuationToken });+ } catch (error) {+ const errorId = logError(log, "session-clear request failed", error);+ return Response.json(+ { error: "Failed to clear the session context.", errorId, ok: false },+ { status: 500 },+ );+ }++ const response: ClearResponse =+ 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_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);+ const body = await parseContinuationTokenBody(req);if (body instanceof Response) return body;let result: Awaited<ReturnType<typeof compact>>;@@ -711,11 +741,13 @@ interface ParsedCancelTurnBody {turnId?: string;}-interface ParsedResetSessionBody {+interface ParsedContinuationTokenBody {readonly continuationToken: string;}-async function parseResetSessionBody(req: Request): Promise<ParsedResetSessionBody | Response> {+async function parseContinuationTokenBody(+ req: Request,+): Promise<ParsedContinuationTokenBody | Response> {let payload: unknown;try {payload = await req.json();diff --git a/packages/eve/src/public/channels/github/githubChannel.test.ts b/packages/eve/src/public/channels/github/githubChannel.test.tsindex a7866355d..93a64ddaf 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(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),resolveActiveSession: async () => undefined,diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex 0535c9140..b2b87af48 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 ClearFn,+ type ClearOptions,+ type ClearSessionResult,type CompactFn,type CompactOptions,type CompactSessionResult,diff --git a/packages/eve/src/public/channels/linear/linearChannel.test.ts b/packages/eve/src/public/channels/linear/linearChannel.test.tsindex 1313a319b..1b534360d 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(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),resolveActiveSession: async () => undefined,diff --git a/packages/eve/src/public/channels/teams/teamsChannel.test.ts b/packages/eve/src/public/channels/teams/teamsChannel.test.tsindex 195bad67b..039f6a4d4 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(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),params: {},diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex 538507803..c97edab3b 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -25,6 +25,7 @@ declare const CHANNEL_METADATA_TYPE: unique symbol;export type {CancelTurnInput,CancelTurnResult,+ ClearSessionResult,CompactSessionResult,GetEventStreamOptions,} from "#channel/types.js";@@ -34,6 +35,8 @@ export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";export type {CancelFn,CancelOptions,+ ClearFn,+ ClearOptions,CompactFn,CompactOptions,ResetFn,@@ -243,6 +246,7 @@ type ChannelSessionFailedHandler<TCtx> = (* and the channel context, with no `ctx`.*/export interface ChannelEvents<TCtx = void> {+ readonly "context.cleared"?: ChannelEventHandler<"context.cleared", TCtx>;readonly "compaction.requested"?: ChannelEventHandler<"compaction.requested", TCtx>;readonly "compaction.completed"?: ChannelEventHandler<"compaction.completed", TCtx>;readonly "turn.started"?: ChannelEventHandler<"turn.started", TCtx>;@@ -348,6 +352,7 @@ 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> = {+ "context.cleared": null,"compaction.requested": null,"compaction.completed": null,"turn.started": null,diff --git a/packages/eve/src/public/definitions/hook.ts b/packages/eve/src/public/definitions/hook.tsindex 30d256b7c..3dfef0cf1 100644--- a/packages/eve/src/public/definitions/hook.ts+++ b/packages/eve/src/public/definitions/hook.ts@@ -22,6 +22,7 @@ export interface HookEventMap {readonly "authorization.required": ProtocolEvent<"authorization.required">;readonly "compaction.completed": ProtocolEvent<"compaction.completed">;readonly "compaction.requested": ProtocolEvent<"compaction.requested">;+ readonly "context.cleared": ProtocolEvent<"context.cleared">;readonly "input.requested": ProtocolEvent<"input.requested">;readonly "message.appended": ProtocolEvent<"message.appended">;readonly "message.completed": ProtocolEvent<"message.completed">;diff --git a/packages/eve/test/eve-run-stream-channel.test.ts b/packages/eve/test/eve-run-stream-channel.test.tsindex 1bb2b9b74..bdb83a2a4 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(),+ clear: vi.fn(),compact: vi.fn(),reset: vi.fn(),getSession: input.getSession,diff --git a/packages/eve/test/scenarios/cross-channel-receive.scenario.test.ts b/packages/eve/test/scenarios/cross-channel-receive.scenario.test.tsindex 47fab9cc8..5fa5ac906 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 clearSession() {+ throw new Error("clearSession should not be called in this scenario");+ },async compactSession() {throw new Error("compactSession should not be called in this scenario");},@@ -188,6 +191,9 @@ describe("cross-channel receive end-to-end", () => {cancel: async () => {throw new Error("webhook should not cancel turns");},+ clear: async () => {+ throw new Error("webhook should not clear session context");+ },compact: async () => {throw new Error("webhook should not compact sessions");},diff --git a/packages/eve/test/scenarios/schedule-trigger.scenario.test.ts b/packages/eve/test/scenarios/schedule-trigger.scenario.test.tsindex f2a1e7c79..9ee9071ed 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 clearSession() {+ throw new Error("clearSession should not be called in this scenario");+ },async compactSession() {throw new Error("compactSession should not be called in this scenario");},