The Open Framework for Building Agents
feat(eve): surface stranded sessions in the client, HTTP channel, and TUI (#4481)
prhab04acbb4eb8b
diff --git a/.changeset/retire-incompatible-child-runs.md b/.changeset/retire-incompatible-child-runs.mdnew file mode 100644index 000000000..939385efd--- /dev/null+++ b/.changeset/retire-incompatible-child-runs.md@@ -0,0 +1,5 @@+---+"eve": patch+---++On worlds without per-deployment routing, incompatible subagent sessions and workflow tool runs (including tasks) are now cancelled when their queue deliveries arrive, instead of attempting replay on the new eve version. Top-level sessions remain available for replacement or reset, and session timeout workflows continue to run.diff --git a/.changeset/stranded-sessions.md b/.changeset/stranded-sessions.mdnew file mode 100644index 000000000..34d8f7778--- /dev/null+++ b/.changeset/stranded-sessions.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Sessions whose workflow run cannot execute after an eve upgrade (a stranded session) are no longer accepted and left unanswered, and the local World and Postgres stop replaying and failing them with `CORRUPTED_EVENT_LOG`. eve treats every World other than Vercel as running one eve version at a time, so the next message through a channel address (Slack, `from(address).send()`) ends a stranded session and starts a fresh one. Sends by session ID throw `SessionStrandedError` (`ClientSessionStrandedError` in `eve/client`), and the eve HTTP channel returns `409 session_stranded`; `reset()` ends a stranded session while `clear()` refuses one, and recorded history stays readable with `stream({ follow: false })` or `follow=false` on the stream route. On Worlds other than Vercel, a retired session's own session timeout now ends it at its deadline, so a retired session no longer stays active forever when no message arrives.diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdxindex c9348455f..a595de4f6 100644--- a/docs/channels/custom.mdx+++ b/docs/channels/custom.mdx@@ -116,6 +116,15 @@ await source.reset({ reason: "Start over" });const currentSession = await resolveSession(threadId);```+When the session at an address is+[stranded](../concepts/execution-model-and-durability#stranded-sessions) because another eve version+built it, `send()` ends that session and starts a fresh one. The message becomes the fresh+session's first turn, and the fresh session can read recent text from the earlier conversation;+see [What a replacement session receives](../concepts/execution-model-and-durability#what-a-replacement-session-receives). Concurrent sends to the same stranded address still+produce one fresh session. A `respond()` call, or a `deliver()` that includes input responses,+carries answers a fresh session has no request for, so it throws `SessionStrandedError` and leaves+the stranded session in place.+`Session` is fixed: every call targets exactly one durable ID. It never creates,follows, or resolves a replacement.@@ -131,6 +140,23 @@ await session.reset({ reason: "Retire this session" });await session.getEventStream({ startIndex: 12 });```+For a stranded session, `Session.send()`, `Session.respond()`, and a following+`Session.getEventStream()` throw `SessionStrandedError` from `eve/channels` and deliver nothing.+`getEventStream({ follow: false })` still reads the recorded history up to the current tail without+changing the session. `error.owner.eveVersion` names the eve release that built the session when it recorded one. Call+`reset()` to end the stranded session, then start a new one:++```ts+import { SessionStrandedError } from "eve/channels";++try {+ await attachSession(sessionId).send(text, { auth });+} catch (error) {+ if (!SessionStrandedError.is(error)) throw error;+ await attachSession(sessionId).reset({ reason: "Session was stranded by an upgrade" });+}+```+`respond()` accepts exact response literals directly. If responses have alreadybeen widened to `InputResponse[]`—for example, after decoding a platformpayload—validate them with eve's strict schema before delivery. The validateddiff --git a/docs/channels/eve.mdx b/docs/channels/eve.mdxindex c3452ab4f..b7fb5c46e 100644--- a/docs/channels/eve.mdx+++ b/docs/channels/eve.mdx@@ -159,13 +159,15 @@ Set `turnPolicy: "queue"` on `eveChannel(...)` when follow-ups should wait for aSending a message to an unknown or terminal session ID returns `409` with`{"code":"session_not_active","error":"The session is no longer active.","ok":false}`.An existing workflow whose inbox is not yet available returns `409 session_not_ready` instead.-TypeScript clients expose the stable code as `ClientError.code`. The route never-creates or follows a replacement session.+A session that another eve version built returns `409 session_stranded` with the `eveVersion`+that built it.### Stream eventsStream a session as newline-delimited JSON from `GET /eve/v1/session/:sessionId/stream`. The [session protocol](../concepts/sessions-runs-and-streaming#stream-a-session) defines the event set, envelopes, cursors, and reconnection behavior.+Following a stranded session's stream returns `409 session_stranded`, just like a send. The TypeScript client reports `ClientSessionStrandedError` without retrying. Pass `follow=false` to read the recorded history instead: the response ends at the durable tail, carries the `x-eve-stream-tail-index` header, and never inspects or changes the session, so it works before a reset. A reset attempts to append `session.failed` with code `session_stranded` and close the stream. Existing readers finish when they receive that terminal event.+### Cancel a turnPost to `/eve/v1/session/:sessionId/cancel` to request cancellation of the active turn. You can include the observed `turnId` to keep a late request from cancelling a newer turn. Cancellation is asynchronous; confirm the turn boundary on the stream as `turn.cancelled` followed by `session.waiting`.@@ -174,7 +176,7 @@ See [Cancel the in-flight turn](../concepts/sessions-runs-and-streaming#cancel-t### Clear context-Post to `/eve/v1/session/:sessionId/clear` to remove model-message history while preserving the session ID, system prompt, tools, skills, durable state, limits, and sandbox. See [Compact, clear, and reset](../concepts/sessions-runs-and-streaming#compact-clear-and-reset).+Post to `/eve/v1/session/:sessionId/clear` to remove model-message history while preserving the session ID, system prompt, tools, skills, durable state, limits, and sandbox. A stranded session cannot run the clear, so the route returns `409 session_stranded` and changes nothing; post to the `reset` route to end it instead. See [Compact, clear, and reset](../concepts/sessions-runs-and-streaming#compact-clear-and-reset).### Compact context@@ -182,7 +184,7 @@ Post to `/eve/v1/session/:sessionId/compact` to summarize context without sendin### Reset a session-Post to `/eve/v1/session/:sessionId/reset` to terminally retire that session. Reset never replaces the ID automatically; create a new session explicitly for a fresh conversation. See [Compact, clear, and reset](../concepts/sessions-runs-and-streaming#compact-clear-and-reset).+Post to `/eve/v1/session/:sessionId/reset` to terminally retire that session. Reset never replaces the ID automatically; create a new session explicitly for a fresh conversation. Reset also works on a stranded session: eve cancels the stranded workflow run directly instead of delivering the command to it. See [Compact, clear, and reset](../concepts/sessions-runs-and-streaming#compact-clear-and-reset).## Replace or disable the defaultsdiff --git a/docs/concepts/execution-model-and-durability.mdx b/docs/concepts/execution-model-and-durability.mdxindex ae1c6d714..ef9e867ab 100644--- a/docs/concepts/execution-model-and-durability.mdx+++ b/docs/concepts/execution-model-and-durability.mdx@@ -37,6 +37,51 @@ Every workflow run records each step it executes, so a session that ran on one rThe move happens once the turn settles and nothing else is waiting: no queued messages, running tasks or subagents, or pending human input. The new run receives the compacted history and settled state, then waits for the next message. If a single message reaches an otherwise idle session before the move completes, eve moves the session with that message, and the message's turn runs on the new run. If work is still pending, eve tries again after a later turn settles. The session keeps its ID, event stream, continuation addresses, and deadline; compaction never extends [`sessionTimeoutMs`](../agent-config#runtime-limits). If the new run cannot take ownership, the current run keeps the session, writes a `session handoff failed` warning to its runtime logs, and tries again later.+### Stranded sessions++A session is stranded when another eve version built the workflow run that owns it. A run can only be replayed by the eve version that started it, so the conversation is still stored, but nothing on the current deployment can process a new message. On worlds without per-deployment routing, eve checks the owner before delivering channel messages and input responses, rather than committing them to a session that cannot answer.++eve treats every world other than Vercel Workflow as running one eve version at a time, so a stranded session can never run again:++| World | When a session is stranded |+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Vercel Workflow | eve does not check. Each run keeps executing on the deployment that started it, and handoff moves idle sessions to newer deployments. |+| Local world with `eve start` | After any upgrade that changes the eve version. Sessions created before eve recorded its version on the run are treated the same way. |+| Postgres and other worlds | Same as the local world. Serve one world from one eve version at a time: a deployment running another version cannot replay these sessions, and eve does not route runs between deployments. |+| `eve dev` | After an eve version change. A session from a previous dev server invocation built by the same eve version is not stranded: it stays dormant until you restart `eve dev` with [`--resume`](../reference/cli#local-workflow-recovery). |++eve ends a stranded session without running any of its code. When that happens depends on the kind of run:++- **A root session**, one that a channel or client started, stays where it is. It keeps its address and executes nothing until a new channel message replaces it, a reset ends it, or its session timeout elapses, whichever comes first.+- **A subagent session or workflow tool run**, including a task, is cancelled the next time the world delivers work to it, for example when the local world or Postgres recovers active runs at startup. No later message could resume its interrupted work, so eve does not wait.++See [How a stranded session ends](#how-a-stranded-session-ends) for the details.++For a root session, what happens next depends on how the message is addressed:++- **A channel address**, such as a Slack thread or any `from(address).send(...)`, resets the stranded session and starts a fresh session at the same address. The message becomes the fresh session's first turn. Concurrent messages to the address produce one fresh session. A delivery that carries input responses, with or without a message, throws `SessionStrandedError` and leaves the stranded session in place, because a fresh session has no request for them to answer. See [custom channels](../channels/custom#channel-operations-and-session-handles).+- **A session ID** is never reset implicitly. The eve HTTP channel returns `409` with `code: "session_stranded"` and the `eveVersion` that built the session when it recorded one. `Session.send()` and `Session.respond()` throw `SessionStrandedError` from `eve/channels`, and the TypeScript client's `ClientSession.send()` and `respond()` throw `ClientSessionStrandedError` from `eve/client`. Nothing is delivered, and the stranded run keeps its status and event log. See [Start and continue a session](../channels/eve#start-and-continue-a-session).+- **Following a stream** of a stranded session returns the same `409 session_stranded`. The TypeScript client stops reconnecting and reports `ClientSessionStrandedError`; the TUI explains how to recover. An existing connection learns this when it reconnects. Messages accepted before the upgrade are not redelivered.+- **Reading recorded history** still works. A bounded read (`stream({ follow: false })`, or `follow=false` on the stream route) returns the events recorded so far without inspecting or changing the session, so you can read a stranded conversation before deciding to reset it.+- **Reset** works on a stranded session through a channel address or a session ID. **Clear** would keep a session that cannot run, so it is refused: `Session.clear()` throws `SessionStrandedError`, the eve HTTP channel returns `409 session_stranded`, and nothing changes. Reset the session instead.+- **Session timeouts** end a stranded session the same way a reset does; see [How a stranded session ends](#how-a-stranded-session-ends).++A reset ends the stranded session without running any of its code. eve cancels the session's owner run and, after a handoff, the original run that anchors its event stream, then waits until the world releases the session's addresses. If another run has taken over the session since eve inspected it, the reset ends nothing and fails so the request can be retried. The stranded session's `session.completed` and `session.failed` hooks do not run; the fresh session runs `session.started` as usual. Before cancelling, eve attempts to append a `session.failed` event with code `session_stranded` and close the old stream, without invoking authored hooks. Stream publication is best effort and waits at most 5 seconds: missing payload keys, unavailable storage, or a stalled write do not prevent reset. Each step tolerates an earlier attempt having completed it, so a reset that fails part way can be retried.++Each reset logs a `warn` record, `Reset stranded session`, with the previous session ID, both eve versions, and the `trigger`: `message`, `reset`, or `timeout`.++A reset cannot be undone. Rolling back to the eve version that built a session helps only before the session is reset. On a world other than Vercel Workflow, pin the exact eve version in `package.json` so upgrades happen only when you choose them.++#### How a stranded session ends++A stranded root session ends on its next channel message, a reset, or its [session timeout](../agent-config#runtime-limits), whichever comes first. It executes nothing while it waits. When the local world or Postgres recovers active runs at startup, eve acknowledges the root session's delivery without replaying it and logs a warning naming the run and both eve versions. The run keeps its `pending` or `running` status and its addresses. A later restart skips it the same way.++The timeout is the session's own durable timer, armed for the deadline `sessionTimeoutMs` sets from the session's creation or latest deployment handoff (30 days by default; compaction handoffs keep the deadline). The timer is a separate workflow run that keeps working after the upgrade, and when it fires on a stranded session it ends the session the same way a reset does, without starting a fresh one. The next message to the address then starts an ordinary session. A session with `sessionTimeoutMs: false` has no timer, so a stranded one stays until a message or a reset, just as a healthy one would stay open.++Ending a root session does not find or cancel its subagent sessions and workflow tool runs. Each one is cancelled when a delivery for it reaches the current deployment, with the cancellation reason `Run retired: its eve deployment is no longer available`, and eve logs a `Retired stranded descendant run` warning. A run that never receives a delivery, such as one parked in a dormant `eve dev` generation, can stay active; cancel it in your Workflow world if you need to. Cancellation does not run authored cleanup or lifecycle hooks, undo side effects, or stop independent external jobs, and results and approvals do not carry over to a replacement session.++Runs that recorded no eve version, including every run from a release before eve recorded versions, are treated as stranded.+### Upgrading sessions from the former execution modelYou can upgrade directly from a release that used a session driver and separatediff --git a/docs/concepts/sessions-runs-and-streaming.md b/docs/concepts/sessions-runs-and-streaming.mdindex 926b6f867..a949568ee 100644--- a/docs/concepts/sessions-runs-and-streaming.md+++ b/docs/concepts/sessions-runs-and-streaming.md@@ -265,6 +265,8 @@ Clear removes model-message history in place, including static and dynamic user-Reset terminally retires the exact session ID. A reset ID never becomes a new session; create another session explicitly for a fresh conversation. Compact, clear, and reset return `"no_active_session"` when the target is already inactive.+A [stranded session](./execution-model-and-durability#stranded-sessions) cannot run commands. Reset still works: eve cancels the stranded workflow run and returns `"reset"`. Clear is refused with `409 session_stranded` (`SessionStrandedError` from a `Session` handle), because it would keep a session that cannot run. Compact returns `"no_active_session"` and cancel returns `"no_active_turn"`.+## Reconnect and rewindThe stream is durable. Every event is recorded before a step completes, so consumers can reconnect from their cursor when an HTTP connection ends. A nonnegative `startIndex` is an absolute event count: use it to pick up where you dropped off or pass `0` to rewind to the start.@@ -294,7 +296,7 @@ curl -i "http://127.0.0.1:2000/eve/v1/session/<sessionId>/stream?startIndex=<cou# x-eve-stream-tail-index: <tail>```-The lookup is opt-in; requests without the parameter get no header. The TypeScript client wraps this into `stream({ follow: false })`.+The lookup is opt-in; requests without the parameter get no header. Passing `follow=false` instead bounds the response at the durable tail on the server and implies the header. A bounded read only reads recorded history, so it also works for a [stranded session](./execution-model-and-durability#stranded-sessions), whose live stream returns `409 session_stranded`. The TypeScript client wraps this into `stream({ follow: false })`.## Use the client from TypeScriptdiff --git a/docs/guides/client/messages.mdx b/docs/guides/client/messages.mdxindex 4b3c024f3..90ca4504c 100644--- a/docs/guides/client/messages.mdx+++ b/docs/guides/client/messages.mdx@@ -40,7 +40,16 @@ When the stream includes `session.failed`, the turn returns `status: "failed"` rseconds when a durable run has been accepted but its command inbox is still starting. The caller'sabort signal cancels the wait. Other errors, `session.respond()`, control methods, and raw HTTPrequests do not use this retry. An unknown-or terminal session throws `ClientError` immediately with `session_not_active`. The client never creates a replacement session.+or terminal session throws `ClientError` immediately with `session_not_active`. A+[stranded](../../concepts/execution-model-and-durability#stranded-sessions) session throws+`ClientSessionStrandedError`, a `ClientError` with `code: "session_stranded"` and the+`eveVersion` that built the session when it recorded one. It is never retried automatically. Call+`session.reset()` and create a new session.+The client never creates a replacement session. Following or reconnecting to a stranded session's+stream reports the same typed error without retrying, including when you were waiting for a+response to a message accepted before the upgrade. That accepted message is not redelivered.+`session.clear()` throws the same error, because clearing would keep a session that cannot run.+`session.stream({ follow: false })` and `session.snapshot()` still read the recorded history.## Send a full turn payloaddiff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex bd3e169b3..db97b6876 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -35,6 +35,8 @@ Before your first message, the empty composer may suggest asking your local agen| `/help` | List available commands. || `/exit` | Quit the UI. |+When a message or stream reconnection reaches a [stranded session](../concepts/execution-model-and-durability#stranded-sessions), the TUI says why and which eve version built it, when known. New messages and approvals are not delivered. Run `/new` to end the stranded session; your next message starts a fresh one. `/clear` is refused, because it would keep the stranded session. A session from a previous `eve dev` invocation that the same eve version built is not stranded; see [local workflow recovery](../reference/cli#local-workflow-recovery). A message accepted before the upgrade is not redelivered.+`/login`, `/model`, `/add`, `/deploy`, `/info`, and `/traces` are available when `eve dev` runs locally. They are unavailable when the UI connects through `eve remote connect`.## Set up a new agentdiff --git a/packages/eve/extension-contracts/compatibility/channel/v56.ts b/packages/eve/extension-contracts/compatibility/channel/v56.tsnew file mode 100644index 000000000..961549782--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/channel/v56.ts@@ -0,0 +1,13 @@+import { defineChannel, GET } from "#public/channels/index.js";++// Epoch 56 reads session streams from a start index without a follow option.+export default defineChannel({+ routes: [+ GET("/threads/:threadId/events", async (_request, { from, params }) => {+ const session = await from(params.threadId!).send("Read the thread.", { auth: null });+ const events = await session.getEventStream({ startIndex: 0 });+ await events.cancel();+ return new Response("ok");+ }),+ ],+});diff --git a/packages/eve/extension-contracts/compatibility/schedule/v29.ts b/packages/eve/extension-contracts/compatibility/schedule/v29.tsnew file mode 100644index 000000000..4901ac574--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/schedule/v29.ts@@ -0,0 +1,19 @@+import { defineChannel } from "#public/channels/index.js";+import { defineSchedule } from "#public/schedules/index.js";++// Epoch 29 reads session streams from a start index without a follow option.+const reports = defineChannel({+ routes: [],+ receive(input, { from }) {+ return from("nightly-report").send(input.message, { auth: input.auth });+ },+});++export default defineSchedule({+ cron: "0 2 * * *",+ async run({ to, appAuth, waitUntil }) {+ const session = await to(reports, {}).send("Prepare the nightly report.", { auth: appAuth });+ const events = await session.getEventStream({ startIndex: 0 });+ waitUntil(events.cancel());+ },+});diff --git a/packages/eve/extension-contracts/entrypoints/channel.ts b/packages/eve/extension-contracts/entrypoints/channel.tsindex a96385e13..d7cce14d5 100644--- a/packages/eve/extension-contracts/entrypoints/channel.ts+++ b/packages/eve/extension-contracts/entrypoints/channel.ts@@ -6,6 +6,7 @@ export {PATCH,POST,PUT,+ SessionStrandedError,WS,createWebSocketUpgradeServer,defineChannel,diff --git a/packages/eve/extension-contracts/reports/channel/v57.json b/packages/eve/extension-contracts/reports/channel/v57.jsonnew file mode 100644index 000000000..5428be090--- /dev/null+++ b/packages/eve/extension-contracts/reports/channel/v57.json@@ -0,0 +1,22 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "channel",+ "epoch": 57,+ "sha256": "589e73e202dfafe4a1f911843700c5970de66b400e6da9cd1512c2b4ec0e4eee",+ "exports": [+ "DELETE",+ "GET",+ "HEAD",+ "OPTIONS",+ "PATCH",+ "POST",+ "PUT",+ "SessionStrandedError",+ "WS",+ "createWebSocketUpgradeServer",+ "defineChannel",+ "disableRoute",+ "isChannel",+ "isDisabledRouteSentinel"+ ]+}diff --git a/packages/eve/extension-contracts/reports/schedule/v30.json b/packages/eve/extension-contracts/reports/schedule/v30.jsonnew file mode 100644index 000000000..58e32fe96--- /dev/null+++ b/packages/eve/extension-contracts/reports/schedule/v30.json@@ -0,0 +1,15 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "schedule",+ "epoch": 30,+ "sha256": "3ad021586d269333842b27217412337d1a8e934ede2f92865f736e59dac23c07",+ "exports": [+ "ScheduleDefinition",+ "ScheduleHandlerArgs",+ "ScheduleRunHandler",+ "ScheduleToFn",+ "TypedReceiveTarget",+ "defineSchedule",+ "isScheduleAuth"+ ]+}diff --git a/packages/eve/src/channel/session-stranded-error.ts b/packages/eve/src/channel/session-stranded-error.tsindex 49dbfdfeb..148c16072 100644--- a/packages/eve/src/channel/session-stranded-error.ts+++ b/packages/eve/src/channel/session-stranded-error.ts@@ -8,7 +8,7 @@ interface StrandedSessionOwner {* Thrown when sending, responding, clearing, or following the live stream of* a session whose owner another eve version built, on a World that only runs* this build, so the owner can never execute again. Nothing is delivered and- * nothing is mutated.+ * nothing is mutated. Historical reads with `follow: false` still succeed.* Call `reset()` to end the session, then start a new one. Narrow with* {@link SessionStrandedError.is}.*/diff --git a/packages/eve/src/channel/session.ts b/packages/eve/src/channel/session.tsindex bac61b045..486788043 100644--- a/packages/eve/src/channel/session.ts+++ b/packages/eve/src/channel/session.ts@@ -9,6 +9,7 @@ import type {CancelTurnResult,ClearSessionResult,CompactSessionResult,+ GetEventStreamOptions,ResetSessionResult,Runtime,SessionAuthContext,@@ -61,8 +62,12 @@ export interface Session {clear(): Promise<ClearSessionResult>;/** Terminally retires this exact session ID. */reset(options?: { reason?: string }): Promise<ResetSessionResult>;- /** Opens the recorded stream. Throws `SessionStrandedError` while its owner is stranded. */- getEventStream(options?: { startIndex?: number }): Promise<ReadableStream<MessageStreamEvent>>;+ /**+ * Opens the recorded stream. Following it throws `SessionStrandedError`+ * while its owner is stranded; `follow: false` reads recorded history up to+ * the current tail without inspecting or changing the session.+ */+ getEventStream(options?: GetEventStreamOptions): Promise<ReadableStream<MessageStreamEvent>>;getStreamTailIndex(): Promise<number>;}@@ -175,7 +180,7 @@ export function createSession(sessionId: id,});},- async getEventStream(options?: { startIndex?: number }) {+ async getEventStream(options?: GetEventStreamOptions) {return runtime.getEventStream(id, options);},async getStreamTailIndex() {diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 9af412170..61cb4f67c 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -641,8 +641,9 @@ export interface Runtime {* The framework HTTP session-stream route forwards the `startIndex` query* parameter unchanged.*- * Throws `SessionStrandedError` when the session's owner cannot execute- * here.+ * A following read throws `SessionStrandedError` when the session's owner+ * cannot execute here. A historical read (`follow: false`) never inspects+ * or changes the session's lifecycle.*/getEventStream(sessionId: string,@@ -668,4 +669,10 @@ export interface GetEventStreamOptions {* (replay the entire stream).*/readonly startIndex?: number;+ /**+ * Whether to keep following events recorded after the read opens. When+ * `false`, the stream ends at the durable tail observed when it opens, and+ * it stays readable while the session is stranded. Defaults to `true`.+ */+ readonly follow?: boolean;}diff --git a/packages/eve/src/cli/dev/tui/runner.test.ts b/packages/eve/src/cli/dev/tui/runner.test.tsindex 7e43d3d73..1b34b65df 100644--- a/packages/eve/src/cli/dev/tui/runner.test.ts+++ b/packages/eve/src/cli/dev/tui/runner.test.ts@@ -1436,6 +1436,47 @@ describe("EveTUIRunner session commands", () => {expect(server.requestsTo("POST", "/session_1")).toHaveLength(0);});+ it("names a stranded session, refuses to clear it, and starts fresh after /new", async () => {+ const server = new FakeEveServer();+ const stranded = {+ code: "session_stranded",+ error: "This session is stranded.",+ eveVersion: "0.0.1",+ ok: false,+ };+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {+ const path = new URL(String(input)).pathname;+ if (+ init?.method === "POST" &&+ (path === "/eve/v1/session/session_1" || path === "/eve/v1/session/session_1/clear")+ ) {+ await server.fetch(input, init);+ return Response.json(stranded, { status: 409 });+ }+ return await server.fetch(input, init);+ });+ const outcomes: unknown[] = [];+ const renderError = vi.fn();+ await new EveTUIRunner({+ client: stubClient(),+ renderer: turnTaking(+ ["Hello.", "Still there?", "/clear", "/new", "Fresh start.", undefined],+ { finishCommand: (outcome) => outcomes.push(outcome), renderError },+ ).renderer,+ }).run();++ const notice =+ "Session session_1 is stranded (built by eve 0.0.1): the deployment that ran it is no longer available. The session cannot continue. Run /new to end it and start a fresh session.";+ expect(renderError).toHaveBeenCalledWith("Session stranded", notice);+ expect(outcomes).toEqual([+ { kind: "result", message: notice, summary: "Couldn't clear the session" },+ { kind: "dismiss" },+ ]);+ expect(server.requestsTo("POST", "/session_1/clear")).toHaveLength(1);+ expect(server.requestsTo("POST", "/session_1/reset")).toHaveLength(1);+ expect(server.sessionId).toBe("session_2");+ });+it("keeps the conversation when /reset cannot retire the session", async () => {const server = new FakeEveServer();vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) =>diff --git a/packages/eve/src/cli/dev/tui/runner.ts b/packages/eve/src/cli/dev/tui/runner.tsindex 4fc3fca94..6e334bb19 100644--- a/packages/eve/src/cli/dev/tui/runner.ts+++ b/packages/eve/src/cli/dev/tui/runner.ts@@ -9,6 +9,7 @@ import {EveAgentStore,} from "#client/eve-agent-store.js";import { isAbortError } from "#client/eve-agent-store-helpers.js";+import { formatStrandedSessionNotice } from "./stranded-session.js";import { normalizeActionRequest, normalizeActionResult } from "#client/message-action-parts.js";import { isTerminalToolCallPart } from "./terminal-tool-part.js";import { userText } from "./transcript-parts.js";@@ -853,10 +854,7 @@ export class EveTUIRunner {: { message, turnPolicy: "queue" };void this.#store.send(input).catch((error: unknown) => {if (this.#disposed || isAbortError(error)) return;- this.#renderer.renderError?.(- steering ? "Steering failed" : "Error",- this.#formatTransportError(error),- );+ this.#renderSendError(steering ? "Steering failed" : "Error", error);});}@@ -912,8 +910,31 @@ export class EveTUIRunner {if (error === undefined || error === this.#reportedError) return;this.#reportedError = error;if (sessionFailed) return;- this.#remoteConnection?.reportFailure(error);- this.#renderer.renderError?.("Error", this.#formatTransportError(error));+ // A stranded session is a property of that session, not of the connection.+ if (!this.#renderStrandedSession(error)) {+ this.#remoteConnection?.reportFailure(error);+ this.#renderer.renderError?.("Error", this.#formatTransportError(error));+ }+ }++ #renderSendError(title: string, error: unknown): void {+ if (this.#renderStrandedSession(error)) return;+ this.#renderer.renderError?.(title, this.#formatTransportError(error));+ }++ #strandedSessionNotice(error: unknown): string | undefined {+ return formatStrandedSessionNotice(error, {+ localServer: this.#appRoot !== undefined,+ sessionId: this.#store.snapshot.session?.sessionId,+ });+ }++ /** Renders a stranded-session notice; false when `error` is anything else. */+ #renderStrandedSession(error: unknown): boolean {+ const notice = this.#strandedSessionNotice(error);+ if (notice === undefined) return false;+ this.#renderer.renderError?.("Session stranded", notice);+ return true;}#reportFirstResponse(conversation: ConversationState): void {@@ -954,7 +975,7 @@ export class EveTUIRunner {}void this.#store.send({ inputResponses: [response] }).catch((error: unknown) => {if (this.#disposed || isAbortError(error)) return;- this.#renderer.renderError?.("Error", this.#formatTransportError(error));+ this.#renderSendError("Error", error);});}}@@ -1050,7 +1071,7 @@ export class EveTUIRunner {} catch (error) {this.#finishCommand({kind: "result",- message: toErrorMessage(error),+ message: this.#strandedSessionNotice(error) ?? toErrorMessage(error),summary: input.failed,});}diff --git a/packages/eve/src/cli/dev/tui/stranded-session.ts b/packages/eve/src/cli/dev/tui/stranded-session.tsnew file mode 100644index 000000000..6929b318e--- /dev/null+++ b/packages/eve/src/cli/dev/tui/stranded-session.ts@@ -0,0 +1,23 @@+import { ClientSessionStrandedError } from "#client/client-error.js";+import { resolveInstalledPackageInfo } from "#internal/application/package.js";++/**+ * One notice naming the session, the cause, the version pair, and the+ * command that gets the user unstuck; `undefined` for any other error. The+ * server's eve version is known only when the TUI runs its own dev server.+ */+export function formatStrandedSessionNotice(+ error: unknown,+ input: { readonly localServer: boolean; readonly sessionId: string | undefined },+): string | undefined {+ if (!(error instanceof ClientSessionStrandedError)) return undefined;+ const versions = [+ error.eveVersion === undefined ? undefined : `built by eve ${error.eveVersion}`,+ input.localServer+ ? `this dev server runs eve ${resolveInstalledPackageInfo().version}`+ : undefined,+ ].filter((part) => part !== undefined);+ const detail = versions.length === 0 ? "" : ` (${versions.join("; ")})`;+ const session = `Session ${input.sessionId ?? "unknown"}`;+ return `${session} is stranded${detail}: the deployment that ran it is no longer available. The session cannot continue. Run /new to end it and start a fresh session.`;+}diff --git a/packages/eve/src/client/client-error.ts b/packages/eve/src/client/client-error.tsindex 597278955..4c85a4c9c 100644--- a/packages/eve/src/client/client-error.ts+++ b/packages/eve/src/client/client-error.ts@@ -24,25 +24,63 @@ export class ClientError extends Error {constructor(status: number, body: string, headers?: ConstructorParameters<typeof Headers>[0]) {const normalizedHeaders = Object.freeze(Object.fromEntries(new Headers(headers).entries()));const contentType = normalizedHeaders["content-type"]?.toLowerCase();+ const parsed = parseJsonObject(body);let message = body || `Server returned ${status}.`;- let code: string | undefined;- try {- const parsed: unknown = JSON.parse(body);- if (isObject(parsed)) {- if (typeof parsed.error === "string") message = parsed.error;- if (typeof parsed.code === "string") code = parsed.code;- }- } catch {- if (contentType?.includes("text/html")) {- message = `Server returned ${status} with an HTML response. Check the eve route and development server configuration.`;- }+ if (typeof parsed?.error === "string") message = parsed.error;+ else if (parsed === undefined && contentType?.includes("text/html")) {+ message = `Server returned ${status} with an HTML response. Check the eve route and development server configuration.`;}super(message);this.name = "ClientError";- this.code = code;+ this.code = typeof parsed?.code === "string" ? parsed.code : undefined;this.status = status;this.body = body;this.headers = normalizedHeaders;}}++/**+ * Thrown by `ClientSession.send()`, `respond()`, `clear()`, and live stream connections when the server+ * answers `409 session_stranded`: another eve version built the session's owner, so it can never+ * execute on that deployment and new input is not delivered. Call `reset()` on the session, then+ * create a new one. `stream({ follow: false })` still reads recorded history.+ */+export class ClientSessionStrandedError extends ClientError {+ declare readonly code: "session_stranded";+ /** The eve version that built the session, when it recorded one. */+ readonly eveVersion: string | undefined;++ constructor(+ status: number,+ body: string,+ headers: ConstructorParameters<typeof Headers>[0] | undefined,+ details: { readonly eveVersion: string | undefined },+ ) {+ super(status, body, headers);+ this.name = "ClientSessionStrandedError";+ this.eveVersion = details.eveVersion;+ }+}++/** Builds the most specific client error for a failed eve session request. */+export function createClientError(+ status: number,+ body: string,+ headers?: ConstructorParameters<typeof Headers>[0],+): ClientError {+ const parsed = status === 409 ? parseJsonObject(body) : undefined;+ if (parsed?.code !== "session_stranded") return new ClientError(status, body, headers);+ return new ClientSessionStrandedError(status, body, headers, {+ eveVersion: typeof parsed.eveVersion === "string" ? parsed.eveVersion : undefined,+ });+}++function parseJsonObject(body: string): Record<string, unknown> | undefined {+ try {+ const parsed: unknown = JSON.parse(body);+ return isObject(parsed) ? parsed : undefined;+ } catch {+ return undefined;+ }+}diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex f4edecc4e..b859dc3bc 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -6,7 +6,7 @@ export { EveAgentStore } from "#client/eve-agent-store.js";export { Client } from "#client/client.js";export { AgentInfoResponseError } from "#client/agent-info-error.js";export { HealthResponseError } from "#client/health-response-error.js";-export { ClientError } from "#client/client-error.js";+export { ClientError, ClientSessionStrandedError } from "#client/client-error.js";export { defaultMessageReducer } from "#client/message-reducer.js";export { conversationReducer } from "#client/conversation-reducer.js";export { openConversationInputs } from "#client/conversation-state.js";diff --git a/packages/eve/src/client/open-stream.test.ts b/packages/eve/src/client/open-stream.test.tsindex 3216d29e9..f7e9794f7 100644--- a/packages/eve/src/client/open-stream.test.ts+++ b/packages/eve/src/client/open-stream.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { followStreamIterable, openStreamBody } from "./open-stream.js";+import { ClientSessionStrandedError } from "#client/client-error.js";import type { StreamReconnectPolicy } from "#client/types.js";import {EVE_MESSAGE_STREAM_VERSION,@@ -46,6 +47,29 @@ describe("openStreamBody", () => {expect(signal?.aborted).toBe(true);});+ it("stops reconnecting when a stranded stream returns an actionable conflict", async () => {+ const fetchMock = vi.fn(async () =>+ Response.json(+ {+ code: "session_stranded",+ eveVersion: "0.0.1",+ error: "Reset this session to continue.",+ },+ { status: 409 },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const stream = followStreamIterable({+ host: "https://agent.example",+ path: "/eve/v1/session/session_1/stream",+ resolveHeaders: async () => new Headers(),+ startIndex: 0,+ keepAlive: true,+ });+ await expect(stream.next()).rejects.toThrow(ClientSessionStrandedError);+ expect(fetchMock).toHaveBeenCalledOnce();+ });+it("advertises support for versioned stream controls", async () => {let requestUrl: URL | undefined;vi.stubGlobal(@@ -103,6 +127,30 @@ describe("openStreamBody", () => {});describe("followStreamIterable", () => {+ it("finishes a live follow when reset publishes a terminal event", async () => {+ const event = {+ type: "session.failed",+ data: { code: "session_stranded", message: "Start a new session.", sessionId: "session_1" },+ };+ const fetchMock = vi.fn(+ async () =>+ new Response(JSON.stringify(event) + "\n", {+ headers: { [EVE_STREAM_VERSION_HEADER]: EVE_MESSAGE_STREAM_VERSION },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const stream = followStreamIterable({+ host: "https://agent.example",+ path: "/eve/v1/session/session_1/stream",+ resolveHeaders: async () => new Headers(),+ startIndex: 0,+ keepAlive: true,+ });+ await expect(stream.next()).resolves.toMatchObject({ done: false, value: event });+ await expect(stream.next()).resolves.toMatchObject({ done: true });+ expect(fetchMock).toHaveBeenCalledOnce();+ });+it("honors explicit idle retry limits even while following continuously", async () => {const fetchMock = vi.fn(async () =>diff --git a/packages/eve/src/client/open-stream.ts b/packages/eve/src/client/open-stream.tsindex 3818a7aae..c2d4fa375 100644--- a/packages/eve/src/client/open-stream.ts+++ b/packages/eve/src/client/open-stream.ts@@ -5,7 +5,11 @@ import {EVE_STREAM_TAIL_INDEX_HEADER,} from "#protocol/message.js";import type { MessageStreamVersion } from "#protocol/message-version.js";-import { ClientError } from "#client/client-error.js";+import {+ ClientError,+ ClientSessionStrandedError,+ createClientError,+} from "#client/client-error.js";import { isStreamDisconnectError, readNdjsonStream } from "#client/ndjson.js";import { readMessageStreamVersion } from "#client/stream-version.js";import type {@@ -114,9 +118,11 @@ interface OpenStreamInput extends FollowStreamInput {* transparently reconnecting whenever the transport ends.** Transport endings reconnect from the advanced cursor. Progress resets the- * idle budget; repeated empty streams eventually stop the follow. Callers own- * boundary handling. Negative tail-relative cursors use one connection because- * they cannot be advanced safely.+ * idle budget; repeated empty streams eventually stop the follow. A+ * `session.completed` or `session.failed` event ends the follow, since a+ * session records nothing after it; callers own turn-boundary handling.+ * Negative tail-relative cursors use one connection because they cannot be+ * advanced safely.** With `follow: false`, the first connection fixes the bound: the iterator* yields events until the cursor passes that tail, reconnecting as needed,@@ -208,6 +214,7 @@ export async function* followStreamIterable(caughtUp = true;input.onCaughtUp?.();}+ if (event.type === "session.failed" || event.type === "session.completed") return;if (input.follow === false && tailIndex !== undefined && startIndex > tailIndex) {return;}@@ -284,6 +291,10 @@ export async function openStreamBody(if (input.requestTailIndex === true) {searchParams.includeTailIndex = "1";}+ // Recorded history stays readable after the session can no longer run.+ if (input.follow === false) {+ searchParams.follow = "false";+ }for (let attempt = 0; attempt < openRetryPolicy.maxAttempts; attempt += 1) {input.signal?.throwIfAborted();@@ -347,8 +358,13 @@ export async function openStreamBody(lastBody = await response.text();lastHeaders = response.headers;- if (!retryPolicy.retryableErrorStatuses.has(response.status)) {- throw new ClientError(response.status, lastBody, response.headers);+ const error = createClientError(response.status, lastBody, response.headers);+ // 409 is retryable by default, but a stranded session's 409 is final.+ if (+ error instanceof ClientSessionStrandedError ||+ !retryPolicy.retryableErrorStatuses.has(response.status)+ ) {+ throw error;}if (attempt < openRetryPolicy.maxAttempts - 1) {diff --git a/packages/eve/src/client/session-controls.ts b/packages/eve/src/client/session-controls.tsindex e70cf611e..170f6a578 100644--- a/packages/eve/src/client/session-controls.ts+++ b/packages/eve/src/client/session-controls.ts@@ -1,4 +1,4 @@-import { ClientError } from "#client/client-error.js";+import { createClientError } from "#client/client-error.js";import type {CancelSessionResult,ClearResult,@@ -141,7 +141,7 @@ async function postJson(input: {),);const text = await response.text();- if (!response.ok) throw new ClientError(response.status, text, response.headers);+ if (!response.ok) throw createClientError(response.status, text, response.headers);try {return { payload: JSON.parse(text) as unknown, response };} catch {diff --git a/packages/eve/src/client/session.test.ts b/packages/eve/src/client/session.test.tsindex 44e1d4595..30eb39065 100644--- a/packages/eve/src/client/session.test.ts+++ b/packages/eve/src/client/session.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { ClientError } from "#client/client-error.js";+import { ClientError, ClientSessionStrandedError } from "#client/client-error.js";import { ClientSession } from "#client/session.js";import type { ClientSessionState } from "#client/types.js";import {@@ -191,6 +191,8 @@ describe("ClientSession", () => {const requestUrl = new URL(requests[0]!);expect(requestUrl.searchParams.get("startIndex")).toBeNull();expect(requestUrl.searchParams.get("includeTailIndex")).toBe("1");+ // A bounded read asks for history only, which a stranded session still serves.+ expect(requestUrl.searchParams.get("follow")).toBe("false");expect(snapshot.events.map((event) => event.type)).toEqual(["turn.started", "session.waiting"]);expect(snapshot.session).toEqual({sessionId: "session_1",@@ -397,6 +399,38 @@ describe("ClientSession", () => {},);+ it.each([+ ["send", (session: ClientSession) => session.send("hello")],+ [+ "respond",+ (session: ClientSession) => session.respond([{ requestId: "req_1", optionId: "approve" }]),+ ],+ ] as const)("throws a typed stranded error from %s without retrying", async (_, invoke) => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ Response.json(+ {+ code: "session_stranded",+ error: "This session is stranded.",+ eveVersion: "0.0.1",+ ok: false,+ },+ { status: 409 },+ ),+ );+ const session = createSession({ sessionId: "session_1", streamIndex: 0 });++ const error = await invoke(session).catch((cause: unknown) => cause);++ expect(error).toBeInstanceOf(ClientSessionStrandedError);+ expect(error).toMatchObject({+ code: "session_stranded",+ eveVersion: "0.0.1",+ message: "This session is stranded.",+ status: 409,+ });+ expect(fetchMock).toHaveBeenCalledOnce();+ });+it("does not retry session_not_ready from respond", async () => {const fetchMock = vi.spyOn(globalThis, "fetch")diff --git a/packages/eve/src/client/session.ts b/packages/eve/src/client/session.tsindex 5e6006bce..f0b751929 100644--- a/packages/eve/src/client/session.ts+++ b/packages/eve/src/client/session.ts@@ -7,7 +7,7 @@ import {createEveSessionStreamRoutePath,} from "#protocol/routes.js";import { ClientAgentSession } from "#client/agent-session.js";-import { ClientError } from "#client/client-error.js";+import { ClientError, createClientError } from "#client/client-error.js";import { MessageResponse } from "#client/message-response.js";import { followStreamIterable, sleep } from "#client/open-stream.js";import {@@ -430,7 +430,7 @@ async function postTurn(});if (!response.ok) {const responseBody = await response.text();- throw new ClientError(response.status, responseBody, response.headers);+ throw createClientError(response.status, responseBody, response.headers);}return response;}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex d144cb999..1e3ba83a9 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -132,10 +132,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},channel: {- current: 56,+ current: 57,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,- 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56,+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57,],dropped: {12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",@@ -158,10 +158,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {},},schedule: {- current: 29,+ current: 30,supported: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,- 29,+ 29, 30,],dropped: {5: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex 19f203b18..e94ebd34b 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -86,6 +86,7 @@ import {type RemoteAgentBinding,normalizeEveCors,resolveOnMessage,+ strandedSessionResponse,} from "#eve-channel/support.js";import type { EveChannel, EveChannelInput, EveEventContext } from "#eve-channel/types.js";@@ -445,6 +446,8 @@ export function eveChannel(input: EveChannelInput): EveChannel {? await session.send(body.message!, options): await session.respond(body.inputResponses, options);} catch (error) {+ const stranded = strandedSessionResponse(error);+ if (stranded !== undefined) return stranded;const errorId = logError(log, "session-message request failed", error, { sessionId });return Response.json({ error: "Failed to send the session message.", errorId, ok: false },@@ -557,25 +560,18 @@ export function eveChannel(input: EveChannelInput): EveChannel {try {result = await attachSession(sessionId).clear();} catch (error) {+ const stranded = strandedSessionResponse(error);+ if (stranded !== undefined) return stranded;const errorId = logError(log, "session-clear request failed", error, { sessionId });return Response.json({ error: "Failed to clear the session context.", errorId, ok: false },{ status: 500 },);}- return Response.json(- result.status === "accepted"- ? ({- ok: true,- sessionId: result.sessionId,- status: "accepted",- } satisfies ClearResponse)- : ({ ok: true, status: "no_active_session" } satisfies ClearResponse),- {- headers: { "cache-control": "no-store" },- status: result.status === "accepted" ? 202 : 200,- },- );+ return Response.json({ ok: true, ...result } satisfies ClearResponse, {+ headers: { "cache-control": "no-store" },+ status: result.status === "accepted" ? 202 : 200,+ });}),POST(EVE_SESSION_RESET_ROUTE_PATTERN, async (req, { attachSession, params }) => {diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.tsindex cded0cd65..d6afefb20 100644--- a/packages/eve/src/eve-channel/request.ts+++ b/packages/eve/src/eve-channel/request.ts@@ -8,6 +8,7 @@ import type {TurnPolicy,} from "#channel/types.js";import type { Session } from "#channel/session.js";+import { strandedSessionResponse } from "#eve-channel/support.js";import { parseSessionCallback } from "#channel/session-callback.js";import { hasInternalRefScheme } from "#internal/attachments/url-refs.js";import { isMissingWorkflowRunError } from "#internal/workflow/is-inactive-workflow-run-error.js";@@ -297,13 +298,14 @@ export async function createSessionStreamResponse(): Promise<Response> {const startIndex = parseStartIndex(request);if (startIndex instanceof Response) return startIndex;- const includeTailIndex = parseIncludeTailIndex(request);+ const follow = parseFollow(request);+ const includeTailIndex = !follow || parseIncludeTailIndex(request);try {- // An unknown or unreachable session would otherwise answer 200 and then- // fail mid-body, so the tail must resolve before any bytes are committed.- // The event stream opens alongside it to save a round trip.- const eventsPromise = session.getEventStream({ startIndex });+ // Resolve the tail before committing a response; otherwise an unknown or+ // unreachable session would answer 200 and fail mid-body. Open the event+ // stream alongside the tail lookup to avoid an extra round trip.+ const eventsPromise = session.getEventStream({ follow, startIndex });// Handled below; this keeps an early rejection from being reported as unhandled.eventsPromise.catch(() => {});let tailIndex: number;@@ -340,6 +342,8 @@ export async function createSessionStreamResponse({ headers },);} catch (error) {+ const stranded = strandedSessionResponse(error);+ if (stranded !== undefined) return stranded;const notFound = isMissingWorkflowRunError(error);return Response.json({ error: notFound ? "Session not found." : "Session stream unavailable.", ok: false },@@ -611,6 +615,12 @@ export function parseIncludeTailIndex(request: Request): boolean {return raw === "1" || raw === "true";}+/** `follow=false` (or `0`) bounds the read at the durable tail; following is the default. */+function parseFollow(request: Request): boolean {+ const raw = new URL(request.url).searchParams.get("follow");+ return raw !== "0" && raw !== "false";+}+export function parseStartIndex(request: Request): number | undefined | Response {const raw = new URL(request.url).searchParams.get("startIndex");if (raw === null) return undefined;diff --git a/packages/eve/src/eve-channel/support.ts b/packages/eve/src/eve-channel/support.tsindex ec4a3f559..9e378b386 100644--- a/packages/eve/src/eve-channel/support.ts+++ b/packages/eve/src/eve-channel/support.ts@@ -1,5 +1,6 @@import type { UserContent } from "ai";+import { SessionStrandedError } from "#channel/session-stranded-error.js";import type { SessionAuthContext } from "#channel/types.js";import { workflowEntryReference } from "#execution/workflow-runtime.js";import { createLogger, logError } from "#internal/logging.js";@@ -25,6 +26,18 @@ export function healthResponse(): Response {});}+/** Clients display the error text directly; keep operator details in structured fields. */+export function strandedSessionResponse(error: unknown): Response | undefined {+ if (!SessionStrandedError.is(error)) return undefined;+ const body: Record<string, unknown> = {+ code: "session_stranded",+ error: "This session is no longer available.",+ ok: false,+ };+ if (error.owner.eveVersion !== undefined) body.eveVersion = error.owner.eveVersion;+ return Response.json(body, { headers: { "cache-control": "no-store" }, status: 409 });+}+/** Where a remote child the parent session recorded runs, and its credential key. */export interface RemoteAgentBinding {readonly forwardPrincipal?: boolean;diff --git a/packages/eve/src/execution/session-event-stream.ts b/packages/eve/src/execution/session-event-stream.tsindex 49ce5e22a..dd568a274 100644--- a/packages/eve/src/execution/session-event-stream.ts+++ b/packages/eve/src/execution/session-event-stream.ts@@ -38,6 +38,28 @@ export function readSessionEventStream();}+/**+ * Reads one session's recorded events up to the durable tail observed when+ * the read opens, then ends. Negative `startIndex` values count back from+ * that tail.+ */+export function readSessionEventHistory(+ sessionId: string,+ startIndex?: number,+): ReadableStream<MessageStreamEvent> {+ const events = streamSessionEvents(sessionId, { follow: false, startIndex });+ return new ReadableStream<MessageStreamEvent>({+ async pull(controller) {+ const next = await events.next();+ if (next.done) controller.close();+ else controller.enqueue(next.value);+ },+ async cancel() {+ await events.return(undefined);+ },+ });+}+/** Returns the index of the last durably recorded event, or `-1` before the first. */export async function readSessionStreamTailIndex(sessionId: string): Promise<number> {// The readable is never consumed; cancel it so the unread source does not linger.diff --git a/packages/eve/src/execution/session-stranded.integration.test.ts b/packages/eve/src/execution/session-stranded.integration.test.tsindex 4f345cce5..bff62a9da 100644--- a/packages/eve/src/execution/session-stranded.integration.test.ts+++ b/packages/eve/src/execution/session-stranded.integration.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";import { createChannelAddress } from "#channel/channel-address.js";import { createSession } from "#channel/session.js";import { SessionStrandedError } from "#channel/session-stranded-error.js";+import { createSessionStreamResponse } from "#eve-channel/request.js";import type { Runtime } from "#channel/types.js";import {EVE_SESSION_ATTRIBUTE,@@ -299,6 +300,20 @@ describe("stranded sessions", () => {expect(refusal).toBeInstanceOf(SessionStrandedError);expect(refusal).toMatchObject({ owner: { eveVersion: PREVIOUS_EVE_VERSION } });expect((refusal as Error).message).not.toContain(stranded.runId);+ const response = await createSessionStreamResponse(+ new Request(`https://eve.test/eve/v1/session/${stranded.runId}/stream`),+ createSession(stranded.runId, runtime),+ );+ expect(response.status).toBe(409);+ await expect(response.json()).resolves.toMatchObject({ code: "session_stranded" });+ // Recorded history stays readable without resetting the session first.+ const history = await createSessionStreamResponse(+ new Request(`https://eve.test/eve/v1/session/${stranded.runId}/stream?follow=false`),+ createSession(stranded.runId, runtime),+ );+ expect(history.status).toBe(200);+ expect(history.headers.get("x-eve-stream-tail-index")).not.toBeNull();+ await expect(history.text()).resolves.toBeTypeOf("string");expect(runtime.createSession).not.toHaveBeenCalled();await expect(stranded.status).resolves.toBe("running");await expect(listEventIds(stranded.runId)).resolves.toEqual(eventsBefore);diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex bd315a481..849857a81 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -46,6 +46,7 @@ import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-import { buildRunContext } from "#execution/runtime-context.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";import {+ readSessionEventHistory,readSessionEventStream,readSessionStreamTailIndex,} from "#execution/session-event-stream.js";@@ -269,6 +270,8 @@ export function createWorkflowRuntime(config: {sessionId: string,options?: GetEventStreamOptions,): Promise<ReadableStream<MessageStreamEvent>> {+ // Recorded history needs no owner, so reading it never inspects the session's lifecycle.+ if (options?.follow === false) return readSessionEventHistory(sessionId, options.startIndex);// An ended session has no inbox, and a dormant `eve dev` run may resume;// either recorded stream stays readable. Only a stranded owner refuses.try {diff --git a/packages/eve/src/public/channels/eve-session-routes.test.ts b/packages/eve/src/public/channels/eve-session-routes.test.tsindex a5567a4f8..642fb6bbf 100644--- a/packages/eve/src/public/channels/eve-session-routes.test.ts+++ b/packages/eve/src/public/channels/eve-session-routes.test.ts@@ -10,6 +10,7 @@ import { none } from "#public/channels/auth.js";import { eveChannel, type TrustedForwarders } from "#public/channels/eve.js";import { captureLogRecords } from "#internal/testing/log-records.js";import { mockAgentRouteArgs } from "#internal/testing/mocks/mock-route-args.js";+import { SessionStrandedError } from "#channel/session-stranded-error.js";function route(method: "GET" | "POST",@@ -479,6 +480,29 @@ describe("eve ID-addressed session routes", () => {});});+ it("returns a user-facing stranded conflict with structured diagnostic metadata", async () => {+ const session = createFixedSession({+ send: vi.fn().mockRejectedValue(new SessionStrandedError({ eveVersion: "0.1.0" })),+ });+ const response = await route("POST", "/eve/v1/session/:sessionId")(+ new Request("https://eve.test/eve/v1/session/wrun_A", {+ body: JSON.stringify({ message: "Alice follows up after the upgrade." }),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ createArgs(session),+ );++ expect(response.status).toBe(409);+ expect(response.headers.get("cache-control")).toBe("no-store");+ await expect(response.json()).resolves.toEqual({+ code: "session_stranded",+ error: "This session is no longer available.",+ eveVersion: "0.1.0",+ ok: false,+ });+ });+it.each([["cancel", "/eve/v1/session/:sessionId/cancel"],["compact", "/eve/v1/session/:sessionId/compact"],diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex 469473763..9eab26e87 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -574,7 +574,20 @@ describe("eveChannel — stream cursor", () => {);expect(response.status).toBe(200);- expect(handler.getEventStream).toHaveBeenCalledWith({ startIndex });+ expect(handler.getEventStream).toHaveBeenCalledWith({ follow: true, startIndex });+ });++ it("bounds a historical read at the durable tail and asks for it without following", async () => {+ const handler = createEveStreamHandler({ auth: none() });+ handler.getStreamTailIndex.mockResolvedValueOnce(41);++ const response = await handler.fetch(+ "https://eve.test/eve/v1/session/test-session-id/stream?follow=false",+ );++ expect(response.status).toBe(200);+ expect(response.headers.get("x-eve-stream-tail-index")).toBe("41");+ expect(handler.getEventStream).toHaveBeenCalledWith({ follow: false, startIndex: undefined });});it.each(["1.5", "1junk", "0x10", "1e2", ""])(diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.tsindex a5c1b5385..bd2a3edc7 100644--- a/packages/eve/src/public/channels/index.ts+++ b/packages/eve/src/public/channels/index.ts@@ -14,6 +14,7 @@ export {type ClearSessionResult,type CompactSessionResult,type ResetSessionResult,+ SessionStrandedError,type Channel,type ChannelAudience,type AudienceCaller,diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.tsindex 429ce504d..357f98abc 100644--- a/packages/eve/src/public/definitions/channel.ts+++ b/packages/eve/src/public/definitions/channel.ts@@ -38,6 +38,7 @@ export type {SessionCallback,TurnPolicy,} from "#channel/types.js";+export { SessionStrandedError } from "#channel/session-stranded-error.js";export type { Session, SessionHandle } from "#channel/session.js";export type { ChannelAudience } from "#shared/channel-audience.js";export type {diff --git a/packages/eve/test/scenarios/cli.scenario.test.ts b/packages/eve/test/scenarios/cli.scenario.test.tsindex 4aca3e74e..6b56142e3 100644--- a/packages/eve/test/scenarios/cli.scenario.test.ts+++ b/packages/eve/test/scenarios/cli.scenario.test.ts@@ -1,4 +1,4 @@-import { execFile, spawn, type ChildProcess } from "node:child_process";+import { execFile } from "node:child_process";import { access, mkdir, realpath, writeFile } from "node:fs/promises";import { join } from "node:path";import { fileURLToPath } from "node:url";@@ -19,6 +19,7 @@ import {EVE_SESSION_STREAM_ROUTE_PATTERN,} from "../../src/protocol/routes.js";import { useTemporaryDirectories } from "../../src/internal/testing/use-temporary-app-roots.js";+import { startPackagedEveStart } from "./eve-start-harness.js";const EVE_BIN_PATH = fileURLToPath(new URL("../../bin/eve.js", import.meta.url));const scenarioApp = useScenarioApp();@@ -42,13 +43,6 @@ function clearCliBuildEnvironment(): void {}}-interface RunningEveStart {- readonly url: string;- stderr(): string;- stdout(): string;- stop(): Promise<void>;-}-async function createMinimalAppRoot(prefix: string): Promise<string> {const appRoot = await createScratchDirectory(prefix);@@ -77,117 +71,6 @@ async function createMinimalAppRoot(prefix: string): Promise<string> {return appRoot;}-async function startPackagedEveStart(appRoot: string): Promise<RunningEveStart> {- const child = spawn(- process.execPath,- [EVE_BIN_PATH, "start", "--host", "127.0.0.1", "--port", "0"],- {- cwd: appRoot,- stdio: ["ignore", "pipe", "pipe"],- },- );- let stderr = "";- let stdout = "";-- child.stdout.setEncoding("utf8");- child.stderr.setEncoding("utf8");- child.stdout.on("data", (chunk: string) => {- stdout += chunk;- });- child.stderr.on("data", (chunk: string) => {- stderr += chunk;- });-- let url: string;- try {- url = await waitForStartUrl({- child,- getOutput: () => ({- stderr,- stdout,- }),- });- } catch (error) {- await stopChildProcess(child);- throw error;- }-- return {- stderr: () => stderr,- stdout: () => stdout,- async stop() {- await stopChildProcess(child);- },- url,- };-}--async function waitForStartUrl(input: {- readonly child: ChildProcess;- readonly getOutput: () => {- readonly stderr: string;- readonly stdout: string;- };-}): Promise<string> {- const startedAt = Date.now();-- while (Date.now() - startedAt < 60_000) {- const output = input.getOutput();- const url = parseStartUrl(output.stdout);-- if (url !== undefined) {- return url;- }-- if (input.child.exitCode !== null || input.child.signalCode !== null) {- throw new Error(- [- `eve start exited before printing its server URL (code ${String(- input.child.exitCode,- )}, signal ${String(input.child.signalCode)}).`,- `stdout:\n${output.stdout}`,- `stderr:\n${output.stderr}`,- ].join("\n\n"),- );- }-- await new Promise((resolve) => setTimeout(resolve, 100));- }-- const output = input.getOutput();- throw new Error(- [- "Timed out waiting for eve start to print its server URL.",- `stdout:\n${output.stdout}`,- `stderr:\n${output.stderr}`,- ].join("\n\n"),- );-}--function parseStartUrl(output: string): string | undefined {- const match = /\[START\] server listening at (https?:\/\/[^\s]+)/.exec(output);- return match?.[1];-}--async function stopChildProcess(child: ChildProcess): Promise<void> {- if (child.exitCode !== null || child.signalCode !== null) {- return;- }-- await new Promise<void>((resolve) => {- const timeout = setTimeout(() => {- child.kill("SIGKILL");- resolve();- }, 10_000);-- child.once("exit", () => {- clearTimeout(timeout);- resolve();- });- child.kill("SIGTERM");- });-}-afterEach(() => {clearCliBuildEnvironment();});diff --git a/packages/eve/test/scenarios/eve-start-harness.ts b/packages/eve/test/scenarios/eve-start-harness.tsnew file mode 100644index 000000000..20915d684--- /dev/null+++ b/packages/eve/test/scenarios/eve-start-harness.ts@@ -0,0 +1,123 @@+import { spawn, type ChildProcess } from "node:child_process";+import { fileURLToPath } from "node:url";++const EVE_BIN_PATH = fileURLToPath(new URL("../../bin/eve.js", import.meta.url));++export interface RunningEveStart {+ readonly url: string;+ stderr(): string;+ stdout(): string;+ stop(): Promise<void>;+}++/** Runs the packaged `eve start` for a built app on an available local port. */+export async function startPackagedEveStart(appRoot: string): Promise<RunningEveStart> {+ const child = spawn(+ process.execPath,+ [EVE_BIN_PATH, "start", "--host", "127.0.0.1", "--port", "0"],+ {+ cwd: appRoot,+ stdio: ["ignore", "pipe", "pipe"],+ },+ );+ let stderr = "";+ let stdout = "";++ child.stdout.setEncoding("utf8");+ child.stderr.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ stdout += chunk;+ });+ child.stderr.on("data", (chunk: string) => {+ stderr += chunk;+ });++ let url: string;+ try {+ url = await waitForStartUrl({+ child,+ getOutput: () => ({+ stderr,+ stdout,+ }),+ });+ } catch (error) {+ await stopChildProcess(child);+ throw error;+ }++ return {+ stderr: () => stderr,+ stdout: () => stdout,+ async stop() {+ await stopChildProcess(child);+ },+ url,+ };+}++async function waitForStartUrl(input: {+ readonly child: ChildProcess;+ readonly getOutput: () => {+ readonly stderr: string;+ readonly stdout: string;+ };+}): Promise<string> {+ const startedAt = Date.now();++ while (Date.now() - startedAt < 60_000) {+ const output = input.getOutput();+ const url = parseStartUrl(output.stdout);++ if (url !== undefined) {+ return url;+ }++ if (input.child.exitCode !== null || input.child.signalCode !== null) {+ throw new Error(+ [+ `eve start exited before printing its server URL (code ${String(+ input.child.exitCode,+ )}, signal ${String(input.child.signalCode)}).`,+ `stdout:\n${output.stdout}`,+ `stderr:\n${output.stderr}`,+ ].join("\n\n"),+ );+ }++ await new Promise((resolve) => setTimeout(resolve, 100));+ }++ const output = input.getOutput();+ throw new Error(+ [+ "Timed out waiting for eve start to print its server URL.",+ `stdout:\n${output.stdout}`,+ `stderr:\n${output.stderr}`,+ ].join("\n\n"),+ );+}++function parseStartUrl(output: string): string | undefined {+ const match = /\[START\] server listening at (https?:\/\/[^\s]+)/.exec(output);+ return match?.[1];+}++async function stopChildProcess(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) {+ return;+ }++ await new Promise<void>((resolve) => {+ const timeout = setTimeout(() => {+ child.kill("SIGKILL");+ resolve();+ }, 10_000);++ child.once("exit", () => {+ clearTimeout(timeout);+ resolve();+ });+ child.kill("SIGTERM");+ });+}diff --git a/packages/eve/test/scenarios/stranded-session-reset.scenario.test.ts b/packages/eve/test/scenarios/stranded-session-reset.scenario.test.tsnew file mode 100644index 000000000..7cfb6ac01--- /dev/null+++ b/packages/eve/test/scenarios/stranded-session-reset.scenario.test.ts@@ -0,0 +1,186 @@+import { readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";++import { describe, expect, it } from "vitest";++import {+ type ScenarioAppDescriptor,+ useScenarioApp,+} from "../../src/internal/testing/scenario-app.js";+import { resolveLocalWorkflowWorldDataDirectory } from "../../src/internal/workflow/local-world-data-directory.js";+import { type RunningEveStart, startPackagedEveStart } from "./eve-start-harness.js";++const scenarioApp = useScenarioApp();+const SCENARIO_TIMEOUT_MS = 300_000;+const WAIT_TIMEOUT_MS = 60_000;++const STRANDED_SESSION_DESCRIPTOR: ScenarioAppDescriptor = {+ files: {+ "agent/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";++export default defineAgent({+ model: mockModel(() => "Noted."),+ modelContextWindowTokens: 32_000,+});+`,+ "agent/instructions.md": "Acknowledge each message briefly.\n",+ "agent/channels/threads.ts": `import { defineChannel, GET, POST, SessionStrandedError } from "eve/channels";++export default defineChannel({+ routes: [+ POST("/threads/:threadId", async (request, { from, params }) => {+ const session = await from(params.threadId!).send(await request.text(), { auth: null });+ return Response.json({ sessionId: session.id });+ }),+ POST("/sessions/:sessionId", async (request, { attachSession, params }) => {+ try {+ await attachSession(params.sessionId!).send(await request.text(), { auth: null });+ return Response.json({ delivered: true });+ } catch (error) {+ if (!SessionStrandedError.is(error)) throw error;+ return Response.json(+ { eveVersion: error.owner.eveVersion, stranded: true },+ { status: 409 },+ );+ }+ }),+ GET("/sessions/:sessionId/stream", async (_request, { attachSession, params }) => {+ const events = await attachSession(params.sessionId!).getEventStream();+ const ndjson = events+ .pipeThrough(+ new TransformStream({+ transform(event, controller) {+ controller.enqueue(JSON.stringify(event) + "\\n");+ },+ }),+ )+ .pipeThrough(new TextEncoderStream());+ return new Response(ndjson, {+ headers: { "content-type": "application/x-ndjson; charset=utf-8" },+ });+ }),+ ],+});+`,+ },+ installDependencies: true,+ name: "stranded-session-reset",+};++/** Fetches from the running app, attaching its output to any transport failure. */+async function request(server: RunningEveStart, path: string, init?: RequestInit) {+ try {+ return await fetch(new URL(path, server.url), init);+ } catch (error) {+ throw new Error(+ `${init?.method ?? "GET"} ${path} failed.\n${server.stdout()}\n${server.stderr()}`,+ {+ cause: error,+ },+ );+ }+}++async function sendToThread(server: RunningEveStart, message: string): Promise<string> {+ const response = await request(server, "/threads/alice", { body: message, method: "POST" });+ const body = await response.text();+ expect(response.status, `${body}\n${server.stderr()}`).toBe(200);+ return (JSON.parse(body) as { sessionId: string }).sessionId;+}++/** Reads the session's event stream until its first turn has finished. */+async function waitForTurnCompleted(server: RunningEveStart, sessionId: string): Promise<void> {+ const response = await request(server, `/sessions/${sessionId}/stream`, {+ signal: AbortSignal.timeout(WAIT_TIMEOUT_MS),+ });+ const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();+ let buffered = "";+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) throw new Error(`Stream ended before the turn completed.\n${server.stderr()}`);+ buffered += value;+ if (buffered.includes('"type":"turn.completed"')) return;+ }+ } finally {+ await reader.cancel().catch(() => {});+ }+}++async function waitForOutput(server: RunningEveStart, text: string): Promise<void> {+ const deadline = Date.now() + WAIT_TIMEOUT_MS;+ while (!server.stderr().includes(text) && !server.stdout().includes(text)) {+ if (Date.now() > deadline) {+ throw new Error(`Timed out waiting for "${text}".\n${server.stdout()}\n${server.stderr()}`);+ }+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+}++/** The local World keeps each run's record, including its attributes, at `runs/<runId>.json`. */+function runFilePath(appRoot: string, runId: string): string {+ return join(resolveLocalWorkflowWorldDataDirectory(appRoot), "runs", `${runId}.json`);+}++async function readRun(+ path: string,+): Promise<{ attributes: Record<string, string>; status: string }> {+ return JSON.parse(await readFile(path, "utf8")) as {+ attributes: Record<string, string>;+ status: string;+ };+}++describe("stranded sessions across an eve upgrade", () => {+ it(+ "parks the old session at startup and resets it on its next channel message",+ async () => {+ const { buildApplication } = await import("../../src/internal/nitro/host.js");+ const { appRoot } = await scenarioApp(STRANDED_SESSION_DESCRIPTOR);+ await buildApplication(appRoot, { skipSandboxPrewarm: true });++ let server = await startPackagedEveStart(appRoot);+ let strandedSessionId: string;+ try {+ strandedSessionId = await sendToThread(server, "Alice opens the thread.");+ await waitForTurnCompleted(server, strandedSessionId);+ } finally {+ await server.stop();+ }++ // Simulate the first upgrade from a release that did not stamp owner versions.+ const runFile = runFilePath(appRoot, strandedSessionId);+ const parked = await readRun(runFile);+ expect(parked.status).toBe("running");+ delete parked.attributes["$eve.version"];+ await writeFile(runFile, JSON.stringify(parked));++ server = await startPackagedEveStart(appRoot);+ try {+ await waitForOutput(+ server,+ `Skipping replay of stranded session run "${strandedSessionId}"`,+ );++ const byId = await request(server, `/sessions/${strandedSessionId}`, {+ body: "Bob follows up on the old session.",+ method: "POST",+ });+ expect(byId.status, server.stderr()).toBe(409);+ // The parked run recorded no eve version, as on the first upgrade.+ await expect(byId.json()).resolves.toEqual({ stranded: true });++ const freshSessionId = await sendToThread(server, "Alice continues the thread.");+ expect(freshSessionId).not.toBe(strandedSessionId);+ await waitForTurnCompleted(server, freshSessionId);+ await waitForOutput(server, "Reset stranded session");+ await expect(readRun(runFile)).resolves.toMatchObject({ status: "cancelled" });+ expect(server.stdout() + server.stderr()).not.toContain("CORRUPTED_EVENT_LOG");+ } finally {+ await server.stop();+ }+ },+ SCENARIO_TIMEOUT_MS,+ );+});